diff --git a/dist/index.js b/dist/index.js index 23fe6a6..a45f90a 100644 --- a/dist/index.js +++ b/dist/index.js @@ -5098,6 +5098,8 @@ __export(index_exports, { KMSDisabledException: () => KMSDisabledException, KMSInvalidStateException: () => KMSInvalidStateException, KMSNotFoundException: () => KMSNotFoundException, + KafkaSchemaRegistryAuthType: () => KafkaSchemaRegistryAuthType, + KafkaSchemaValidationAttribute: () => KafkaSchemaValidationAttribute, Lambda: () => Lambda, LambdaClient: () => LambdaClient, LambdaServiceException: () => LambdaServiceException, @@ -5147,6 +5149,7 @@ __export(index_exports, { Runtime: () => Runtime, RuntimeVersionConfigFilterSensitiveLog: () => RuntimeVersionConfigFilterSensitiveLog, RuntimeVersionErrorFilterSensitiveLog: () => RuntimeVersionErrorFilterSensitiveLog, + SchemaRegistryEventRecordFormat: () => SchemaRegistryEventRecordFormat, ServiceException: () => ServiceException, SnapStartApplyOn: () => SnapStartApplyOn, SnapStartException: () => SnapStartException, @@ -5550,6 +5553,19 @@ var FunctionUrlAuthType = { AWS_IAM: "AWS_IAM", NONE: "NONE" }; +var KafkaSchemaRegistryAuthType = { + BASIC_AUTH: "BASIC_AUTH", + CLIENT_CERTIFICATE_TLS_AUTH: "CLIENT_CERTIFICATE_TLS_AUTH", + SERVER_ROOT_CA_CERTIFICATE: "SERVER_ROOT_CA_CERTIFICATE" +}; +var SchemaRegistryEventRecordFormat = { + JSON: "JSON", + SOURCE: "SOURCE" +}; +var KafkaSchemaValidationAttribute = { + KEY: "KEY", + VALUE: "VALUE" +}; var ApplicationLogLevel = { Debug: "DEBUG", Error: "ERROR", @@ -5594,6 +5610,28 @@ var EventSourcePosition = { LATEST: "LATEST", TRIM_HORIZON: "TRIM_HORIZON" }; +var ResourceInUseException = class _ResourceInUseException extends LambdaServiceException { + static { + __name(this, "ResourceInUseException"); + } + name = "ResourceInUseException"; + $fault = "client"; + Type; + Message; + /** + * @internal + */ + constructor(opts) { + super({ + name: "ResourceInUseException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ResourceInUseException.prototype); + this.Type = opts.Type; + this.Message = opts.Message; + } +}; var CodeSigningConfigNotFoundException = class _CodeSigningConfigNotFoundException extends LambdaServiceException { static { __name(this, "CodeSigningConfigNotFoundException"); @@ -5816,57 +5854,10 @@ var InvokeMode = { BUFFERED: "BUFFERED", RESPONSE_STREAM: "RESPONSE_STREAM" }; -var ResourceInUseException = class _ResourceInUseException extends LambdaServiceException { - static { - __name(this, "ResourceInUseException"); - } - name = "ResourceInUseException"; - $fault = "client"; - Type; - Message; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ResourceInUseException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ResourceInUseException.prototype); - this.Type = opts.Type; - this.Message = opts.Message; - } -}; var RecursiveLoop = { Allow: "Allow", Terminate: "Terminate" }; -var ProvisionedConcurrencyStatusEnum = { - FAILED: "FAILED", - IN_PROGRESS: "IN_PROGRESS", - READY: "READY" -}; -var ProvisionedConcurrencyConfigNotFoundException = class _ProvisionedConcurrencyConfigNotFoundException extends LambdaServiceException { - static { - __name(this, "ProvisionedConcurrencyConfigNotFoundException"); - } - name = "ProvisionedConcurrencyConfigNotFoundException"; - $fault = "client"; - Type; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ProvisionedConcurrencyConfigNotFoundException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ProvisionedConcurrencyConfigNotFoundException.prototype); - this.Type = opts.Type; - } -}; var UpdateRuntimeOn = { Auto: "Auto", FunctionUpdate: "FunctionUpdate", @@ -6456,6 +6447,31 @@ var InvokeWithResponseStreamResponseEvent; var FunctionVersion = { ALL: "ALL" }; +var ProvisionedConcurrencyStatusEnum = { + FAILED: "FAILED", + IN_PROGRESS: "IN_PROGRESS", + READY: "READY" +}; +var ProvisionedConcurrencyConfigNotFoundException = class _ProvisionedConcurrencyConfigNotFoundException extends LambdaServiceException { + static { + __name(this, "ProvisionedConcurrencyConfigNotFoundException"); + } + name = "ProvisionedConcurrencyConfigNotFoundException"; + $fault = "client"; + Type; + /** + * @internal + */ + constructor(opts) { + super({ + name: "ProvisionedConcurrencyConfigNotFoundException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ProvisionedConcurrencyConfigNotFoundException.prototype); + this.Type = opts.Type; + } +}; var FunctionCodeFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ ...obj, ...obj.ZipFile && { ZipFile: import_smithy_client.SENSITIVE_STRING } @@ -6541,6 +6557,14 @@ var ListFunctionsResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ ...obj, ...obj.Functions && { Functions: obj.Functions.map((item) => FunctionConfigurationFilterSensitiveLog(item)) } }), "ListFunctionsResponseFilterSensitiveLog"); +var UpdateFunctionCodeRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.ZipFile && { ZipFile: import_smithy_client.SENSITIVE_STRING } +}), "UpdateFunctionCodeRequestFilterSensitiveLog"); +var UpdateFunctionConfigurationRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Environment && { Environment: EnvironmentFilterSensitiveLog(obj.Environment) } +}), "UpdateFunctionConfigurationRequestFilterSensitiveLog"); var ListVersionsByFunctionResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ ...obj, ...obj.Versions && { Versions: obj.Versions.map((item) => FunctionConfigurationFilterSensitiveLog(item)) } @@ -6553,14 +6577,6 @@ var PublishLayerVersionRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) ...obj, ...obj.Content && { Content: LayerVersionContentInputFilterSensitiveLog(obj.Content) } }), "PublishLayerVersionRequestFilterSensitiveLog"); -var UpdateFunctionCodeRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.ZipFile && { ZipFile: import_smithy_client.SENSITIVE_STRING } -}), "UpdateFunctionCodeRequestFilterSensitiveLog"); -var UpdateFunctionConfigurationRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Environment && { Environment: EnvironmentFilterSensitiveLog(obj.Environment) } -}), "UpdateFunctionConfigurationRequestFilterSensitiveLog"); // src/protocols/Aws_restJson1.ts var se_AddLayerVersionPermissionCommand = /* @__PURE__ */ __name(async (input, context) => { @@ -7495,6 +7511,7 @@ var se_UpdateEventSourceMappingCommand = /* @__PURE__ */ __name(async (input, co let body; body = JSON.stringify( (0, import_smithy_client.take)(input, { + AmazonManagedKafkaEventSourceConfig: /* @__PURE__ */ __name((_) => (0, import_smithy_client._json)(_), "AmazonManagedKafkaEventSourceConfig"), BatchSize: [], BisectBatchOnFunctionError: [], DestinationConfig: /* @__PURE__ */ __name((_) => (0, import_smithy_client._json)(_), "DestinationConfig"), @@ -7511,6 +7528,7 @@ var se_UpdateEventSourceMappingCommand = /* @__PURE__ */ __name(async (input, co ParallelizationFactor: [], ProvisionedPollerConfig: /* @__PURE__ */ __name((_) => (0, import_smithy_client._json)(_), "ProvisionedPollerConfig"), ScalingConfig: /* @__PURE__ */ __name((_) => (0, import_smithy_client._json)(_), "ScalingConfig"), + SelfManagedKafkaEventSourceConfig: /* @__PURE__ */ __name((_) => (0, import_smithy_client._json)(_), "SelfManagedKafkaEventSourceConfig"), SourceAccessConfigurations: /* @__PURE__ */ __name((_) => (0, import_smithy_client._json)(_), "SourceAccessConfigurations"), TumblingWindowInSeconds: [] }) @@ -9603,7 +9621,7 @@ var de_InvokeWithResponseStreamResponseEvent = /* @__PURE__ */ __name((output, c InvokeComplete: await de_InvokeWithResponseStreamCompleteEvent_event(event["InvokeComplete"], context) }; } - return { $unknown: output }; + return { $unknown: event }; }); }, "de_InvokeWithResponseStreamResponseEvent"); var de_InvokeResponseStreamUpdate_event = /* @__PURE__ */ __name(async (output, context) => { @@ -10960,11 +10978,11 @@ var checkState = /* @__PURE__ */ __name(async (client, input) => { return { state: import_util_waiter.WaiterState.RETRY, reason }; }, "checkState"); var waitForFunctionActive = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + const serviceDefaults = { minDelay: 5, maxDelay: 300 }; return (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState); }, "waitForFunctionActive"); var waitUntilFunctionActive = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + const serviceDefaults = { minDelay: 5, maxDelay: 300 }; const result = await (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState); return (0, import_util_waiter.checkExceptions)(result); }, "waitUntilFunctionActive"); @@ -11009,11 +11027,11 @@ var checkState2 = /* @__PURE__ */ __name(async (client, input) => { return { state: import_util_waiter.WaiterState.RETRY, reason }; }, "checkState"); var waitForFunctionActiveV2 = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 1, maxDelay: 120 }; + const serviceDefaults = { minDelay: 1, maxDelay: 300 }; return (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState2); }, "waitForFunctionActiveV2"); var waitUntilFunctionActiveV2 = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 1, maxDelay: 120 }; + const serviceDefaults = { minDelay: 1, maxDelay: 300 }; const result = await (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState2); return (0, import_util_waiter.checkExceptions)(result); }, "waitUntilFunctionActiveV2"); @@ -11035,11 +11053,11 @@ var checkState3 = /* @__PURE__ */ __name(async (client, input) => { return { state: import_util_waiter.WaiterState.RETRY, reason }; }, "checkState"); var waitForFunctionExists = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 1, maxDelay: 120 }; + const serviceDefaults = { minDelay: 1, maxDelay: 20 }; return (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState3); }, "waitForFunctionExists"); var waitUntilFunctionExists = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 1, maxDelay: 120 }; + const serviceDefaults = { minDelay: 1, maxDelay: 20 }; const result = await (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState3); return (0, import_util_waiter.checkExceptions)(result); }, "waitUntilFunctionExists"); @@ -11084,11 +11102,11 @@ var checkState4 = /* @__PURE__ */ __name(async (client, input) => { return { state: import_util_waiter.WaiterState.RETRY, reason }; }, "checkState"); var waitForFunctionUpdated = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + const serviceDefaults = { minDelay: 5, maxDelay: 300 }; return (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState4); }, "waitForFunctionUpdated"); var waitUntilFunctionUpdated = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + const serviceDefaults = { minDelay: 5, maxDelay: 300 }; const result = await (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState4); return (0, import_util_waiter.checkExceptions)(result); }, "waitUntilFunctionUpdated"); @@ -11133,11 +11151,11 @@ var checkState5 = /* @__PURE__ */ __name(async (client, input) => { return { state: import_util_waiter.WaiterState.RETRY, reason }; }, "checkState"); var waitForFunctionUpdatedV2 = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 1, maxDelay: 120 }; + const serviceDefaults = { minDelay: 1, maxDelay: 300 }; return (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState5); }, "waitForFunctionUpdatedV2"); var waitUntilFunctionUpdatedV2 = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 1, maxDelay: 120 }; + const serviceDefaults = { minDelay: 1, maxDelay: 300 }; const result = await (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState5); return (0, import_util_waiter.checkExceptions)(result); }, "waitUntilFunctionUpdatedV2"); @@ -11182,11 +11200,11 @@ var checkState6 = /* @__PURE__ */ __name(async (client, input) => { return { state: import_util_waiter.WaiterState.RETRY, reason }; }, "checkState"); var waitForPublishedVersionActive = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + const serviceDefaults = { minDelay: 5, maxDelay: 1560 }; return (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState6); }, "waitForPublishedVersionActive"); var waitUntilPublishedVersionActive = /* @__PURE__ */ __name(async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + const serviceDefaults = { minDelay: 5, maxDelay: 1560 }; const result = await (0, import_util_waiter.createWaiter)({ ...serviceDefaults, ...params }, input, checkState6); return (0, import_util_waiter.checkExceptions)(result); }, "waitUntilPublishedVersionActive"); @@ -11313,7 +11331,7 @@ exports.getRuntimeConfig = getRuntimeConfig; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveHttpAuthSchemeConfig = exports.defaultS3HttpAuthSchemeProvider = exports.defaultS3HttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(8078); +const core_1 = __nccwpck_require__(9963); const signature_v4_multi_region_1 = __nccwpck_require__(1856); const middleware_endpoint_1 = __nccwpck_require__(2918); const util_middleware_1 = __nccwpck_require__(2390); @@ -11448,7 +11466,7 @@ exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(1256); +const util_endpoints_1 = __nccwpck_require__(3350); const util_endpoints_2 = __nccwpck_require__(5473); const ruleset_1 = __nccwpck_require__(6114); const cache = new util_endpoints_2.EndpointCache({ @@ -11781,11 +11799,11 @@ module.exports = __toCommonJS(index_exports); // src/S3Client.ts var import_middleware_expect_continue = __nccwpck_require__(1990); var import_middleware_flexible_checksums = __nccwpck_require__(3799); -var import_middleware_host_header = __nccwpck_require__(8725); -var import_middleware_logger = __nccwpck_require__(2568); -var import_middleware_recursion_detection = __nccwpck_require__(7960); +var import_middleware_host_header = __nccwpck_require__(2545); +var import_middleware_logger = __nccwpck_require__(14); +var import_middleware_recursion_detection = __nccwpck_require__(5525); var import_middleware_sdk_s32 = __nccwpck_require__(1139); -var import_middleware_user_agent = __nccwpck_require__(3030); +var import_middleware_user_agent = __nccwpck_require__(4688); var import_config_resolver = __nccwpck_require__(3098); var import_core3 = __nccwpck_require__(5829); var import_eventstream_serde_config_resolver = __nccwpck_require__(6181); @@ -12479,7 +12497,7 @@ var ListBucketInventoryConfigurationsOutputFilterSensitiveLog = /* @__PURE__ */ }), "ListBucketInventoryConfigurationsOutputFilterSensitiveLog"); // src/protocols/Aws_restXml.ts -var import_core = __nccwpck_require__(8078); +var import_core = __nccwpck_require__(9963); var import_xml_builder = __nccwpck_require__(7406); var import_core2 = __nccwpck_require__(5829); var import_protocol_http = __nccwpck_require__(4418); @@ -20686,7 +20704,7 @@ var CreateSessionCommand = class extends import_smithy_client.Command.classBuild var import_runtimeConfig = __nccwpck_require__(2714); // src/runtimeExtensions.ts -var import_region_config_resolver = __nccwpck_require__(8859); +var import_region_config_resolver = __nccwpck_require__(8156); @@ -23293,12 +23311,12 @@ 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__(677)); -const core_1 = __nccwpck_require__(8078); -const credential_provider_node_1 = __nccwpck_require__(2424); +const core_1 = __nccwpck_require__(9963); +const credential_provider_node_1 = __nccwpck_require__(5531); const middleware_bucket_endpoint_1 = __nccwpck_require__(6689); const middleware_flexible_checksums_1 = __nccwpck_require__(3799); const middleware_sdk_s3_1 = __nccwpck_require__(1139); -const util_user_agent_node_1 = __nccwpck_require__(5380); +const util_user_agent_node_1 = __nccwpck_require__(8095); const config_resolver_1 = __nccwpck_require__(3098); const eventstream_serde_node_1 = __nccwpck_require__(7682); const hash_node_1 = __nccwpck_require__(3081); @@ -23371,7 +23389,7 @@ exports.getRuntimeConfig = getRuntimeConfig; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(8078); +const core_1 = __nccwpck_require__(9963); const signature_v4_multi_region_1 = __nccwpck_require__(1856); const smithy_client_1 = __nccwpck_require__(3570); const url_parser_1 = __nccwpck_require__(4681); @@ -23418,14 +23436,192 @@ exports.getRuntimeConfig = getRuntimeConfig; /***/ }), -/***/ 4459: +/***/ 7406: +/***/ ((module) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + XmlNode: () => XmlNode, + XmlText: () => XmlText +}); +module.exports = __toCommonJS(index_exports); + +// src/escape-attribute.ts +function escapeAttribute(value) { + return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} +__name(escapeAttribute, "escapeAttribute"); + +// src/escape-element.ts +function escapeElement(value) { + return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">").replace(/\r/g, " ").replace(/\n/g, " ").replace(/\u0085/g, "…").replace(/\u2028/, "
"); +} +__name(escapeElement, "escapeElement"); + +// src/XmlText.ts +var XmlText = class { + constructor(value) { + this.value = value; + } + static { + __name(this, "XmlText"); + } + toString() { + return escapeElement("" + this.value); + } +}; + +// src/XmlNode.ts +var XmlNode = class _XmlNode { + constructor(name, children = []) { + this.name = name; + this.children = children; + } + static { + __name(this, "XmlNode"); + } + attributes = {}; + static of(name, childText, withName) { + const node = new _XmlNode(name); + if (childText !== void 0) { + node.addChildNode(new XmlText(childText)); + } + if (withName !== void 0) { + node.withName(withName); + } + return node; + } + withName(name) { + this.name = name; + return this; + } + addAttribute(name, value) { + this.attributes[name] = value; + return this; + } + addChildNode(child) { + this.children.push(child); + return this; + } + removeAttribute(name) { + delete this.attributes[name]; + return this; + } + /** + * @internal + * Alias of {@link XmlNode#withName(string)} for codegen brevity. + */ + n(name) { + this.name = name; + return this; + } + /** + * @internal + * Alias of {@link XmlNode#addChildNode(string)} for codegen brevity. + */ + c(child) { + this.children.push(child); + return this; + } + /** + * @internal + * Checked version of {@link XmlNode#addAttribute(string)} for codegen brevity. + */ + a(name, value) { + if (value != null) { + this.attributes[name] = value; + } + return this; + } + /** + * Create a child node. + * Used in serialization of string fields. + * @internal + */ + cc(input, field, withName = field) { + if (input[field] != null) { + const node = _XmlNode.of(field, input[field]).withName(withName); + this.c(node); + } + } + /** + * Creates list child nodes. + * @internal + */ + l(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + nodes.map((node) => { + node.withName(memberName); + this.c(node); + }); + } + } + /** + * Creates list child nodes with container. + * @internal + */ + lc(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + const containerNode = new _XmlNode(memberName); + nodes.map((node) => { + containerNode.c(node); + }); + this.c(containerNode); + } + } + toString() { + const hasChildren = Boolean(this.children.length); + let xmlText = `<${this.name}`; + const attributes = this.attributes; + for (const attributeName of Object.keys(attributes)) { + const attribute = attributes[attributeName]; + if (attribute != null) { + xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; + } + } + return xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`; + } +}; +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 9344: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.resolveHttpAuthSchemeConfig = exports.defaultSSOHttpAuthSchemeProvider = exports.defaultSSOHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(8078); +const core_1 = __nccwpck_require__(9963); const util_middleware_1 = __nccwpck_require__(2390); const defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => { return { @@ -23494,16 +23690,16 @@ exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; /***/ }), -/***/ 8987: +/***/ 898: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(1256); +const util_endpoints_1 = __nccwpck_require__(3350); const util_endpoints_2 = __nccwpck_require__(5473); -const ruleset_1 = __nccwpck_require__(2345); +const ruleset_1 = __nccwpck_require__(3341); const cache = new util_endpoints_2.EndpointCache({ size: 50, params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], @@ -23520,7 +23716,7 @@ util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunct /***/ }), -/***/ 2345: +/***/ 3341: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -23535,7 +23731,7 @@ exports.ruleSet = _data; /***/ }), -/***/ 3015: +/***/ 2666: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -23586,17 +23782,17 @@ __export(index_exports, { module.exports = __toCommonJS(index_exports); // src/SSOClient.ts -var import_middleware_host_header = __nccwpck_require__(8725); -var import_middleware_logger = __nccwpck_require__(2568); -var import_middleware_recursion_detection = __nccwpck_require__(7960); -var import_middleware_user_agent = __nccwpck_require__(3030); +var import_middleware_host_header = __nccwpck_require__(2545); +var import_middleware_logger = __nccwpck_require__(14); +var import_middleware_recursion_detection = __nccwpck_require__(5525); +var import_middleware_user_agent = __nccwpck_require__(4688); var import_config_resolver = __nccwpck_require__(3098); var import_core = __nccwpck_require__(5829); var import_middleware_content_length = __nccwpck_require__(2800); var import_middleware_endpoint = __nccwpck_require__(2918); var import_middleware_retry = __nccwpck_require__(6039); -var import_httpAuthSchemeProvider = __nccwpck_require__(4459); +var import_httpAuthSchemeProvider = __nccwpck_require__(9344); // src/endpoint/EndpointParameters.ts var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { @@ -23614,10 +23810,10 @@ var commonParams = { }; // src/SSOClient.ts -var import_runtimeConfig = __nccwpck_require__(1581); +var import_runtimeConfig = __nccwpck_require__(9756); // src/runtimeExtensions.ts -var import_region_config_resolver = __nccwpck_require__(8859); +var import_region_config_resolver = __nccwpck_require__(8156); var import_protocol_http = __nccwpck_require__(4418); var import_smithy_client = __nccwpck_require__(3570); @@ -23852,7 +24048,7 @@ var LogoutRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ }), "LogoutRequestFilterSensitiveLog"); // src/protocols/Aws_restJson1.ts -var import_core2 = __nccwpck_require__(8078); +var import_core2 = __nccwpck_require__(9963); var se_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (input, context) => { @@ -24146,7 +24342,7 @@ var paginateListAccounts = (0, import_core.createPaginator)(SSOClient, ListAccou /***/ }), -/***/ 1581: +/***/ 9756: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -24154,9 +24350,9 @@ var paginateListAccounts = (0, import_core.createPaginator)(SSOClient, ListAccou 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__(3859)); -const core_1 = __nccwpck_require__(8078); -const util_user_agent_node_1 = __nccwpck_require__(5380); +const package_json_1 = tslib_1.__importDefault(__nccwpck_require__(1092)); +const core_1 = __nccwpck_require__(9963); +const util_user_agent_node_1 = __nccwpck_require__(8095); const config_resolver_1 = __nccwpck_require__(3098); const hash_node_1 = __nccwpck_require__(3081); const middleware_retry_1 = __nccwpck_require__(6039); @@ -24164,7 +24360,7 @@ const node_config_provider_1 = __nccwpck_require__(3461); const node_http_handler_1 = __nccwpck_require__(258); const util_body_length_node_1 = __nccwpck_require__(8075); const util_retry_1 = __nccwpck_require__(4902); -const runtimeConfig_shared_1 = __nccwpck_require__(6844); +const runtimeConfig_shared_1 = __nccwpck_require__(4809); const smithy_client_1 = __nccwpck_require__(3570); const util_defaults_mode_node_1 = __nccwpck_require__(2429); const smithy_client_2 = __nccwpck_require__(3570); @@ -24208,21 +24404,21 @@ exports.getRuntimeConfig = getRuntimeConfig; /***/ }), -/***/ 6844: +/***/ 4809: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(8078); +const core_1 = __nccwpck_require__(9963); const core_2 = __nccwpck_require__(5829); const smithy_client_1 = __nccwpck_require__(3570); const url_parser_1 = __nccwpck_require__(4681); const util_base64_1 = __nccwpck_require__(5600); const util_utf8_1 = __nccwpck_require__(1895); -const httpAuthSchemeProvider_1 = __nccwpck_require__(4459); -const endpointResolver_1 = __nccwpck_require__(8987); +const httpAuthSchemeProvider_1 = __nccwpck_require__(9344); +const endpointResolver_1 = __nccwpck_require__(898); const getRuntimeConfig = (config) => { return { apiVersion: "2019-06-10", @@ -24256,113 +24452,260 @@ exports.getRuntimeConfig = getRuntimeConfig; /***/ }), -/***/ 8078: +/***/ 4195: /***/ ((__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__(912), exports); -tslib_1.__exportStar(__nccwpck_require__(5948), exports); -tslib_1.__exportStar(__nccwpck_require__(8008), exports); +exports.STSClient = exports.__Client = void 0; +const middleware_host_header_1 = __nccwpck_require__(9514); +const middleware_logger_1 = __nccwpck_require__(5675); +const middleware_recursion_detection_1 = __nccwpck_require__(7977); +const middleware_user_agent_1 = __nccwpck_require__(6634); +const config_resolver_1 = __nccwpck_require__(3098); +const core_1 = __nccwpck_require__(5829); +const middleware_content_length_1 = __nccwpck_require__(2800); +const middleware_endpoint_1 = __nccwpck_require__(2918); +const middleware_retry_1 = __nccwpck_require__(6039); +const smithy_client_1 = __nccwpck_require__(3570); +Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); +const httpAuthSchemeProvider_1 = __nccwpck_require__(7145); +const EndpointParameters_1 = __nccwpck_require__(510); +const runtimeConfig_1 = __nccwpck_require__(3405); +const runtimeExtensions_1 = __nccwpck_require__(2053); +class STSClient extends smithy_client_1.Client { + config; + constructor(...[configuration]) { + const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); + const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); + const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); + const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); + const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); + const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); + 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, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); + } + destroy() { + super.destroy(); + } +} +exports.STSClient = STSClient; /***/ }), -/***/ 912: -/***/ ((module) => { +/***/ 8527: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; -// src/submodules/client/index.ts -var index_exports = {}; -__export(index_exports, { - emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, - setCredentialFeature: () => setCredentialFeature, - setFeature: () => setFeature, - setTokenFeature: () => setTokenFeature, - state: () => state -}); -module.exports = __toCommonJS(index_exports); -// src/submodules/client/emitWarningIfUnsupportedVersion.ts -var state = { - warningEmitted: false -}; -var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { - if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { - state.warningEmitted = true; - process.emitWarning( - `NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will -no longer support Node.js 16.x on January 6, 2025. +/***/ }), -To continue receiving updates to AWS services, bug fixes, and security -updates please upgrade to a supported Node.js LTS version. +/***/ 7145: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -More information can be found at: https://a.co/74kJMmI` - ); - } -}, "emitWarningIfUnsupportedVersion"); +"use strict"; -// src/submodules/client/setCredentialFeature.ts -function setCredentialFeature(credentials, feature, value) { - if (!credentials.$source) { - credentials.$source = {}; - } - credentials.$source[feature] = value; - return credentials; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; +const core_1 = __nccwpck_require__(2143); +const util_middleware_1 = __nccwpck_require__(2390); +const STSClient_1 = __nccwpck_require__(4195); +const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sts", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; } -__name(setCredentialFeature, "setCredentialFeature"); - -// src/submodules/client/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__aws_sdk_context) { - context.__aws_sdk_context = { - features: {} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", }; - } else if (!context.__aws_sdk_context.features) { - context.__aws_sdk_context.features = {}; - } - context.__aws_sdk_context.features[feature] = value; } -__name(setFeature, "setFeature"); +const defaultSTSHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "AssumeRoleWithSAML": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "AssumeRoleWithWebIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; +const resolveStsAuthConfig = (input) => Object.assign(input, { + stsClientCtor: STSClient_1.STSClient, +}); +exports.resolveStsAuthConfig = resolveStsAuthConfig; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, exports.resolveStsAuthConfig)(config); + const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); + return Object.assign(config_1, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; -// src/submodules/client/setTokenFeature.ts -function setTokenFeature(token, feature, value) { - if (!token.$source) { - token.$source = {}; - } - token.$source[feature] = value; - return token; -} -__name(setTokenFeature, "setTokenFeature"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); + +/***/ }), + +/***/ 510: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.commonParams = exports.resolveClientEndpointParameters = void 0; +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + useGlobalEndpoint: options.useGlobalEndpoint ?? false, + defaultSigningName: "sts", + }); +}; +exports.resolveClientEndpointParameters = resolveClientEndpointParameters; +exports.commonParams = { + 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" }, +}; + + +/***/ }), + +/***/ 1203: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = __nccwpck_require__(4241); +const util_endpoints_2 = __nccwpck_require__(5473); +const ruleset_1 = __nccwpck_require__(6882); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; + + +/***/ }), + +/***/ 6882: +/***/ ((__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; /***/ }), -/***/ 5948: +/***/ 2209: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -24384,2116 +24727,1769 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/httpAuthSchemes/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - AWSSDKSigV4Signer: () => AWSSDKSigV4Signer, - AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner, - AwsSdkSigV4Signer: () => AwsSdkSigV4Signer, - NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, - NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS, - getBearerTokenEnvKey: () => getBearerTokenEnvKey, - resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config, - resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig, - resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config, - validateSigningProperties: () => validateSigningProperties + AssumeRoleCommand: () => AssumeRoleCommand, + AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog, + AssumeRoleWithSAMLCommand: () => AssumeRoleWithSAMLCommand, + AssumeRoleWithSAMLRequestFilterSensitiveLog: () => AssumeRoleWithSAMLRequestFilterSensitiveLog, + AssumeRoleWithSAMLResponseFilterSensitiveLog: () => AssumeRoleWithSAMLResponseFilterSensitiveLog, + AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand, + AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog, + AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog, + AssumeRootCommand: () => AssumeRootCommand, + AssumeRootResponseFilterSensitiveLog: () => AssumeRootResponseFilterSensitiveLog, + ClientInputEndpointParameters: () => import_EndpointParameters10.ClientInputEndpointParameters, + CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog, + DecodeAuthorizationMessageCommand: () => DecodeAuthorizationMessageCommand, + ExpiredTokenException: () => ExpiredTokenException, + GetAccessKeyInfoCommand: () => GetAccessKeyInfoCommand, + GetCallerIdentityCommand: () => GetCallerIdentityCommand, + GetFederationTokenCommand: () => GetFederationTokenCommand, + GetFederationTokenResponseFilterSensitiveLog: () => GetFederationTokenResponseFilterSensitiveLog, + GetSessionTokenCommand: () => GetSessionTokenCommand, + GetSessionTokenResponseFilterSensitiveLog: () => GetSessionTokenResponseFilterSensitiveLog, + IDPCommunicationErrorException: () => IDPCommunicationErrorException, + IDPRejectedClaimException: () => IDPRejectedClaimException, + InvalidAuthorizationMessageException: () => InvalidAuthorizationMessageException, + InvalidIdentityTokenException: () => InvalidIdentityTokenException, + MalformedPolicyDocumentException: () => MalformedPolicyDocumentException, + PackedPolicyTooLargeException: () => PackedPolicyTooLargeException, + RegionDisabledException: () => RegionDisabledException, + STS: () => STS, + STSServiceException: () => STSServiceException, + decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, + getDefaultRoleAssumer: () => getDefaultRoleAssumer2, + getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 }); module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(4195), module.exports); -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts -var import_protocol_http2 = __nccwpck_require__(4418); +// src/STS.ts -// src/submodules/httpAuthSchemes/utils/getDateHeader.ts -var import_protocol_http = __nccwpck_require__(4418); -var getDateHeader = /* @__PURE__ */ __name((response) => import_protocol_http.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0, "getDateHeader"); -// src/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.ts -var getSkewCorrectedDate = /* @__PURE__ */ __name((systemClockOffset) => new Date(Date.now() + systemClockOffset), "getSkewCorrectedDate"); +// src/commands/AssumeRoleCommand.ts +var import_middleware_endpoint = __nccwpck_require__(2918); +var import_middleware_serde = __nccwpck_require__(1238); -// src/submodules/httpAuthSchemes/utils/isClockSkewed.ts -var isClockSkewed = /* @__PURE__ */ __name((clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5, "isClockSkewed"); +var import_EndpointParameters = __nccwpck_require__(510); -// src/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.ts -var getUpdatedSystemClockOffset = /* @__PURE__ */ __name((clockTime, currentSystemClockOffset) => { - const clockTimeInMs = Date.parse(clockTime); - if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { - return clockTimeInMs - Date.now(); - } - return currentSystemClockOffset; -}, "getUpdatedSystemClockOffset"); +// src/models/models_0.ts -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts -var throwSigningPropertyError = /* @__PURE__ */ __name((name, property) => { - if (!property) { - throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); + +// src/models/STSServiceException.ts +var import_smithy_client = __nccwpck_require__(3570); +var STSServiceException = class _STSServiceException extends import_smithy_client.ServiceException { + static { + __name(this, "STSServiceException"); } - return property; -}, "throwSigningPropertyError"); -var validateSigningProperties = /* @__PURE__ */ __name(async (signingProperties) => { - const context = throwSigningPropertyError( - "context", - signingProperties.context - ); - const config = throwSigningPropertyError("config", signingProperties.config); - const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; - const signerFunction = throwSigningPropertyError( - "signer", - config.signer - ); - const signer = await signerFunction(authScheme); - const signingRegion = signingProperties?.signingRegion; - const signingRegionSet = signingProperties?.signingRegionSet; - const signingName = signingProperties?.signingName; - return { - config, - signer, - signingRegion, - signingRegionSet, - signingName - }; -}, "validateSigningProperties"); -var AwsSdkSigV4Signer = class { + /** + * @internal + */ + constructor(options) { + super(options); + Object.setPrototypeOf(this, _STSServiceException.prototype); + } +}; + +// src/models/models_0.ts +var ExpiredTokenException = class _ExpiredTokenException extends STSServiceException { static { - __name(this, "AwsSdkSigV4Signer"); + __name(this, "ExpiredTokenException"); } - async sign(httpRequest, identity, signingProperties) { - if (!import_protocol_http2.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const validatedProps = await validateSigningProperties(signingProperties); - const { config, signer } = validatedProps; - let { signingRegion, signingName } = validatedProps; - const handlerExecutionContext = signingProperties.context; - if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { - const [first, second] = handlerExecutionContext.authSchemes; - if (first?.name === "sigv4a" && second?.name === "sigv4") { - signingRegion = second?.signingRegion ?? signingRegion; - signingName = second?.signingName ?? signingName; - } - } - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion, - signingService: signingName + name = "ExpiredTokenException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts }); - return signedRequest; + Object.setPrototypeOf(this, _ExpiredTokenException.prototype); } - errorHandler(signingProperties) { - return (error) => { - const serverTime = error.ServerTime ?? getDateHeader(error.$response); - if (serverTime) { - const config = throwSigningPropertyError("config", signingProperties.config); - const initialSystemClockOffset = config.systemClockOffset; - config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); - const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; - if (clockSkewCorrected && error.$metadata) { - error.$metadata.clockSkewCorrected = true; - } - } - throw error; - }; +}; +var MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { + static { + __name(this, "MalformedPolicyDocumentException"); } - successHandler(httpResponse, signingProperties) { - const dateHeader = getDateHeader(httpResponse); - if (dateHeader) { - const config = throwSigningPropertyError("config", signingProperties.config); - config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); - } + name = "MalformedPolicyDocumentException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "MalformedPolicyDocumentException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); } }; -var AWSSDKSigV4Signer = AwsSdkSigV4Signer; - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.ts -var import_protocol_http3 = __nccwpck_require__(4418); -var AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer { +var PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { static { - __name(this, "AwsSdkSigV4ASigner"); + __name(this, "PackedPolicyTooLargeException"); } - async sign(httpRequest, identity, signingProperties) { - if (!import_protocol_http3.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties( - signingProperties - ); - const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); - const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(","); - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion: multiRegionOverride, - signingService: signingName + name = "PackedPolicyTooLargeException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "PackedPolicyTooLargeException", + $fault: "client", + ...opts }); - return signedRequest; + Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); } }; - -// src/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.ts -var getArrayForCommaSeparatedString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [], "getArrayForCommaSeparatedString"); - -// src/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.ts -var getBearerTokenEnvKey = /* @__PURE__ */ __name((signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`, "getBearerTokenEnvKey"); - -// src/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.ts -var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; -var NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; -var NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { +var RegionDisabledException = class _RegionDisabledException extends STSServiceException { + static { + __name(this, "RegionDisabledException"); + } + name = "RegionDisabledException"; + $fault = "client"; /** - * Retrieves auth scheme preference from environment variables - * @param env - Node process environment object - * @returns Array of auth scheme strings if preference is set, undefined otherwise + * @internal */ - environmentVariableSelector: /* @__PURE__ */ __name((env, options) => { - if (options?.signingName) { - const bearerTokenKey = getBearerTokenEnvKey(options.signingName); - if (bearerTokenKey in env) return ["httpBearerAuth"]; - } - if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) return void 0; - return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); - }, "environmentVariableSelector"), + constructor(opts) { + super({ + name: "RegionDisabledException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _RegionDisabledException.prototype); + } +}; +var IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { + static { + __name(this, "IDPRejectedClaimException"); + } + name = "IDPRejectedClaimException"; + $fault = "client"; /** - * Retrieves auth scheme preference from config file - * @param profile - Config profile object - * @returns Array of auth scheme strings if preference is set, undefined otherwise + * @internal */ - configFileSelector: /* @__PURE__ */ __name((profile) => { - if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) return void 0; - return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); - }, "configFileSelector"), + constructor(opts) { + super({ + name: "IDPRejectedClaimException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); + } +}; +var InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { + static { + __name(this, "InvalidIdentityTokenException"); + } + name = "InvalidIdentityTokenException"; + $fault = "client"; /** - * Default auth scheme preference if not specified in environment or config + * @internal */ - default: [] + constructor(opts) { + super({ + name: "InvalidIdentityTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); + } }; - -// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.ts -var import_core = __nccwpck_require__(5829); -var import_property_provider = __nccwpck_require__(9721); -var resolveAwsSdkSigV4AConfig = /* @__PURE__ */ __name((config) => { - config.sigv4aSigningRegionSet = (0, import_core.normalizeProvider)(config.sigv4aSigningRegionSet); - return config; -}, "resolveAwsSdkSigV4AConfig"); -var NODE_SIGV4A_CONFIG_OPTIONS = { - environmentVariableSelector(env) { - if (env.AWS_SIGV4A_SIGNING_REGION_SET) { - return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); - } - throw new import_property_provider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { - tryNextLink: true +var IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { + static { + __name(this, "IDPCommunicationErrorException"); + } + name = "IDPCommunicationErrorException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "IDPCommunicationErrorException", + $fault: "client", + ...opts }); - }, - configFileSelector(profile) { - if (profile.sigv4a_signing_region_set) { - return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); - } - throw new import_property_provider.ProviderError("sigv4a_signing_region_set not set in profile.", { - tryNextLink: true + Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); + } +}; +var InvalidAuthorizationMessageException = class _InvalidAuthorizationMessageException extends STSServiceException { + static { + __name(this, "InvalidAuthorizationMessageException"); + } + name = "InvalidAuthorizationMessageException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidAuthorizationMessageException", + $fault: "client", + ...opts }); - }, - default: void 0 + Object.setPrototypeOf(this, _InvalidAuthorizationMessageException.prototype); + } }; +var CredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client.SENSITIVE_STRING } +}), "CredentialsFilterSensitiveLog"); +var AssumeRoleResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } +}), "AssumeRoleResponseFilterSensitiveLog"); +var AssumeRoleWithSAMLRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.SAMLAssertion && { SAMLAssertion: import_smithy_client.SENSITIVE_STRING } +}), "AssumeRoleWithSAMLRequestFilterSensitiveLog"); +var AssumeRoleWithSAMLResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } +}), "AssumeRoleWithSAMLResponseFilterSensitiveLog"); +var AssumeRoleWithWebIdentityRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client.SENSITIVE_STRING } +}), "AssumeRoleWithWebIdentityRequestFilterSensitiveLog"); +var AssumeRoleWithWebIdentityResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } +}), "AssumeRoleWithWebIdentityResponseFilterSensitiveLog"); +var AssumeRootResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } +}), "AssumeRootResponseFilterSensitiveLog"); +var GetFederationTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } +}), "GetFederationTokenResponseFilterSensitiveLog"); +var GetSessionTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } +}), "GetSessionTokenResponseFilterSensitiveLog"); -// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.ts -var import_client = __nccwpck_require__(912); -var import_core2 = __nccwpck_require__(5829); -var import_signature_v4 = __nccwpck_require__(1528); -var resolveAwsSdkSigV4Config = /* @__PURE__ */ __name((config) => { - let inputCredentials = config.credentials; - let isUserSupplied = !!config.credentials; - let resolvedCredentials = void 0; - Object.defineProperty(config, "credentials", { - set(credentials) { - if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { - isUserSupplied = true; - } - inputCredentials = credentials; - const memoizedProvider = normalizeCredentialProvider(config, { - credentials: inputCredentials, - credentialDefaultProvider: config.credentialDefaultProvider - }); - const boundProvider = bindCallerConfig(config, memoizedProvider); - if (isUserSupplied && !boundProvider.attributed) { - resolvedCredentials = /* @__PURE__ */ __name(async (options) => boundProvider(options).then( - (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_CODE", "e") - ), "resolvedCredentials"); - resolvedCredentials.memoized = boundProvider.memoized; - resolvedCredentials.configBound = boundProvider.configBound; - resolvedCredentials.attributed = true; - } else { - resolvedCredentials = boundProvider; - } - }, - get() { - return resolvedCredentials; - }, - enumerable: true, - configurable: true +// src/protocols/Aws_query.ts +var import_core = __nccwpck_require__(2143); +var import_protocol_http = __nccwpck_require__(4418); + +var se_AssumeRoleCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_AssumeRoleRequest(input, context), + [_A]: _AR, + [_V]: _ }); - config.credentials = inputCredentials; - const { - // Default for signingEscapePath - signingEscapePath = true, - // Default for systemClockOffset - systemClockOffset = config.systemClockOffset || 0, - // No default for sha256 since it is platform dependent - sha256 - } = config; - let signer; - if (config.signer) { - signer = (0, import_core2.normalizeProvider)(config.signer); - } else if (config.regionInfoProvider) { - signer = /* @__PURE__ */ __name(() => (0, import_core2.normalizeProvider)(config.region)().then( - async (region) => [ - await config.regionInfoProvider(region, { - useFipsEndpoint: await config.useFipsEndpoint(), - useDualstackEndpoint: await config.useDualstackEndpoint() - }) || {}, - region - ] - ).then(([regionInfo, region]) => { - const { signingRegion, signingService } = regionInfo; - config.signingRegion = config.signingRegion || signingRegion || region; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }), "signer"); - } else { - signer = /* @__PURE__ */ __name(async (authScheme) => { - authScheme = Object.assign( - {}, - { - name: "sigv4", - signingName: config.signingName || config.defaultSigningName, - signingRegion: await (0, import_core2.normalizeProvider)(config.region)(), - properties: {} - }, - authScheme - ); - const signingRegion = authScheme.signingRegion; - const signingService = authScheme.signingName; - config.signingRegion = config.signingRegion || signingRegion; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }, "signer"); - } - const resolvedConfig = Object.assign(config, { - systemClockOffset, - signingEscapePath, - signer + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_AssumeRoleCommand"); +var se_AssumeRoleWithSAMLCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_AssumeRoleWithSAMLRequest(input, context), + [_A]: _ARWSAML, + [_V]: _ }); - return resolvedConfig; -}, "resolveAwsSdkSigV4Config"); -var resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; -function normalizeCredentialProvider(config, { - credentials, - credentialDefaultProvider -}) { - let credentialsProvider; - if (credentials) { - if (!credentials?.memoized) { - credentialsProvider = (0, import_core2.memoizeIdentityProvider)(credentials, import_core2.isIdentityExpired, import_core2.doesIdentityRequireRefresh); - } else { - credentialsProvider = credentials; - } - } else { - if (credentialDefaultProvider) { - credentialsProvider = (0, import_core2.normalizeProvider)( - credentialDefaultProvider( - Object.assign({}, config, { - parentClientConfig: config - }) - ) - ); - } else { - credentialsProvider = /* @__PURE__ */ __name(async () => { - throw new Error( - "@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured." - ); - }, "credentialsProvider"); - } + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_AssumeRoleWithSAMLCommand"); +var se_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_AssumeRoleWithWebIdentityRequest(input, context), + [_A]: _ARWWI, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_AssumeRoleWithWebIdentityCommand"); +var se_AssumeRootCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_AssumeRootRequest(input, context), + [_A]: _ARs, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_AssumeRootCommand"); +var se_DecodeAuthorizationMessageCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_DecodeAuthorizationMessageRequest(input, context), + [_A]: _DAM, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_DecodeAuthorizationMessageCommand"); +var se_GetAccessKeyInfoCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_GetAccessKeyInfoRequest(input, context), + [_A]: _GAKI, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_GetAccessKeyInfoCommand"); +var se_GetCallerIdentityCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_GetCallerIdentityRequest(input, context), + [_A]: _GCI, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_GetCallerIdentityCommand"); +var se_GetFederationTokenCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_GetFederationTokenRequest(input, context), + [_A]: _GFT, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_GetFederationTokenCommand"); +var se_GetSessionTokenCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_GetSessionTokenRequest(input, context), + [_A]: _GST, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_GetSessionTokenCommand"); +var de_AssumeRoleCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - credentialsProvider.memoized = true; - return credentialsProvider; -} -__name(normalizeCredentialProvider, "normalizeCredentialProvider"); -function bindCallerConfig(config, credentialsProvider) { - if (credentialsProvider.configBound) { - return credentialsProvider; + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_AssumeRoleResponse(data.AssumeRoleResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_AssumeRoleCommand"); +var de_AssumeRoleWithSAMLCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - const fn = /* @__PURE__ */ __name(async (options) => credentialsProvider({ ...options, callerClientConfig: config }), "fn"); - fn.memoized = credentialsProvider.memoized; - fn.configBound = true; - return fn; -} -__name(bindCallerConfig, "bindCallerConfig"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 8008: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_AssumeRoleWithSAMLResponse(data.AssumeRoleWithSAMLResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_AssumeRoleWithSAMLCommand"); +var de_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/protocols/index.ts -var index_exports = {}; -__export(index_exports, { - AwsEc2QueryProtocol: () => AwsEc2QueryProtocol, - AwsJson1_0Protocol: () => AwsJson1_0Protocol, - AwsJson1_1Protocol: () => AwsJson1_1Protocol, - AwsJsonRpcProtocol: () => AwsJsonRpcProtocol, - AwsQueryProtocol: () => AwsQueryProtocol, - AwsRestJsonProtocol: () => AwsRestJsonProtocol, - AwsRestXmlProtocol: () => AwsRestXmlProtocol, - JsonCodec: () => JsonCodec, - JsonShapeDeserializer: () => JsonShapeDeserializer, - JsonShapeSerializer: () => JsonShapeSerializer, - XmlCodec: () => XmlCodec, - XmlShapeDeserializer: () => XmlShapeDeserializer, - XmlShapeSerializer: () => XmlShapeSerializer, - _toBool: () => _toBool, - _toNum: () => _toNum, - _toStr: () => _toStr, - awsExpectUnion: () => awsExpectUnion, - loadRestJsonErrorCode: () => loadRestJsonErrorCode, - loadRestXmlErrorCode: () => loadRestXmlErrorCode, - parseJsonBody: () => parseJsonBody, - parseJsonErrorBody: () => parseJsonErrorBody, - parseXmlBody: () => parseXmlBody, - parseXmlErrorBody: () => parseXmlErrorBody -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/protocols/coercing-serializers.ts -var _toStr = /* @__PURE__ */ __name((val) => { - if (val == null) { - return val; + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_AssumeRoleWithWebIdentityCommand"); +var de_AssumeRootCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - 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); + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_AssumeRootResponse(data.AssumeRootResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_AssumeRootCommand"); +var de_DecodeAuthorizationMessageCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - 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); + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_DecodeAuthorizationMessageResponse(data.DecodeAuthorizationMessageResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_DecodeAuthorizationMessageCommand"); +var de_GetAccessKeyInfoCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - return val; -}, "_toStr"); -var _toBool = /* @__PURE__ */ __name((val) => { - if (val == null) { - return val; + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_GetAccessKeyInfoResponse(data.GetAccessKeyInfoResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_GetAccessKeyInfoCommand"); +var de_GetCallerIdentityCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - if (typeof val === "number") { + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_GetCallerIdentityResponse(data.GetCallerIdentityResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_GetCallerIdentityCommand"); +var de_GetFederationTokenCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - 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"; + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_GetFederationTokenResponse(data.GetFederationTokenResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_GetFederationTokenCommand"); +var de_GetSessionTokenCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - return val; -}, "_toBool"); -var _toNum = /* @__PURE__ */ __name((val) => { - if (val == null) { - return val; + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_GetSessionTokenResponse(data.GetSessionTokenResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_GetSessionTokenCommand"); +var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { + const parsedOutput = { + ...output, + body: await (0, import_core.parseXmlErrorBody)(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); + 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 "IDPCommunicationError": + case "com.amazonaws.sts#IDPCommunicationErrorException": + throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context); + 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 + }); } - if (typeof val === "boolean") { +}, "de_CommandError"); +var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_ExpiredTokenException(body.Error, context); + const exception = new ExpiredTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client.decorateServiceException)(exception, body); +}, "de_ExpiredTokenExceptionRes"); +var de_IDPCommunicationErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_IDPCommunicationErrorException(body.Error, context); + const exception = new IDPCommunicationErrorException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client.decorateServiceException)(exception, body); +}, "de_IDPCommunicationErrorExceptionRes"); +var de_IDPRejectedClaimExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_IDPRejectedClaimException(body.Error, context); + const exception = new IDPRejectedClaimException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client.decorateServiceException)(exception, body); +}, "de_IDPRejectedClaimExceptionRes"); +var de_InvalidAuthorizationMessageExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_InvalidAuthorizationMessageException(body.Error, context); + const exception = new InvalidAuthorizationMessageException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client.decorateServiceException)(exception, body); +}, "de_InvalidAuthorizationMessageExceptionRes"); +var de_InvalidIdentityTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_InvalidIdentityTokenException(body.Error, context); + const exception = new InvalidIdentityTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client.decorateServiceException)(exception, body); +}, "de_InvalidIdentityTokenExceptionRes"); +var de_MalformedPolicyDocumentExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_MalformedPolicyDocumentException(body.Error, context); + const exception = new MalformedPolicyDocumentException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client.decorateServiceException)(exception, body); +}, "de_MalformedPolicyDocumentExceptionRes"); +var de_PackedPolicyTooLargeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_PackedPolicyTooLargeException(body.Error, context); + const exception = new PackedPolicyTooLargeException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client.decorateServiceException)(exception, body); +}, "de_PackedPolicyTooLargeExceptionRes"); +var de_RegionDisabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_RegionDisabledException(body.Error, context); + const exception = new RegionDisabledException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client.decorateServiceException)(exception, body); +}, "de_RegionDisabledExceptionRes"); +var se_AssumeRoleRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_RA] != null) { + entries[_RA] = input[_RA]; } - 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; + if (input[_RSN] != null) { + entries[_RSN] = input[_RSN]; + } + if (input[_PA] != null) { + const memberEntries = se_policyDescriptorListType(input[_PA], context); + if (input[_PA]?.length === 0) { + entries.PolicyArns = []; } - return num; + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `PolicyArns.${key}`; + entries[loc] = value; + }); } - return val; -}, "_toNum"); - -// src/submodules/protocols/json/AwsJsonRpcProtocol.ts -var import_protocols = __nccwpck_require__(2241); -var import_schema3 = __nccwpck_require__(9826); -var import_util_body_length_browser = __nccwpck_require__(713); - -// src/submodules/protocols/ConfigurableSerdeContext.ts -var SerdeContextConfig = class { - static { - __name(this, "SerdeContextConfig"); + if (input[_P] != null) { + entries[_P] = input[_P]; } - serdeContext; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; + if (input[_DS] != null) { + entries[_DS] = input[_DS]; } -}; - -// src/submodules/protocols/json/JsonShapeDeserializer.ts -var import_schema = __nccwpck_require__(9826); -var import_serde2 = __nccwpck_require__(7669); -var import_util_base64 = __nccwpck_require__(5600); - -// src/submodules/protocols/json/jsonReviver.ts -var import_serde = __nccwpck_require__(7669); -function jsonReviver(key, value, context) { - if (context?.source) { - const numericString = context.source; - if (typeof value === "number") { - if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { - const isFractional = numericString.includes("."); - if (isFractional) { - return new import_serde.NumericValue(numericString, "bigDecimal"); - } else { - return BigInt(numericString); - } - } + if (input[_T] != null) { + const memberEntries = se_tagListType(input[_T], context); + if (input[_T]?.length === 0) { + entries.Tags = []; } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `Tags.${key}`; + entries[loc] = value; + }); } - return value; -} -__name(jsonReviver, "jsonReviver"); - -// src/submodules/protocols/common.ts -var import_smithy_client = __nccwpck_require__(3570); -var collectBodyString = /* @__PURE__ */ __name((streamBody, context) => (0, import_smithy_client.collectBody)(streamBody, context).then((body) => context.utf8Encoder(body)), "collectBodyString"); - -// src/submodules/protocols/json/parseJsonBody.ts -var parseJsonBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - try { - return JSON.parse(encoded); - } catch (e) { - if (e?.name === "SyntaxError") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded - }); - } - throw e; + if (input[_TTK] != null) { + const memberEntries = se_tagKeyListType(input[_TTK], context); + if (input[_TTK]?.length === 0) { + entries.TransitiveTagKeys = []; } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `TransitiveTagKeys.${key}`; + entries[loc] = value; + }); } - return {}; -}), "parseJsonBody"); -var parseJsonErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { - const value = await parseJsonBody(errorBody, context); - value.message = value.message ?? value.Message; - return value; -}, "parseJsonErrorBody"); -var loadRestJsonErrorCode = /* @__PURE__ */ __name((output, data) => { - const findKey = /* @__PURE__ */ __name((object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()), "findKey"); - const sanitizeErrorCode = /* @__PURE__ */ __name((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; - }, "sanitizeErrorCode"); - const headerKey = findKey(output.headers, "x-amzn-errortype"); - if (headerKey !== void 0) { - return sanitizeErrorCode(output.headers[headerKey]); + if (input[_EI] != null) { + entries[_EI] = input[_EI]; } - if (data && typeof data === "object") { - const codeKey = findKey(data, "code"); - if (codeKey && data[codeKey] !== void 0) { - return sanitizeErrorCode(data[codeKey]); - } - if (data["__type"] !== void 0) { - return sanitizeErrorCode(data["__type"]); - } + if (input[_SN] != null) { + entries[_SN] = input[_SN]; } -}, "loadRestJsonErrorCode"); - -// src/submodules/protocols/json/JsonShapeDeserializer.ts -var JsonShapeDeserializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; + if (input[_TC] != null) { + entries[_TC] = input[_TC]; } - static { - __name(this, "JsonShapeDeserializer"); + if (input[_SI] != null) { + entries[_SI] = input[_SI]; } - async read(schema, data) { - return this._read( - schema, - typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext) - ); + if (input[_PC] != null) { + const memberEntries = se_ProvidedContextsListType(input[_PC], context); + if (input[_PC]?.length === 0) { + entries.ProvidedContexts = []; + } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `ProvidedContexts.${key}`; + entries[loc] = value; + }); } - readObject(schema, data) { - return this._read(schema, data); + return entries; +}, "se_AssumeRoleRequest"); +var se_AssumeRoleWithSAMLRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_RA] != null) { + entries[_RA] = input[_RA]; } - _read(schema, value) { - const isObject = value !== null && typeof value === "object"; - const ns = import_schema.NormalizedSchema.of(schema); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._read(listMember, item)); - } - } - return out; - } else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._read(mapMember, _v); - } - } - return out; - } else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const deserializedValue = this._read(memberSchema, value[fromKey]); - if (deserializedValue != null) { - out[memberName] = deserializedValue; - } - } - return out; - } - if (ns.isBlobSchema() && typeof value === "string") { - return (0, import_util_base64.fromBase64)(value); - } - const mediaType = ns.getMergedTraits().mediaType; - if (ns.isStringSchema() && typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return import_serde2.LazyJsonString.from(value); - } - } - if (ns.isTimestampSchema()) { - const options = this.settings.timestampFormat; - const format = options.useTrait ? ns.getSchema() === import_schema.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; - switch (format) { - case import_schema.SCHEMA.TIMESTAMP_DATE_TIME: - return (0, import_serde2.parseRfc3339DateTimeWithOffset)(value); - case import_schema.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde2.parseRfc7231DateTime)(value); - case import_schema.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return (0, import_serde2.parseEpochTimestamp)(value); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", value); - return new Date(value); - } - } - if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { - return BigInt(value); - } - if (ns.isBigDecimalSchema() && value != void 0) { - if (value instanceof import_serde2.NumericValue) { - return value; - } - return new import_serde2.NumericValue(String(value), "bigDecimal"); - } - if (ns.isNumericSchema() && typeof value === "string") { - switch (value) { - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - case "NaN": - return NaN; - } - } - return value; + if (input[_PAr] != null) { + entries[_PAr] = input[_PAr]; } -}; - -// src/submodules/protocols/json/JsonShapeSerializer.ts -var import_schema2 = __nccwpck_require__(9826); -var import_serde4 = __nccwpck_require__(7669); - -// src/submodules/protocols/json/jsonReplacer.ts -var import_serde3 = __nccwpck_require__(7669); -var NUMERIC_CONTROL_CHAR = String.fromCharCode(925); -var JsonReplacer = class { - static { - __name(this, "JsonReplacer"); + if (input[_SAMLA] != null) { + entries[_SAMLA] = input[_SAMLA]; } - /** - * Stores placeholder key to true serialized value lookup. - */ - values = /* @__PURE__ */ new Map(); - counter = 0; - stage = 0; - /** - * Creates a jsonReplacer function that reserves big integer and big decimal values - * for later replacement. - */ - createReplacer() { - if (this.stage === 1) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + if (input[_PA] != null) { + const memberEntries = se_policyDescriptorListType(input[_PA], context); + if (input[_PA]?.length === 0) { + entries.PolicyArns = []; } - this.stage = 1; - return (key, value) => { - if (value instanceof import_serde3.NumericValue) { - const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; - this.values.set(`"${v}"`, value.string); - return v; - } - if (typeof value === "bigint") { - const s = value.toString(); - const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; - this.values.set(`"${v}"`, s); - return v; - } - return value; - }; + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `PolicyArns.${key}`; + entries[loc] = value; + }); } - /** - * Replaces placeholder keys with their true values. - */ - replaceInJson(json) { - if (this.stage === 0) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 2; - if (this.counter === 0) { - return json; - } - for (const [key, value] of this.values) { - json = json.replace(key, value); - } - return json; + if (input[_P] != null) { + entries[_P] = input[_P]; } -}; - -// src/submodules/protocols/json/JsonShapeSerializer.ts -var JsonShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; + if (input[_DS] != null) { + entries[_DS] = input[_DS]; } - static { - __name(this, "JsonShapeSerializer"); + return entries; +}, "se_AssumeRoleWithSAMLRequest"); +var se_AssumeRoleWithWebIdentityRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_RA] != null) { + entries[_RA] = input[_RA]; } - buffer; - rootSchema; - write(schema, value) { - this.rootSchema = import_schema2.NormalizedSchema.of(schema); - this.buffer = this._write(this.rootSchema, value); + if (input[_RSN] != null) { + entries[_RSN] = input[_RSN]; } - flush() { - if (this.rootSchema?.isStructSchema() || this.rootSchema?.isDocumentSchema()) { - const replacer = new JsonReplacer(); - return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); - } - return this.buffer; + if (input[_WIT] != null) { + entries[_WIT] = input[_WIT]; } - _write(schema, value, container) { - const isObject = value !== null && typeof value === "object"; - const ns = import_schema2.NormalizedSchema.of(schema); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._write(listMember, item)); - } - } - return out; - } else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._write(mapMember, _v); - } - } - return out; - } else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const serializableValue = this._write(memberSchema, value[memberName], ns); - if (serializableValue !== void 0) { - out[targetKey] = serializableValue; - } - } - return out; - } - if (value === null && container?.isStructSchema()) { - return void 0; - } - if (ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string")) { - if (ns === this.rootSchema) { - return value; - } - if (!this.serdeContext?.base64Encoder) { - throw new Error("Missing base64Encoder in serdeContext"); - } - return this.serdeContext?.base64Encoder(value); - } - if (ns.isTimestampSchema() && value instanceof Date) { - const options = this.settings.timestampFormat; - const format = options.useTrait ? ns.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; - switch (format) { - case import_schema2.SCHEMA.TIMESTAMP_DATE_TIME: - return value.toISOString().replace(".000Z", "Z"); - case import_schema2.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde4.dateToUtcString)(value); - case import_schema2.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return value.getTime() / 1e3; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - return value.getTime() / 1e3; - } - } - if (ns.isNumericSchema() && typeof value === "number") { - if (Math.abs(value) === Infinity || isNaN(value)) { - return String(value); - } - } - if (ns.isStringSchema()) { - if (typeof value === "undefined" && ns.isIdempotencyToken()) { - return (0, import_serde4.generateIdempotencyToken)(); - } - const mediaType = ns.getMergedTraits().mediaType; - if (typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return import_serde4.LazyJsonString.from(value); - } - } + if (input[_PI] != null) { + entries[_PI] = input[_PI]; + } + if (input[_PA] != null) { + const memberEntries = se_policyDescriptorListType(input[_PA], context); + if (input[_PA]?.length === 0) { + entries.PolicyArns = []; } - return value; + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `PolicyArns.${key}`; + entries[loc] = value; + }); } -}; - -// src/submodules/protocols/json/JsonCodec.ts -var JsonCodec = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; + if (input[_P] != null) { + entries[_P] = input[_P]; } - static { - __name(this, "JsonCodec"); + if (input[_DS] != null) { + entries[_DS] = input[_DS]; } - createSerializer() { - const serializer = new JsonShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; + return entries; +}, "se_AssumeRoleWithWebIdentityRequest"); +var se_AssumeRootRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_TP] != null) { + entries[_TP] = input[_TP]; } - createDeserializer() { - const deserializer = new JsonShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; + if (input[_TPA] != null) { + const memberEntries = se_PolicyDescriptorType(input[_TPA], context); + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `TaskPolicyArn.${key}`; + entries[loc] = value; + }); } -}; - -// src/submodules/protocols/json/AwsJsonRpcProtocol.ts -var AwsJsonRpcProtocol = class extends import_protocols.RpcProtocol { - static { - __name(this, "AwsJsonRpcProtocol"); + if (input[_DS] != null) { + entries[_DS] = input[_DS]; } - serializer; - deserializer; - serviceTarget; - codec; - constructor({ defaultNamespace, serviceTarget }) { - super({ - defaultNamespace - }); - this.serviceTarget = serviceTarget; - this.codec = new JsonCodec({ - timestampFormat: { - useTrait: true, - default: import_schema3.SCHEMA.TIMESTAMP_EPOCH_SECONDS - }, - jsonName: false - }); - this.serializer = this.codec.createSerializer(); - this.deserializer = this.codec.createDeserializer(); + return entries; +}, "se_AssumeRootRequest"); +var se_DecodeAuthorizationMessageRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_EM] != null) { + entries[_EM] = input[_EM]; } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; + return entries; +}, "se_DecodeAuthorizationMessageRequest"); +var se_GetAccessKeyInfoRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_AKI] != null) { + entries[_AKI] = input[_AKI]; + } + return entries; +}, "se_GetAccessKeyInfoRequest"); +var se_GetCallerIdentityRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + return entries; +}, "se_GetCallerIdentityRequest"); +var se_GetFederationTokenRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_N] != null) { + entries[_N] = input[_N]; + } + if (input[_P] != null) { + entries[_P] = input[_P]; + } + if (input[_PA] != null) { + const memberEntries = se_policyDescriptorListType(input[_PA], context); + if (input[_PA]?.length === 0) { + entries.PolicyArns = []; } - Object.assign(request.headers, { - "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, - "x-amz-target": `${this.serviceTarget}.${import_schema3.NormalizedSchema.of(operationSchema).getName()}` + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `PolicyArns.${key}`; + entries[loc] = value; }); - if ((0, import_schema3.deref)(operationSchema.input) === "unit" || !request.body) { - request.body = "{}"; - } - try { - request.headers["content-length"] = String((0, import_util_body_length_browser.calculateBodyLength)(request.body)); - } catch (e) { + } + if (input[_DS] != null) { + entries[_DS] = input[_DS]; + } + if (input[_T] != null) { + const memberEntries = se_tagListType(input[_T], context); + if (input[_T]?.length === 0) { + entries.Tags = []; } - return request; + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `Tags.${key}`; + entries[loc] = value; + }); } - getPayloadCodec() { - return this.codec; + return entries; +}, "se_GetFederationTokenRequest"); +var se_GetSessionTokenRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_DS] != null) { + entries[_DS] = input[_DS]; } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); + if (input[_SN] != null) { + entries[_SN] = input[_SN]; + } + if (input[_TC] != null) { + entries[_TC] = input[_TC]; + } + return entries; +}, "se_GetSessionTokenRequest"); +var se_policyDescriptorListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; } - const registry = import_schema3.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorIdentifier); - } catch (e) { - const baseExceptionSchema = import_schema3.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), dataObject); - } - throw new Error(errorName); - } - const ns = import_schema3.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); + const memberEntries = se_PolicyDescriptorType(entry, context); + Object.entries(memberEntries).forEach(([key, value]) => { + entries[`member.${counter}.${key}`] = value; + }); + counter++; + } + return entries; +}, "se_policyDescriptorListType"); +var se_PolicyDescriptorType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_a] != null) { + entries[_a] = input[_a]; + } + return entries; +}, "se_PolicyDescriptorType"); +var se_ProvidedContext = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_PAro] != null) { + entries[_PAro] = input[_PAro]; + } + if (input[_CA] != null) { + entries[_CA] = input[_CA]; + } + return entries; +}, "se_ProvidedContext"); +var se_ProvidedContextsListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output + const memberEntries = se_ProvidedContext(entry, context); + Object.entries(memberEntries).forEach(([key, value]) => { + entries[`member.${counter}.${key}`] = value; }); - throw exception; + counter++; } -}; - -// src/submodules/protocols/json/AwsJson1_0Protocol.ts -var AwsJson1_0Protocol = class extends AwsJsonRpcProtocol { - static { - __name(this, "AwsJson1_0Protocol"); + return entries; +}, "se_ProvidedContextsListType"); +var se_Tag = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_K] != null) { + entries[_K] = input[_K]; } - constructor({ defaultNamespace, serviceTarget }) { - super({ - defaultNamespace, - serviceTarget + if (input[_Va] != null) { + entries[_Va] = input[_Va]; + } + return entries; +}, "se_Tag"); +var se_tagKeyListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; + } + entries[`member.${counter}`] = entry; + counter++; + } + return entries; +}, "se_tagKeyListType"); +var se_tagListType = /* @__PURE__ */ __name((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++; } - getShapeId() { - return "aws.protocols#awsJson1_0"; + return entries; +}, "se_tagListType"); +var de_AssumedRoleUser = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_ARI] != null) { + contents[_ARI] = (0, import_smithy_client.expectString)(output[_ARI]); } - getJsonRpcVersion() { - return "1.0"; + if (output[_Ar] != null) { + contents[_Ar] = (0, import_smithy_client.expectString)(output[_Ar]); } - /** - * @override - */ - getDefaultContentType() { - return "application/x-amz-json-1.0"; + return contents; +}, "de_AssumedRoleUser"); +var de_AssumeRoleResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C], context); } -}; - -// src/submodules/protocols/json/AwsJson1_1Protocol.ts -var AwsJson1_1Protocol = class extends AwsJsonRpcProtocol { - static { - __name(this, "AwsJson1_1Protocol"); + if (output[_ARU] != null) { + contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); } - constructor({ defaultNamespace, serviceTarget }) { - super({ - defaultNamespace, - serviceTarget - }); + if (output[_PPS] != null) { + contents[_PPS] = (0, import_smithy_client.strictParseInt32)(output[_PPS]); } - getShapeId() { - return "aws.protocols#awsJson1_1"; + if (output[_SI] != null) { + contents[_SI] = (0, import_smithy_client.expectString)(output[_SI]); } - getJsonRpcVersion() { - return "1.1"; + return contents; +}, "de_AssumeRoleResponse"); +var de_AssumeRoleWithSAMLResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C], context); } - /** - * @override - */ - getDefaultContentType() { - return "application/x-amz-json-1.1"; + if (output[_ARU] != null) { + contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); } -}; - -// src/submodules/protocols/json/AwsRestJsonProtocol.ts -var import_protocols2 = __nccwpck_require__(2241); -var import_schema4 = __nccwpck_require__(9826); -var import_util_body_length_browser2 = __nccwpck_require__(713); -var AwsRestJsonProtocol = class extends import_protocols2.HttpBindingProtocol { - static { - __name(this, "AwsRestJsonProtocol"); + if (output[_PPS] != null) { + contents[_PPS] = (0, import_smithy_client.strictParseInt32)(output[_PPS]); } - serializer; - deserializer; - codec; - constructor({ defaultNamespace }) { - super({ - defaultNamespace - }); - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS - }, - httpBindings: true, - jsonName: true - }; - this.codec = new JsonCodec(settings); - this.serializer = new import_protocols2.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new import_protocols2.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + if (output[_S] != null) { + contents[_S] = (0, import_smithy_client.expectString)(output[_S]); } - getShapeId() { - return "aws.protocols#restJson1"; + if (output[_ST] != null) { + contents[_ST] = (0, import_smithy_client.expectString)(output[_ST]); } - getPayloadCodec() { - return this.codec; + if (output[_I] != null) { + contents[_I] = (0, import_smithy_client.expectString)(output[_I]); } - setSerdeContext(serdeContext) { - this.codec.setSerdeContext(serdeContext); - super.setSerdeContext(serdeContext); + if (output[_Au] != null) { + contents[_Au] = (0, import_smithy_client.expectString)(output[_Au]); } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = import_schema4.NormalizedSchema.of(operationSchema.input); - const members = inputSchema.getMemberSchemas(); - if (!request.headers["content-type"]) { - const httpPayloadMember = Object.values(members).find((m) => { - return !!m.getMergedTraits().httpPayload; - }); - if (httpPayloadMember) { - const mediaType = httpPayloadMember.getMergedTraits().mediaType; - if (mediaType) { - request.headers["content-type"] = mediaType; - } else if (httpPayloadMember.isStringSchema()) { - request.headers["content-type"] = "text/plain"; - } else if (httpPayloadMember.isBlobSchema()) { - request.headers["content-type"] = "application/octet-stream"; - } else { - request.headers["content-type"] = this.getDefaultContentType(); - } - } else if (!inputSchema.isUnitSchema()) { - const hasBody = Object.values(members).find((m) => { - const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); - return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && httpPrefixHeaders === void 0; - }); - if (hasBody) { - request.headers["content-type"] = this.getDefaultContentType(); - } - } - } - if (request.headers["content-type"] && !request.body) { - request.body = "{}"; - } - if (request.body) { - try { - request.headers["content-length"] = String((0, import_util_body_length_browser2.calculateBodyLength)(request.body)); - } catch (e) { - } - } - return request; + if (output[_NQ] != null) { + contents[_NQ] = (0, import_smithy_client.expectString)(output[_NQ]); } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const registry = import_schema4.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorIdentifier); - } catch (e) { - const baseExceptionSchema = import_schema4.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), dataObject); - } - throw new Error(errorName); - } - const ns = import_schema4.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output - }); - throw exception; + if (output[_SI] != null) { + contents[_SI] = (0, import_smithy_client.expectString)(output[_SI]); } - /** - * @override - */ - getDefaultContentType() { - return "application/json"; + return contents; +}, "de_AssumeRoleWithSAMLResponse"); +var de_AssumeRoleWithWebIdentityResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C], context); } -}; - -// src/submodules/protocols/json/awsExpectUnion.ts -var import_smithy_client2 = __nccwpck_require__(3570); -var awsExpectUnion = /* @__PURE__ */ __name((value) => { - if (value == null) { - return void 0; + if (output[_SFWIT] != null) { + contents[_SFWIT] = (0, import_smithy_client.expectString)(output[_SFWIT]); } - if (typeof value === "object" && "__type" in value) { - delete value.__type; + if (output[_ARU] != null) { + contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); } - return (0, import_smithy_client2.expectUnion)(value); -}, "awsExpectUnion"); - -// src/submodules/protocols/query/AwsQueryProtocol.ts -var import_protocols5 = __nccwpck_require__(2241); -var import_schema7 = __nccwpck_require__(9826); -var import_util_body_length_browser3 = __nccwpck_require__(713); - -// src/submodules/protocols/xml/XmlShapeDeserializer.ts -var import_protocols3 = __nccwpck_require__(2241); -var import_schema5 = __nccwpck_require__(9826); -var import_smithy_client3 = __nccwpck_require__(3570); -var import_util_utf8 = __nccwpck_require__(1895); -var import_fast_xml_parser = __nccwpck_require__(2689); -var XmlShapeDeserializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - this.stringDeserializer = new import_protocols3.FromStringShapeDeserializer(settings); + if (output[_PPS] != null) { + contents[_PPS] = (0, import_smithy_client.strictParseInt32)(output[_PPS]); } - static { - __name(this, "XmlShapeDeserializer"); + if (output[_Pr] != null) { + contents[_Pr] = (0, import_smithy_client.expectString)(output[_Pr]); } - stringDeserializer; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.stringDeserializer.setSerdeContext(serdeContext); + if (output[_Au] != null) { + contents[_Au] = (0, import_smithy_client.expectString)(output[_Au]); } - /** - * @param schema - describing the data. - * @param bytes - serialized data. - * @param key - used by AwsQuery to step one additional depth into the object before reading it. - */ - read(schema, bytes, key) { - const ns = import_schema5.NormalizedSchema.of(schema); - const memberSchemas = ns.getMemberSchemas(); - const isEventPayload = ns.isStructSchema() && ns.isMemberSchema() && !!Object.values(memberSchemas).find((memberNs) => { - return !!memberNs.getMemberTraits().eventPayload; - }); - if (isEventPayload) { - const output = {}; - const memberName = Object.keys(memberSchemas)[0]; - const eventMemberSchema = memberSchemas[memberName]; - if (eventMemberSchema.isBlobSchema()) { - output[memberName] = bytes; - } else { - output[memberName] = this.read(memberSchemas[memberName], bytes); - } - return output; - } - const xmlString = (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)(bytes); - const parsedObject = this.parseXml(xmlString); - return this.readSchema(schema, key ? parsedObject[key] : parsedObject); + if (output[_SI] != null) { + contents[_SI] = (0, import_smithy_client.expectString)(output[_SI]); } - readSchema(_schema, value) { - const ns = import_schema5.NormalizedSchema.of(_schema); - const traits = ns.getMergedTraits(); - if (ns.isListSchema() && !Array.isArray(value)) { - return this.readSchema(ns, [value]); - } - if (value == null) { - return value; - } - if (typeof value === "object") { - const sparse = !!traits.sparse; - const flat = !!traits.xmlFlattened; - if (ns.isListSchema()) { - const listValue = ns.getValueSchema(); - const buffer2 = []; - const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; - const source = flat ? value : (value[0] ?? value)[sourceKey]; - const sourceArray = Array.isArray(source) ? source : [source]; - for (const v of sourceArray) { - if (v != null || sparse) { - buffer2.push(this.readSchema(listValue, v)); - } - } - return buffer2; - } - const buffer = {}; - if (ns.isMapSchema()) { - const keyNs = ns.getKeySchema(); - const memberNs = ns.getValueSchema(); - let entries; - if (flat) { - entries = Array.isArray(value) ? value : [value]; - } else { - entries = Array.isArray(value.entry) ? value.entry : [value.entry]; - } - const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; - const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; - for (const entry of entries) { - const key = entry[keyProperty]; - const value2 = entry[valueProperty]; - if (value2 != null || sparse) { - buffer[key] = this.readSchema(memberNs, value2); - } - } - return buffer; - } - if (ns.isStructSchema()) { - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMergedTraits(); - const xmlObjectKey = !memberTraits.httpPayload ? memberSchema.getMemberTraits().xmlName ?? memberName : memberTraits.xmlName ?? memberSchema.getName(); - if (value[xmlObjectKey] != null) { - buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); - } - } - return buffer; - } - if (ns.isDocumentSchema()) { - return value; - } - throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); - } - if (ns.isListSchema()) { - return []; - } - if (ns.isMapSchema() || ns.isStructSchema()) { - return {}; - } - return this.stringDeserializer.read(ns, value); + return contents; +}, "de_AssumeRoleWithWebIdentityResponse"); +var de_AssumeRootResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C], context); } - parseXml(xml) { - if (xml.length) { - const parser = new import_fast_xml_parser.XMLParser({ - attributeNamePrefix: "", - htmlEntities: true, - ignoreAttributes: false, - ignoreDeclaration: true, - parseTagValue: false, - trimValues: false, - tagValueProcessor: /* @__PURE__ */ __name((_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, "tagValueProcessor") - }); - parser.addEntity("#xD", "\r"); - parser.addEntity("#10", "\n"); - let parsedObj; - try { - parsedObj = parser.parse(xml, true); - } catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: xml - }); - } - throw e; - } - 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, import_smithy_client3.getValueFromTextNode)(parsedObjToReturn); - } - return {}; + if (output[_SI] != null) { + contents[_SI] = (0, import_smithy_client.expectString)(output[_SI]); } -}; - -// src/submodules/protocols/query/QueryShapeSerializer.ts -var import_protocols4 = __nccwpck_require__(2241); -var import_schema6 = __nccwpck_require__(9826); -var import_serde5 = __nccwpck_require__(7669); -var import_smithy_client4 = __nccwpck_require__(3570); -var import_util_base642 = __nccwpck_require__(5600); -var QueryShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; + return contents; +}, "de_AssumeRootResponse"); +var de_Credentials = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_AKI] != null) { + contents[_AKI] = (0, import_smithy_client.expectString)(output[_AKI]); } - static { - __name(this, "QueryShapeSerializer"); + if (output[_SAK] != null) { + contents[_SAK] = (0, import_smithy_client.expectString)(output[_SAK]); } - buffer; - write(schema, value, prefix = "") { - if (this.buffer === void 0) { - this.buffer = ""; - } - const ns = import_schema6.NormalizedSchema.of(schema); - if (prefix && !prefix.endsWith(".")) { - prefix += "."; - } - if (ns.isBlobSchema()) { - if (typeof value === "string" || value instanceof Uint8Array) { - this.writeKey(prefix); - this.writeValue((this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value)); - } - } else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } else if (ns.isIdempotencyToken()) { - this.writeKey(prefix); - this.writeValue((0, import_serde5.generateIdempotencyToken)()); - } - } else if (ns.isBigIntegerSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } - } else if (ns.isBigDecimalSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(value instanceof import_serde5.NumericValue ? value.string : String(value)); - } - } else if (ns.isTimestampSchema()) { - if (value instanceof Date) { - this.writeKey(prefix); - const format = (0, import_protocols4.determineTimestampFormat)(ns, this.settings); - switch (format) { - case import_schema6.SCHEMA.TIMESTAMP_DATE_TIME: - this.writeValue(value.toISOString().replace(".000Z", "Z")); - break; - case import_schema6.SCHEMA.TIMESTAMP_HTTP_DATE: - this.writeValue((0, import_smithy_client4.dateToUtcString)(value)); - break; - case import_schema6.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - this.writeValue(String(value.getTime() / 1e3)); - break; - } - } - } else if (ns.isDocumentSchema()) { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unsupported document type ${ns.getName(true)}`); - } else if (ns.isListSchema()) { - if (Array.isArray(value)) { - if (value.length === 0) { - if (this.settings.serializeEmptyLists) { - this.writeKey(prefix); - this.writeValue(""); - } - } else { - const member = ns.getValueSchema(); - const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const item of value) { - if (item == null) { - continue; - } - const suffix = this.getKey("member", member.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; - this.write(member, item, key); - ++i; - } - } - } - } else if (ns.isMapSchema()) { - if (value && typeof value === "object") { - const keySchema = ns.getKeySchema(); - const memberSchema = ns.getValueSchema(); - const flat = ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const [k, v] of Object.entries(value)) { - if (v == null) { - continue; - } - const keySuffix = this.getKey("key", keySchema.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; - const valueSuffix = this.getKey("value", memberSchema.getMergedTraits().xmlName); - const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; - this.write(keySchema, k, key); - this.write(memberSchema, v, valueKey); - ++i; - } - } - } else if (ns.isStructSchema()) { - if (value && typeof value === "object") { - for (const [memberName, member] of ns.structIterator()) { - if (value[memberName] == null && !member.isIdempotencyToken()) { - continue; - } - const suffix = this.getKey(memberName, member.getMergedTraits().xmlName); - const key = `${prefix}${suffix}`; - this.write(member, value[memberName], key); - } - } - } else if (ns.isUnitSchema()) { - } else { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); - } + if (output[_STe] != null) { + contents[_STe] = (0, import_smithy_client.expectString)(output[_STe]); } - flush() { - if (this.buffer === void 0) { - throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); - } - const str = this.buffer; - delete this.buffer; - return str; + if (output[_E] != null) { + contents[_E] = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseRfc3339DateTimeWithOffset)(output[_E])); } - getKey(memberName, xmlName) { - const key = xmlName ?? memberName; - if (this.settings.capitalizeKeys) { - return key[0].toUpperCase() + key.slice(1); - } - return key; + return contents; +}, "de_Credentials"); +var de_DecodeAuthorizationMessageResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_DM] != null) { + contents[_DM] = (0, import_smithy_client.expectString)(output[_DM]); } - writeKey(key) { - if (key.endsWith(".")) { - key = key.slice(0, key.length - 1); - } - this.buffer += `&${(0, import_protocols4.extendedEncodeURIComponent)(key)}=`; + return contents; +}, "de_DecodeAuthorizationMessageResponse"); +var de_ExpiredTokenException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client.expectString)(output[_m]); } - writeValue(value) { - this.buffer += (0, import_protocols4.extendedEncodeURIComponent)(value); + return contents; +}, "de_ExpiredTokenException"); +var de_FederatedUser = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_FUI] != null) { + contents[_FUI] = (0, import_smithy_client.expectString)(output[_FUI]); } -}; - -// src/submodules/protocols/query/AwsQueryProtocol.ts -var AwsQueryProtocol = class extends import_protocols5.RpcProtocol { - constructor(options) { - super({ - defaultNamespace: options.defaultNamespace - }); - this.options = options; - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema7.SCHEMA.TIMESTAMP_DATE_TIME - }, - httpBindings: false, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace, - serializeEmptyLists: true - }; - this.serializer = new QueryShapeSerializer(settings); - this.deserializer = new XmlShapeDeserializer(settings); + if (output[_Ar] != null) { + contents[_Ar] = (0, import_smithy_client.expectString)(output[_Ar]); } - static { - __name(this, "AwsQueryProtocol"); + return contents; +}, "de_FederatedUser"); +var de_GetAccessKeyInfoResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_Ac] != null) { + contents[_Ac] = (0, import_smithy_client.expectString)(output[_Ac]); } - serializer; - deserializer; - getShapeId() { - return "aws.protocols#awsQuery"; + return contents; +}, "de_GetAccessKeyInfoResponse"); +var de_GetCallerIdentityResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_UI] != null) { + contents[_UI] = (0, import_smithy_client.expectString)(output[_UI]); } - setSerdeContext(serdeContext) { - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); + if (output[_Ac] != null) { + contents[_Ac] = (0, import_smithy_client.expectString)(output[_Ac]); } - getPayloadCodec() { - throw new Error("AWSQuery protocol has no payload codec."); + if (output[_Ar] != null) { + contents[_Ar] = (0, import_smithy_client.expectString)(output[_Ar]); } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-www-form-urlencoded` - }); - if ((0, import_schema7.deref)(operationSchema.input) === "unit" || !request.body) { - request.body = ""; - } - request.body = `Action=${operationSchema.name.split("#")[1]}&Version=${this.options.version}` + request.body; - if (request.body.endsWith("&")) { - request.body = request.body.slice(-1); - } - try { - request.headers["content-length"] = String((0, import_util_body_length_browser3.calculateBodyLength)(request.body)); - } catch (e) { - } - return request; + return contents; +}, "de_GetCallerIdentityResponse"); +var de_GetFederationTokenResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C], context); } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema7.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes2 = await (0, import_protocols5.collectBody)(response.body, context); - if (bytes2.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema7.SCHEMA.DOCUMENT, bytes2)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? operationSchema.name.split("#")[1] + "Result" : void 0; - const bytes = await (0, import_protocols5.collectBody)(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); - } - const output = { - $metadata: this.deserializeMetadata(response), - ...dataObject - }; - return output; + if (output[_FU] != null) { + contents[_FU] = de_FederatedUser(output[_FU], context); } - /** - * EC2 Query overrides this. - */ - useNestedResult() { - return true; + if (output[_PPS] != null) { + contents[_PPS] = (0, import_smithy_client.strictParseInt32)(output[_PPS]); } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const errorDataSource = this.loadQueryError(dataObject); - const registry = import_schema7.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.find( - (schema) => import_schema7.NormalizedSchema.of(schema).getMergedTraits().awsQueryError?.[0] === errorName - ); - if (!errorSchema) { - errorSchema = registry.getSchema(errorIdentifier); - } - } catch (e) { - const baseExceptionSchema = import_schema7.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), errorDataSource); - } - throw new Error(errorName); - } - const ns = import_schema7.NormalizedSchema.of(errorSchema); - const message = this.loadQueryErrorMessage(dataObject); - const exception = new errorSchema.ctor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = errorDataSource[target] ?? dataObject[target]; - output[name] = this.deserializer.readSchema(member, value); - } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output - }); - throw exception; + return contents; +}, "de_GetFederationTokenResponse"); +var de_GetSessionTokenResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C], context); } - /** - * The variations in the error and error message locations are attributed to - * divergence between AWS Query and EC2 Query behavior. - */ - loadQueryErrorCode(output, data) { - const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; - if (code !== void 0) { - return code; - } - if (output.statusCode == 404) { - return "NotFound"; - } + return contents; +}, "de_GetSessionTokenResponse"); +var de_IDPCommunicationErrorException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client.expectString)(output[_m]); } - loadQueryError(data) { - return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; + return contents; +}, "de_IDPCommunicationErrorException"); +var de_IDPRejectedClaimException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client.expectString)(output[_m]); } - loadQueryErrorMessage(data) { - const errorData = this.loadQueryError(data); - return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; + return contents; +}, "de_IDPRejectedClaimException"); +var de_InvalidAuthorizationMessageException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client.expectString)(output[_m]); } - /** - * @override - */ - getDefaultContentType() { - return "application/x-www-form-urlencoded"; + return contents; +}, "de_InvalidAuthorizationMessageException"); +var de_InvalidIdentityTokenException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client.expectString)(output[_m]); + } + return contents; +}, "de_InvalidIdentityTokenException"); +var de_MalformedPolicyDocumentException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client.expectString)(output[_m]); + } + return contents; +}, "de_MalformedPolicyDocumentException"); +var de_PackedPolicyTooLargeException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client.expectString)(output[_m]); + } + return contents; +}, "de_PackedPolicyTooLargeException"); +var de_RegionDisabledException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client.expectString)(output[_m]); + } + return contents; +}, "de_RegionDisabledException"); +var deserializeMetadata = /* @__PURE__ */ __name((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"] +}), "deserializeMetadata"); +var throwDefaultError = (0, import_smithy_client.withBaseException)(STSServiceException); +var buildHttpRpcRequest = /* @__PURE__ */ __name(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 !== void 0) { + contents.hostname = resolvedHostname; + } + if (body !== void 0) { + contents.body = body; } + return new import_protocol_http.HttpRequest(contents); +}, "buildHttpRpcRequest"); +var SHARED_HEADERS = { + "content-type": "application/x-www-form-urlencoded" }; - -// src/submodules/protocols/query/AwsEc2QueryProtocol.ts -var AwsEc2QueryProtocol = class extends AwsQueryProtocol { - constructor(options) { - super(options); - this.options = options; - const ec2Settings = { - capitalizeKeys: true, - flattenLists: true, - serializeEmptyLists: false - }; - Object.assign(this.serializer.settings, ec2Settings); +var _ = "2011-06-15"; +var _A = "Action"; +var _AKI = "AccessKeyId"; +var _AR = "AssumeRole"; +var _ARI = "AssumedRoleId"; +var _ARU = "AssumedRoleUser"; +var _ARWSAML = "AssumeRoleWithSAML"; +var _ARWWI = "AssumeRoleWithWebIdentity"; +var _ARs = "AssumeRoot"; +var _Ac = "Account"; +var _Ar = "Arn"; +var _Au = "Audience"; +var _C = "Credentials"; +var _CA = "ContextAssertion"; +var _DAM = "DecodeAuthorizationMessage"; +var _DM = "DecodedMessage"; +var _DS = "DurationSeconds"; +var _E = "Expiration"; +var _EI = "ExternalId"; +var _EM = "EncodedMessage"; +var _FU = "FederatedUser"; +var _FUI = "FederatedUserId"; +var _GAKI = "GetAccessKeyInfo"; +var _GCI = "GetCallerIdentity"; +var _GFT = "GetFederationToken"; +var _GST = "GetSessionToken"; +var _I = "Issuer"; +var _K = "Key"; +var _N = "Name"; +var _NQ = "NameQualifier"; +var _P = "Policy"; +var _PA = "PolicyArns"; +var _PAr = "PrincipalArn"; +var _PAro = "ProviderArn"; +var _PC = "ProvidedContexts"; +var _PI = "ProviderId"; +var _PPS = "PackedPolicySize"; +var _Pr = "Provider"; +var _RA = "RoleArn"; +var _RSN = "RoleSessionName"; +var _S = "Subject"; +var _SAK = "SecretAccessKey"; +var _SAMLA = "SAMLAssertion"; +var _SFWIT = "SubjectFromWebIdentityToken"; +var _SI = "SourceIdentity"; +var _SN = "SerialNumber"; +var _ST = "SubjectType"; +var _STe = "SessionToken"; +var _T = "Tags"; +var _TC = "TokenCode"; +var _TP = "TargetPrincipal"; +var _TPA = "TaskPolicyArn"; +var _TTK = "TransitiveTagKeys"; +var _UI = "UserId"; +var _V = "Version"; +var _Va = "Value"; +var _WIT = "WebIdentityToken"; +var _a = "arn"; +var _m = "message"; +var buildFormUrlencodedString = /* @__PURE__ */ __name((formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client.extendedEncodeURIComponent)(value)).join("&"), "buildFormUrlencodedString"); +var loadQueryErrorCode = /* @__PURE__ */ __name((output, data) => { + if (data.Error?.Code !== void 0) { + return data.Error.Code; + } + if (output.statusCode == 404) { + return "NotFound"; } +}, "loadQueryErrorCode"); + +// src/commands/AssumeRoleCommand.ts +var AssumeRoleCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() { static { - __name(this, "AwsEc2QueryProtocol"); + __name(this, "AssumeRoleCommand"); } - /** - * EC2 Query reads XResponse.XResult instead of XResponse directly. - */ - useNestedResult() { - return false; +}; + +// src/commands/AssumeRoleWithSAMLCommand.ts + + + +var import_EndpointParameters2 = __nccwpck_require__(510); +var AssumeRoleWithSAMLCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters2.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithSAML", {}).n("STSClient", "AssumeRoleWithSAMLCommand").f(AssumeRoleWithSAMLRequestFilterSensitiveLog, AssumeRoleWithSAMLResponseFilterSensitiveLog).ser(se_AssumeRoleWithSAMLCommand).de(de_AssumeRoleWithSAMLCommand).build() { + static { + __name(this, "AssumeRoleWithSAMLCommand"); } }; -// src/submodules/protocols/xml/AwsRestXmlProtocol.ts -var import_protocols6 = __nccwpck_require__(2241); -var import_schema9 = __nccwpck_require__(9826); -var import_util_body_length_browser4 = __nccwpck_require__(713); +// src/commands/AssumeRoleWithWebIdentityCommand.ts -// src/submodules/protocols/xml/parseXmlBody.ts -var import_smithy_client5 = __nccwpck_require__(3570); -var import_fast_xml_parser2 = __nccwpck_require__(2689); -var parseXmlBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - const parser = new import_fast_xml_parser2.XMLParser({ - attributeNamePrefix: "", - htmlEntities: true, - ignoreAttributes: false, - ignoreDeclaration: true, - parseTagValue: false, - trimValues: false, - tagValueProcessor: /* @__PURE__ */ __name((_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, "tagValueProcessor") - }); - parser.addEntity("#xD", "\r"); - parser.addEntity("#10", "\n"); - let parsedObj; - try { - parsedObj = parser.parse(encoded, true); - } catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded - }); - } - throw e; - } - 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, import_smithy_client5.getValueFromTextNode)(parsedObjToReturn); + + +var import_EndpointParameters3 = __nccwpck_require__(510); +var AssumeRoleWithWebIdentityCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters3.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() { + static { + __name(this, "AssumeRoleWithWebIdentityCommand"); } - return {}; -}), "parseXmlBody"); -var parseXmlErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { - const value = await parseXmlBody(errorBody, context); - if (value.Error) { - value.Error.message = value.Error.message ?? value.Error.Message; +}; + +// src/commands/AssumeRootCommand.ts + + + +var import_EndpointParameters4 = __nccwpck_require__(510); +var AssumeRootCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters4.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "AssumeRoot", {}).n("STSClient", "AssumeRootCommand").f(void 0, AssumeRootResponseFilterSensitiveLog).ser(se_AssumeRootCommand).de(de_AssumeRootCommand).build() { + static { + __name(this, "AssumeRootCommand"); } - return value; -}, "parseXmlErrorBody"); -var loadRestXmlErrorCode = /* @__PURE__ */ __name((output, data) => { - if (data?.Error?.Code !== void 0) { - return data.Error.Code; +}; + +// src/commands/DecodeAuthorizationMessageCommand.ts + + + +var import_EndpointParameters5 = __nccwpck_require__(510); +var DecodeAuthorizationMessageCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters5.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "DecodeAuthorizationMessage", {}).n("STSClient", "DecodeAuthorizationMessageCommand").f(void 0, void 0).ser(se_DecodeAuthorizationMessageCommand).de(de_DecodeAuthorizationMessageCommand).build() { + static { + __name(this, "DecodeAuthorizationMessageCommand"); } - if (data?.Code !== void 0) { - return data.Code; +}; + +// src/commands/GetAccessKeyInfoCommand.ts + + + +var import_EndpointParameters6 = __nccwpck_require__(510); +var GetAccessKeyInfoCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters6.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "GetAccessKeyInfo", {}).n("STSClient", "GetAccessKeyInfoCommand").f(void 0, void 0).ser(se_GetAccessKeyInfoCommand).de(de_GetAccessKeyInfoCommand).build() { + static { + __name(this, "GetAccessKeyInfoCommand"); } - if (output.statusCode == 404) { - return "NotFound"; +}; + +// src/commands/GetCallerIdentityCommand.ts + + + +var import_EndpointParameters7 = __nccwpck_require__(510); +var GetCallerIdentityCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters7.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "GetCallerIdentity", {}).n("STSClient", "GetCallerIdentityCommand").f(void 0, void 0).ser(se_GetCallerIdentityCommand).de(de_GetCallerIdentityCommand).build() { + static { + __name(this, "GetCallerIdentityCommand"); } -}, "loadRestXmlErrorCode"); +}; -// src/submodules/protocols/xml/XmlShapeSerializer.ts -var import_xml_builder = __nccwpck_require__(7406); -var import_schema8 = __nccwpck_require__(9826); -var import_serde6 = __nccwpck_require__(7669); -var import_smithy_client6 = __nccwpck_require__(3570); -var import_util_base643 = __nccwpck_require__(5600); -var XmlShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; +// src/commands/GetFederationTokenCommand.ts + + + +var import_EndpointParameters8 = __nccwpck_require__(510); +var GetFederationTokenCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters8.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "GetFederationToken", {}).n("STSClient", "GetFederationTokenCommand").f(void 0, GetFederationTokenResponseFilterSensitiveLog).ser(se_GetFederationTokenCommand).de(de_GetFederationTokenCommand).build() { + static { + __name(this, "GetFederationTokenCommand"); } +}; + +// src/commands/GetSessionTokenCommand.ts + + + +var import_EndpointParameters9 = __nccwpck_require__(510); +var GetSessionTokenCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters9.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "GetSessionToken", {}).n("STSClient", "GetSessionTokenCommand").f(void 0, GetSessionTokenResponseFilterSensitiveLog).ser(se_GetSessionTokenCommand).de(de_GetSessionTokenCommand).build() { static { - __name(this, "XmlShapeSerializer"); + __name(this, "GetSessionTokenCommand"); } - stringBuffer; - byteBuffer; - buffer; - write(schema, value) { - const ns = import_schema8.NormalizedSchema.of(schema); - if (ns.isStringSchema() && typeof value === "string") { - this.stringBuffer = value; - } else if (ns.isBlobSchema()) { - this.byteBuffer = "byteLength" in value ? value : (this.serdeContext?.base64Decoder ?? import_util_base643.fromBase64)(value); - } else { - this.buffer = this.writeStruct(ns, value, void 0); - const traits = ns.getMergedTraits(); - if (traits.httpPayload && !traits.xmlName) { - this.buffer.withName(ns.getName()); - } - } +}; + +// src/STS.ts +var import_STSClient = __nccwpck_require__(4195); +var commands = { + AssumeRoleCommand, + AssumeRoleWithSAMLCommand, + AssumeRoleWithWebIdentityCommand, + AssumeRootCommand, + DecodeAuthorizationMessageCommand, + GetAccessKeyInfoCommand, + GetCallerIdentityCommand, + GetFederationTokenCommand, + GetSessionTokenCommand +}; +var STS = class extends import_STSClient.STSClient { + static { + __name(this, "STS"); } - flush() { - if (this.byteBuffer !== void 0) { - const bytes = this.byteBuffer; - delete this.byteBuffer; - return bytes; - } - if (this.stringBuffer !== void 0) { - const str = this.stringBuffer; - delete this.stringBuffer; - return str; - } - const buffer = this.buffer; - if (this.settings.xmlNamespace) { - if (!buffer?.attributes?.["xmlns"]) { - buffer.addAttribute("xmlns", this.settings.xmlNamespace); - } +}; +(0, import_smithy_client.createAggregatedClient)(commands, STS); + +// src/index.ts +var import_EndpointParameters10 = __nccwpck_require__(510); + +// src/defaultStsRoleAssumers.ts +var import_client = __nccwpck_require__(6510); +var ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; +var getAccountIdFromAssumedRoleUser = /* @__PURE__ */ __name((assumedRoleUser) => { + if (typeof assumedRoleUser?.Arn === "string") { + const arnComponents = assumedRoleUser.Arn.split(":"); + if (arnComponents.length > 4 && arnComponents[4] !== "") { + return arnComponents[4]; } - delete this.buffer; - return buffer.toString(); } - writeStruct(ns, value, parentXmlns) { - const traits = ns.getMergedTraits(); - const name = ns.isMemberSchema() && !traits.httpPayload ? ns.getMemberTraits().xmlName ?? ns.getMemberName() : traits.xmlName ?? ns.getName(); - if (!name || !ns.isStructSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName( - true - )}.` + return void 0; +}, "getAccountIdFromAssumedRoleUser"); +var resolveRegion = /* @__PURE__ */ __name(async (_region, _parentRegion, credentialProviderLogger) => { + const region = typeof _region === "function" ? await _region() : _region; + const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; + credentialProviderLogger?.debug?.( + "@aws-sdk/client-sts::resolveRegion", + "accepting first of:", + `${region} (provider)`, + `${parentRegion} (parent client)`, + `${ASSUME_ROLE_DEFAULT_REGION} (STS default)` + ); + return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION; +}, "resolveRegion"); +var getDefaultRoleAssumer = /* @__PURE__ */ __name((stsOptions, STSClient3) => { + let stsClient; + let closureSourceCreds; + return async (sourceCreds, params) => { + closureSourceCreds = sourceCreds; + if (!stsClient) { + const { + logger = stsOptions?.parentClientConfig?.logger, + region, + requestHandler = stsOptions?.parentClientConfig?.requestHandler, + credentialProviderLogger + } = stsOptions; + const resolvedRegion = await resolveRegion( + region, + stsOptions?.parentClientConfig?.region, + credentialProviderLogger ); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient3({ + profile: stsOptions?.parentClientConfig?.profile, + // A hack to make sts client uses the credential in current closure. + credentialDefaultProvider: /* @__PURE__ */ __name(() => async () => closureSourceCreds, "credentialDefaultProvider"), + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, + logger + }); } - const structXmlNode = import_xml_builder.XmlNode.of(name); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - if (xmlns) { - structXmlNode.addAttribute(xmlnsAttr, xmlns); - } - for (const [memberName, memberSchema] of ns.structIterator()) { - const val = value[memberName]; - if (val != null || memberSchema.isIdempotencyToken()) { - if (memberSchema.getMergedTraits().xmlAttribute) { - structXmlNode.addAttribute( - memberSchema.getMergedTraits().xmlName ?? memberName, - this.writeSimple(memberSchema, val) - ); - continue; - } - if (memberSchema.isListSchema()) { - this.writeList(memberSchema, val, structXmlNode, xmlns); - } else if (memberSchema.isMapSchema()) { - this.writeMap(memberSchema, val, structXmlNode, xmlns); - } else if (memberSchema.isStructSchema()) { - structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); - } else { - const memberNode = import_xml_builder.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); - this.writeSimpleInto(memberSchema, val, memberNode, xmlns); - structXmlNode.addChildNode(memberNode); - } - } + const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleCommand(params)); + if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); } - return structXmlNode; - } - writeList(listMember, array, container, parentXmlns) { - if (!listMember.isMemberSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}` + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); + const credentials = { + accessKeyId: Credentials2.AccessKeyId, + secretAccessKey: Credentials2.SecretAccessKey, + sessionToken: Credentials2.SessionToken, + expiration: Credentials2.Expiration, + // TODO(credentialScope): access normally when shape is updated. + ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, + ...accountId && { accountId } + }; + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); + return credentials; + }; +}, "getDefaultRoleAssumer"); +var getDefaultRoleAssumerWithWebIdentity = /* @__PURE__ */ __name((stsOptions, STSClient3) => { + let stsClient; + return async (params) => { + if (!stsClient) { + const { + logger = stsOptions?.parentClientConfig?.logger, + region, + requestHandler = stsOptions?.parentClientConfig?.requestHandler, + credentialProviderLogger + } = stsOptions; + const resolvedRegion = await resolveRegion( + region, + stsOptions?.parentClientConfig?.region, + credentialProviderLogger ); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient3({ + profile: stsOptions?.parentClientConfig?.profile, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, + logger + }); } - const listTraits = listMember.getMergedTraits(); - const listValueSchema = listMember.getValueSchema(); - const listValueTraits = listValueSchema.getMergedTraits(); - const sparse = !!listValueTraits.sparse; - const flat = !!listTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); - const writeItem = /* @__PURE__ */ __name((container2, value) => { - if (listValueSchema.isListSchema()) { - this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container2, xmlns); - } else if (listValueSchema.isMapSchema()) { - this.writeMap(listValueSchema, value, container2, xmlns); - } else if (listValueSchema.isStructSchema()) { - const struct = this.writeStruct(listValueSchema, value, xmlns); - container2.addChildNode( - struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member") - ); - } else { - const listItemNode = import_xml_builder.XmlNode.of( - flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member" - ); - this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); - container2.addChildNode(listItemNode); - } - }, "writeItem"); - if (flat) { - for (const value of array) { - if (sparse || value != null) { - writeItem(container, value); - } - } - } else { - const listNode = import_xml_builder.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); - if (xmlns) { - listNode.addAttribute(xmlnsAttr, xmlns); - } - for (const value of array) { - if (sparse || value != null) { - writeItem(listNode, value); - } - } - container.addChildNode(listNode); + const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); + if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); } - } - writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { - if (!mapMember.isMemberSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}` - ); + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); + const credentials = { + accessKeyId: Credentials2.AccessKeyId, + secretAccessKey: Credentials2.SecretAccessKey, + sessionToken: Credentials2.SessionToken, + expiration: Credentials2.Expiration, + // TODO(credentialScope): access normally when shape is updated. + ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, + ...accountId && { accountId } + }; + if (accountId) { + (0, import_client.setCredentialFeature)(credentials, "RESOLVED_ACCOUNT_ID", "T"); } - const mapTraits = mapMember.getMergedTraits(); - const mapKeySchema = mapMember.getKeySchema(); - const mapKeyTraits = mapKeySchema.getMergedTraits(); - const keyTag = mapKeyTraits.xmlName ?? "key"; - const mapValueSchema = mapMember.getValueSchema(); - const mapValueTraits = mapValueSchema.getMergedTraits(); - const valueTag = mapValueTraits.xmlName ?? "value"; - const sparse = !!mapValueTraits.sparse; - const flat = !!mapTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); - const addKeyValue = /* @__PURE__ */ __name((entry, key, val) => { - const keyNode = import_xml_builder.XmlNode.of(keyTag, key); - const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); - if (keyXmlns) { - keyNode.addAttribute(keyXmlnsAttr, keyXmlns); - } - entry.addChildNode(keyNode); - let valueNode = import_xml_builder.XmlNode.of(valueTag); - if (mapValueSchema.isListSchema()) { - this.writeList(mapValueSchema, val, valueNode, xmlns); - } else if (mapValueSchema.isMapSchema()) { - this.writeMap(mapValueSchema, val, valueNode, xmlns, true); - } else if (mapValueSchema.isStructSchema()) { - valueNode = this.writeStruct(mapValueSchema, val, xmlns); - } else { - this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); - } - entry.addChildNode(valueNode); - }, "addKeyValue"); - if (flat) { - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = import_xml_builder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - addKeyValue(entry, key, val); - container.addChildNode(entry); - } - } - } else { - let mapNode; - if (!containerIsMap) { - mapNode = import_xml_builder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - if (xmlns) { - mapNode.addAttribute(xmlnsAttr, xmlns); - } - container.addChildNode(mapNode); - } - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = import_xml_builder.XmlNode.of("entry"); - addKeyValue(entry, key, val); - (containerIsMap ? container : mapNode).addChildNode(entry); - } + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); + return credentials; + }; +}, "getDefaultRoleAssumerWithWebIdentity"); +var isH2 = /* @__PURE__ */ __name((requestHandler) => { + return requestHandler?.metadata?.handlerProtocol === "h2"; +}, "isH2"); + +// src/defaultRoleAssumers.ts +var import_STSClient2 = __nccwpck_require__(4195); +var getCustomizableStsClientCtor = /* @__PURE__ */ __name((baseCtor, customizations) => { + if (!customizations) return baseCtor; + else + return class CustomizableSTSClient extends baseCtor { + static { + __name(this, "CustomizableSTSClient"); } - } - } - writeSimple(_schema, value) { - if (null === value) { - throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); - } - const ns = import_schema8.NormalizedSchema.of(_schema); - let nodeContents = null; - if (value && typeof value === "object") { - if (ns.isBlobSchema()) { - nodeContents = (this.serdeContext?.base64Encoder ?? import_util_base643.toBase64)(value); - } else if (ns.isTimestampSchema() && value instanceof Date) { - const options = this.settings.timestampFormat; - const format = options.useTrait ? ns.getSchema() === import_schema8.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; - switch (format) { - case import_schema8.SCHEMA.TIMESTAMP_DATE_TIME: - nodeContents = value.toISOString().replace(".000Z", "Z"); - break; - case import_schema8.SCHEMA.TIMESTAMP_HTTP_DATE: - nodeContents = (0, import_smithy_client6.dateToUtcString)(value); - break; - case import_schema8.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - nodeContents = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using http date", value); - nodeContents = (0, import_smithy_client6.dateToUtcString)(value); - break; - } - } else if (ns.isBigDecimalSchema() && value) { - if (value instanceof import_serde6.NumericValue) { - return value.string; + constructor(config) { + super(config); + for (const customization of customizations) { + this.middlewareStack.use(customization); } - return String(value); - } else if (ns.isMapSchema() || ns.isListSchema()) { - throw new Error( - "@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead." - ); - } else { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName( - true - )}` - ); } - } - if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { - nodeContents = String(value); - } - if (ns.isStringSchema()) { - if (value === void 0 && ns.isIdempotencyToken()) { - nodeContents = (0, import_serde6.generateIdempotencyToken)(); - } else { - nodeContents = String(value); - } - } - if (nodeContents === null) { - throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); - } - return nodeContents; - } - writeSimpleInto(_schema, value, into, parentXmlns) { - const nodeContents = this.writeSimple(_schema, value); - const ns = import_schema8.NormalizedSchema.of(_schema); - const content = new import_xml_builder.XmlText(nodeContents); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - if (xmlns) { - into.addAttribute(xmlnsAttr, xmlns); - } - into.addChildNode(content); - } - getXmlnsAttribute(ns, parentXmlns) { - const traits = ns.getMergedTraits(); - const [prefix, xmlns] = traits.xmlNamespace ?? []; - if (xmlns && xmlns !== parentXmlns) { - return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; - } - return [void 0, void 0]; - } + }; +}, "getCustomizableStsClientCtor"); +var getDefaultRoleAssumer2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumer"); +var getDefaultRoleAssumerWithWebIdentity2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumerWithWebIdentity"); +var decorateDefaultCredentialProvider = /* @__PURE__ */ __name((provider) => (input) => provider({ + roleAssumer: getDefaultRoleAssumer2(input), + roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input), + ...input +}), "decorateDefaultCredentialProvider"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 3405: +/***/ ((__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 core_1 = __nccwpck_require__(2143); +const credential_provider_node_1 = __nccwpck_require__(3196); +const util_user_agent_node_1 = __nccwpck_require__(7330); +const config_resolver_1 = __nccwpck_require__(3098); +const core_2 = __nccwpck_require__(5829); +const hash_node_1 = __nccwpck_require__(3081); +const middleware_retry_1 = __nccwpck_require__(6039); +const node_config_provider_1 = __nccwpck_require__(3461); +const node_http_handler_1 = __nccwpck_require__(258); +const util_body_length_node_1 = __nccwpck_require__(8075); +const util_retry_1 = __nccwpck_require__(4902); +const runtimeConfig_shared_1 = __nccwpck_require__(2642); +const smithy_client_1 = __nccwpck_require__(3570); +const util_defaults_mode_node_1 = __nccwpck_require__(2429); +const smithy_client_2 = __nccwpck_require__(3570); +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); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + credentialDefaultProvider: config?.credentialDefaultProvider ?? credential_provider_node_1.defaultProvider, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || + (async (idProps) => await (0, credential_provider_node_1.defaultProvider)(idProps?.__config || {})()), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, + }, config), + 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, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; }; +exports.getRuntimeConfig = getRuntimeConfig; -// src/submodules/protocols/xml/XmlCodec.ts -var XmlCodec = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "XmlCodec"); - } - createSerializer() { - const serializer = new XmlShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new XmlShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } + +/***/ }), + +/***/ 2642: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const core_1 = __nccwpck_require__(2143); +const core_2 = __nccwpck_require__(5829); +const smithy_client_1 = __nccwpck_require__(3570); +const url_parser_1 = __nccwpck_require__(4681); +const util_base64_1 = __nccwpck_require__(5600); +const util_utf8_1 = __nccwpck_require__(1895); +const httpAuthSchemeProvider_1 = __nccwpck_require__(7145); +const endpointResolver_1 = __nccwpck_require__(1203); +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 ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + 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; -// src/submodules/protocols/xml/AwsRestXmlProtocol.ts -var AwsRestXmlProtocol = class extends import_protocols6.HttpBindingProtocol { - static { - __name(this, "AwsRestXmlProtocol"); - } - codec; - serializer; - deserializer; - constructor(options) { - super(options); - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema9.SCHEMA.TIMESTAMP_DATE_TIME - }, - httpBindings: true, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace + +/***/ }), + +/***/ 2053: +/***/ ((__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__(6976); +const protocol_http_1 = __nccwpck_require__(4418); +const smithy_client_1 = __nccwpck_require__(3570); +const httpAuthExtensionConfiguration_1 = __nccwpck_require__(8527); +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); +}; +exports.resolveRuntimeExtensions = resolveRuntimeExtensions; + + +/***/ }), + +/***/ 6555: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthSchemeConfig = exports.defaultSSOHttpAuthSchemeProvider = exports.defaultSSOHttpAuthSchemeParametersProvider = void 0; +const core_1 = __nccwpck_require__(2143); +const util_middleware_1 = __nccwpck_require__(2390); +const defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), }; - this.codec = new XmlCodec(settings); - this.serializer = new import_protocols6.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new import_protocols6.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); - } - getPayloadCodec() { - return this.codec; - } - getShapeId() { - return "aws.protocols#restXml"; - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const ns = import_schema9.NormalizedSchema.of(operationSchema.input); - const members = ns.getMemberSchemas(); - request.path = String(request.path).split("/").filter((segment) => { - return segment !== "{Bucket}"; - }).join("/") || "/"; - if (!request.headers["content-type"]) { - const httpPayloadMember = Object.values(members).find((m) => { - return !!m.getMergedTraits().httpPayload; - }); - if (httpPayloadMember) { - const mediaType = httpPayloadMember.getMergedTraits().mediaType; - if (mediaType) { - request.headers["content-type"] = mediaType; - } else if (httpPayloadMember.isStringSchema()) { - request.headers["content-type"] = "text/plain"; - } else if (httpPayloadMember.isBlobSchema()) { - request.headers["content-type"] = "application/octet-stream"; - } else { - request.headers["content-type"] = this.getDefaultContentType(); +}; +exports.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "awsssoportal", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSSOHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "GetRoleCredentials": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; } - } else if (!ns.isUnitSchema()) { - const hasBody = Object.values(members).find((m) => { - const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); - return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && httpPrefixHeaders === void 0; - }); - if (hasBody) { - request.headers["content-type"] = this.getDefaultContentType(); + case "ListAccountRoles": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "ListAccounts": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "Logout": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); } - } - } - if (request.headers["content-type"] === this.getDefaultContentType()) { - if (typeof request.body === "string") { - request.body = '' + request.body; - } - } - if (request.body) { - try { - request.headers["content-length"] = String((0, import_util_body_length_browser4.calculateBodyLength)(request.body)); - } catch (e) { - } - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - return super.deserializeResponse(operationSchema, context, response); - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const registry = import_schema9.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorIdentifier); - } catch (e) { - const baseExceptionSchema = import_schema9.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), dataObject); - } - throw new Error(errorName); - } - const ns = import_schema9.NormalizedSchema.of(errorSchema); - const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = dataObject.Error?.[target] ?? dataObject[target]; - output[name] = this.codec.createDeserializer().readSchema(member, value); } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output + return options; +}; +exports.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), }); - throw exception; - } - /** - * @override - */ - getDefaultContentType() { - return "application/xml"; - } }; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; + + +/***/ }), + +/***/ 3584: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = __nccwpck_require__(4241); +const util_endpoints_2 = __nccwpck_require__(5473); +const ruleset_1 = __nccwpck_require__(7957); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; + + +/***/ }), + +/***/ 7957: +/***/ ((__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; /***/ }), -/***/ 8519: +/***/ 1687: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -26520,709 +26516,582 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID, - ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE, - ENV_EXPIRATION: () => ENV_EXPIRATION, - ENV_KEY: () => ENV_KEY, - ENV_SECRET: () => ENV_SECRET, - ENV_SESSION: () => ENV_SESSION, - fromEnv: () => fromEnv + GetRoleCredentialsCommand: () => GetRoleCredentialsCommand, + GetRoleCredentialsRequestFilterSensitiveLog: () => GetRoleCredentialsRequestFilterSensitiveLog, + GetRoleCredentialsResponseFilterSensitiveLog: () => GetRoleCredentialsResponseFilterSensitiveLog, + InvalidRequestException: () => InvalidRequestException, + ListAccountRolesCommand: () => ListAccountRolesCommand, + ListAccountRolesRequestFilterSensitiveLog: () => ListAccountRolesRequestFilterSensitiveLog, + ListAccountsCommand: () => ListAccountsCommand, + ListAccountsRequestFilterSensitiveLog: () => ListAccountsRequestFilterSensitiveLog, + LogoutCommand: () => LogoutCommand, + LogoutRequestFilterSensitiveLog: () => LogoutRequestFilterSensitiveLog, + ResourceNotFoundException: () => ResourceNotFoundException, + RoleCredentialsFilterSensitiveLog: () => RoleCredentialsFilterSensitiveLog, + SSO: () => SSO, + SSOClient: () => SSOClient, + SSOServiceException: () => SSOServiceException, + TooManyRequestsException: () => TooManyRequestsException, + UnauthorizedException: () => UnauthorizedException, + __Client: () => import_smithy_client.Client, + paginateListAccountRoles: () => paginateListAccountRoles, + paginateListAccounts: () => paginateListAccounts }); module.exports = __toCommonJS(index_exports); -// src/fromEnv.ts -var import_client = __nccwpck_require__(912); -var import_property_provider = __nccwpck_require__(9721); -var ENV_KEY = "AWS_ACCESS_KEY_ID"; -var ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; -var ENV_SESSION = "AWS_SESSION_TOKEN"; -var ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; -var ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; -var ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; -var fromEnv = /* @__PURE__ */ __name((init) => async () => { - init?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); - const accessKeyId = process.env[ENV_KEY]; - const secretAccessKey = process.env[ENV_SECRET]; - const sessionToken = process.env[ENV_SESSION]; - const expiry = process.env[ENV_EXPIRATION]; - const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; - const accountId = process.env[ENV_ACCOUNT_ID]; - if (accessKeyId && secretAccessKey) { - const credentials = { - accessKeyId, - secretAccessKey, - ...sessionToken && { sessionToken }, - ...expiry && { expiration: new Date(expiry) }, - ...credentialScope && { credentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS", "g"); - return credentials; - } - throw new import_property_provider.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init?.logger }); -}, "fromEnv"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), +// src/SSOClient.ts +var import_middleware_host_header = __nccwpck_require__(9514); +var import_middleware_logger = __nccwpck_require__(5675); +var import_middleware_recursion_detection = __nccwpck_require__(7977); +var import_middleware_user_agent = __nccwpck_require__(6634); +var import_config_resolver = __nccwpck_require__(3098); +var import_core = __nccwpck_require__(5829); +var import_middleware_content_length = __nccwpck_require__(2800); +var import_middleware_endpoint = __nccwpck_require__(2918); +var import_middleware_retry = __nccwpck_require__(6039); -/***/ 7606: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var import_httpAuthSchemeProvider = __nccwpck_require__(6555); -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkUrl = void 0; -const property_provider_1 = __nccwpck_require__(9721); -const LOOPBACK_CIDR_IPv4 = "127.0.0.0/8"; -const LOOPBACK_CIDR_IPv6 = "::1/128"; -const ECS_CONTAINER_HOST = "169.254.170.2"; -const EKS_CONTAINER_HOST_IPv4 = "169.254.170.23"; -const EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]"; -const checkUrl = (url, logger) => { - if (url.protocol === "https:") { - return; - } - if (url.hostname === ECS_CONTAINER_HOST || - url.hostname === EKS_CONTAINER_HOST_IPv4 || - url.hostname === EKS_CONTAINER_HOST_IPv6) { - return; - } - if (url.hostname.includes("[")) { - if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") { - return; - } - } - else { - if (url.hostname === "localhost") { - return; - } - const ipComponents = url.hostname.split("."); - const inRange = (component) => { - const num = parseInt(component, 10); - return 0 <= num && num <= 255; - }; - if (ipComponents[0] === "127" && - inRange(ipComponents[1]) && - inRange(ipComponents[2]) && - inRange(ipComponents[3]) && - ipComponents.length === 4) { - return; - } - } - throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following: - - loopback CIDR 127.0.0.0/8 or [::1/128] - - ECS container host 169.254.170.2 - - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger }); -}; -exports.checkUrl = checkUrl; - - -/***/ }), - -/***/ 2120: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromHttp = void 0; -const tslib_1 = __nccwpck_require__(4351); -const client_1 = __nccwpck_require__(912); -const node_http_handler_1 = __nccwpck_require__(258); -const property_provider_1 = __nccwpck_require__(9721); -const promises_1 = tslib_1.__importDefault(__nccwpck_require__(3292)); -const checkUrl_1 = __nccwpck_require__(7606); -const requestHelpers_1 = __nccwpck_require__(8082); -const retry_wrapper_1 = __nccwpck_require__(9359); -const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; -const DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; -const AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; -const AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"; -const AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; -const fromHttp = (options = {}) => { - options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp"); - let host; - const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI]; - const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI]; - const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN]; - const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE]; - const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger ? console.warn : options.logger.warn; - if (relative && full) { - warn("@aws-sdk/credential-provider-http: " + - "you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."); - warn("awsContainerCredentialsFullUri will take precedence."); - } - if (token && tokenFile) { - warn("@aws-sdk/credential-provider-http: " + - "you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."); - warn("awsContainerAuthorizationToken will take precedence."); - } - if (full) { - host = full; - } - else if (relative) { - host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`; - } - else { - throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided. -Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger }); - } - const url = new URL(host); - (0, checkUrl_1.checkUrl)(url, options.logger); - const requestHandler = new node_http_handler_1.NodeHttpHandler({ - requestTimeout: options.timeout ?? 1000, - connectionTimeout: options.timeout ?? 1000, - }); - return (0, retry_wrapper_1.retryWrapper)(async () => { - const request = (0, requestHelpers_1.createGetRequest)(url); - if (token) { - request.headers.Authorization = token; - } - else if (tokenFile) { - request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString(); - } - try { - const result = await requestHandler.handle(request); - return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z")); - } - catch (e) { - throw new property_provider_1.CredentialsProviderError(String(e), { logger: options.logger }); - } - }, options.maxRetries ?? 3, options.timeout ?? 1000); +// src/endpoint/EndpointParameters.ts +var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "awsssoportal" + }); +}, "resolveClientEndpointParameters"); +var commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } }; -exports.fromHttp = fromHttp; - - -/***/ }), -/***/ 8082: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/SSOClient.ts +var import_runtimeConfig = __nccwpck_require__(1012); -"use strict"; +// src/runtimeExtensions.ts +var import_region_config_resolver = __nccwpck_require__(6976); +var import_protocol_http = __nccwpck_require__(4418); +var import_smithy_client = __nccwpck_require__(3570); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createGetRequest = createGetRequest; -exports.getCredentials = getCredentials; -const property_provider_1 = __nccwpck_require__(9721); -const protocol_http_1 = __nccwpck_require__(4418); -const smithy_client_1 = __nccwpck_require__(3570); -const util_stream_1 = __nccwpck_require__(6607); -function createGetRequest(url) { - return new protocol_http_1.HttpRequest({ - protocol: url.protocol, - hostname: url.hostname, - port: Number(url.port), - path: url.pathname, - query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => { - acc[k] = v; - return acc; - }, {}), - fragment: url.hash, - }); -} -async function getCredentials(response, logger) { - const stream = (0, util_stream_1.sdkStreamMixin)(response.body); - const str = await stream.transformToString(); - if (response.statusCode === 200) { - const parsed = JSON.parse(str); - if (typeof parsed.AccessKeyId !== "string" || - typeof parsed.SecretAccessKey !== "string" || - typeof parsed.Token !== "string" || - typeof parsed.Expiration !== "string") { - throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: " + - "{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger }); - } - return { - accessKeyId: parsed.AccessKeyId, - secretAccessKey: parsed.SecretAccessKey, - sessionToken: parsed.Token, - expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration), - }; - } - if (response.statusCode >= 400 && response.statusCode < 500) { - let parsedBody = {}; - try { - parsedBody = JSON.parse(str); - } - catch (e) { } - throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), { - Code: parsedBody.Code, - Message: parsedBody.Message, - }); +// src/auth/httpAuthExtensionConfiguration.ts +var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; } - throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }); -} - - -/***/ }), - -/***/ 9359: -/***/ ((__unused_webpack_module, exports) => { + }; +}, "getHttpAuthExtensionConfiguration"); +var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials() + }; +}, "resolveHttpAuthRuntimeConfig"); -"use strict"; +// src/runtimeExtensions.ts +var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign( + (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), + (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), + (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), + getHttpAuthExtensionConfiguration(runtimeConfig) + ); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign( + runtimeConfig, + (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), + (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), + (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), + resolveHttpAuthRuntimeConfig(extensionConfiguration) + ); +}, "resolveRuntimeExtensions"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.retryWrapper = void 0; -const retryWrapper = (toRetry, maxRetries, delayMs) => { - return async () => { - for (let i = 0; i < maxRetries; ++i) { - try { - return await toRetry(); - } - catch (e) { - await new Promise((resolve) => setTimeout(resolve, delayMs)); - } - } - return await toRetry(); - }; +// src/SSOClient.ts +var SSOClient = class extends import_smithy_client.Client { + static { + __name(this, "SSOClient"); + } + /** + * The resolved configuration of SSOClient class. This is resolved and normalized from the {@link SSOClientConfig | constructor configuration interface}. + */ + config; + constructor(...[configuration]) { + const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); + const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); + const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); + const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use( + (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { + httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials + }), "identityProviderConfigProvider") + }) + ); + this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); + } + /** + * Destroy underlying resources, like sockets. It's usually not necessary to do this. + * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. + * Otherwise, sockets might stay open for quite a long time before the server terminates them. + */ + destroy() { + super.destroy(); + } }; -exports.retryWrapper = retryWrapper; - -/***/ }), +// src/SSO.ts -/***/ 2618: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +// src/commands/GetRoleCredentialsCommand.ts -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromHttp = void 0; -var fromHttp_1 = __nccwpck_require__(2120); -Object.defineProperty(exports, "fromHttp", ({ enumerable: true, get: function () { return fromHttp_1.fromHttp; } })); +var import_middleware_serde = __nccwpck_require__(1238); -/***/ }), +// src/models/models_0.ts -/***/ 9139: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +// src/models/SSOServiceException.ts -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var SSOServiceException = class _SSOServiceException extends import_smithy_client.ServiceException { + static { + __name(this, "SSOServiceException"); + } + /** + * @internal + */ + constructor(options) { + super(options); + Object.setPrototypeOf(this, _SSOServiceException.prototype); } - return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromIni: () => fromIni -}); -module.exports = __toCommonJS(index_exports); - -// src/fromIni.ts - - -// src/resolveProfileData.ts - -// src/resolveAssumeRoleCredentials.ts - - -var import_shared_ini_file_loader = __nccwpck_require__(3507); - -// src/resolveCredentialSource.ts -var import_client = __nccwpck_require__(912); -var import_property_provider = __nccwpck_require__(9721); -var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName, logger) => { - const sourceProvidersMap = { - EcsContainer: /* @__PURE__ */ __name(async (options) => { - const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(2618))); - const { fromContainerMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); - return async () => (0, import_property_provider.chain)(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); - }, "EcsContainer"), - Ec2InstanceMetadata: /* @__PURE__ */ __name(async (options) => { - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata"); - const { fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); - return async () => fromInstanceMetadata(options)().then(setNamedProvider); - }, "Ec2InstanceMetadata"), - Environment: /* @__PURE__ */ __name(async (options) => { - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); - const { fromEnv } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(8519))); - return async () => fromEnv(options)().then(setNamedProvider); - }, "Environment") - }; - if (credentialSource in sourceProvidersMap) { - return sourceProvidersMap[credentialSource]; - } else { - throw new import_property_provider.CredentialsProviderError( - `Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, - { logger } - ); +// src/models/models_0.ts +var InvalidRequestException = class _InvalidRequestException extends SSOServiceException { + static { + __name(this, "InvalidRequestException"); } -}, "resolveCredentialSource"); -var setNamedProvider = /* @__PURE__ */ __name((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"), "setNamedProvider"); - -// src/resolveAssumeRoleCredentials.ts -var isAssumeRoleProfile = /* @__PURE__ */ __name((arg, { profile = "default", logger } = {}) => { - return 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, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger })); -}, "isAssumeRoleProfile"); -var isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger }) => { - const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; - if (withSourceProfile) { - logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`); + name = "InvalidRequestException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidRequestException.prototype); } - return withSourceProfile; -}, "isAssumeRoleWithSourceProfile"); -var isCredentialSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger }) => { - const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; - if (withProviderProfile) { - logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`); +}; +var ResourceNotFoundException = class _ResourceNotFoundException extends SSOServiceException { + static { + __name(this, "ResourceNotFoundException"); } - return withProviderProfile; -}, "isCredentialSourceProfile"); -var resolveAssumeRoleCredentials = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => { - options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)"); - const profileData = profiles[profileName]; - const { source_profile, region } = profileData; - if (!options.roleAssumer) { - const { getDefaultRoleAssumer } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(3715))); - options.roleAssumer = getDefaultRoleAssumer( - { - ...options.clientConfig, - credentialProviderLogger: options.logger, - parentClientConfig: { - ...options?.parentClientConfig, - region: region ?? options?.parentClientConfig?.region - } - }, - options.clientPlugins - ); + name = "ResourceNotFoundException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ResourceNotFoundException.prototype); } - if (source_profile && source_profile in visitedProfiles) { - throw new import_property_provider.CredentialsProviderError( - `Detected a cycle attempting to resolve credentials for profile ${(0, import_shared_ini_file_loader.getProfileName)(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), - { logger: options.logger } - ); +}; +var TooManyRequestsException = class _TooManyRequestsException extends SSOServiceException { + static { + __name(this, "TooManyRequestsException"); } - options.logger?.debug( - `@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}` - ); - const sourceCredsProvider = source_profile ? resolveProfileData( - source_profile, - profiles, - options, - { - ...visitedProfiles, - [source_profile]: true - }, - isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {}) - ) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))(); - if (isCredentialSourceWithoutRoleArn(profileData)) { - return sourceCredsProvider.then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); - } else { - const params = { - RoleArn: profileData.role_arn, - RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`, - ExternalId: profileData.external_id, - DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10) - }; - const { mfa_serial } = profileData; - if (mfa_serial) { - if (!options.mfaCodeProvider) { - throw new import_property_provider.CredentialsProviderError( - `Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, - { logger: options.logger, tryNextLink: false } - ); - } - params.SerialNumber = mfa_serial; - params.TokenCode = await options.mfaCodeProvider(mfa_serial); - } - const sourceCreds = await sourceCredsProvider; - return options.roleAssumer(sourceCreds, params).then( - (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o") - ); + name = "TooManyRequestsException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "TooManyRequestsException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _TooManyRequestsException.prototype); } -}, "resolveAssumeRoleCredentials"); -var isCredentialSourceWithoutRoleArn = /* @__PURE__ */ __name((section) => { - return !section.role_arn && !!section.credential_source; -}, "isCredentialSourceWithoutRoleArn"); - -// src/resolveProcessCredentials.ts +}; +var UnauthorizedException = class _UnauthorizedException extends SSOServiceException { + static { + __name(this, "UnauthorizedException"); + } + name = "UnauthorizedException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "UnauthorizedException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _UnauthorizedException.prototype); + } +}; +var GetRoleCredentialsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } +}), "GetRoleCredentialsRequestFilterSensitiveLog"); +var RoleCredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.secretAccessKey && { secretAccessKey: import_smithy_client.SENSITIVE_STRING }, + ...obj.sessionToken && { sessionToken: import_smithy_client.SENSITIVE_STRING } +}), "RoleCredentialsFilterSensitiveLog"); +var GetRoleCredentialsResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) } +}), "GetRoleCredentialsResponseFilterSensitiveLog"); +var ListAccountRolesRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } +}), "ListAccountRolesRequestFilterSensitiveLog"); +var ListAccountsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } +}), "ListAccountsRequestFilterSensitiveLog"); +var LogoutRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } +}), "LogoutRequestFilterSensitiveLog"); -var isProcessProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", "isProcessProfile"); -var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => __toESM(__nccwpck_require__(9197))).then( - ({ fromProcess }) => fromProcess({ - ...options, - profile - })().then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_PROCESS", "v")) -), "resolveProcessCredentials"); +// src/protocols/Aws_restJson1.ts +var import_core2 = __nccwpck_require__(2143); -// src/resolveSsoCredentials.ts -var resolveSsoCredentials = /* @__PURE__ */ __name(async (profile, profileData, options = {}) => { - const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7027))); - return fromSSO({ - profile, - logger: options.logger, - parentClientConfig: options.parentClientConfig, - clientConfig: options.clientConfig - })().then((creds) => { - if (profileData.sso_session) { - return (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO", "r"); - } else { - return (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t"); - } +var se_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (input, context) => { + const b = (0, import_core.requestBuilder)(input, context); + const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { + [_xasbt]: input[_aT] }); -}, "resolveSsoCredentials"); -var isSsoProfile = /* @__PURE__ */ __name((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"), "isSsoProfile"); - -// src/resolveStaticCredentials.ts - -var isStaticCredsProfile = /* @__PURE__ */ __name((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 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1, "isStaticCredsProfile"); -var resolveStaticCredentials = /* @__PURE__ */ __name(async (profile, options) => { - options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials"); - const credentials = { - accessKeyId: profile.aws_access_key_id, - secretAccessKey: profile.aws_secret_access_key, - sessionToken: profile.aws_session_token, - ...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }, - ...profile.aws_account_id && { accountId: profile.aws_account_id } - }; - return (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROFILE", "n"); -}, "resolveStaticCredentials"); - -// src/resolveWebIdentityCredentials.ts - -var isWebIdentityProfile = /* @__PURE__ */ __name((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, "isWebIdentityProfile"); -var resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => __toESM(__nccwpck_require__(4331))).then( - ({ fromTokenFile }) => fromTokenFile({ - webIdentityTokenFile: profile.web_identity_token_file, - roleArn: profile.role_arn, - roleSessionName: profile.role_session_name, - roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, - logger: options.logger, - parentClientConfig: options.parentClientConfig - })().then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q")) -), "resolveWebIdentityCredentials"); - -// src/resolveProfileData.ts -var resolveProfileData = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => { - const data = profiles[profileName]; - if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) { - return resolveStaticCredentials(data, options); + b.bp("/federation/credentials"); + const query = (0, import_smithy_client.map)({ + [_rn]: [, (0, import_smithy_client.expectNonNull)(input[_rN], `roleName`)], + [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)] + }); + let body; + b.m("GET").h(headers).q(query).b(body); + return b.build(); +}, "se_GetRoleCredentialsCommand"); +var se_ListAccountRolesCommand = /* @__PURE__ */ __name(async (input, context) => { + const b = (0, import_core.requestBuilder)(input, context); + const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { + [_xasbt]: input[_aT] + }); + b.bp("/assignment/roles"); + const query = (0, import_smithy_client.map)({ + [_nt]: [, input[_nT]], + [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()], + [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)] + }); + let body; + b.m("GET").h(headers).q(query).b(body); + return b.build(); +}, "se_ListAccountRolesCommand"); +var se_ListAccountsCommand = /* @__PURE__ */ __name(async (input, context) => { + const b = (0, import_core.requestBuilder)(input, context); + const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { + [_xasbt]: input[_aT] + }); + b.bp("/assignment/accounts"); + const query = (0, import_smithy_client.map)({ + [_nt]: [, input[_nT]], + [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()] + }); + let body; + b.m("GET").h(headers).q(query).b(body); + return b.build(); +}, "se_ListAccountsCommand"); +var se_LogoutCommand = /* @__PURE__ */ __name(async (input, context) => { + const b = (0, import_core.requestBuilder)(input, context); + const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { + [_xasbt]: input[_aT] + }); + b.bp("/logout"); + let body; + b.m("POST").h(headers).b(body); + return b.build(); +}, "se_LogoutCommand"); +var de_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); } - if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) { - return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles); + const contents = (0, import_smithy_client.map)({ + $metadata: deserializeMetadata(output) + }); + const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); + const doc = (0, import_smithy_client.take)(data, { + roleCredentials: import_smithy_client._json + }); + Object.assign(contents, doc); + return contents; +}, "de_GetRoleCredentialsCommand"); +var de_ListAccountRolesCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); } - if (isStaticCredsProfile(data)) { - return resolveStaticCredentials(data, options); + const contents = (0, import_smithy_client.map)({ + $metadata: deserializeMetadata(output) + }); + const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); + const doc = (0, import_smithy_client.take)(data, { + nextToken: import_smithy_client.expectString, + roleList: import_smithy_client._json + }); + Object.assign(contents, doc); + return contents; +}, "de_ListAccountRolesCommand"); +var de_ListAccountsCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); } - if (isWebIdentityProfile(data)) { - return resolveWebIdentityCredentials(data, options); + const contents = (0, import_smithy_client.map)({ + $metadata: deserializeMetadata(output) + }); + const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); + const doc = (0, import_smithy_client.take)(data, { + accountList: import_smithy_client._json, + nextToken: import_smithy_client.expectString + }); + Object.assign(contents, doc); + return contents; +}, "de_ListAccountsCommand"); +var de_LogoutCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); } - if (isProcessProfile(data)) { - return resolveProcessCredentials(options, profileName); + const contents = (0, import_smithy_client.map)({ + $metadata: deserializeMetadata(output) + }); + await (0, import_smithy_client.collectBody)(output.body, context); + return contents; +}, "de_LogoutCommand"); +var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { + const parsedOutput = { + ...output, + body: await (0, import_core2.parseJsonErrorBody)(output.body, context) + }; + const errorCode = (0, import_core2.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 + }); } - if (isSsoProfile(data)) { - return await resolveSsoCredentials(profileName, data, options); +}, "de_CommandError"); +var throwDefaultError = (0, import_smithy_client.withBaseException)(SSOServiceException); +var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client.take)(data, { + message: import_smithy_client.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidRequestException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidRequestExceptionRes"); +var de_ResourceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client.take)(data, { + message: import_smithy_client.expectString + }); + Object.assign(contents, doc); + const exception = new ResourceNotFoundException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); +}, "de_ResourceNotFoundExceptionRes"); +var de_TooManyRequestsExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client.take)(data, { + message: import_smithy_client.expectString + }); + Object.assign(contents, doc); + const exception = new TooManyRequestsException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); +}, "de_TooManyRequestsExceptionRes"); +var de_UnauthorizedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client.take)(data, { + message: import_smithy_client.expectString + }); + Object.assign(contents, doc); + const exception = new UnauthorizedException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); +}, "de_UnauthorizedExceptionRes"); +var deserializeMetadata = /* @__PURE__ */ __name((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"] +}), "deserializeMetadata"); +var _aI = "accountId"; +var _aT = "accessToken"; +var _ai = "account_id"; +var _mR = "maxResults"; +var _mr = "max_result"; +var _nT = "nextToken"; +var _nt = "next_token"; +var _rN = "roleName"; +var _rn = "role_name"; +var _xasbt = "x-amz-sso_bearer_token"; + +// src/commands/GetRoleCredentialsCommand.ts +var GetRoleCredentialsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog).ser(se_GetRoleCredentialsCommand).de(de_GetRoleCredentialsCommand).build() { + static { + __name(this, "GetRoleCredentialsCommand"); } - throw new import_property_provider.CredentialsProviderError( - `Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, - { logger: options.logger } - ); -}, "resolveProfileData"); +}; -// src/fromIni.ts -var fromIni = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { - const init = { - ..._init, - parentClientConfig: { - ...callerClientConfig, - ..._init.parentClientConfig - } - }; - init.logger?.debug("@aws-sdk/credential-provider-ini - fromIni"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - return resolveProfileData( - (0, import_shared_ini_file_loader.getProfileName)({ - profile: _init.profile ?? callerClientConfig?.profile - }), - profiles, - init - ); -}, "fromIni"); -// Annotate the CommonJS export names for ESM import in node: +// src/commands/ListAccountRolesCommand.ts -0 && (0); +var ListAccountRolesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").f(ListAccountRolesRequestFilterSensitiveLog, void 0).ser(se_ListAccountRolesCommand).de(de_ListAccountRolesCommand).build() { + static { + __name(this, "ListAccountRolesCommand"); + } +}; -/***/ }), +// src/commands/ListAccountsCommand.ts -/***/ 2424: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var ListAccountsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").f(ListAccountsRequestFilterSensitiveLog, void 0).ser(se_ListAccountsCommand).de(de_ListAccountsCommand).build() { + static { + __name(this, "ListAccountsCommand"); } - return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - credentialsTreatedAsExpired: () => credentialsTreatedAsExpired, - credentialsWillNeedRefresh: () => credentialsWillNeedRefresh, - defaultProvider: () => defaultProvider -}); -module.exports = __toCommonJS(index_exports); +// src/commands/LogoutCommand.ts -// src/defaultProvider.ts -var import_credential_provider_env = __nccwpck_require__(8519); -var import_shared_ini_file_loader = __nccwpck_require__(3507); -// src/remoteProvider.ts -var import_property_provider = __nccwpck_require__(9721); -var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; -var remoteProvider = /* @__PURE__ */ __name(async (init) => { - const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); - if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { - init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); - const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(2618))); - return (0, import_property_provider.chain)(fromHttp(init), fromContainerMetadata(init)); +var LogoutCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").f(LogoutRequestFilterSensitiveLog, void 0).ser(se_LogoutCommand).de(de_LogoutCommand).build() { + static { + __name(this, "LogoutCommand"); } - if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { - return async () => { - throw new import_property_provider.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init.logger }); - }; +}; + +// src/SSO.ts +var commands = { + GetRoleCredentialsCommand, + ListAccountRolesCommand, + ListAccountsCommand, + LogoutCommand +}; +var SSO = class extends SSOClient { + static { + __name(this, "SSO"); } - init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); - return fromInstanceMetadata(init); -}, "remoteProvider"); +}; +(0, import_smithy_client.createAggregatedClient)(commands, SSO); -// src/defaultProvider.ts -var multipleCredentialSourceWarningEmitted = false; -var defaultProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( - (0, import_property_provider.chain)( - async () => { - const profile = init.profile ?? process.env[import_shared_ini_file_loader.ENV_PROFILE]; - if (profile) { - const envStaticCredentialsAreSet = process.env[import_credential_provider_env.ENV_KEY] && process.env[import_credential_provider_env.ENV_SECRET]; - if (envStaticCredentialsAreSet) { - if (!multipleCredentialSourceWarningEmitted) { - const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" ? init.logger.warn : console.warn; - warnFn( - `@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: - Multiple credential sources detected: - Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. - This SDK will proceed with the AWS_PROFILE value. - - However, a future version may change this behavior to prefer the ENV static credentials. - Please ensure that your environment only sets either the AWS_PROFILE or the - AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. -` - ); - multipleCredentialSourceWarningEmitted = true; - } - } - throw new import_property_provider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { - logger: init.logger, - tryNextLink: true - }); - } - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); - return (0, import_credential_provider_env.fromEnv)(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - throw new import_property_provider.CredentialsProviderError( - "Skipping SSO provider in default chain (inputs do not include SSO fields).", - { logger: init.logger } - ); - } - const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7027))); - return fromSSO(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); - const { fromIni } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(9139))); - return fromIni(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); - const { fromProcess } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(9197))); - return fromProcess(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); - const { fromTokenFile } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(4331))); - return fromTokenFile(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); - return (await remoteProvider(init))(); - }, - async () => { - throw new import_property_provider.CredentialsProviderError("Could not load credentials from any providers", { - tryNextLink: false, - logger: init.logger - }); - } - ), - credentialsTreatedAsExpired, - credentialsWillNeedRefresh -), "defaultProvider"); -var credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0, "credentialsWillNeedRefresh"); -var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired"); +// src/pagination/ListAccountRolesPaginator.ts + +var paginateListAccountRoles = (0, import_core.createPaginator)(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults"); + +// src/pagination/ListAccountsPaginator.ts + +var paginateListAccounts = (0, import_core.createPaginator)(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -27231,8 +27100,132 @@ var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials) => creden /***/ }), -/***/ 9197: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 1012: +/***/ ((__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__(4665)); +const core_1 = __nccwpck_require__(2143); +const util_user_agent_node_1 = __nccwpck_require__(7330); +const config_resolver_1 = __nccwpck_require__(3098); +const hash_node_1 = __nccwpck_require__(3081); +const middleware_retry_1 = __nccwpck_require__(6039); +const node_config_provider_1 = __nccwpck_require__(3461); +const node_http_handler_1 = __nccwpck_require__(258); +const util_body_length_node_1 = __nccwpck_require__(8075); +const util_retry_1 = __nccwpck_require__(4902); +const runtimeConfig_shared_1 = __nccwpck_require__(7369); +const smithy_client_1 = __nccwpck_require__(3570); +const util_defaults_mode_node_1 = __nccwpck_require__(2429); +const smithy_client_2 = __nccwpck_require__(3570); +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); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ 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, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, + }, config), + 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, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; + + +/***/ }), + +/***/ 7369: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const core_1 = __nccwpck_require__(2143); +const core_2 = __nccwpck_require__(5829); +const smithy_client_1 = __nccwpck_require__(3570); +const url_parser_1 = __nccwpck_require__(4681); +const util_base64_1 = __nccwpck_require__(5600); +const util_utf8_1 = __nccwpck_require__(1895); +const httpAuthSchemeProvider_1 = __nccwpck_require__(6555); +const endpointResolver_1 = __nccwpck_require__(3584); +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 ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + 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; + + +/***/ }), + +/***/ 2143: +/***/ ((__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__(6510), exports); +tslib_1.__exportStar(__nccwpck_require__(3017), exports); +tslib_1.__exportStar(__nccwpck_require__(5743), exports); + + +/***/ }), + +/***/ 6510: +/***/ ((module) => { "use strict"; @@ -27255,103 +27248,75 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/client/index.ts var index_exports = {}; __export(index_exports, { - fromProcess: () => fromProcess + emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, + setCredentialFeature: () => setCredentialFeature, + setFeature: () => setFeature, + setTokenFeature: () => setTokenFeature, + state: () => state }); module.exports = __toCommonJS(index_exports); -// src/fromProcess.ts -var import_shared_ini_file_loader = __nccwpck_require__(3507); +// src/submodules/client/emitWarningIfUnsupportedVersion.ts +var state = { + warningEmitted: false +}; +var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { + if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { + state.warningEmitted = true; + process.emitWarning( + `NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will +no longer support Node.js 16.x on January 6, 2025. -// src/resolveProcessCredentials.ts -var import_property_provider = __nccwpck_require__(9721); -var import_child_process = __nccwpck_require__(2081); -var import_util = __nccwpck_require__(3837); +To continue receiving updates to AWS services, bug fixes, and security +updates please upgrade to a supported Node.js LTS version. -// src/getValidatedProcessCredentials.ts -var import_client = __nccwpck_require__(912); -var getValidatedProcessCredentials = /* @__PURE__ */ __name((profileName, data, profiles) => { - if (data.Version !== 1) { - throw Error(`Profile ${profileName} credential_process did not return Version 1.`); - } - if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) { - throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); - } - if (data.Expiration) { - const currentTime = /* @__PURE__ */ new Date(); - const expireTime = new Date(data.Expiration); - if (expireTime < currentTime) { - throw Error(`Profile ${profileName} credential_process returned expired credentials.`); - } +More information can be found at: https://a.co/74kJMmI` + ); } - let accountId = data.AccountId; - if (!accountId && profiles?.[profileName]?.aws_account_id) { - accountId = profiles[profileName].aws_account_id; +}, "emitWarningIfUnsupportedVersion"); + +// src/submodules/client/setCredentialFeature.ts +function setCredentialFeature(credentials, feature, value) { + if (!credentials.$source) { + credentials.$source = {}; } - const credentials = { - accessKeyId: data.AccessKeyId, - secretAccessKey: data.SecretAccessKey, - ...data.SessionToken && { sessionToken: data.SessionToken }, - ...data.Expiration && { expiration: new Date(data.Expiration) }, - ...data.CredentialScope && { credentialScope: data.CredentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROCESS", "w"); + credentials.$source[feature] = value; return credentials; -}, "getValidatedProcessCredentials"); +} +__name(setCredentialFeature, "setCredentialFeature"); -// src/resolveProcessCredentials.ts -var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger) => { - const profile = profiles[profileName]; - if (profiles[profileName]) { - const credentialProcess = profile["credential_process"]; - if (credentialProcess !== void 0) { - const execPromise = (0, import_util.promisify)(import_child_process.exec); - try { - const { stdout } = await execPromise(credentialProcess); - let data; - try { - data = JSON.parse(stdout.trim()); - } catch { - throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); - } - return getValidatedProcessCredentials(profileName, data, profiles); - } catch (error) { - throw new import_property_provider.CredentialsProviderError(error.message, { logger }); - } - } else { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger }); - } - } else { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { - logger - }); +// src/submodules/client/setFeature.ts +function setFeature(context, feature, value) { + if (!context.__aws_sdk_context) { + context.__aws_sdk_context = { + features: {} + }; + } else if (!context.__aws_sdk_context.features) { + context.__aws_sdk_context.features = {}; } -}, "resolveProcessCredentials"); + context.__aws_sdk_context.features[feature] = value; +} +__name(setFeature, "setFeature"); -// src/fromProcess.ts -var fromProcess = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { - init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - return resolveProcessCredentials( - (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }), - profiles, - init.logger - ); -}, "fromProcess"); +// src/submodules/client/setTokenFeature.ts +function setTokenFeature(token, feature, value) { + if (!token.$source) { + token.$source = {}; + } + token.$source[feature] = value; + return token; +} +__name(setTokenFeature, "setTokenFeature"); // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 7027: +/***/ 3017: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -27361,9 +27326,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -27378,373 +27340,371 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/loadSso.ts -var loadSso_exports = {}; -__export(loadSso_exports, { - GetRoleCredentialsCommand: () => import_client_sso.GetRoleCredentialsCommand, - SSOClient: () => import_client_sso.SSOClient -}); -var import_client_sso; -var init_loadSso = __esm({ - "src/loadSso.ts"() { - "use strict"; - import_client_sso = __nccwpck_require__(3015); - } -}); - -// src/index.ts +// src/submodules/httpAuthSchemes/index.ts var index_exports = {}; __export(index_exports, { - fromSSO: () => fromSSO, - isSsoProfile: () => isSsoProfile, - validateSsoProfile: () => validateSsoProfile + AWSSDKSigV4Signer: () => AWSSDKSigV4Signer, + AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner, + AwsSdkSigV4Signer: () => AwsSdkSigV4Signer, + NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, + NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS, + getBearerTokenEnvKey: () => getBearerTokenEnvKey, + resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config, + resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig, + resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config, + validateSigningProperties: () => validateSigningProperties }); module.exports = __toCommonJS(index_exports); -// src/fromSSO.ts +// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts +var import_protocol_http2 = __nccwpck_require__(4418); +// src/submodules/httpAuthSchemes/utils/getDateHeader.ts +var import_protocol_http = __nccwpck_require__(4418); +var getDateHeader = /* @__PURE__ */ __name((response) => import_protocol_http.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0, "getDateHeader"); +// src/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.ts +var getSkewCorrectedDate = /* @__PURE__ */ __name((systemClockOffset) => new Date(Date.now() + systemClockOffset), "getSkewCorrectedDate"); -// src/isSsoProfile.ts -var isSsoProfile = /* @__PURE__ */ __name((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"), "isSsoProfile"); +// src/submodules/httpAuthSchemes/utils/isClockSkewed.ts +var isClockSkewed = /* @__PURE__ */ __name((clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5, "isClockSkewed"); -// src/resolveSSOCredentials.ts -var import_client = __nccwpck_require__(912); -var import_token_providers = __nccwpck_require__(3822); -var import_property_provider = __nccwpck_require__(9721); -var import_shared_ini_file_loader = __nccwpck_require__(3507); -var SHOULD_FAIL_CREDENTIAL_CHAIN = false; -var resolveSSOCredentials = /* @__PURE__ */ __name(async ({ - ssoStartUrl, - ssoSession, - ssoAccountId, - ssoRegion, - ssoRoleName, - ssoClient, - clientConfig, - parentClientConfig, - profile, - logger -}) => { - let token; - const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; - if (ssoSession) { - try { - const _token = await (0, import_token_providers.fromSso)({ profile })(); - token = { - accessToken: _token.token, - expiresAt: new Date(_token.expiration).toISOString() - }; - } catch (e) { - throw new import_property_provider.CredentialsProviderError(e.message, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - } else { - try { - token = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoStartUrl); - } catch (e) { - throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } +// src/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.ts +var getUpdatedSystemClockOffset = /* @__PURE__ */ __name((clockTime, currentSystemClockOffset) => { + const clockTimeInMs = Date.parse(clockTime); + if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { + return clockTimeInMs - Date.now(); } - if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { - throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); + return currentSystemClockOffset; +}, "getUpdatedSystemClockOffset"); + +// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts +var throwSigningPropertyError = /* @__PURE__ */ __name((name, property) => { + if (!property) { + throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); } - const { accessToken } = token; - const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports)); - const sso = ssoClient || new SSOClient2( - Object.assign({}, clientConfig ?? {}, { - logger: clientConfig?.logger ?? parentClientConfig?.logger, - region: clientConfig?.region ?? ssoRegion - }) + return property; +}, "throwSigningPropertyError"); +var validateSigningProperties = /* @__PURE__ */ __name(async (signingProperties) => { + const context = throwSigningPropertyError( + "context", + signingProperties.context ); - let ssoResp; - try { - ssoResp = await sso.send( - new GetRoleCredentialsCommand2({ - accountId: ssoAccountId, - roleName: ssoRoleName, - accessToken - }) - ); - } catch (e) { - throw new import_property_provider.CredentialsProviderError(e, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); + const config = throwSigningPropertyError("config", signingProperties.config); + const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; + const signerFunction = throwSigningPropertyError( + "signer", + config.signer + ); + const signer = await signerFunction(authScheme); + const signingRegion = signingProperties?.signingRegion; + const signingRegionSet = signingProperties?.signingRegionSet; + const signingName = signingProperties?.signingName; + return { + config, + signer, + signingRegion, + signingRegionSet, + signingName + }; +}, "validateSigningProperties"); +var AwsSdkSigV4Signer = class { + static { + __name(this, "AwsSdkSigV4Signer"); } - const { - roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} - } = ssoResp; - if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { - throw new import_property_provider.CredentialsProviderError("SSO returns an invalid temporary credential.", { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger + async sign(httpRequest, identity, signingProperties) { + if (!import_protocol_http2.HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const validatedProps = await validateSigningProperties(signingProperties); + const { config, signer } = validatedProps; + let { signingRegion, signingName } = validatedProps; + const handlerExecutionContext = signingProperties.context; + if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { + const [first, second] = handlerExecutionContext.authSchemes; + if (first?.name === "sigv4a" && second?.name === "sigv4") { + signingRegion = second?.signingRegion ?? signingRegion; + signingName = second?.signingName ?? signingName; + } + } + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion, + signingService: signingName }); + return signedRequest; } - const credentials = { - accessKeyId, - secretAccessKey, - sessionToken, - expiration: new Date(expiration), - ...credentialScope && { credentialScope }, - ...accountId && { accountId } - }; - if (ssoSession) { - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO", "s"); - } else { - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO_LEGACY", "u"); + errorHandler(signingProperties) { + return (error) => { + const serverTime = error.ServerTime ?? getDateHeader(error.$response); + if (serverTime) { + const config = throwSigningPropertyError("config", signingProperties.config); + const initialSystemClockOffset = config.systemClockOffset; + config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); + const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; + if (clockSkewCorrected && error.$metadata) { + error.$metadata.clockSkewCorrected = true; + } + } + throw error; + }; } - return credentials; -}, "resolveSSOCredentials"); - -// src/validateSsoProfile.ts - -var validateSsoProfile = /* @__PURE__ */ __name((profile, logger) => { - 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 import_property_provider.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( - ", " - )} -Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, - { tryNextLink: false, logger } - ); + successHandler(httpResponse, signingProperties) { + const dateHeader = getDateHeader(httpResponse); + if (dateHeader) { + const config = throwSigningPropertyError("config", signingProperties.config); + config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); + } } - return profile; -}, "validateSsoProfile"); +}; +var AWSSDKSigV4Signer = AwsSdkSigV4Signer; -// src/fromSSO.ts -var fromSSO = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { - init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; - const { ssoClient } = init; - const profileName = (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }); - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - const profile = profiles[profileName]; - if (!profile) { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger }); - } - if (!isSsoProfile(profile)) { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { - logger: init.logger - }); - } - if (profile?.sso_session) { - const ssoSessions = await (0, import_shared_ini_file_loader.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 import_property_provider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { - tryNextLink: false, - logger: init.logger - }); - } - if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { - throw new import_property_provider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { - tryNextLink: false, - logger: init.logger - }); - } - profile.sso_region = session.sso_region; - profile.sso_start_url = session.sso_start_url; +// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.ts +var import_protocol_http3 = __nccwpck_require__(4418); +var AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer { + static { + __name(this, "AwsSdkSigV4ASigner"); + } + async sign(httpRequest, identity, signingProperties) { + if (!import_protocol_http3.HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); } - const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile( - profile, - init.logger - ); - return resolveSSOCredentials({ - ssoStartUrl: sso_start_url, - ssoSession: sso_session, - ssoAccountId: sso_account_id, - ssoRegion: sso_region, - ssoRoleName: sso_role_name, - ssoClient, - clientConfig: init.clientConfig, - parentClientConfig: init.parentClientConfig, - profile: profileName - }); - } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { - throw new import_property_provider.CredentialsProviderError( - 'Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', - { tryNextLink: false, logger: init.logger } + const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties( + signingProperties ); - } else { - return resolveSSOCredentials({ - ssoStartUrl, - ssoSession, - ssoAccountId, - ssoRegion, - ssoRoleName, - ssoClient, - clientConfig: init.clientConfig, - parentClientConfig: init.parentClientConfig, - profile: profileName + const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); + const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(","); + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion: multiRegionOverride, + signingService: signingName }); + return signedRequest; } -}, "fromSSO"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), +}; -/***/ 673: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.ts +var getArrayForCommaSeparatedString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [], "getArrayForCommaSeparatedString"); -"use strict"; +// src/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.ts +var getBearerTokenEnvKey = /* @__PURE__ */ __name((signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`, "getBearerTokenEnvKey"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromTokenFile = void 0; -const client_1 = __nccwpck_require__(912); -const property_provider_1 = __nccwpck_require__(9721); -const fs_1 = __nccwpck_require__(7147); -const fromWebToken_1 = __nccwpck_require__(2978); -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 () => { - init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); - const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; - const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN]; - const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; - if (!webIdentityTokenFile || !roleArn) { - throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { - logger: init.logger, - }); - } - const credentials = await (0, fromWebToken_1.fromWebToken)({ - ...init, - webIdentityToken: (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), - roleArn, - roleSessionName, - })(); - if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { - (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); +// src/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.ts +var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; +var NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; +var NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { + /** + * Retrieves auth scheme preference from environment variables + * @param env - Node process environment object + * @returns Array of auth scheme strings if preference is set, undefined otherwise + */ + environmentVariableSelector: /* @__PURE__ */ __name((env, options) => { + if (options?.signingName) { + const bearerTokenKey = getBearerTokenEnvKey(options.signingName); + if (bearerTokenKey in env) return ["httpBearerAuth"]; } - return credentials; + if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) return void 0; + return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); + }, "environmentVariableSelector"), + /** + * Retrieves auth scheme preference from config file + * @param profile - Config profile object + * @returns Array of auth scheme strings if preference is set, undefined otherwise + */ + configFileSelector: /* @__PURE__ */ __name((profile) => { + if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) return void 0; + return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); + }, "configFileSelector"), + /** + * Default auth scheme preference if not specified in environment or config + */ + default: [] }; -exports.fromTokenFile = fromTokenFile; - -/***/ }), - -/***/ 2978: -/***/ (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]; } }; +// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.ts +var import_core = __nccwpck_require__(5829); +var import_property_provider = __nccwpck_require__(9721); +var resolveAwsSdkSigV4AConfig = /* @__PURE__ */ __name((config) => { + config.sigv4aSigningRegionSet = (0, import_core.normalizeProvider)(config.sigv4aSigningRegionSet); + return config; +}, "resolveAwsSdkSigV4AConfig"); +var NODE_SIGV4A_CONFIG_OPTIONS = { + environmentVariableSelector(env) { + if (env.AWS_SIGV4A_SIGNING_REGION_SET) { + return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); } - 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 () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromWebToken = void 0; -const fromWebToken = (init) => async (awsIdentityProperties) => { - init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); - const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init; - let { roleAssumerWithWebIdentity } = init; - if (!roleAssumerWithWebIdentity) { - const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(3715))); - roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({ - ...init.clientConfig, - credentialProviderLogger: init.logger, - parentClientConfig: { - ...awsIdentityProperties?.callerClientConfig, - ...init.parentClientConfig, - }, - }, init.clientPlugins); + throw new import_property_provider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { + tryNextLink: true + }); + }, + configFileSelector(profile) { + if (profile.sigv4a_signing_region_set) { + return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); } - return roleAssumerWithWebIdentity({ - RoleArn: roleArn, - RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, - WebIdentityToken: webIdentityToken, - ProviderId: providerId, - PolicyArns: policyArns, - Policy: policy, - DurationSeconds: durationSeconds, + throw new import_property_provider.ProviderError("sigv4a_signing_region_set not set in profile.", { + tryNextLink: true }); + }, + default: void 0 }; -exports.fromWebToken = fromWebToken; - - -/***/ }), -/***/ 4331: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.ts +var import_client = __nccwpck_require__(6510); +var import_core2 = __nccwpck_require__(5829); +var import_signature_v4 = __nccwpck_require__(1528); +var resolveAwsSdkSigV4Config = /* @__PURE__ */ __name((config) => { + let inputCredentials = config.credentials; + let isUserSupplied = !!config.credentials; + let resolvedCredentials = void 0; + Object.defineProperty(config, "credentials", { + set(credentials) { + if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { + isUserSupplied = true; + } + inputCredentials = credentials; + const memoizedProvider = normalizeCredentialProvider(config, { + credentials: inputCredentials, + credentialDefaultProvider: config.credentialDefaultProvider + }); + const boundProvider = bindCallerConfig(config, memoizedProvider); + if (isUserSupplied && !boundProvider.attributed) { + resolvedCredentials = /* @__PURE__ */ __name(async (options) => boundProvider(options).then( + (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_CODE", "e") + ), "resolvedCredentials"); + resolvedCredentials.memoized = boundProvider.memoized; + resolvedCredentials.configBound = boundProvider.configBound; + resolvedCredentials.attributed = true; + } else { + resolvedCredentials = boundProvider; + } + }, + get() { + return resolvedCredentials; + }, + enumerable: true, + configurable: true + }); + config.credentials = inputCredentials; + const { + // Default for signingEscapePath + signingEscapePath = true, + // Default for systemClockOffset + systemClockOffset = config.systemClockOffset || 0, + // No default for sha256 since it is platform dependent + sha256 + } = config; + let signer; + if (config.signer) { + signer = (0, import_core2.normalizeProvider)(config.signer); + } else if (config.regionInfoProvider) { + signer = /* @__PURE__ */ __name(() => (0, import_core2.normalizeProvider)(config.region)().then( + async (region) => [ + await config.regionInfoProvider(region, { + useFipsEndpoint: await config.useFipsEndpoint(), + useDualstackEndpoint: await config.useDualstackEndpoint() + }) || {}, + region + ] + ).then(([regionInfo, region]) => { + const { signingRegion, signingService } = regionInfo; + config.signingRegion = config.signingRegion || signingRegion || region; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath + }; + const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; + return new SignerCtor(params); + }), "signer"); + } else { + signer = /* @__PURE__ */ __name(async (authScheme) => { + authScheme = Object.assign( + {}, + { + name: "sigv4", + signingName: config.signingName || config.defaultSigningName, + signingRegion: await (0, import_core2.normalizeProvider)(config.region)(), + properties: {} + }, + authScheme + ); + const signingRegion = authScheme.signingRegion; + const signingService = authScheme.signingName; + config.signingRegion = config.signingRegion || signingRegion; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath + }; + const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; + return new SignerCtor(params); + }, "signer"); } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(673), module.exports); -__reExport(index_exports, __nccwpck_require__(2978), module.exports); + const resolvedConfig = Object.assign(config, { + systemClockOffset, + signingEscapePath, + signer + }); + return resolvedConfig; +}, "resolveAwsSdkSigV4Config"); +var resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; +function normalizeCredentialProvider(config, { + credentials, + credentialDefaultProvider +}) { + let credentialsProvider; + if (credentials) { + if (!credentials?.memoized) { + credentialsProvider = (0, import_core2.memoizeIdentityProvider)(credentials, import_core2.isIdentityExpired, import_core2.doesIdentityRequireRefresh); + } else { + credentialsProvider = credentials; + } + } else { + if (credentialDefaultProvider) { + credentialsProvider = (0, import_core2.normalizeProvider)( + credentialDefaultProvider( + Object.assign({}, config, { + parentClientConfig: config + }) + ) + ); + } else { + credentialsProvider = /* @__PURE__ */ __name(async () => { + throw new Error( + "@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured." + ); + }, "credentialsProvider"); + } + } + credentialsProvider.memoized = true; + return credentialsProvider; +} +__name(normalizeCredentialProvider, "normalizeCredentialProvider"); +function bindCallerConfig(config, credentialsProvider) { + if (credentialsProvider.configBound) { + return credentialsProvider; + } + const fn = /* @__PURE__ */ __name(async (options) => credentialsProvider({ ...options, callerClientConfig: config }), "fn"); + fn.memoized = credentialsProvider.memoized; + fn.configBound = true; + return fn; +} +__name(bindCallerConfig, "bindCallerConfig"); // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 8725: +/***/ 5743: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -27768,16038 +27728,750 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/protocols/index.ts var index_exports = {}; __export(index_exports, { - getHostHeaderPlugin: () => getHostHeaderPlugin, - hostHeaderMiddleware: () => hostHeaderMiddleware, - hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions, - resolveHostHeaderConfig: () => resolveHostHeaderConfig + AwsEc2QueryProtocol: () => AwsEc2QueryProtocol, + AwsJson1_0Protocol: () => AwsJson1_0Protocol, + AwsJson1_1Protocol: () => AwsJson1_1Protocol, + AwsJsonRpcProtocol: () => AwsJsonRpcProtocol, + AwsQueryProtocol: () => AwsQueryProtocol, + AwsRestJsonProtocol: () => AwsRestJsonProtocol, + AwsRestXmlProtocol: () => AwsRestXmlProtocol, + JsonCodec: () => JsonCodec, + JsonShapeDeserializer: () => JsonShapeDeserializer, + JsonShapeSerializer: () => JsonShapeSerializer, + XmlCodec: () => XmlCodec, + XmlShapeDeserializer: () => XmlShapeDeserializer, + XmlShapeSerializer: () => XmlShapeSerializer, + _toBool: () => _toBool, + _toNum: () => _toNum, + _toStr: () => _toStr, + awsExpectUnion: () => awsExpectUnion, + loadRestJsonErrorCode: () => loadRestJsonErrorCode, + loadRestXmlErrorCode: () => loadRestXmlErrorCode, + parseJsonBody: () => parseJsonBody, + parseJsonErrorBody: () => parseJsonErrorBody, + parseXmlBody: () => parseXmlBody, + parseXmlErrorBody: () => parseXmlErrorBody }); module.exports = __toCommonJS(index_exports); -var import_protocol_http = __nccwpck_require__(4418); -function resolveHostHeaderConfig(input) { - return input; -} -__name(resolveHostHeaderConfig, "resolveHostHeaderConfig"); -var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { - if (!import_protocol_http.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); -}, "hostHeaderMiddleware"); -var hostHeaderMiddlewareOptions = { - name: "hostHeaderMiddleware", - step: "build", - priority: "low", - tags: ["HOST"], - override: true -}; -var getHostHeaderPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); - }, "applyToStack") -}), "getHostHeaderPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), -/***/ 2568: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/submodules/protocols/coercing-serializers.ts +var _toStr = /* @__PURE__ */ __name((val) => { + if (val == null) { + return val; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getLoggerPlugin: () => getLoggerPlugin, - loggerMiddleware: () => loggerMiddleware, - loggerMiddlewareOptions: () => loggerMiddlewareOptions -}); -module.exports = __toCommonJS(index_exports); - -// src/loggerMiddleware.ts -var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => { - try { - const response = await next(args); - const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; - const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; - const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; - const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; - const { $metadata, ...outputWithoutMetadata } = response.output; - logger?.info?.({ - 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 ?? context.inputFilterSensitiveLog; - logger?.error?.({ - clientName, - commandName, - input: inputFilterSensitiveLog(args.input), - error, - metadata: error.$metadata - }); - throw error; + 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); } -}, "loggerMiddleware"); -var loggerMiddlewareOptions = { - name: "loggerMiddleware", - tags: ["LOGGER"], - step: "initialize", - override: true -}; -var getLoggerPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); - }, "applyToStack") -}), "getLoggerPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 7960: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + 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 to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - addRecursionDetectionMiddlewareOptions: () => addRecursionDetectionMiddlewareOptions, - getRecursionDetectionPlugin: () => getRecursionDetectionPlugin, - recursionDetectionMiddleware: () => recursionDetectionMiddleware -}); -module.exports = __toCommonJS(index_exports); -var import_protocol_http = __nccwpck_require__(4418); -var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; -var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; -var ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; -var recursionDetectionMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { - const { request } = args; - if (!import_protocol_http.HttpRequest.isInstance(request) || options.runtime !== "node") { - return next(args); + return val; +}, "_toStr"); +var _toBool = /* @__PURE__ */ __name((val) => { + if (val == null) { + return val; } - const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME; - if (request.headers.hasOwnProperty(traceIdHeader)) { - return next(args); + if (typeof val === "number") { } - const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; - const traceId = process.env[ENV_TRACE_ID]; - const nonEmptyString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0, "nonEmptyString"); - if (nonEmptyString(functionName) && nonEmptyString(traceId)) { - request.headers[TRACE_ID_HEADER_NAME] = traceId; + 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 next({ - ...args, - request - }); -}, "recursionDetectionMiddleware"); -var addRecursionDetectionMiddlewareOptions = { - step: "build", - tags: ["RECURSION_DETECTION"], - name: "recursionDetectionMiddleware", - override: true, - priority: "low" -}; -var getRecursionDetectionPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions); - }, "applyToStack") -}), "getRecursionDetectionPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 3030: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return val; +}, "_toBool"); +var _toNum = /* @__PURE__ */ __name((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; +}, "_toNum"); -"use strict"; +// src/submodules/protocols/json/AwsJsonRpcProtocol.ts +var import_protocols = __nccwpck_require__(2241); +var import_schema3 = __nccwpck_require__(9826); +var import_util_body_length_browser = __nccwpck_require__(713); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/submodules/protocols/ConfigurableSerdeContext.ts +var SerdeContextConfig = class { + static { + __name(this, "SerdeContextConfig"); + } + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - DEFAULT_UA_APP_ID: () => DEFAULT_UA_APP_ID, - getUserAgentMiddlewareOptions: () => getUserAgentMiddlewareOptions, - getUserAgentPlugin: () => getUserAgentPlugin, - resolveUserAgentConfig: () => resolveUserAgentConfig, - userAgentMiddleware: () => userAgentMiddleware -}); -module.exports = __toCommonJS(index_exports); +// src/submodules/protocols/json/JsonShapeDeserializer.ts +var import_schema = __nccwpck_require__(9826); +var import_serde2 = __nccwpck_require__(7669); +var import_util_base64 = __nccwpck_require__(5600); -// src/configurations.ts -var import_core = __nccwpck_require__(5829); -var DEFAULT_UA_APP_ID = void 0; -function isValidUserAgentAppId(appId) { - if (appId === void 0) { - return true; - } - return typeof appId === "string" && appId.length <= 50; -} -__name(isValidUserAgentAppId, "isValidUserAgentAppId"); -function resolveUserAgentConfig(input) { - const normalizedAppIdProvider = (0, import_core.normalizeProvider)(input.userAgentAppId ?? DEFAULT_UA_APP_ID); - const { customUserAgent } = input; - return Object.assign(input, { - customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, - userAgentAppId: /* @__PURE__ */ __name(async () => { - const appId = await normalizedAppIdProvider(); - if (!isValidUserAgentAppId(appId)) { - const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; - if (typeof appId !== "string") { - logger?.warn("userAgentAppId must be a string or undefined."); - } else if (appId.length > 50) { - logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); +// src/submodules/protocols/json/jsonReviver.ts +var import_serde = __nccwpck_require__(7669); +function jsonReviver(key, value, context) { + if (context?.source) { + const numericString = context.source; + if (typeof value === "number") { + if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { + const isFractional = numericString.includes("."); + if (isFractional) { + return new import_serde.NumericValue(numericString, "bigDecimal"); + } else { + return BigInt(numericString); } } - return appId; - }, "userAgentAppId") - }); + } + } + return value; } -__name(resolveUserAgentConfig, "resolveUserAgentConfig"); +__name(jsonReviver, "jsonReviver"); -// src/user-agent-middleware.ts -var import_util_endpoints = __nccwpck_require__(1256); -var import_protocol_http = __nccwpck_require__(4418); +// src/submodules/protocols/common.ts +var import_smithy_client = __nccwpck_require__(3570); +var collectBodyString = /* @__PURE__ */ __name((streamBody, context) => (0, import_smithy_client.collectBody)(streamBody, context).then((body) => context.utf8Encoder(body)), "collectBodyString"); -// src/check-features.ts -var import_core2 = __nccwpck_require__(8078); -var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; -async function checkFeatures(context, config, args) { - const request = args.request; - if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { - (0, import_core2.setFeature)(context, "PROTOCOL_RPC_V2_CBOR", "M"); - } - if (typeof config.retryStrategy === "function") { - const retryStrategy = await config.retryStrategy(); - if (typeof retryStrategy.acquireInitialRetryToken === "function") { - if (retryStrategy.constructor?.name?.includes("Adaptive")) { - (0, import_core2.setFeature)(context, "RETRY_MODE_ADAPTIVE", "F"); - } else { - (0, import_core2.setFeature)(context, "RETRY_MODE_STANDARD", "E"); +// src/submodules/protocols/json/parseJsonBody.ts +var parseJsonBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + try { + return JSON.parse(encoded); + } catch (e) { + if (e?.name === "SyntaxError") { + Object.defineProperty(e, "$responseBodyText", { + value: encoded + }); } - } else { - (0, import_core2.setFeature)(context, "RETRY_MODE_LEGACY", "D"); + throw e; } } - if (typeof config.accountIdEndpointMode === "function") { - const endpointV2 = context.endpointV2; - if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { - (0, import_core2.setFeature)(context, "ACCOUNT_ID_ENDPOINT", "O"); + return {}; +}), "parseJsonBody"); +var parseJsonErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { + const value = await parseJsonBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}, "parseJsonErrorBody"); +var loadRestJsonErrorCode = /* @__PURE__ */ __name((output, data) => { + const findKey = /* @__PURE__ */ __name((object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()), "findKey"); + const sanitizeErrorCode = /* @__PURE__ */ __name((rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); } - switch (await config.accountIdEndpointMode?.()) { - case "disabled": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); - break; - case "preferred": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); - break; - case "required": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); - break; + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; } - } - const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; - if (identity?.$source) { - const credentials = identity; - if (credentials.accountId) { - (0, import_core2.setFeature)(context, "RESOLVED_ACCOUNT_ID", "T"); + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; } - for (const [key, value] of Object.entries(credentials.$source ?? {})) { - (0, import_core2.setFeature)(context, key, value); + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; } + return cleanValue; + }, "sanitizeErrorCode"); + const headerKey = findKey(output.headers, "x-amzn-errortype"); + if (headerKey !== void 0) { + return sanitizeErrorCode(output.headers[headerKey]); } -} -__name(checkFeatures, "checkFeatures"); - -// src/constants.ts -var USER_AGENT = "user-agent"; -var X_AMZ_USER_AGENT = "x-amz-user-agent"; -var SPACE = " "; -var UA_NAME_SEPARATOR = "/"; -var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g; -var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g; -var UA_ESCAPE_CHAR = "-"; - -// src/encode-features.ts -var BYTE_LIMIT = 1024; -function encodeFeatures(features) { - let buffer = ""; - for (const key in features) { - const val = features[key]; - if (buffer.length + val.length + 1 <= BYTE_LIMIT) { - if (buffer.length) { - buffer += "," + val; - } else { - buffer += val; - } - continue; + if (data && typeof data === "object") { + const codeKey = findKey(data, "code"); + if (codeKey && data[codeKey] !== void 0) { + return sanitizeErrorCode(data[codeKey]); + } + if (data["__type"] !== void 0) { + return sanitizeErrorCode(data["__type"]); } - break; } - return buffer; -} -__name(encodeFeatures, "encodeFeatures"); +}, "loadRestJsonErrorCode"); -// src/user-agent-middleware.ts -var userAgentMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { - const { request } = args; - if (!import_protocol_http.HttpRequest.isInstance(request)) { - return next(args); +// src/submodules/protocols/json/JsonShapeDeserializer.ts +var JsonShapeDeserializer = class extends SerdeContextConfig { + constructor(settings) { + super(); + this.settings = settings; } - const { headers } = request; - const userAgent = context?.userAgent?.map(escapeUserAgent) || []; - const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); - await checkFeatures(context, options, args); - const awsContext = context; - defaultUserAgent.push( - `m/${encodeFeatures( - Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features) - )}` - ); - const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; - const appId = await options.userAgentAppId(); - if (appId) { - defaultUserAgent.push(escapeUserAgent([`app/${appId}`])); + static { + __name(this, "JsonShapeDeserializer"); } - const prefix = (0, import_util_endpoints.getUserAgentPrefix)(); - const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE); - const normalUAValue = [ - ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), - ...customUserAgent - ].join(SPACE); - if (options.runtime !== "browser") { - if (normalUAValue) { - headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue; - } - headers[USER_AGENT] = sdkUserAgentValue; - } else { - headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; + async read(schema, data) { + return this._read( + schema, + typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext) + ); } - return next({ - ...args, - request - }); -}, "userAgentMiddleware"); -var escapeUserAgent = /* @__PURE__ */ __name((userAgentPair) => { - const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); - const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); - const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); - const prefix = name.substring(0, prefixSeparatorIndex); - let uaName = name.substring(prefixSeparatorIndex + 1); - if (prefix === "api") { - uaName = uaName.toLowerCase(); + readObject(schema, data) { + return this._read(schema, data); } - 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}`; + _read(schema, value) { + const isObject = value !== null && typeof value === "object"; + const ns = import_schema.NormalizedSchema.of(schema); + if (ns.isListSchema() && Array.isArray(value)) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._read(listMember, item)); + } + } + return out; + } else if (ns.isMapSchema() && isObject) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const [_k, _v] of Object.entries(value)) { + if (sparse || _v != null) { + out[_k] = this._read(mapMember, _v); + } + } + return out; + } else if (ns.isStructSchema() && isObject) { + const out = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; + const deserializedValue = this._read(memberSchema, value[fromKey]); + if (deserializedValue != null) { + out[memberName] = deserializedValue; + } + } + return out; } - }, ""); -}, "escapeUserAgent"); -var getUserAgentMiddlewareOptions = { - name: "getUserAgentMiddleware", - step: "build", - priority: "low", - tags: ["SET_USER_AGENT", "USER_AGENT"], - override: true -}; -var getUserAgentPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); - }, "applyToStack") -}), "getUserAgentPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 7009: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.defaultSSOOIDCHttpAuthSchemeProvider = exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(8078); -const util_middleware_1 = __nccwpck_require__(2390); -const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sso-oauth", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "CreateToken": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } + if (ns.isBlobSchema() && typeof value === "string") { + return (0, import_util_base64.fromBase64)(value); } - return options; -}; -exports.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - - -/***/ }), - -/***/ 5065: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(1256); -const util_endpoints_2 = __nccwpck_require__(5473); -const ruleset_1 = __nccwpck_require__(6723); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); -}; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - - -/***/ }), - -/***/ 6723: -/***/ ((__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://oidc-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://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://oidc-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://oidc.{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://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; -exports.ruleSet = _data; - - -/***/ }), - -/***/ 2604: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/sso-oidc/index.ts -var index_exports = {}; -__export(index_exports, { - $Command: () => import_smithy_client6.Command, - AccessDeniedException: () => AccessDeniedException, - AuthorizationPendingException: () => AuthorizationPendingException, - CreateTokenCommand: () => CreateTokenCommand, - CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog, - CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog, - ExpiredTokenException: () => ExpiredTokenException, - InternalServerException: () => InternalServerException, - InvalidClientException: () => InvalidClientException, - InvalidGrantException: () => InvalidGrantException, - InvalidRequestException: () => InvalidRequestException, - InvalidScopeException: () => InvalidScopeException, - SSOOIDC: () => SSOOIDC, - SSOOIDCClient: () => SSOOIDCClient, - SSOOIDCServiceException: () => SSOOIDCServiceException, - SlowDownException: () => SlowDownException, - UnauthorizedClientException: () => UnauthorizedClientException, - UnsupportedGrantTypeException: () => UnsupportedGrantTypeException, - __Client: () => import_smithy_client2.Client -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/sso-oidc/SSOOIDCClient.ts -var import_middleware_host_header = __nccwpck_require__(8725); -var import_middleware_logger = __nccwpck_require__(2568); -var import_middleware_recursion_detection = __nccwpck_require__(7960); -var import_middleware_user_agent = __nccwpck_require__(3030); -var import_config_resolver = __nccwpck_require__(3098); -var import_core = __nccwpck_require__(5829); -var import_middleware_content_length = __nccwpck_require__(2800); -var import_middleware_endpoint = __nccwpck_require__(2918); -var import_middleware_retry = __nccwpck_require__(6039); -var import_smithy_client2 = __nccwpck_require__(3570); -var import_httpAuthSchemeProvider = __nccwpck_require__(7009); - -// src/submodules/sso-oidc/endpoint/EndpointParameters.ts -var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "sso-oauth" - }); -}, "resolveClientEndpointParameters"); -var commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } -}; - -// src/submodules/sso-oidc/SSOOIDCClient.ts -var import_runtimeConfig = __nccwpck_require__(9750); - -// src/submodules/sso-oidc/runtimeExtensions.ts -var import_region_config_resolver = __nccwpck_require__(8859); -var import_protocol_http = __nccwpck_require__(4418); -var import_smithy_client = __nccwpck_require__(3570); - -// src/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.ts -var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return import_serde2.LazyJsonString.from(value); } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; } - }; -}, "getHttpAuthExtensionConfiguration"); -var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; -}, "resolveHttpAuthRuntimeConfig"); + if (ns.isTimestampSchema()) { + const options = this.settings.timestampFormat; + const format = options.useTrait ? ns.getSchema() === import_schema.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; + switch (format) { + case import_schema.SCHEMA.TIMESTAMP_DATE_TIME: + return (0, import_serde2.parseRfc3339DateTimeWithOffset)(value); + case import_schema.SCHEMA.TIMESTAMP_HTTP_DATE: + return (0, import_serde2.parseRfc7231DateTime)(value); + case import_schema.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + return (0, import_serde2.parseEpochTimestamp)(value); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", value); + return new Date(value); + } + } + if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + return BigInt(value); + } + if (ns.isBigDecimalSchema() && value != void 0) { + if (value instanceof import_serde2.NumericValue) { + return value; + } + return new import_serde2.NumericValue(String(value), "bigDecimal"); + } + if (ns.isNumericSchema() && typeof value === "string") { + switch (value) { + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + case "NaN": + return NaN; + } + } + return value; + } +}; -// src/submodules/sso-oidc/runtimeExtensions.ts -var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign( - (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), - (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), - (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), - getHttpAuthExtensionConfiguration(runtimeConfig) - ); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign( - runtimeConfig, - (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), - (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), - (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), - resolveHttpAuthRuntimeConfig(extensionConfiguration) - ); -}, "resolveRuntimeExtensions"); +// src/submodules/protocols/json/JsonShapeSerializer.ts +var import_schema2 = __nccwpck_require__(9826); +var import_serde4 = __nccwpck_require__(7669); +var import_serde5 = __nccwpck_require__(7669); -// src/submodules/sso-oidc/SSOOIDCClient.ts -var SSOOIDCClient = class extends import_smithy_client2.Client { +// src/submodules/protocols/json/jsonReplacer.ts +var import_serde3 = __nccwpck_require__(7669); +var NUMERIC_CONTROL_CHAR = String.fromCharCode(925); +var JsonReplacer = class { static { - __name(this, "SSOOIDCClient"); + __name(this, "JsonReplacer"); } /** - * The resolved configuration of SSOOIDCClient class. This is resolved and normalized from the {@link SSOOIDCClientConfig | constructor configuration interface}. + * Stores placeholder key to true serialized value lookup. */ - config; - constructor(...[configuration]) { - const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); - const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use( - (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials - }), "identityProviderConfigProvider") - }) - ); - this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); + values = /* @__PURE__ */ new Map(); + counter = 0; + stage = 0; + /** + * Creates a jsonReplacer function that reserves big integer and big decimal values + * for later replacement. + */ + createReplacer() { + if (this.stage === 1) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 1; + return (key, value) => { + if (value instanceof import_serde3.NumericValue) { + const v = `${NUMERIC_CONTROL_CHAR + +"nv" + this.counter++}_` + value.string; + this.values.set(`"${v}"`, value.string); + return v; + } + if (typeof value === "bigint") { + const s = value.toString(); + const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; + this.values.set(`"${v}"`, s); + return v; + } + return value; + }; } /** - * Destroy underlying resources, like sockets. It's usually not necessary to do this. - * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. - * Otherwise, sockets might stay open for quite a long time before the server terminates them. + * Replaces placeholder keys with their true values. */ - destroy() { - super.destroy(); + replaceInJson(json) { + if (this.stage === 0) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 2; + if (this.counter === 0) { + return json; + } + for (const [key, value] of this.values) { + json = json.replace(key, value); + } + return json; } }; -// src/submodules/sso-oidc/SSOOIDC.ts -var import_smithy_client7 = __nccwpck_require__(3570); - -// src/submodules/sso-oidc/commands/CreateTokenCommand.ts -var import_middleware_endpoint2 = __nccwpck_require__(2918); -var import_middleware_serde = __nccwpck_require__(1238); -var import_smithy_client6 = __nccwpck_require__(3570); - -// src/submodules/sso-oidc/models/models_0.ts -var import_smithy_client4 = __nccwpck_require__(3570); - -// src/submodules/sso-oidc/models/SSOOIDCServiceException.ts -var import_smithy_client3 = __nccwpck_require__(3570); -var SSOOIDCServiceException = class _SSOOIDCServiceException extends import_smithy_client3.ServiceException { +// src/submodules/protocols/json/JsonShapeSerializer.ts +var JsonShapeSerializer = class extends SerdeContextConfig { + constructor(settings) { + super(); + this.settings = settings; + } static { - __name(this, "SSOOIDCServiceException"); + __name(this, "JsonShapeSerializer"); } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype); + buffer; + rootSchema; + write(schema, value) { + this.rootSchema = import_schema2.NormalizedSchema.of(schema); + this.buffer = this._write(this.rootSchema, value); + } + flush() { + if (this.rootSchema?.isStructSchema() || this.rootSchema?.isDocumentSchema()) { + const replacer = new JsonReplacer(); + return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); + } + return this.buffer; + } + _write(schema, value, container) { + const isObject = value !== null && typeof value === "object"; + const ns = import_schema2.NormalizedSchema.of(schema); + if (ns.isListSchema() && Array.isArray(value)) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._write(listMember, item)); + } + } + return out; + } else if (ns.isMapSchema() && isObject) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const [_k, _v] of Object.entries(value)) { + if (sparse || _v != null) { + out[_k] = this._write(mapMember, _v); + } + } + return out; + } else if (ns.isStructSchema() && isObject) { + const out = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; + const serializableValue = this._write(memberSchema, value[memberName], ns); + if (serializableValue !== void 0) { + out[targetKey] = serializableValue; + } + } + return out; + } + if (value === null && container?.isStructSchema()) { + return void 0; + } + if (ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string")) { + if (ns === this.rootSchema) { + return value; + } + if (!this.serdeContext?.base64Encoder) { + throw new Error("Missing base64Encoder in serdeContext"); + } + return this.serdeContext?.base64Encoder(value); + } + if (ns.isTimestampSchema() && value instanceof Date) { + const options = this.settings.timestampFormat; + const format = options.useTrait ? ns.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; + switch (format) { + case import_schema2.SCHEMA.TIMESTAMP_DATE_TIME: + return value.toISOString().replace(".000Z", "Z"); + case import_schema2.SCHEMA.TIMESTAMP_HTTP_DATE: + return (0, import_serde4.dateToUtcString)(value); + case import_schema2.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + return value.getTime() / 1e3; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + return value.getTime() / 1e3; + } + } + if (ns.isNumericSchema() && typeof value === "number") { + if (Math.abs(value) === Infinity || isNaN(value)) { + return String(value); + } + } + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return import_serde5.LazyJsonString.from(value); + } + } + return value; } }; -// src/submodules/sso-oidc/models/models_0.ts -var AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException { +// src/submodules/protocols/json/JsonCodec.ts +var JsonCodec = class extends SerdeContextConfig { + constructor(settings) { + super(); + this.settings = settings; + } static { - __name(this, "AccessDeniedException"); + __name(this, "JsonCodec"); } - name = "AccessDeniedException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be access_denied.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AccessDeniedException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + createSerializer() { + const serializer = new JsonShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new JsonShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; } }; -var AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException { + +// src/submodules/protocols/json/AwsJsonRpcProtocol.ts +var AwsJsonRpcProtocol = class extends import_protocols.RpcProtocol { static { - __name(this, "AuthorizationPendingException"); + __name(this, "AwsJsonRpcProtocol"); } - name = "AuthorizationPendingException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * authorization_pending.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { + serializer; + deserializer; + codec; + constructor({ defaultNamespace }) { super({ - name: "AuthorizationPendingException", - $fault: "client", - ...opts + defaultNamespace }); - Object.setPrototypeOf(this, _AuthorizationPendingException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var CreateTokenRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.clientSecret && { clientSecret: import_smithy_client4.SENSITIVE_STRING }, - ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.codeVerifier && { codeVerifier: import_smithy_client4.SENSITIVE_STRING } -}), "CreateTokenRequestFilterSensitiveLog"); -var CreateTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.idToken && { idToken: import_smithy_client4.SENSITIVE_STRING } -}), "CreateTokenResponseFilterSensitiveLog"); -var ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException { - static { - __name(this, "ExpiredTokenException"); + this.codec = new JsonCodec({ + timestampFormat: { + useTrait: true, + default: import_schema3.SCHEMA.TIMESTAMP_EPOCH_SECONDS + }, + jsonName: false + }); + this.serializer = this.codec.createSerializer(); + this.deserializer = this.codec.createDeserializer(); } - name = "ExpiredTokenException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be expired_token.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + Object.assign(request.headers, { + "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, + "x-amz-target": (this.getJsonRpcVersion() === "1.0" ? `JsonRpc10.` : `JsonProtocol.`) + import_schema3.NormalizedSchema.of(operationSchema).getName() }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + if ((0, import_schema3.deref)(operationSchema.input) === "unit" || !request.body) { + request.body = "{}"; + } + try { + request.headers["content-length"] = String((0, import_util_body_length_browser.calculateBodyLength)(request.body)); + } catch (e) { + } + return request; } -}; -var InternalServerException = class _InternalServerException extends SSOOIDCServiceException { - static { - __name(this, "InternalServerException"); + getPayloadCodec() { + return this.codec; } - name = "InternalServerException"; - $fault = "server"; - /** - *

Single error code. For this exception the value will be server_error.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InternalServerException", - $fault: "server", - ...opts + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + let namespace = this.options.defaultNamespace; + let errorName = errorIdentifier; + if (errorIdentifier.includes("#")) { + [namespace, errorName] = errorIdentifier.split("#"); + } + const registry = import_schema3.TypeRegistry.for(namespace); + let errorSchema; + try { + errorSchema = registry.getSchema(errorIdentifier); + } catch (e) { + const baseExceptionSchema = import_schema3.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = baseExceptionSchema.ctor; + throw Object.assign(new ErrorCtor(errorName), dataObject); + } + throw new Error(errorName); + } + const ns = import_schema3.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new errorSchema.ctor(message); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().jsonName ?? name; + output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); + } + Object.assign(exception, { + $metadata: metadata, + $response: response, + $fault: ns.getMergedTraits().error, + message, + ...output }); - Object.setPrototypeOf(this, _InternalServerException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + throw exception; } }; -var InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException { + +// src/submodules/protocols/json/AwsJson1_0Protocol.ts +var AwsJson1_0Protocol = class extends AwsJsonRpcProtocol { static { - __name(this, "InvalidClientException"); + __name(this, "AwsJson1_0Protocol"); } - name = "InvalidClientException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * invalid_client.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { + constructor({ defaultNamespace }) { super({ - name: "InvalidClientException", - $fault: "client", - ...opts + defaultNamespace }); - Object.setPrototypeOf(this, _InvalidClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; } -}; -var InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException { - static { - __name(this, "InvalidGrantException"); + getShapeId() { + return "aws.protocols#awsJson1_0"; } - name = "InvalidGrantException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be invalid_grant.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidGrantException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidGrantException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + getJsonRpcVersion() { + return "1.0"; } }; -var InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException { + +// src/submodules/protocols/json/AwsJson1_1Protocol.ts +var AwsJson1_1Protocol = class extends AwsJsonRpcProtocol { static { - __name(this, "InvalidRequestException"); + __name(this, "AwsJson1_1Protocol"); } - name = "InvalidRequestException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * invalid_request.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { + constructor({ defaultNamespace }) { super({ - name: "InvalidRequestException", - $fault: "client", - ...opts + defaultNamespace }); - Object.setPrototypeOf(this, _InvalidRequestException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; } -}; -var InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException { - static { - __name(this, "InvalidScopeException"); + getShapeId() { + return "aws.protocols#awsJson1_1"; } - name = "InvalidScopeException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be invalid_scope.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidScopeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidScopeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + getJsonRpcVersion() { + return "1.1"; } }; -var SlowDownException = class _SlowDownException extends SSOOIDCServiceException { + +// src/submodules/protocols/json/AwsRestJsonProtocol.ts +var import_protocols2 = __nccwpck_require__(2241); +var import_schema4 = __nccwpck_require__(9826); +var import_util_body_length_browser2 = __nccwpck_require__(713); +var AwsRestJsonProtocol = class extends import_protocols2.HttpBindingProtocol { static { - __name(this, "SlowDownException"); + __name(this, "AwsRestJsonProtocol"); } - name = "SlowDownException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be slow_down.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { + serializer; + deserializer; + codec; + constructor({ defaultNamespace }) { super({ - name: "SlowDownException", - $fault: "client", - ...opts + defaultNamespace }); - Object.setPrototypeOf(this, _SlowDownException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + const settings = { + timestampFormat: { + useTrait: true, + default: import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS + }, + httpBindings: true, + jsonName: true + }; + this.codec = new JsonCodec(settings); + this.serializer = new import_protocols2.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new import_protocols2.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); } -}; -var UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException { - static { - __name(this, "UnauthorizedClientException"); + getShapeId() { + return "aws.protocols#restJson1"; } - name = "UnauthorizedClientException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * unauthorized_client.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnauthorizedClientException", - $fault: "client", - ...opts + getPayloadCodec() { + return this.codec; + } + setSerdeContext(serdeContext) { + this.codec.setSerdeContext(serdeContext); + super.setSerdeContext(serdeContext); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = import_schema4.NormalizedSchema.of(operationSchema.input); + const members = inputSchema.getMemberSchemas(); + if (!request.headers["content-type"]) { + const httpPayloadMember = Object.values(members).find((m) => { + return !!m.getMergedTraits().httpPayload; + }); + if (httpPayloadMember) { + const mediaType = httpPayloadMember.getMergedTraits().mediaType; + if (mediaType) { + request.headers["content-type"] = mediaType; + } else if (httpPayloadMember.isStringSchema()) { + request.headers["content-type"] = "text/plain"; + } else if (httpPayloadMember.isBlobSchema()) { + request.headers["content-type"] = "application/octet-stream"; + } else { + request.headers["content-type"] = "application/json"; + } + } else if (!inputSchema.isUnitSchema()) { + const hasBody = Object.values(members).find((m) => { + const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); + return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && httpPrefixHeaders === void 0; + }); + if (hasBody) { + request.headers["content-type"] = "application/json"; + } + } + } + if (request.headers["content-type"] && !request.body) { + request.body = "{}"; + } + if (request.body) { + try { + request.headers["content-length"] = String((0, import_util_body_length_browser2.calculateBodyLength)(request.body)); + } catch (e) { + } + } + return request; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + let namespace = this.options.defaultNamespace; + let errorName = errorIdentifier; + if (errorIdentifier.includes("#")) { + [namespace, errorName] = errorIdentifier.split("#"); + } + const registry = import_schema4.TypeRegistry.for(namespace); + let errorSchema; + try { + errorSchema = registry.getSchema(errorIdentifier); + } catch (e) { + const baseExceptionSchema = import_schema4.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = baseExceptionSchema.ctor; + throw Object.assign(new ErrorCtor(errorName), dataObject); + } + throw new Error(errorName); + } + const ns = import_schema4.NormalizedSchema.of(errorSchema); + const message = dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new errorSchema.ctor(message); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + for (const [name, member] of ns.structIterator()) { + const target = member.getMergedTraits().jsonName ?? name; + output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); + } + Object.assign(exception, { + $metadata: metadata, + $response: response, + $fault: ns.getMergedTraits().error, + message, + ...output }); - Object.setPrototypeOf(this, _UnauthorizedClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + throw exception; } }; -var UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException { + +// src/submodules/protocols/json/awsExpectUnion.ts +var import_smithy_client2 = __nccwpck_require__(3570); +var awsExpectUnion = /* @__PURE__ */ __name((value) => { + if (value == null) { + return void 0; + } + if (typeof value === "object" && "__type" in value) { + delete value.__type; + } + return (0, import_smithy_client2.expectUnion)(value); +}, "awsExpectUnion"); + +// src/submodules/protocols/query/AwsQueryProtocol.ts +var import_protocols5 = __nccwpck_require__(2241); +var import_schema7 = __nccwpck_require__(9826); +var import_util_body_length_browser3 = __nccwpck_require__(713); + +// src/submodules/protocols/xml/XmlShapeDeserializer.ts +var import_protocols3 = __nccwpck_require__(2241); +var import_schema5 = __nccwpck_require__(9826); +var import_smithy_client3 = __nccwpck_require__(3570); +var import_util_utf8 = __nccwpck_require__(1895); +var import_fast_xml_parser = __nccwpck_require__(4577); +var XmlShapeDeserializer = class extends SerdeContextConfig { + constructor(settings) { + super(); + this.settings = settings; + this.stringDeserializer = new import_protocols3.FromStringShapeDeserializer(settings); + } static { - __name(this, "UnsupportedGrantTypeException"); + __name(this, "XmlShapeDeserializer"); + } + stringDeserializer; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.stringDeserializer.setSerdeContext(serdeContext); } - name = "UnsupportedGrantTypeException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * unsupported_grant_type.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; /** - * @internal - */ - constructor(opts) { - super({ - name: "UnsupportedGrantTypeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; - -// src/submodules/sso-oidc/protocols/Aws_restJson1.ts -var import_core2 = __nccwpck_require__(8078); -var import_core3 = __nccwpck_require__(5829); -var import_smithy_client5 = __nccwpck_require__(3570); -var se_CreateTokenCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core3.requestBuilder)(input, context); - const headers = { - "content-type": "application/json" - }; - b.bp("/token"); - let body; - body = JSON.stringify( - (0, import_smithy_client5.take)(input, { - clientId: [], - clientSecret: [], - code: [], - codeVerifier: [], - deviceCode: [], - grantType: [], - redirectUri: [], - refreshToken: [], - scope: /* @__PURE__ */ __name((_) => (0, import_smithy_client5._json)(_), "scope") - }) - ); - b.m("POST").h(headers).b(body); - return b.build(); -}, "se_CreateTokenCommand"); -var de_CreateTokenCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client5.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client5.expectNonNull)((0, import_smithy_client5.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client5.take)(data, { - accessToken: import_smithy_client5.expectString, - expiresIn: import_smithy_client5.expectInt32, - idToken: import_smithy_client5.expectString, - refreshToken: import_smithy_client5.expectString, - tokenType: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - return contents; -}, "de_CreateTokenCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core2.parseJsonErrorBody)(output.body, context) - }; - const errorCode = (0, import_core2.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 - }); - } -}, "de_CommandError"); -var throwDefaultError = (0, import_smithy_client5.withBaseException)(SSOOIDCServiceException); -var de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new AccessDeniedException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_AccessDeniedExceptionRes"); -var de_AuthorizationPendingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new AuthorizationPendingException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_AuthorizationPendingExceptionRes"); -var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new ExpiredTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_ExpiredTokenExceptionRes"); -var de_InternalServerExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InternalServerException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InternalServerExceptionRes"); -var de_InvalidClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidClientException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidClientExceptionRes"); -var de_InvalidGrantExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidGrantException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidGrantExceptionRes"); -var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidRequestException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidRequestExceptionRes"); -var de_InvalidScopeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidScopeException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidScopeExceptionRes"); -var de_SlowDownExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new SlowDownException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_SlowDownExceptionRes"); -var de_UnauthorizedClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new UnauthorizedClientException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnauthorizedClientExceptionRes"); -var de_UnsupportedGrantTypeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new UnsupportedGrantTypeException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnsupportedGrantTypeExceptionRes"); -var deserializeMetadata = /* @__PURE__ */ __name((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"] -}), "deserializeMetadata"); - -// src/submodules/sso-oidc/commands/CreateTokenCommand.ts -var CreateTokenCommand = class extends import_smithy_client6.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() { - static { - __name(this, "CreateTokenCommand"); - } -}; - -// src/submodules/sso-oidc/SSOOIDC.ts -var commands = { - CreateTokenCommand -}; -var SSOOIDC = class extends SSOOIDCClient { - static { - __name(this, "SSOOIDC"); - } -}; -(0, import_smithy_client7.createAggregatedClient)(commands, SSOOIDC); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 9750: -/***/ ((__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__(3942)); -const core_1 = __nccwpck_require__(8078); -const util_user_agent_node_1 = __nccwpck_require__(5380); -const config_resolver_1 = __nccwpck_require__(3098); -const hash_node_1 = __nccwpck_require__(3081); -const middleware_retry_1 = __nccwpck_require__(6039); -const node_config_provider_1 = __nccwpck_require__(3461); -const node_http_handler_1 = __nccwpck_require__(258); -const util_body_length_node_1 = __nccwpck_require__(8075); -const util_retry_1 = __nccwpck_require__(4902); -const runtimeConfig_shared_1 = __nccwpck_require__(8319); -const smithy_client_1 = __nccwpck_require__(3570); -const util_defaults_mode_node_1 = __nccwpck_require__(2429); -const smithy_client_2 = __nccwpck_require__(3570); -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); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ 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, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, - }, config), - 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, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 8319: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(8078); -const core_2 = __nccwpck_require__(5829); -const smithy_client_1 = __nccwpck_require__(3570); -const url_parser_1 = __nccwpck_require__(4681); -const util_base64_1 = __nccwpck_require__(5600); -const util_utf8_1 = __nccwpck_require__(1895); -const httpAuthSchemeProvider_1 = __nccwpck_require__(7009); -const endpointResolver_1 = __nccwpck_require__(5065); -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 ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - serviceId: config?.serviceId ?? "SSO OIDC", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 4113: -/***/ ((__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__(8725); -const middleware_logger_1 = __nccwpck_require__(2568); -const middleware_recursion_detection_1 = __nccwpck_require__(7960); -const middleware_user_agent_1 = __nccwpck_require__(3030); -const config_resolver_1 = __nccwpck_require__(3098); -const core_1 = __nccwpck_require__(5829); -const middleware_content_length_1 = __nccwpck_require__(2800); -const middleware_endpoint_1 = __nccwpck_require__(2918); -const middleware_retry_1 = __nccwpck_require__(6039); -const smithy_client_1 = __nccwpck_require__(3570); -Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); -const httpAuthSchemeProvider_1 = __nccwpck_require__(5569); -const EndpointParameters_1 = __nccwpck_require__(3207); -const runtimeConfig_1 = __nccwpck_require__(2719); -const runtimeExtensions_1 = __nccwpck_require__(9660); -class STSClient extends smithy_client_1.Client { - config; - constructor(...[configuration]) { - const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); - const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); - const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); - const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); - const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); - 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, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - }), - })); - this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); - } - destroy() { - super.destroy(); - } -} -exports.STSClient = STSClient; - - -/***/ }), - -/***/ 2995: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - }; -}; -exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - }; -}; -exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; - - -/***/ }), - -/***/ 5569: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(8078); -const util_middleware_1 = __nccwpck_require__(2390); -const STSClient_1 = __nccwpck_require__(4113); -const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sts", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSTSHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "AssumeRoleWithWebIdentity": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; -const resolveStsAuthConfig = (input) => Object.assign(input, { - stsClientCtor: STSClient_1.STSClient, -}); -exports.resolveStsAuthConfig = resolveStsAuthConfig; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, exports.resolveStsAuthConfig)(config); - const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); - return Object.assign(config_1, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - - -/***/ }), - -/***/ 3207: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.commonParams = exports.resolveClientEndpointParameters = void 0; -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - useGlobalEndpoint: options.useGlobalEndpoint ?? false, - defaultSigningName: "sts", - }); -}; -exports.resolveClientEndpointParameters = resolveClientEndpointParameters; -exports.commonParams = { - 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" }, -}; - - -/***/ }), - -/***/ 2282: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(1256); -const util_endpoints_2 = __nccwpck_require__(5473); -const ruleset_1 = __nccwpck_require__(505); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); -}; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - - -/***/ }), - -/***/ 505: -/***/ ((__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; - - -/***/ }), - -/***/ 3715: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/sts/index.ts -var index_exports = {}; -__export(index_exports, { - AssumeRoleCommand: () => AssumeRoleCommand, - AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog, - AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand, - AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog, - AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog, - ClientInputEndpointParameters: () => import_EndpointParameters3.ClientInputEndpointParameters, - CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog, - ExpiredTokenException: () => ExpiredTokenException, - IDPCommunicationErrorException: () => IDPCommunicationErrorException, - IDPRejectedClaimException: () => IDPRejectedClaimException, - InvalidIdentityTokenException: () => InvalidIdentityTokenException, - MalformedPolicyDocumentException: () => MalformedPolicyDocumentException, - PackedPolicyTooLargeException: () => PackedPolicyTooLargeException, - RegionDisabledException: () => RegionDisabledException, - STS: () => STS, - STSServiceException: () => STSServiceException, - decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, - getDefaultRoleAssumer: () => getDefaultRoleAssumer2, - getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 -}); -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(4113), module.exports); - -// src/submodules/sts/STS.ts -var import_smithy_client6 = __nccwpck_require__(3570); - -// src/submodules/sts/commands/AssumeRoleCommand.ts -var import_middleware_endpoint = __nccwpck_require__(2918); -var import_middleware_serde = __nccwpck_require__(1238); -var import_smithy_client4 = __nccwpck_require__(3570); -var import_EndpointParameters = __nccwpck_require__(3207); - -// src/submodules/sts/models/models_0.ts -var import_smithy_client2 = __nccwpck_require__(3570); - -// src/submodules/sts/models/STSServiceException.ts -var import_smithy_client = __nccwpck_require__(3570); -var STSServiceException = class _STSServiceException extends import_smithy_client.ServiceException { - static { - __name(this, "STSServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _STSServiceException.prototype); - } -}; - -// src/submodules/sts/models/models_0.ts -var CredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client2.SENSITIVE_STRING } -}), "CredentialsFilterSensitiveLog"); -var AssumeRoleResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleResponseFilterSensitiveLog"); -var ExpiredTokenException = class _ExpiredTokenException extends STSServiceException { - static { - __name(this, "ExpiredTokenException"); - } - name = "ExpiredTokenException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - } -}; -var MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { - static { - __name(this, "MalformedPolicyDocumentException"); - } - name = "MalformedPolicyDocumentException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "MalformedPolicyDocumentException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); - } -}; -var PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { - static { - __name(this, "PackedPolicyTooLargeException"); - } - name = "PackedPolicyTooLargeException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "PackedPolicyTooLargeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); - } -}; -var RegionDisabledException = class _RegionDisabledException extends STSServiceException { - static { - __name(this, "RegionDisabledException"); - } - name = "RegionDisabledException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "RegionDisabledException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _RegionDisabledException.prototype); - } -}; -var IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { - static { - __name(this, "IDPRejectedClaimException"); - } - name = "IDPRejectedClaimException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "IDPRejectedClaimException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); - } -}; -var InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { - static { - __name(this, "InvalidIdentityTokenException"); - } - name = "InvalidIdentityTokenException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidIdentityTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); - } -}; -var AssumeRoleWithWebIdentityRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client2.SENSITIVE_STRING } -}), "AssumeRoleWithWebIdentityRequestFilterSensitiveLog"); -var AssumeRoleWithWebIdentityResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleWithWebIdentityResponseFilterSensitiveLog"); -var IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { - static { - __name(this, "IDPCommunicationErrorException"); - } - name = "IDPCommunicationErrorException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "IDPCommunicationErrorException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); - } -}; - -// src/submodules/sts/protocols/Aws_query.ts -var import_core = __nccwpck_require__(8078); -var import_protocol_http = __nccwpck_require__(4418); -var import_smithy_client3 = __nccwpck_require__(3570); -var se_AssumeRoleCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleRequest(input, context), - [_A]: _AR, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleCommand"); -var se_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleWithWebIdentityRequest(input, context), - [_A]: _ARWWI, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleWithWebIdentityCommand"); -var de_AssumeRoleCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleResponse(data.AssumeRoleResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleCommand"); -var de_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleWithWebIdentityCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core.parseXmlErrorBody)(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); - 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); - default: - const parsedBody = parsedOutput.body; - return throwDefaultError({ - output, - parsedBody: parsedBody.Error, - errorCode - }); - } -}, "de_CommandError"); -var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_ExpiredTokenException(body.Error, context); - const exception = new ExpiredTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_ExpiredTokenExceptionRes"); -var de_IDPCommunicationErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_IDPCommunicationErrorException(body.Error, context); - const exception = new IDPCommunicationErrorException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_IDPCommunicationErrorExceptionRes"); -var de_IDPRejectedClaimExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_IDPRejectedClaimException(body.Error, context); - const exception = new IDPRejectedClaimException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_IDPRejectedClaimExceptionRes"); -var de_InvalidIdentityTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_InvalidIdentityTokenException(body.Error, context); - const exception = new InvalidIdentityTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_InvalidIdentityTokenExceptionRes"); -var de_MalformedPolicyDocumentExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_MalformedPolicyDocumentException(body.Error, context); - const exception = new MalformedPolicyDocumentException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_MalformedPolicyDocumentExceptionRes"); -var de_PackedPolicyTooLargeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_PackedPolicyTooLargeException(body.Error, context); - const exception = new PackedPolicyTooLargeException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_PackedPolicyTooLargeExceptionRes"); -var de_RegionDisabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_RegionDisabledException(body.Error, context); - const exception = new RegionDisabledException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_RegionDisabledExceptionRes"); -var se_AssumeRoleRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; - } - if (input[_RSN] != null) { - entries[_RSN] = input[_RSN]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - if (input[_T] != null) { - const memberEntries = se_tagListType(input[_T], context); - if (input[_T]?.length === 0) { - entries.Tags = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `Tags.${key}`; - entries[loc] = value; - }); - } - if (input[_TTK] != null) { - const memberEntries = se_tagKeyListType(input[_TTK], context); - if (input[_TTK]?.length === 0) { - entries.TransitiveTagKeys = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `TransitiveTagKeys.${key}`; - entries[loc] = value; - }); - } - if (input[_EI] != null) { - entries[_EI] = input[_EI]; - } - if (input[_SN] != null) { - entries[_SN] = input[_SN]; - } - if (input[_TC] != null) { - entries[_TC] = input[_TC]; - } - if (input[_SI] != null) { - entries[_SI] = input[_SI]; - } - if (input[_PC] != null) { - const memberEntries = se_ProvidedContextsListType(input[_PC], context); - if (input[_PC]?.length === 0) { - entries.ProvidedContexts = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `ProvidedContexts.${key}`; - entries[loc] = value; - }); - } - return entries; -}, "se_AssumeRoleRequest"); -var se_AssumeRoleWithWebIdentityRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; - } - if (input[_RSN] != null) { - entries[_RSN] = input[_RSN]; - } - if (input[_WIT] != null) { - entries[_WIT] = input[_WIT]; - } - if (input[_PI] != null) { - entries[_PI] = input[_PI]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - return entries; -}, "se_AssumeRoleWithWebIdentityRequest"); -var se_policyDescriptorListType = /* @__PURE__ */ __name((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; -}, "se_policyDescriptorListType"); -var se_PolicyDescriptorType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_a] != null) { - entries[_a] = input[_a]; - } - return entries; -}, "se_PolicyDescriptorType"); -var se_ProvidedContext = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_PAr] != null) { - entries[_PAr] = input[_PAr]; - } - if (input[_CA] != null) { - entries[_CA] = input[_CA]; - } - return entries; -}, "se_ProvidedContext"); -var se_ProvidedContextsListType = /* @__PURE__ */ __name((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; -}, "se_ProvidedContextsListType"); -var se_Tag = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_K] != null) { - entries[_K] = input[_K]; - } - if (input[_Va] != null) { - entries[_Va] = input[_Va]; - } - return entries; -}, "se_Tag"); -var se_tagKeyListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; - } - entries[`member.${counter}`] = entry; - counter++; - } - return entries; -}, "se_tagKeyListType"); -var se_tagListType = /* @__PURE__ */ __name((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; -}, "se_tagListType"); -var de_AssumedRoleUser = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_ARI] != null) { - contents[_ARI] = (0, import_smithy_client3.expectString)(output[_ARI]); - } - if (output[_Ar] != null) { - contents[_Ar] = (0, import_smithy_client3.expectString)(output[_Ar]); - } - return contents; -}, "de_AssumedRoleUser"); -var de_AssumeRoleResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); - } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); - } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); - } - return contents; -}, "de_AssumeRoleResponse"); -var de_AssumeRoleWithWebIdentityResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_SFWIT] != null) { - contents[_SFWIT] = (0, import_smithy_client3.expectString)(output[_SFWIT]); - } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); - } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); - } - if (output[_Pr] != null) { - contents[_Pr] = (0, import_smithy_client3.expectString)(output[_Pr]); - } - if (output[_Au] != null) { - contents[_Au] = (0, import_smithy_client3.expectString)(output[_Au]); - } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); - } - return contents; -}, "de_AssumeRoleWithWebIdentityResponse"); -var de_Credentials = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_AKI] != null) { - contents[_AKI] = (0, import_smithy_client3.expectString)(output[_AKI]); - } - if (output[_SAK] != null) { - contents[_SAK] = (0, import_smithy_client3.expectString)(output[_SAK]); - } - if (output[_ST] != null) { - contents[_ST] = (0, import_smithy_client3.expectString)(output[_ST]); - } - if (output[_E] != null) { - contents[_E] = (0, import_smithy_client3.expectNonNull)((0, import_smithy_client3.parseRfc3339DateTimeWithOffset)(output[_E])); - } - return contents; -}, "de_Credentials"); -var de_ExpiredTokenException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_ExpiredTokenException"); -var de_IDPCommunicationErrorException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_IDPCommunicationErrorException"); -var de_IDPRejectedClaimException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_IDPRejectedClaimException"); -var de_InvalidIdentityTokenException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_InvalidIdentityTokenException"); -var de_MalformedPolicyDocumentException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_MalformedPolicyDocumentException"); -var de_PackedPolicyTooLargeException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_PackedPolicyTooLargeException"); -var de_RegionDisabledException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_RegionDisabledException"); -var deserializeMetadata = /* @__PURE__ */ __name((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"] -}), "deserializeMetadata"); -var throwDefaultError = (0, import_smithy_client3.withBaseException)(STSServiceException); -var buildHttpRpcRequest = /* @__PURE__ */ __name(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 !== void 0) { - contents.hostname = resolvedHostname; - } - if (body !== void 0) { - contents.body = body; - } - return new import_protocol_http.HttpRequest(contents); -}, "buildHttpRpcRequest"); -var SHARED_HEADERS = { - "content-type": "application/x-www-form-urlencoded" -}; -var _ = "2011-06-15"; -var _A = "Action"; -var _AKI = "AccessKeyId"; -var _AR = "AssumeRole"; -var _ARI = "AssumedRoleId"; -var _ARU = "AssumedRoleUser"; -var _ARWWI = "AssumeRoleWithWebIdentity"; -var _Ar = "Arn"; -var _Au = "Audience"; -var _C = "Credentials"; -var _CA = "ContextAssertion"; -var _DS = "DurationSeconds"; -var _E = "Expiration"; -var _EI = "ExternalId"; -var _K = "Key"; -var _P = "Policy"; -var _PA = "PolicyArns"; -var _PAr = "ProviderArn"; -var _PC = "ProvidedContexts"; -var _PI = "ProviderId"; -var _PPS = "PackedPolicySize"; -var _Pr = "Provider"; -var _RA = "RoleArn"; -var _RSN = "RoleSessionName"; -var _SAK = "SecretAccessKey"; -var _SFWIT = "SubjectFromWebIdentityToken"; -var _SI = "SourceIdentity"; -var _SN = "SerialNumber"; -var _ST = "SessionToken"; -var _T = "Tags"; -var _TC = "TokenCode"; -var _TTK = "TransitiveTagKeys"; -var _V = "Version"; -var _Va = "Value"; -var _WIT = "WebIdentityToken"; -var _a = "arn"; -var _m = "message"; -var buildFormUrlencodedString = /* @__PURE__ */ __name((formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client3.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client3.extendedEncodeURIComponent)(value)).join("&"), "buildFormUrlencodedString"); -var loadQueryErrorCode = /* @__PURE__ */ __name((output, data) => { - if (data.Error?.Code !== void 0) { - return data.Error.Code; - } - if (output.statusCode == 404) { - return "NotFound"; - } -}, "loadQueryErrorCode"); - -// src/submodules/sts/commands/AssumeRoleCommand.ts -var AssumeRoleCommand = class extends import_smithy_client4.Command.classBuilder().ep(import_EndpointParameters.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() { - static { - __name(this, "AssumeRoleCommand"); - } -}; - -// src/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.ts -var import_middleware_endpoint2 = __nccwpck_require__(2918); -var import_middleware_serde2 = __nccwpck_require__(1238); -var import_smithy_client5 = __nccwpck_require__(3570); -var import_EndpointParameters2 = __nccwpck_require__(3207); -var AssumeRoleWithWebIdentityCommand = class extends import_smithy_client5.Command.classBuilder().ep(import_EndpointParameters2.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde2.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() { - static { - __name(this, "AssumeRoleWithWebIdentityCommand"); - } -}; - -// src/submodules/sts/STS.ts -var import_STSClient = __nccwpck_require__(4113); -var commands = { - AssumeRoleCommand, - AssumeRoleWithWebIdentityCommand -}; -var STS = class extends import_STSClient.STSClient { - static { - __name(this, "STS"); - } -}; -(0, import_smithy_client6.createAggregatedClient)(commands, STS); - -// src/submodules/sts/index.ts -var import_EndpointParameters3 = __nccwpck_require__(3207); - -// src/submodules/sts/defaultStsRoleAssumers.ts -var import_client = __nccwpck_require__(912); -var ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; -var getAccountIdFromAssumedRoleUser = /* @__PURE__ */ __name((assumedRoleUser) => { - if (typeof assumedRoleUser?.Arn === "string") { - const arnComponents = assumedRoleUser.Arn.split(":"); - if (arnComponents.length > 4 && arnComponents[4] !== "") { - return arnComponents[4]; - } - } - return void 0; -}, "getAccountIdFromAssumedRoleUser"); -var resolveRegion = /* @__PURE__ */ __name(async (_region, _parentRegion, credentialProviderLogger) => { - const region = typeof _region === "function" ? await _region() : _region; - const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; - credentialProviderLogger?.debug?.( - "@aws-sdk/client-sts::resolveRegion", - "accepting first of:", - `${region} (provider)`, - `${parentRegion} (parent client)`, - `${ASSUME_ROLE_DEFAULT_REGION} (STS default)` - ); - return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION; -}, "resolveRegion"); -var getDefaultRoleAssumer = /* @__PURE__ */ __name((stsOptions, STSClient3) => { - let stsClient; - let closureSourceCreds; - return async (sourceCreds, params) => { - closureSourceCreds = sourceCreds; - if (!stsClient) { - const { - logger = stsOptions?.parentClientConfig?.logger, - region, - requestHandler = stsOptions?.parentClientConfig?.requestHandler, - credentialProviderLogger - } = stsOptions; - const resolvedRegion = await resolveRegion( - region, - stsOptions?.parentClientConfig?.region, - credentialProviderLogger - ); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient3({ - profile: stsOptions?.parentClientConfig?.profile, - // A hack to make sts client uses the credential in current closure. - credentialDefaultProvider: /* @__PURE__ */ __name(() => async () => closureSourceCreds, "credentialDefaultProvider"), - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger - }); - } - const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleCommand(params)); - if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); - const credentials = { - accessKeyId: Credentials2.AccessKeyId, - secretAccessKey: Credentials2.SecretAccessKey, - sessionToken: Credentials2.SessionToken, - expiration: Credentials2.Expiration, - // TODO(credentialScope): access normally when shape is updated. - ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); - return credentials; - }; -}, "getDefaultRoleAssumer"); -var getDefaultRoleAssumerWithWebIdentity = /* @__PURE__ */ __name((stsOptions, STSClient3) => { - let stsClient; - return async (params) => { - if (!stsClient) { - const { - logger = stsOptions?.parentClientConfig?.logger, - region, - requestHandler = stsOptions?.parentClientConfig?.requestHandler, - credentialProviderLogger - } = stsOptions; - const resolvedRegion = await resolveRegion( - region, - stsOptions?.parentClientConfig?.region, - credentialProviderLogger - ); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient3({ - profile: stsOptions?.parentClientConfig?.profile, - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger - }); - } - const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); - if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); - const credentials = { - accessKeyId: Credentials2.AccessKeyId, - secretAccessKey: Credentials2.SecretAccessKey, - sessionToken: Credentials2.SessionToken, - expiration: Credentials2.Expiration, - // TODO(credentialScope): access normally when shape is updated. - ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, - ...accountId && { accountId } - }; - if (accountId) { - (0, import_client.setCredentialFeature)(credentials, "RESOLVED_ACCOUNT_ID", "T"); - } - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); - return credentials; - }; -}, "getDefaultRoleAssumerWithWebIdentity"); -var isH2 = /* @__PURE__ */ __name((requestHandler) => { - return requestHandler?.metadata?.handlerProtocol === "h2"; -}, "isH2"); - -// src/submodules/sts/defaultRoleAssumers.ts -var import_STSClient2 = __nccwpck_require__(4113); -var getCustomizableStsClientCtor = /* @__PURE__ */ __name((baseCtor, customizations) => { - if (!customizations) return baseCtor; - else - return class CustomizableSTSClient extends baseCtor { - static { - __name(this, "CustomizableSTSClient"); - } - constructor(config) { - super(config); - for (const customization of customizations) { - this.middlewareStack.use(customization); - } - } - }; -}, "getCustomizableStsClientCtor"); -var getDefaultRoleAssumer2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumer"); -var getDefaultRoleAssumerWithWebIdentity2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumerWithWebIdentity"); -var decorateDefaultCredentialProvider = /* @__PURE__ */ __name((provider) => (input) => provider({ - roleAssumer: getDefaultRoleAssumer2(input), - roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input), - ...input -}), "decorateDefaultCredentialProvider"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 2719: -/***/ ((__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__(3942)); -const core_1 = __nccwpck_require__(8078); -const util_user_agent_node_1 = __nccwpck_require__(5380); -const config_resolver_1 = __nccwpck_require__(3098); -const core_2 = __nccwpck_require__(5829); -const hash_node_1 = __nccwpck_require__(3081); -const middleware_retry_1 = __nccwpck_require__(6039); -const node_config_provider_1 = __nccwpck_require__(3461); -const node_http_handler_1 = __nccwpck_require__(258); -const util_body_length_node_1 = __nccwpck_require__(8075); -const util_retry_1 = __nccwpck_require__(4902); -const runtimeConfig_shared_1 = __nccwpck_require__(993); -const smithy_client_1 = __nccwpck_require__(3570); -const util_defaults_mode_node_1 = __nccwpck_require__(2429); -const smithy_client_2 = __nccwpck_require__(3570); -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); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || - (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, - }, config), - 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, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 993: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(8078); -const core_2 = __nccwpck_require__(5829); -const smithy_client_1 = __nccwpck_require__(3570); -const url_parser_1 = __nccwpck_require__(4681); -const util_base64_1 = __nccwpck_require__(5600); -const util_utf8_1 = __nccwpck_require__(1895); -const httpAuthSchemeProvider_1 = __nccwpck_require__(5569); -const endpointResolver_1 = __nccwpck_require__(2282); -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 ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - 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; - - -/***/ }), - -/***/ 9660: -/***/ ((__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__(8859); -const protocol_http_1 = __nccwpck_require__(4418); -const smithy_client_1 = __nccwpck_require__(3570); -const httpAuthExtensionConfiguration_1 = __nccwpck_require__(2995); -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); -}; -exports.resolveRuntimeExtensions = resolveRuntimeExtensions; - - -/***/ }), - -/***/ 8859: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, - NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, - REGION_ENV_NAME: () => REGION_ENV_NAME, - REGION_INI_NAME: () => REGION_INI_NAME, - getAwsRegionExtensionConfiguration: () => getAwsRegionExtensionConfiguration, - resolveAwsRegionExtensionConfiguration: () => resolveAwsRegionExtensionConfiguration, - resolveRegionConfig: () => resolveRegionConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/extensions/index.ts -var getAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setRegion(region) { - runtimeConfig.region = region; - }, - region() { - return runtimeConfig.region; - } - }; -}, "getAwsRegionExtensionConfiguration"); -var resolveAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => { - return { - region: awsRegionExtensionConfiguration.region() - }; -}, "resolveAwsRegionExtensionConfiguration"); - -// src/regionConfig/config.ts -var REGION_ENV_NAME = "AWS_REGION"; -var REGION_INI_NAME = "region"; -var NODE_REGION_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => env[REGION_ENV_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"), - default: /* @__PURE__ */ __name(() => { - throw new Error("Region is missing"); - }, "default") -}; -var NODE_REGION_CONFIG_FILE_OPTIONS = { - preferredFile: "credentials" -}; - -// src/regionConfig/isFipsRegion.ts -var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); - -// src/regionConfig/getRealRegion.ts -var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); - -// src/regionConfig/resolveRegionConfig.ts -var resolveRegionConfig = /* @__PURE__ */ __name((input) => { - const { region, useFipsEndpoint } = input; - if (!region) { - throw new Error("Region is missing"); - } - return Object.assign(input, { - region: /* @__PURE__ */ __name(async () => { - if (typeof region === "string") { - return getRealRegion(region); - } - const providedRegion = await region(); - return getRealRegion(providedRegion); - }, "region"), - useFipsEndpoint: /* @__PURE__ */ __name(async () => { - const providedRegion = typeof region === "string" ? region : await region(); - if (isFipsRegion(providedRegion)) { - return true; - } - return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); - }, "useFipsEndpoint") - }); -}, "resolveRegionConfig"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 3822: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromEnvSigningName: () => fromEnvSigningName, - fromSso: () => fromSso, - fromStatic: () => fromStatic, - nodeProvider: () => nodeProvider -}); -module.exports = __toCommonJS(index_exports); - -// src/fromEnvSigningName.ts -var import_client = __nccwpck_require__(912); -var import_httpAuthSchemes = __nccwpck_require__(5948); -var import_property_provider = __nccwpck_require__(9721); -var fromEnvSigningName = /* @__PURE__ */ __name(({ logger, signingName } = {}) => async () => { - logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); - if (!signingName) { - throw new import_property_provider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); - } - const bearerTokenKey = (0, import_httpAuthSchemes.getBearerTokenEnvKey)(signingName); - if (!(bearerTokenKey in process.env)) { - throw new import_property_provider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); - } - const token = { token: process.env[bearerTokenKey] }; - (0, import_client.setTokenFeature)(token, "BEARER_SERVICE_ENV_VARS", "3"); - return token; -}, "fromEnvSigningName"); - -// src/fromSso.ts - - - -// src/constants.ts -var EXPIRE_WINDOW_MS = 5 * 60 * 1e3; -var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; - -// src/getSsoOidcClient.ts -var getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion, init = {}) => { - const { SSOOIDCClient } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(2604))); - const ssoOidcClient = new SSOOIDCClient( - Object.assign({}, init.clientConfig ?? {}, { - region: ssoRegion ?? init.clientConfig?.region, - logger: init.clientConfig?.logger ?? init.parentClientConfig?.logger - }) - ); - return ssoOidcClient; -}, "getSsoOidcClient"); - -// src/getNewSsoOidcToken.ts -var getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion, init = {}) => { - const { CreateTokenCommand } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(2604))); - const ssoOidcClient = await getSsoOidcClient(ssoRegion, init); - return ssoOidcClient.send( - new CreateTokenCommand({ - clientId: ssoToken.clientId, - clientSecret: ssoToken.clientSecret, - refreshToken: ssoToken.refreshToken, - grantType: "refresh_token" - }) - ); -}, "getNewSsoOidcToken"); - -// src/validateTokenExpiry.ts - -var validateTokenExpiry = /* @__PURE__ */ __name((token) => { - if (token.expiration && token.expiration.getTime() < Date.now()) { - throw new import_property_provider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); - } -}, "validateTokenExpiry"); - -// src/validateTokenKey.ts - -var validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => { - if (typeof value === "undefined") { - throw new import_property_provider.TokenProviderError( - `Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, - false - ); - } -}, "validateTokenKey"); - -// src/writeSSOTokenToFile.ts -var import_shared_ini_file_loader = __nccwpck_require__(3507); -var import_fs = __nccwpck_require__(7147); -var { writeFile } = import_fs.promises; -var writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => { - const tokenFilepath = (0, import_shared_ini_file_loader.getSSOTokenFilepath)(id); - const tokenString = JSON.stringify(ssoToken, null, 2); - return writeFile(tokenFilepath, tokenString); -}, "writeSSOTokenToFile"); - -// src/fromSso.ts -var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0); -var fromSso = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { - const init = { - ..._init, - parentClientConfig: { - ...callerClientConfig, - ..._init.parentClientConfig - } - }; - init.logger?.debug("@aws-sdk/token-providers - fromSso"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - const profileName = (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }); - const profile = profiles[profileName]; - if (!profile) { - throw new import_property_provider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); - } else if (!profile["sso_session"]) { - throw new import_property_provider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); - } - const ssoSessionName = profile["sso_session"]; - const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init); - const ssoSession = ssoSessions[ssoSessionName]; - if (!ssoSession) { - throw new import_property_provider.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 import_property_provider.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, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoSessionName); - } catch (e) { - throw new import_property_provider.TokenProviderError( - `The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, - false - ); - } - validateTokenKey("accessToken", ssoToken.accessToken); - validateTokenKey("expiresAt", ssoToken.expiresAt); - const { accessToken, expiresAt } = ssoToken; - const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; - if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { - return existingToken; - } - if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) { - validateTokenExpiry(existingToken); - return existingToken; - } - validateTokenKey("clientId", ssoToken.clientId, true); - validateTokenKey("clientSecret", ssoToken.clientSecret, true); - validateTokenKey("refreshToken", ssoToken.refreshToken, true); - try { - lastRefreshAttemptTime.setTime(Date.now()); - const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init); - validateTokenKey("accessToken", newSsoOidcToken.accessToken); - validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); - const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3); - try { - await writeSSOTokenToFile(ssoSessionName, { - ...ssoToken, - accessToken: newSsoOidcToken.accessToken, - expiresAt: newTokenExpiration.toISOString(), - refreshToken: newSsoOidcToken.refreshToken - }); - } catch (error) { - } - return { - token: newSsoOidcToken.accessToken, - expiration: newTokenExpiration - }; - } catch (error) { - validateTokenExpiry(existingToken); - return existingToken; - } -}, "fromSso"); - -// src/fromStatic.ts - -var fromStatic = /* @__PURE__ */ __name(({ token, logger }) => async () => { - logger?.debug("@aws-sdk/token-providers - fromStatic"); - if (!token || !token.token) { - throw new import_property_provider.TokenProviderError(`Please pass a valid token to fromStatic`, false); - } - return token; -}, "fromStatic"); - -// src/nodeProvider.ts - -var nodeProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( - (0, import_property_provider.chain)(fromSso(init), async () => { - throw new import_property_provider.TokenProviderError("Could not load token from any providers", false); - }), - (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5, - (token) => token.expiration !== void 0 -), "nodeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 1256: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - ConditionObject: () => import_util_endpoints.ConditionObject, - DeprecatedObject: () => import_util_endpoints.DeprecatedObject, - EndpointError: () => import_util_endpoints.EndpointError, - EndpointObject: () => import_util_endpoints.EndpointObject, - EndpointObjectHeaders: () => import_util_endpoints.EndpointObjectHeaders, - EndpointObjectProperties: () => import_util_endpoints.EndpointObjectProperties, - EndpointParams: () => import_util_endpoints.EndpointParams, - EndpointResolverOptions: () => import_util_endpoints.EndpointResolverOptions, - EndpointRuleObject: () => import_util_endpoints.EndpointRuleObject, - ErrorRuleObject: () => import_util_endpoints.ErrorRuleObject, - EvaluateOptions: () => import_util_endpoints.EvaluateOptions, - Expression: () => import_util_endpoints.Expression, - FunctionArgv: () => import_util_endpoints.FunctionArgv, - FunctionObject: () => import_util_endpoints.FunctionObject, - FunctionReturn: () => import_util_endpoints.FunctionReturn, - ParameterObject: () => import_util_endpoints.ParameterObject, - ReferenceObject: () => import_util_endpoints.ReferenceObject, - ReferenceRecord: () => import_util_endpoints.ReferenceRecord, - RuleSetObject: () => import_util_endpoints.RuleSetObject, - RuleSetRules: () => import_util_endpoints.RuleSetRules, - TreeRuleObject: () => import_util_endpoints.TreeRuleObject, - awsEndpointFunctions: () => awsEndpointFunctions, - getUserAgentPrefix: () => getUserAgentPrefix, - isIpAddress: () => import_util_endpoints.isIpAddress, - partition: () => partition, - resolveDefaultAwsRegionalEndpointsConfig: () => resolveDefaultAwsRegionalEndpointsConfig, - resolveEndpoint: () => import_util_endpoints.resolveEndpoint, - setPartitionInfo: () => setPartitionInfo, - toEndpointV1: () => toEndpointV1, - useDefaultPartitionInfo: () => useDefaultPartitionInfo -}); -module.exports = __toCommonJS(index_exports); - -// src/aws.ts - - -// src/lib/aws/isVirtualHostableS3Bucket.ts - - -// src/lib/isIpAddress.ts -var import_util_endpoints = __nccwpck_require__(5473); - -// src/lib/aws/isVirtualHostableS3Bucket.ts -var isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => { - if (allowSubDomains) { - for (const label of value.split(".")) { - if (!isVirtualHostableS3Bucket(label)) { - return false; - } - } - return true; - } - if (!(0, import_util_endpoints.isValidHostLabel)(value)) { - return false; - } - if (value.length < 3 || value.length > 63) { - return false; - } - if (value !== value.toLowerCase()) { - return false; - } - if ((0, import_util_endpoints.isIpAddress)(value)) { - return false; - } - return true; -}, "isVirtualHostableS3Bucket"); - -// src/lib/aws/parseArn.ts -var ARN_DELIMITER = ":"; -var RESOURCE_DELIMITER = "/"; -var parseArn = /* @__PURE__ */ __name((value) => { - const segments = value.split(ARN_DELIMITER); - if (segments.length < 6) return null; - const [arn, partition2, service, region, accountId, ...resourcePath] = segments; - if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null; - const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); - return { - partition: partition2, - service, - region, - accountId, - resourceId - }; -}, "parseArn"); - -// src/lib/aws/partitions.json -var partitions_default = { - 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|mx)\\-\\w+\\-\\d+$", - regions: { - "af-south-1": { - description: "Africa (Cape Town)" - }, - "ap-east-1": { - description: "Asia Pacific (Hong Kong)" - }, - "ap-east-2": { - description: "Asia Pacific (Taipei)" - }, - "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)" - }, - "ap-southeast-5": { - description: "Asia Pacific (Malaysia)" - }, - "ap-southeast-7": { - description: "Asia Pacific (Thailand)" - }, - "aws-global": { - description: "AWS Standard global region" - }, - "ca-central-1": { - description: "Canada (Central)" - }, - "ca-west-1": { - description: "Canada West (Calgary)" - }, - "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)" - }, - "mx-central-1": { - description: "Mexico (Central)" - }, - "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: { - "aws-iso-e-global": { - description: "AWS ISOE (Europe) global region" - }, - "eu-isoe-west-1": { - description: "EU ISOE West" - } - } - }, { - 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: { - "aws-iso-f-global": { - description: "AWS ISOF global region" - }, - "us-isof-east-1": { - description: "US ISOF EAST" - }, - "us-isof-south-1": { - description: "US ISOF SOUTH" - } - } - }, { - id: "aws-eusc", - outputs: { - dnsSuffix: "amazonaws.eu", - dualStackDnsSuffix: "amazonaws.eu", - implicitGlobalRegion: "eusc-de-east-1", - name: "aws-eusc", - supportsDualStack: false, - supportsFIPS: true - }, - regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", - regions: { - "eusc-de-east-1": { - description: "EU (Germany)" - } - } - }], - version: "1.1" -}; - -// src/lib/aws/partition.ts -var selectedPartitionsInfo = partitions_default; -var selectedUserAgentPrefix = ""; -var partition = /* @__PURE__ */ __name((value) => { - const { partitions } = selectedPartitionsInfo; - for (const partition2 of partitions) { - const { regions, outputs } = partition2; - for (const [region, regionData] of Object.entries(regions)) { - if (region === value) { - return { - ...outputs, - ...regionData - }; - } - } - } - for (const partition2 of partitions) { - const { regionRegex, outputs } = partition2; - if (new RegExp(regionRegex).test(value)) { - return { - ...outputs - }; - } - } - const DEFAULT_PARTITION = partitions.find((partition2) => partition2.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 - }; -}, "partition"); -var setPartitionInfo = /* @__PURE__ */ __name((partitionsInfo, userAgentPrefix = "") => { - selectedPartitionsInfo = partitionsInfo; - selectedUserAgentPrefix = userAgentPrefix; -}, "setPartitionInfo"); -var useDefaultPartitionInfo = /* @__PURE__ */ __name(() => { - setPartitionInfo(partitions_default, ""); -}, "useDefaultPartitionInfo"); -var getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix"); - -// src/aws.ts -var awsEndpointFunctions = { - isVirtualHostableS3Bucket, - parseArn, - partition -}; -import_util_endpoints.customEndpointFunctions.aws = awsEndpointFunctions; - -// src/resolveDefaultAwsRegionalEndpointsConfig.ts -var import_url_parser = __nccwpck_require__(4681); -var resolveDefaultAwsRegionalEndpointsConfig = /* @__PURE__ */ __name((input) => { - if (typeof input.endpointProvider !== "function") { - throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); - } - const { endpoint } = input; - if (endpoint === void 0) { - input.endpoint = async () => { - return toEndpointV1( - input.endpointProvider( - { - Region: typeof input.region === "function" ? await input.region() : input.region, - UseDualStack: typeof input.useDualstackEndpoint === "function" ? await input.useDualstackEndpoint() : input.useDualstackEndpoint, - UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, - Endpoint: void 0 - }, - { logger: input.logger } - ) - ); - }; - } - return input; -}, "resolveDefaultAwsRegionalEndpointsConfig"); -var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => (0, import_url_parser.parseUrl)(endpoint.url), "toEndpointV1"); - -// src/resolveEndpoint.ts - - -// src/types/EndpointError.ts - - -// src/types/EndpointRuleObject.ts - - -// src/types/ErrorRuleObject.ts - - -// src/types/RuleSetObject.ts - - -// src/types/TreeRuleObject.ts - - -// src/types/shared.ts - -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 5380: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - NODE_APP_ID_CONFIG_OPTIONS: () => NODE_APP_ID_CONFIG_OPTIONS, - UA_APP_ID_ENV_NAME: () => UA_APP_ID_ENV_NAME, - UA_APP_ID_INI_NAME: () => UA_APP_ID_INI_NAME, - createDefaultUserAgentProvider: () => createDefaultUserAgentProvider, - crtAvailability: () => crtAvailability, - defaultUserAgent: () => defaultUserAgent -}); -module.exports = __toCommonJS(index_exports); - -// src/defaultUserAgent.ts -var import_os = __nccwpck_require__(2037); -var import_process = __nccwpck_require__(7282); - -// src/crt-availability.ts -var crtAvailability = { - isCrtAvailable: false -}; - -// src/is-crt-available.ts -var isCrtAvailable = /* @__PURE__ */ __name(() => { - if (crtAvailability.isCrtAvailable) { - return ["md/crt-avail"]; - } - return null; -}, "isCrtAvailable"); - -// src/defaultUserAgent.ts -var createDefaultUserAgentProvider = /* @__PURE__ */ __name(({ serviceId, clientVersion }) => { - return async (config) => { - const sections = [ - // sdk-metadata - ["aws-sdk-js", clientVersion], - // ua-metadata - ["ua", "2.1"], - // os-metadata - [`os/${(0, import_os.platform)()}`, (0, import_os.release)()], - // language-metadata - // ECMAScript edition doesn't matter in JS, so no version needed. - ["lang/js"], - ["md/nodejs", `${import_process.versions.node}`] - ]; - const crtAvailable = isCrtAvailable(); - if (crtAvailable) { - sections.push(crtAvailable); - } - if (serviceId) { - sections.push([`api/${serviceId}`, clientVersion]); - } - if (import_process.env.AWS_EXECUTION_ENV) { - sections.push([`exec-env/${import_process.env.AWS_EXECUTION_ENV}`]); - } - const appId = await config?.userAgentAppId?.(); - const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; - return resolvedUserAgent; - }; -}, "createDefaultUserAgentProvider"); -var defaultUserAgent = createDefaultUserAgentProvider; - -// src/nodeAppIdConfigOptions.ts -var import_middleware_user_agent = __nccwpck_require__(3030); -var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; -var UA_APP_ID_INI_NAME = "sdk_ua_app_id"; -var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; -var NODE_APP_ID_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env2) => env2[UA_APP_ID_ENV_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], "configFileSelector"), - default: import_middleware_user_agent.DEFAULT_UA_APP_ID -}; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 7406: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - XmlNode: () => XmlNode, - XmlText: () => XmlText -}); -module.exports = __toCommonJS(index_exports); - -// src/escape-attribute.ts -function escapeAttribute(value) { - return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); -} -__name(escapeAttribute, "escapeAttribute"); - -// src/escape-element.ts -function escapeElement(value) { - return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">").replace(/\r/g, " ").replace(/\n/g, " ").replace(/\u0085/g, "…").replace(/\u2028/, "
"); -} -__name(escapeElement, "escapeElement"); - -// src/XmlText.ts -var XmlText = class { - constructor(value) { - this.value = value; - } - static { - __name(this, "XmlText"); - } - toString() { - return escapeElement("" + this.value); - } -}; - -// src/XmlNode.ts -var XmlNode = class _XmlNode { - constructor(name, children = []) { - this.name = name; - this.children = children; - } - static { - __name(this, "XmlNode"); - } - attributes = {}; - static of(name, childText, withName) { - const node = new _XmlNode(name); - if (childText !== void 0) { - node.addChildNode(new XmlText(childText)); - } - if (withName !== void 0) { - node.withName(withName); - } - return node; - } - withName(name) { - this.name = name; - return this; - } - addAttribute(name, value) { - this.attributes[name] = value; - return this; - } - addChildNode(child) { - this.children.push(child); - return this; - } - removeAttribute(name) { - delete this.attributes[name]; - return this; - } - /** - * @internal - * Alias of {@link XmlNode#withName(string)} for codegen brevity. - */ - n(name) { - this.name = name; - return this; - } - /** - * @internal - * Alias of {@link XmlNode#addChildNode(string)} for codegen brevity. - */ - c(child) { - this.children.push(child); - return this; - } - /** - * @internal - * Checked version of {@link XmlNode#addAttribute(string)} for codegen brevity. - */ - a(name, value) { - if (value != null) { - this.attributes[name] = value; - } - return this; - } - /** - * Create a child node. - * Used in serialization of string fields. - * @internal - */ - cc(input, field, withName = field) { - if (input[field] != null) { - const node = _XmlNode.of(field, input[field]).withName(withName); - this.c(node); - } - } - /** - * Creates list child nodes. - * @internal - */ - l(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - nodes.map((node) => { - node.withName(memberName); - this.c(node); - }); - } - } - /** - * Creates list child nodes with container. - * @internal - */ - lc(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - const containerNode = new _XmlNode(memberName); - nodes.map((node) => { - containerNode.c(node); - }); - this.c(containerNode); - } - } - toString() { - const hasChildren = Boolean(this.children.length); - let xmlText = `<${this.name}`; - const attributes = this.attributes; - for (const attributeName of Object.keys(attributes)) { - const attribute = attributes[attributeName]; - if (attribute != null) { - xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; - } - } - return xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`; - } -}; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 9344: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.defaultSSOHttpAuthSchemeProvider = exports.defaultSSOHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(9963); -const util_middleware_1 = __nccwpck_require__(2390); -const defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "awsssoportal", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSSOHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "GetRoleCredentials": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "ListAccountRoles": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "ListAccounts": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "Logout": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - - -/***/ }), - -/***/ 898: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(3350); -const util_endpoints_2 = __nccwpck_require__(5473); -const ruleset_1 = __nccwpck_require__(3341); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); -}; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - - -/***/ }), - -/***/ 3341: -/***/ ((__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; - - -/***/ }), - -/***/ 2666: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - GetRoleCredentialsCommand: () => GetRoleCredentialsCommand, - GetRoleCredentialsRequestFilterSensitiveLog: () => GetRoleCredentialsRequestFilterSensitiveLog, - GetRoleCredentialsResponseFilterSensitiveLog: () => GetRoleCredentialsResponseFilterSensitiveLog, - InvalidRequestException: () => InvalidRequestException, - ListAccountRolesCommand: () => ListAccountRolesCommand, - ListAccountRolesRequestFilterSensitiveLog: () => ListAccountRolesRequestFilterSensitiveLog, - ListAccountsCommand: () => ListAccountsCommand, - ListAccountsRequestFilterSensitiveLog: () => ListAccountsRequestFilterSensitiveLog, - LogoutCommand: () => LogoutCommand, - LogoutRequestFilterSensitiveLog: () => LogoutRequestFilterSensitiveLog, - ResourceNotFoundException: () => ResourceNotFoundException, - RoleCredentialsFilterSensitiveLog: () => RoleCredentialsFilterSensitiveLog, - SSO: () => SSO, - SSOClient: () => SSOClient, - SSOServiceException: () => SSOServiceException, - TooManyRequestsException: () => TooManyRequestsException, - UnauthorizedException: () => UnauthorizedException, - __Client: () => import_smithy_client.Client, - paginateListAccountRoles: () => paginateListAccountRoles, - paginateListAccounts: () => paginateListAccounts -}); -module.exports = __toCommonJS(index_exports); - -// src/SSOClient.ts -var import_middleware_host_header = __nccwpck_require__(2545); -var import_middleware_logger = __nccwpck_require__(14); -var import_middleware_recursion_detection = __nccwpck_require__(5525); -var import_middleware_user_agent = __nccwpck_require__(4688); -var import_config_resolver = __nccwpck_require__(3098); -var import_core = __nccwpck_require__(5829); -var import_middleware_content_length = __nccwpck_require__(2800); -var import_middleware_endpoint = __nccwpck_require__(2918); -var import_middleware_retry = __nccwpck_require__(6039); - -var import_httpAuthSchemeProvider = __nccwpck_require__(9344); - -// src/endpoint/EndpointParameters.ts -var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "awsssoportal" - }); -}, "resolveClientEndpointParameters"); -var commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } -}; - -// src/SSOClient.ts -var import_runtimeConfig = __nccwpck_require__(9756); - -// src/runtimeExtensions.ts -var import_region_config_resolver = __nccwpck_require__(8156); -var import_protocol_http = __nccwpck_require__(4418); -var import_smithy_client = __nccwpck_require__(3570); - -// src/auth/httpAuthExtensionConfiguration.ts -var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; -}, "getHttpAuthExtensionConfiguration"); -var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; -}, "resolveHttpAuthRuntimeConfig"); - -// src/runtimeExtensions.ts -var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign( - (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), - (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), - (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), - getHttpAuthExtensionConfiguration(runtimeConfig) - ); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign( - runtimeConfig, - (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), - (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), - (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), - resolveHttpAuthRuntimeConfig(extensionConfiguration) - ); -}, "resolveRuntimeExtensions"); - -// src/SSOClient.ts -var SSOClient = class extends import_smithy_client.Client { - static { - __name(this, "SSOClient"); - } - /** - * The resolved configuration of SSOClient class. This is resolved and normalized from the {@link SSOClientConfig | constructor configuration interface}. - */ - config; - constructor(...[configuration]) { - const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); - const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use( - (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials - }), "identityProviderConfigProvider") - }) - ); - this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); - } - /** - * Destroy underlying resources, like sockets. It's usually not necessary to do this. - * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. - * Otherwise, sockets might stay open for quite a long time before the server terminates them. - */ - destroy() { - super.destroy(); - } -}; - -// src/SSO.ts - - -// src/commands/GetRoleCredentialsCommand.ts - -var import_middleware_serde = __nccwpck_require__(1238); - - -// src/models/models_0.ts - - -// src/models/SSOServiceException.ts - -var SSOServiceException = class _SSOServiceException extends import_smithy_client.ServiceException { - static { - __name(this, "SSOServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SSOServiceException.prototype); - } -}; - -// src/models/models_0.ts -var InvalidRequestException = class _InvalidRequestException extends SSOServiceException { - static { - __name(this, "InvalidRequestException"); - } - name = "InvalidRequestException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidRequestException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidRequestException.prototype); - } -}; -var ResourceNotFoundException = class _ResourceNotFoundException extends SSOServiceException { - static { - __name(this, "ResourceNotFoundException"); - } - name = "ResourceNotFoundException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ResourceNotFoundException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ResourceNotFoundException.prototype); - } -}; -var TooManyRequestsException = class _TooManyRequestsException extends SSOServiceException { - static { - __name(this, "TooManyRequestsException"); - } - name = "TooManyRequestsException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "TooManyRequestsException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _TooManyRequestsException.prototype); - } -}; -var UnauthorizedException = class _UnauthorizedException extends SSOServiceException { - static { - __name(this, "UnauthorizedException"); - } - name = "UnauthorizedException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnauthorizedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnauthorizedException.prototype); - } -}; -var GetRoleCredentialsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "GetRoleCredentialsRequestFilterSensitiveLog"); -var RoleCredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.secretAccessKey && { secretAccessKey: import_smithy_client.SENSITIVE_STRING }, - ...obj.sessionToken && { sessionToken: import_smithy_client.SENSITIVE_STRING } -}), "RoleCredentialsFilterSensitiveLog"); -var GetRoleCredentialsResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) } -}), "GetRoleCredentialsResponseFilterSensitiveLog"); -var ListAccountRolesRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "ListAccountRolesRequestFilterSensitiveLog"); -var ListAccountsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "ListAccountsRequestFilterSensitiveLog"); -var LogoutRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "LogoutRequestFilterSensitiveLog"); - -// src/protocols/Aws_restJson1.ts -var import_core2 = __nccwpck_require__(9963); - - -var se_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/federation/credentials"); - const query = (0, import_smithy_client.map)({ - [_rn]: [, (0, import_smithy_client.expectNonNull)(input[_rN], `roleName`)], - [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)] - }); - let body; - b.m("GET").h(headers).q(query).b(body); - return b.build(); -}, "se_GetRoleCredentialsCommand"); -var se_ListAccountRolesCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/assignment/roles"); - const query = (0, import_smithy_client.map)({ - [_nt]: [, input[_nT]], - [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()], - [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)] - }); - let body; - b.m("GET").h(headers).q(query).b(body); - return b.build(); -}, "se_ListAccountRolesCommand"); -var se_ListAccountsCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/assignment/accounts"); - const query = (0, import_smithy_client.map)({ - [_nt]: [, input[_nT]], - [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()] - }); - let body; - b.m("GET").h(headers).q(query).b(body); - return b.build(); -}, "se_ListAccountsCommand"); -var se_LogoutCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/logout"); - let body; - b.m("POST").h(headers).b(body); - return b.build(); -}, "se_LogoutCommand"); -var de_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client.take)(data, { - roleCredentials: import_smithy_client._json - }); - Object.assign(contents, doc); - return contents; -}, "de_GetRoleCredentialsCommand"); -var de_ListAccountRolesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client.take)(data, { - nextToken: import_smithy_client.expectString, - roleList: import_smithy_client._json - }); - Object.assign(contents, doc); - return contents; -}, "de_ListAccountRolesCommand"); -var de_ListAccountsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client.take)(data, { - accountList: import_smithy_client._json, - nextToken: import_smithy_client.expectString - }); - Object.assign(contents, doc); - return contents; -}, "de_ListAccountsCommand"); -var de_LogoutCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - await (0, import_smithy_client.collectBody)(output.body, context); - return contents; -}, "de_LogoutCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core2.parseJsonErrorBody)(output.body, context) - }; - const errorCode = (0, import_core2.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 - }); - } -}, "de_CommandError"); -var throwDefaultError = (0, import_smithy_client.withBaseException)(SSOServiceException); -var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidRequestException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidRequestExceptionRes"); -var de_ResourceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new ResourceNotFoundException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_ResourceNotFoundExceptionRes"); -var de_TooManyRequestsExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new TooManyRequestsException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_TooManyRequestsExceptionRes"); -var de_UnauthorizedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new UnauthorizedException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnauthorizedExceptionRes"); -var deserializeMetadata = /* @__PURE__ */ __name((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"] -}), "deserializeMetadata"); -var _aI = "accountId"; -var _aT = "accessToken"; -var _ai = "account_id"; -var _mR = "maxResults"; -var _mr = "max_result"; -var _nT = "nextToken"; -var _nt = "next_token"; -var _rN = "roleName"; -var _rn = "role_name"; -var _xasbt = "x-amz-sso_bearer_token"; - -// src/commands/GetRoleCredentialsCommand.ts -var GetRoleCredentialsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog).ser(se_GetRoleCredentialsCommand).de(de_GetRoleCredentialsCommand).build() { - static { - __name(this, "GetRoleCredentialsCommand"); - } -}; - -// src/commands/ListAccountRolesCommand.ts - - - -var ListAccountRolesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").f(ListAccountRolesRequestFilterSensitiveLog, void 0).ser(se_ListAccountRolesCommand).de(de_ListAccountRolesCommand).build() { - static { - __name(this, "ListAccountRolesCommand"); - } -}; - -// src/commands/ListAccountsCommand.ts - - - -var ListAccountsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").f(ListAccountsRequestFilterSensitiveLog, void 0).ser(se_ListAccountsCommand).de(de_ListAccountsCommand).build() { - static { - __name(this, "ListAccountsCommand"); - } -}; - -// src/commands/LogoutCommand.ts - - - -var LogoutCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").f(LogoutRequestFilterSensitiveLog, void 0).ser(se_LogoutCommand).de(de_LogoutCommand).build() { - static { - __name(this, "LogoutCommand"); - } -}; - -// src/SSO.ts -var commands = { - GetRoleCredentialsCommand, - ListAccountRolesCommand, - ListAccountsCommand, - LogoutCommand -}; -var SSO = class extends SSOClient { - static { - __name(this, "SSO"); - } -}; -(0, import_smithy_client.createAggregatedClient)(commands, SSO); - -// src/pagination/ListAccountRolesPaginator.ts - -var paginateListAccountRoles = (0, import_core.createPaginator)(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults"); - -// src/pagination/ListAccountsPaginator.ts - -var paginateListAccounts = (0, import_core.createPaginator)(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 9756: -/***/ ((__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__(1092)); -const core_1 = __nccwpck_require__(9963); -const util_user_agent_node_1 = __nccwpck_require__(8095); -const config_resolver_1 = __nccwpck_require__(3098); -const hash_node_1 = __nccwpck_require__(3081); -const middleware_retry_1 = __nccwpck_require__(6039); -const node_config_provider_1 = __nccwpck_require__(3461); -const node_http_handler_1 = __nccwpck_require__(258); -const util_body_length_node_1 = __nccwpck_require__(8075); -const util_retry_1 = __nccwpck_require__(4902); -const runtimeConfig_shared_1 = __nccwpck_require__(4809); -const smithy_client_1 = __nccwpck_require__(3570); -const util_defaults_mode_node_1 = __nccwpck_require__(2429); -const smithy_client_2 = __nccwpck_require__(3570); -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); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ 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, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, - }, config), - 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, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 4809: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(9963); -const core_2 = __nccwpck_require__(5829); -const smithy_client_1 = __nccwpck_require__(3570); -const url_parser_1 = __nccwpck_require__(4681); -const util_base64_1 = __nccwpck_require__(5600); -const util_utf8_1 = __nccwpck_require__(1895); -const httpAuthSchemeProvider_1 = __nccwpck_require__(9344); -const endpointResolver_1 = __nccwpck_require__(898); -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 ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - 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; - - -/***/ }), - -/***/ 4195: -/***/ ((__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__(9514); -const middleware_logger_1 = __nccwpck_require__(5675); -const middleware_recursion_detection_1 = __nccwpck_require__(7977); -const middleware_user_agent_1 = __nccwpck_require__(6634); -const config_resolver_1 = __nccwpck_require__(3098); -const core_1 = __nccwpck_require__(5829); -const middleware_content_length_1 = __nccwpck_require__(2800); -const middleware_endpoint_1 = __nccwpck_require__(2918); -const middleware_retry_1 = __nccwpck_require__(6039); -const smithy_client_1 = __nccwpck_require__(3570); -Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); -const httpAuthSchemeProvider_1 = __nccwpck_require__(7145); -const EndpointParameters_1 = __nccwpck_require__(510); -const runtimeConfig_1 = __nccwpck_require__(3405); -const runtimeExtensions_1 = __nccwpck_require__(2053); -class STSClient extends smithy_client_1.Client { - config; - constructor(...[configuration]) { - const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); - const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); - const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); - const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); - const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); - 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, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - }), - })); - this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); - } - destroy() { - super.destroy(); - } -} -exports.STSClient = STSClient; - - -/***/ }), - -/***/ 8527: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - }; -}; -exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - }; -}; -exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; - - -/***/ }), - -/***/ 7145: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(2143); -const util_middleware_1 = __nccwpck_require__(2390); -const STSClient_1 = __nccwpck_require__(4195); -const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sts", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSTSHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "AssumeRoleWithSAML": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "AssumeRoleWithWebIdentity": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; -const resolveStsAuthConfig = (input) => Object.assign(input, { - stsClientCtor: STSClient_1.STSClient, -}); -exports.resolveStsAuthConfig = resolveStsAuthConfig; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, exports.resolveStsAuthConfig)(config); - const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); - return Object.assign(config_1, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - - -/***/ }), - -/***/ 510: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.commonParams = exports.resolveClientEndpointParameters = void 0; -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - useGlobalEndpoint: options.useGlobalEndpoint ?? false, - defaultSigningName: "sts", - }); -}; -exports.resolveClientEndpointParameters = resolveClientEndpointParameters; -exports.commonParams = { - 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" }, -}; - - -/***/ }), - -/***/ 1203: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(4241); -const util_endpoints_2 = __nccwpck_require__(5473); -const ruleset_1 = __nccwpck_require__(6882); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); -}; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - - -/***/ }), - -/***/ 6882: -/***/ ((__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; - - -/***/ }), - -/***/ 2209: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - AssumeRoleCommand: () => AssumeRoleCommand, - AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog, - AssumeRoleWithSAMLCommand: () => AssumeRoleWithSAMLCommand, - AssumeRoleWithSAMLRequestFilterSensitiveLog: () => AssumeRoleWithSAMLRequestFilterSensitiveLog, - AssumeRoleWithSAMLResponseFilterSensitiveLog: () => AssumeRoleWithSAMLResponseFilterSensitiveLog, - AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand, - AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog, - AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog, - AssumeRootCommand: () => AssumeRootCommand, - AssumeRootResponseFilterSensitiveLog: () => AssumeRootResponseFilterSensitiveLog, - ClientInputEndpointParameters: () => import_EndpointParameters10.ClientInputEndpointParameters, - CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog, - DecodeAuthorizationMessageCommand: () => DecodeAuthorizationMessageCommand, - ExpiredTokenException: () => ExpiredTokenException, - GetAccessKeyInfoCommand: () => GetAccessKeyInfoCommand, - GetCallerIdentityCommand: () => GetCallerIdentityCommand, - GetFederationTokenCommand: () => GetFederationTokenCommand, - GetFederationTokenResponseFilterSensitiveLog: () => GetFederationTokenResponseFilterSensitiveLog, - GetSessionTokenCommand: () => GetSessionTokenCommand, - GetSessionTokenResponseFilterSensitiveLog: () => GetSessionTokenResponseFilterSensitiveLog, - IDPCommunicationErrorException: () => IDPCommunicationErrorException, - IDPRejectedClaimException: () => IDPRejectedClaimException, - InvalidAuthorizationMessageException: () => InvalidAuthorizationMessageException, - InvalidIdentityTokenException: () => InvalidIdentityTokenException, - MalformedPolicyDocumentException: () => MalformedPolicyDocumentException, - PackedPolicyTooLargeException: () => PackedPolicyTooLargeException, - RegionDisabledException: () => RegionDisabledException, - STS: () => STS, - STSServiceException: () => STSServiceException, - decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, - getDefaultRoleAssumer: () => getDefaultRoleAssumer2, - getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 -}); -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(4195), module.exports); - -// src/STS.ts - - -// src/commands/AssumeRoleCommand.ts -var import_middleware_endpoint = __nccwpck_require__(2918); -var import_middleware_serde = __nccwpck_require__(1238); - -var import_EndpointParameters = __nccwpck_require__(510); - -// src/models/models_0.ts - - -// src/models/STSServiceException.ts -var import_smithy_client = __nccwpck_require__(3570); -var STSServiceException = class _STSServiceException extends import_smithy_client.ServiceException { - static { - __name(this, "STSServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _STSServiceException.prototype); - } -}; - -// src/models/models_0.ts -var ExpiredTokenException = class _ExpiredTokenException extends STSServiceException { - static { - __name(this, "ExpiredTokenException"); - } - name = "ExpiredTokenException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - } -}; -var MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { - static { - __name(this, "MalformedPolicyDocumentException"); - } - name = "MalformedPolicyDocumentException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "MalformedPolicyDocumentException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); - } -}; -var PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { - static { - __name(this, "PackedPolicyTooLargeException"); - } - name = "PackedPolicyTooLargeException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "PackedPolicyTooLargeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); - } -}; -var RegionDisabledException = class _RegionDisabledException extends STSServiceException { - static { - __name(this, "RegionDisabledException"); - } - name = "RegionDisabledException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "RegionDisabledException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _RegionDisabledException.prototype); - } -}; -var IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { - static { - __name(this, "IDPRejectedClaimException"); - } - name = "IDPRejectedClaimException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "IDPRejectedClaimException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); - } -}; -var InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { - static { - __name(this, "InvalidIdentityTokenException"); - } - name = "InvalidIdentityTokenException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidIdentityTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); - } -}; -var IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { - static { - __name(this, "IDPCommunicationErrorException"); - } - name = "IDPCommunicationErrorException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "IDPCommunicationErrorException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); - } -}; -var InvalidAuthorizationMessageException = class _InvalidAuthorizationMessageException extends STSServiceException { - static { - __name(this, "InvalidAuthorizationMessageException"); - } - name = "InvalidAuthorizationMessageException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidAuthorizationMessageException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidAuthorizationMessageException.prototype); - } -}; -var CredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client.SENSITIVE_STRING } -}), "CredentialsFilterSensitiveLog"); -var AssumeRoleResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleResponseFilterSensitiveLog"); -var AssumeRoleWithSAMLRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.SAMLAssertion && { SAMLAssertion: import_smithy_client.SENSITIVE_STRING } -}), "AssumeRoleWithSAMLRequestFilterSensitiveLog"); -var AssumeRoleWithSAMLResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleWithSAMLResponseFilterSensitiveLog"); -var AssumeRoleWithWebIdentityRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client.SENSITIVE_STRING } -}), "AssumeRoleWithWebIdentityRequestFilterSensitiveLog"); -var AssumeRoleWithWebIdentityResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleWithWebIdentityResponseFilterSensitiveLog"); -var AssumeRootResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRootResponseFilterSensitiveLog"); -var GetFederationTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "GetFederationTokenResponseFilterSensitiveLog"); -var GetSessionTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "GetSessionTokenResponseFilterSensitiveLog"); - -// src/protocols/Aws_query.ts -var import_core = __nccwpck_require__(2143); -var import_protocol_http = __nccwpck_require__(4418); - -var se_AssumeRoleCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleRequest(input, context), - [_A]: _AR, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleCommand"); -var se_AssumeRoleWithSAMLCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleWithSAMLRequest(input, context), - [_A]: _ARWSAML, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleWithSAMLCommand"); -var se_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleWithWebIdentityRequest(input, context), - [_A]: _ARWWI, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleWithWebIdentityCommand"); -var se_AssumeRootCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRootRequest(input, context), - [_A]: _ARs, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRootCommand"); -var se_DecodeAuthorizationMessageCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_DecodeAuthorizationMessageRequest(input, context), - [_A]: _DAM, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_DecodeAuthorizationMessageCommand"); -var se_GetAccessKeyInfoCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_GetAccessKeyInfoRequest(input, context), - [_A]: _GAKI, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_GetAccessKeyInfoCommand"); -var se_GetCallerIdentityCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_GetCallerIdentityRequest(input, context), - [_A]: _GCI, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_GetCallerIdentityCommand"); -var se_GetFederationTokenCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_GetFederationTokenRequest(input, context), - [_A]: _GFT, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_GetFederationTokenCommand"); -var se_GetSessionTokenCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_GetSessionTokenRequest(input, context), - [_A]: _GST, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_GetSessionTokenCommand"); -var de_AssumeRoleCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleResponse(data.AssumeRoleResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleCommand"); -var de_AssumeRoleWithSAMLCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleWithSAMLResponse(data.AssumeRoleWithSAMLResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleWithSAMLCommand"); -var de_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleWithWebIdentityCommand"); -var de_AssumeRootCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRootResponse(data.AssumeRootResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRootCommand"); -var de_DecodeAuthorizationMessageCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_DecodeAuthorizationMessageResponse(data.DecodeAuthorizationMessageResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_DecodeAuthorizationMessageCommand"); -var de_GetAccessKeyInfoCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_GetAccessKeyInfoResponse(data.GetAccessKeyInfoResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_GetAccessKeyInfoCommand"); -var de_GetCallerIdentityCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_GetCallerIdentityResponse(data.GetCallerIdentityResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_GetCallerIdentityCommand"); -var de_GetFederationTokenCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_GetFederationTokenResponse(data.GetFederationTokenResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_GetFederationTokenCommand"); -var de_GetSessionTokenCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_GetSessionTokenResponse(data.GetSessionTokenResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_GetSessionTokenCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core.parseXmlErrorBody)(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); - 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 "IDPCommunicationError": - case "com.amazonaws.sts#IDPCommunicationErrorException": - throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context); - 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 - }); - } -}, "de_CommandError"); -var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_ExpiredTokenException(body.Error, context); - const exception = new ExpiredTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_ExpiredTokenExceptionRes"); -var de_IDPCommunicationErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_IDPCommunicationErrorException(body.Error, context); - const exception = new IDPCommunicationErrorException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_IDPCommunicationErrorExceptionRes"); -var de_IDPRejectedClaimExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_IDPRejectedClaimException(body.Error, context); - const exception = new IDPRejectedClaimException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_IDPRejectedClaimExceptionRes"); -var de_InvalidAuthorizationMessageExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_InvalidAuthorizationMessageException(body.Error, context); - const exception = new InvalidAuthorizationMessageException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_InvalidAuthorizationMessageExceptionRes"); -var de_InvalidIdentityTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_InvalidIdentityTokenException(body.Error, context); - const exception = new InvalidIdentityTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_InvalidIdentityTokenExceptionRes"); -var de_MalformedPolicyDocumentExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_MalformedPolicyDocumentException(body.Error, context); - const exception = new MalformedPolicyDocumentException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_MalformedPolicyDocumentExceptionRes"); -var de_PackedPolicyTooLargeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_PackedPolicyTooLargeException(body.Error, context); - const exception = new PackedPolicyTooLargeException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_PackedPolicyTooLargeExceptionRes"); -var de_RegionDisabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_RegionDisabledException(body.Error, context); - const exception = new RegionDisabledException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client.decorateServiceException)(exception, body); -}, "de_RegionDisabledExceptionRes"); -var se_AssumeRoleRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; - } - if (input[_RSN] != null) { - entries[_RSN] = input[_RSN]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - if (input[_T] != null) { - const memberEntries = se_tagListType(input[_T], context); - if (input[_T]?.length === 0) { - entries.Tags = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `Tags.${key}`; - entries[loc] = value; - }); - } - if (input[_TTK] != null) { - const memberEntries = se_tagKeyListType(input[_TTK], context); - if (input[_TTK]?.length === 0) { - entries.TransitiveTagKeys = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `TransitiveTagKeys.${key}`; - entries[loc] = value; - }); - } - if (input[_EI] != null) { - entries[_EI] = input[_EI]; - } - if (input[_SN] != null) { - entries[_SN] = input[_SN]; - } - if (input[_TC] != null) { - entries[_TC] = input[_TC]; - } - if (input[_SI] != null) { - entries[_SI] = input[_SI]; - } - if (input[_PC] != null) { - const memberEntries = se_ProvidedContextsListType(input[_PC], context); - if (input[_PC]?.length === 0) { - entries.ProvidedContexts = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `ProvidedContexts.${key}`; - entries[loc] = value; - }); - } - return entries; -}, "se_AssumeRoleRequest"); -var se_AssumeRoleWithSAMLRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; - } - if (input[_PAr] != null) { - entries[_PAr] = input[_PAr]; - } - if (input[_SAMLA] != null) { - entries[_SAMLA] = input[_SAMLA]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - return entries; -}, "se_AssumeRoleWithSAMLRequest"); -var se_AssumeRoleWithWebIdentityRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; - } - if (input[_RSN] != null) { - entries[_RSN] = input[_RSN]; - } - if (input[_WIT] != null) { - entries[_WIT] = input[_WIT]; - } - if (input[_PI] != null) { - entries[_PI] = input[_PI]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - return entries; -}, "se_AssumeRoleWithWebIdentityRequest"); -var se_AssumeRootRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_TP] != null) { - entries[_TP] = input[_TP]; - } - if (input[_TPA] != null) { - const memberEntries = se_PolicyDescriptorType(input[_TPA], context); - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `TaskPolicyArn.${key}`; - entries[loc] = value; - }); - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - return entries; -}, "se_AssumeRootRequest"); -var se_DecodeAuthorizationMessageRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_EM] != null) { - entries[_EM] = input[_EM]; - } - return entries; -}, "se_DecodeAuthorizationMessageRequest"); -var se_GetAccessKeyInfoRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_AKI] != null) { - entries[_AKI] = input[_AKI]; - } - return entries; -}, "se_GetAccessKeyInfoRequest"); -var se_GetCallerIdentityRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - return entries; -}, "se_GetCallerIdentityRequest"); -var se_GetFederationTokenRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_N] != null) { - entries[_N] = input[_N]; - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - if (input[_T] != null) { - const memberEntries = se_tagListType(input[_T], context); - if (input[_T]?.length === 0) { - entries.Tags = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `Tags.${key}`; - entries[loc] = value; - }); - } - return entries; -}, "se_GetFederationTokenRequest"); -var se_GetSessionTokenRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - if (input[_SN] != null) { - entries[_SN] = input[_SN]; - } - if (input[_TC] != null) { - entries[_TC] = input[_TC]; - } - return entries; -}, "se_GetSessionTokenRequest"); -var se_policyDescriptorListType = /* @__PURE__ */ __name((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; -}, "se_policyDescriptorListType"); -var se_PolicyDescriptorType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_a] != null) { - entries[_a] = input[_a]; - } - return entries; -}, "se_PolicyDescriptorType"); -var se_ProvidedContext = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_PAro] != null) { - entries[_PAro] = input[_PAro]; - } - if (input[_CA] != null) { - entries[_CA] = input[_CA]; - } - return entries; -}, "se_ProvidedContext"); -var se_ProvidedContextsListType = /* @__PURE__ */ __name((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; -}, "se_ProvidedContextsListType"); -var se_Tag = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_K] != null) { - entries[_K] = input[_K]; - } - if (input[_Va] != null) { - entries[_Va] = input[_Va]; - } - return entries; -}, "se_Tag"); -var se_tagKeyListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; - } - entries[`member.${counter}`] = entry; - counter++; - } - return entries; -}, "se_tagKeyListType"); -var se_tagListType = /* @__PURE__ */ __name((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; -}, "se_tagListType"); -var de_AssumedRoleUser = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_ARI] != null) { - contents[_ARI] = (0, import_smithy_client.expectString)(output[_ARI]); - } - if (output[_Ar] != null) { - contents[_Ar] = (0, import_smithy_client.expectString)(output[_Ar]); - } - return contents; -}, "de_AssumedRoleUser"); -var de_AssumeRoleResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); - } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client.strictParseInt32)(output[_PPS]); - } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client.expectString)(output[_SI]); - } - return contents; -}, "de_AssumeRoleResponse"); -var de_AssumeRoleWithSAMLResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); - } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client.strictParseInt32)(output[_PPS]); - } - if (output[_S] != null) { - contents[_S] = (0, import_smithy_client.expectString)(output[_S]); - } - if (output[_ST] != null) { - contents[_ST] = (0, import_smithy_client.expectString)(output[_ST]); - } - if (output[_I] != null) { - contents[_I] = (0, import_smithy_client.expectString)(output[_I]); - } - if (output[_Au] != null) { - contents[_Au] = (0, import_smithy_client.expectString)(output[_Au]); - } - if (output[_NQ] != null) { - contents[_NQ] = (0, import_smithy_client.expectString)(output[_NQ]); - } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client.expectString)(output[_SI]); - } - return contents; -}, "de_AssumeRoleWithSAMLResponse"); -var de_AssumeRoleWithWebIdentityResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_SFWIT] != null) { - contents[_SFWIT] = (0, import_smithy_client.expectString)(output[_SFWIT]); - } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); - } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client.strictParseInt32)(output[_PPS]); - } - if (output[_Pr] != null) { - contents[_Pr] = (0, import_smithy_client.expectString)(output[_Pr]); - } - if (output[_Au] != null) { - contents[_Au] = (0, import_smithy_client.expectString)(output[_Au]); - } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client.expectString)(output[_SI]); - } - return contents; -}, "de_AssumeRoleWithWebIdentityResponse"); -var de_AssumeRootResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client.expectString)(output[_SI]); - } - return contents; -}, "de_AssumeRootResponse"); -var de_Credentials = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_AKI] != null) { - contents[_AKI] = (0, import_smithy_client.expectString)(output[_AKI]); - } - if (output[_SAK] != null) { - contents[_SAK] = (0, import_smithy_client.expectString)(output[_SAK]); - } - if (output[_STe] != null) { - contents[_STe] = (0, import_smithy_client.expectString)(output[_STe]); - } - if (output[_E] != null) { - contents[_E] = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.parseRfc3339DateTimeWithOffset)(output[_E])); - } - return contents; -}, "de_Credentials"); -var de_DecodeAuthorizationMessageResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_DM] != null) { - contents[_DM] = (0, import_smithy_client.expectString)(output[_DM]); - } - return contents; -}, "de_DecodeAuthorizationMessageResponse"); -var de_ExpiredTokenException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client.expectString)(output[_m]); - } - return contents; -}, "de_ExpiredTokenException"); -var de_FederatedUser = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_FUI] != null) { - contents[_FUI] = (0, import_smithy_client.expectString)(output[_FUI]); - } - if (output[_Ar] != null) { - contents[_Ar] = (0, import_smithy_client.expectString)(output[_Ar]); - } - return contents; -}, "de_FederatedUser"); -var de_GetAccessKeyInfoResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_Ac] != null) { - contents[_Ac] = (0, import_smithy_client.expectString)(output[_Ac]); - } - return contents; -}, "de_GetAccessKeyInfoResponse"); -var de_GetCallerIdentityResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_UI] != null) { - contents[_UI] = (0, import_smithy_client.expectString)(output[_UI]); - } - if (output[_Ac] != null) { - contents[_Ac] = (0, import_smithy_client.expectString)(output[_Ac]); - } - if (output[_Ar] != null) { - contents[_Ar] = (0, import_smithy_client.expectString)(output[_Ar]); - } - return contents; -}, "de_GetCallerIdentityResponse"); -var de_GetFederationTokenResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_FU] != null) { - contents[_FU] = de_FederatedUser(output[_FU], context); - } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client.strictParseInt32)(output[_PPS]); - } - return contents; -}, "de_GetFederationTokenResponse"); -var de_GetSessionTokenResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - return contents; -}, "de_GetSessionTokenResponse"); -var de_IDPCommunicationErrorException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client.expectString)(output[_m]); - } - return contents; -}, "de_IDPCommunicationErrorException"); -var de_IDPRejectedClaimException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client.expectString)(output[_m]); - } - return contents; -}, "de_IDPRejectedClaimException"); -var de_InvalidAuthorizationMessageException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client.expectString)(output[_m]); - } - return contents; -}, "de_InvalidAuthorizationMessageException"); -var de_InvalidIdentityTokenException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client.expectString)(output[_m]); - } - return contents; -}, "de_InvalidIdentityTokenException"); -var de_MalformedPolicyDocumentException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client.expectString)(output[_m]); - } - return contents; -}, "de_MalformedPolicyDocumentException"); -var de_PackedPolicyTooLargeException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client.expectString)(output[_m]); - } - return contents; -}, "de_PackedPolicyTooLargeException"); -var de_RegionDisabledException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client.expectString)(output[_m]); - } - return contents; -}, "de_RegionDisabledException"); -var deserializeMetadata = /* @__PURE__ */ __name((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"] -}), "deserializeMetadata"); -var throwDefaultError = (0, import_smithy_client.withBaseException)(STSServiceException); -var buildHttpRpcRequest = /* @__PURE__ */ __name(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 !== void 0) { - contents.hostname = resolvedHostname; - } - if (body !== void 0) { - contents.body = body; - } - return new import_protocol_http.HttpRequest(contents); -}, "buildHttpRpcRequest"); -var SHARED_HEADERS = { - "content-type": "application/x-www-form-urlencoded" -}; -var _ = "2011-06-15"; -var _A = "Action"; -var _AKI = "AccessKeyId"; -var _AR = "AssumeRole"; -var _ARI = "AssumedRoleId"; -var _ARU = "AssumedRoleUser"; -var _ARWSAML = "AssumeRoleWithSAML"; -var _ARWWI = "AssumeRoleWithWebIdentity"; -var _ARs = "AssumeRoot"; -var _Ac = "Account"; -var _Ar = "Arn"; -var _Au = "Audience"; -var _C = "Credentials"; -var _CA = "ContextAssertion"; -var _DAM = "DecodeAuthorizationMessage"; -var _DM = "DecodedMessage"; -var _DS = "DurationSeconds"; -var _E = "Expiration"; -var _EI = "ExternalId"; -var _EM = "EncodedMessage"; -var _FU = "FederatedUser"; -var _FUI = "FederatedUserId"; -var _GAKI = "GetAccessKeyInfo"; -var _GCI = "GetCallerIdentity"; -var _GFT = "GetFederationToken"; -var _GST = "GetSessionToken"; -var _I = "Issuer"; -var _K = "Key"; -var _N = "Name"; -var _NQ = "NameQualifier"; -var _P = "Policy"; -var _PA = "PolicyArns"; -var _PAr = "PrincipalArn"; -var _PAro = "ProviderArn"; -var _PC = "ProvidedContexts"; -var _PI = "ProviderId"; -var _PPS = "PackedPolicySize"; -var _Pr = "Provider"; -var _RA = "RoleArn"; -var _RSN = "RoleSessionName"; -var _S = "Subject"; -var _SAK = "SecretAccessKey"; -var _SAMLA = "SAMLAssertion"; -var _SFWIT = "SubjectFromWebIdentityToken"; -var _SI = "SourceIdentity"; -var _SN = "SerialNumber"; -var _ST = "SubjectType"; -var _STe = "SessionToken"; -var _T = "Tags"; -var _TC = "TokenCode"; -var _TP = "TargetPrincipal"; -var _TPA = "TaskPolicyArn"; -var _TTK = "TransitiveTagKeys"; -var _UI = "UserId"; -var _V = "Version"; -var _Va = "Value"; -var _WIT = "WebIdentityToken"; -var _a = "arn"; -var _m = "message"; -var buildFormUrlencodedString = /* @__PURE__ */ __name((formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client.extendedEncodeURIComponent)(value)).join("&"), "buildFormUrlencodedString"); -var loadQueryErrorCode = /* @__PURE__ */ __name((output, data) => { - if (data.Error?.Code !== void 0) { - return data.Error.Code; - } - if (output.statusCode == 404) { - return "NotFound"; - } -}, "loadQueryErrorCode"); - -// src/commands/AssumeRoleCommand.ts -var AssumeRoleCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() { - static { - __name(this, "AssumeRoleCommand"); - } -}; - -// src/commands/AssumeRoleWithSAMLCommand.ts - - - -var import_EndpointParameters2 = __nccwpck_require__(510); -var AssumeRoleWithSAMLCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters2.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithSAML", {}).n("STSClient", "AssumeRoleWithSAMLCommand").f(AssumeRoleWithSAMLRequestFilterSensitiveLog, AssumeRoleWithSAMLResponseFilterSensitiveLog).ser(se_AssumeRoleWithSAMLCommand).de(de_AssumeRoleWithSAMLCommand).build() { - static { - __name(this, "AssumeRoleWithSAMLCommand"); - } -}; - -// src/commands/AssumeRoleWithWebIdentityCommand.ts - - - -var import_EndpointParameters3 = __nccwpck_require__(510); -var AssumeRoleWithWebIdentityCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters3.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() { - static { - __name(this, "AssumeRoleWithWebIdentityCommand"); - } -}; - -// src/commands/AssumeRootCommand.ts - - - -var import_EndpointParameters4 = __nccwpck_require__(510); -var AssumeRootCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters4.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRoot", {}).n("STSClient", "AssumeRootCommand").f(void 0, AssumeRootResponseFilterSensitiveLog).ser(se_AssumeRootCommand).de(de_AssumeRootCommand).build() { - static { - __name(this, "AssumeRootCommand"); - } -}; - -// src/commands/DecodeAuthorizationMessageCommand.ts - - - -var import_EndpointParameters5 = __nccwpck_require__(510); -var DecodeAuthorizationMessageCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters5.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "DecodeAuthorizationMessage", {}).n("STSClient", "DecodeAuthorizationMessageCommand").f(void 0, void 0).ser(se_DecodeAuthorizationMessageCommand).de(de_DecodeAuthorizationMessageCommand).build() { - static { - __name(this, "DecodeAuthorizationMessageCommand"); - } -}; - -// src/commands/GetAccessKeyInfoCommand.ts - - - -var import_EndpointParameters6 = __nccwpck_require__(510); -var GetAccessKeyInfoCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters6.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "GetAccessKeyInfo", {}).n("STSClient", "GetAccessKeyInfoCommand").f(void 0, void 0).ser(se_GetAccessKeyInfoCommand).de(de_GetAccessKeyInfoCommand).build() { - static { - __name(this, "GetAccessKeyInfoCommand"); - } -}; - -// src/commands/GetCallerIdentityCommand.ts - - - -var import_EndpointParameters7 = __nccwpck_require__(510); -var GetCallerIdentityCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters7.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "GetCallerIdentity", {}).n("STSClient", "GetCallerIdentityCommand").f(void 0, void 0).ser(se_GetCallerIdentityCommand).de(de_GetCallerIdentityCommand).build() { - static { - __name(this, "GetCallerIdentityCommand"); - } -}; - -// src/commands/GetFederationTokenCommand.ts - - - -var import_EndpointParameters8 = __nccwpck_require__(510); -var GetFederationTokenCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters8.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "GetFederationToken", {}).n("STSClient", "GetFederationTokenCommand").f(void 0, GetFederationTokenResponseFilterSensitiveLog).ser(se_GetFederationTokenCommand).de(de_GetFederationTokenCommand).build() { - static { - __name(this, "GetFederationTokenCommand"); - } -}; - -// src/commands/GetSessionTokenCommand.ts - - - -var import_EndpointParameters9 = __nccwpck_require__(510); -var GetSessionTokenCommand = class extends import_smithy_client.Command.classBuilder().ep(import_EndpointParameters9.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "GetSessionToken", {}).n("STSClient", "GetSessionTokenCommand").f(void 0, GetSessionTokenResponseFilterSensitiveLog).ser(se_GetSessionTokenCommand).de(de_GetSessionTokenCommand).build() { - static { - __name(this, "GetSessionTokenCommand"); - } -}; - -// src/STS.ts -var import_STSClient = __nccwpck_require__(4195); -var commands = { - AssumeRoleCommand, - AssumeRoleWithSAMLCommand, - AssumeRoleWithWebIdentityCommand, - AssumeRootCommand, - DecodeAuthorizationMessageCommand, - GetAccessKeyInfoCommand, - GetCallerIdentityCommand, - GetFederationTokenCommand, - GetSessionTokenCommand -}; -var STS = class extends import_STSClient.STSClient { - static { - __name(this, "STS"); - } -}; -(0, import_smithy_client.createAggregatedClient)(commands, STS); - -// src/index.ts -var import_EndpointParameters10 = __nccwpck_require__(510); - -// src/defaultStsRoleAssumers.ts -var import_client = __nccwpck_require__(6510); -var ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; -var getAccountIdFromAssumedRoleUser = /* @__PURE__ */ __name((assumedRoleUser) => { - if (typeof assumedRoleUser?.Arn === "string") { - const arnComponents = assumedRoleUser.Arn.split(":"); - if (arnComponents.length > 4 && arnComponents[4] !== "") { - return arnComponents[4]; - } - } - return void 0; -}, "getAccountIdFromAssumedRoleUser"); -var resolveRegion = /* @__PURE__ */ __name(async (_region, _parentRegion, credentialProviderLogger) => { - const region = typeof _region === "function" ? await _region() : _region; - const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; - credentialProviderLogger?.debug?.( - "@aws-sdk/client-sts::resolveRegion", - "accepting first of:", - `${region} (provider)`, - `${parentRegion} (parent client)`, - `${ASSUME_ROLE_DEFAULT_REGION} (STS default)` - ); - return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION; -}, "resolveRegion"); -var getDefaultRoleAssumer = /* @__PURE__ */ __name((stsOptions, STSClient3) => { - let stsClient; - let closureSourceCreds; - return async (sourceCreds, params) => { - closureSourceCreds = sourceCreds; - if (!stsClient) { - const { - logger = stsOptions?.parentClientConfig?.logger, - region, - requestHandler = stsOptions?.parentClientConfig?.requestHandler, - credentialProviderLogger - } = stsOptions; - const resolvedRegion = await resolveRegion( - region, - stsOptions?.parentClientConfig?.region, - credentialProviderLogger - ); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient3({ - profile: stsOptions?.parentClientConfig?.profile, - // A hack to make sts client uses the credential in current closure. - credentialDefaultProvider: /* @__PURE__ */ __name(() => async () => closureSourceCreds, "credentialDefaultProvider"), - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger - }); - } - const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleCommand(params)); - if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); - const credentials = { - accessKeyId: Credentials2.AccessKeyId, - secretAccessKey: Credentials2.SecretAccessKey, - sessionToken: Credentials2.SessionToken, - expiration: Credentials2.Expiration, - // TODO(credentialScope): access normally when shape is updated. - ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); - return credentials; - }; -}, "getDefaultRoleAssumer"); -var getDefaultRoleAssumerWithWebIdentity = /* @__PURE__ */ __name((stsOptions, STSClient3) => { - let stsClient; - return async (params) => { - if (!stsClient) { - const { - logger = stsOptions?.parentClientConfig?.logger, - region, - requestHandler = stsOptions?.parentClientConfig?.requestHandler, - credentialProviderLogger - } = stsOptions; - const resolvedRegion = await resolveRegion( - region, - stsOptions?.parentClientConfig?.region, - credentialProviderLogger - ); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient3({ - profile: stsOptions?.parentClientConfig?.profile, - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger - }); - } - const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); - if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); - const credentials = { - accessKeyId: Credentials2.AccessKeyId, - secretAccessKey: Credentials2.SecretAccessKey, - sessionToken: Credentials2.SessionToken, - expiration: Credentials2.Expiration, - // TODO(credentialScope): access normally when shape is updated. - ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, - ...accountId && { accountId } - }; - if (accountId) { - (0, import_client.setCredentialFeature)(credentials, "RESOLVED_ACCOUNT_ID", "T"); - } - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); - return credentials; - }; -}, "getDefaultRoleAssumerWithWebIdentity"); -var isH2 = /* @__PURE__ */ __name((requestHandler) => { - return requestHandler?.metadata?.handlerProtocol === "h2"; -}, "isH2"); - -// src/defaultRoleAssumers.ts -var import_STSClient2 = __nccwpck_require__(4195); -var getCustomizableStsClientCtor = /* @__PURE__ */ __name((baseCtor, customizations) => { - if (!customizations) return baseCtor; - else - return class CustomizableSTSClient extends baseCtor { - static { - __name(this, "CustomizableSTSClient"); - } - constructor(config) { - super(config); - for (const customization of customizations) { - this.middlewareStack.use(customization); - } - } - }; -}, "getCustomizableStsClientCtor"); -var getDefaultRoleAssumer2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumer"); -var getDefaultRoleAssumerWithWebIdentity2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumerWithWebIdentity"); -var decorateDefaultCredentialProvider = /* @__PURE__ */ __name((provider) => (input) => provider({ - roleAssumer: getDefaultRoleAssumer2(input), - roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input), - ...input -}), "decorateDefaultCredentialProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 3405: -/***/ ((__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 core_1 = __nccwpck_require__(2143); -const credential_provider_node_1 = __nccwpck_require__(3196); -const util_user_agent_node_1 = __nccwpck_require__(7330); -const config_resolver_1 = __nccwpck_require__(3098); -const core_2 = __nccwpck_require__(5829); -const hash_node_1 = __nccwpck_require__(3081); -const middleware_retry_1 = __nccwpck_require__(6039); -const node_config_provider_1 = __nccwpck_require__(3461); -const node_http_handler_1 = __nccwpck_require__(258); -const util_body_length_node_1 = __nccwpck_require__(8075); -const util_retry_1 = __nccwpck_require__(4902); -const runtimeConfig_shared_1 = __nccwpck_require__(2642); -const smithy_client_1 = __nccwpck_require__(3570); -const util_defaults_mode_node_1 = __nccwpck_require__(2429); -const smithy_client_2 = __nccwpck_require__(3570); -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); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - credentialDefaultProvider: config?.credentialDefaultProvider ?? credential_provider_node_1.defaultProvider, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || - (async (idProps) => await (0, credential_provider_node_1.defaultProvider)(idProps?.__config || {})()), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, - }, config), - 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, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 2642: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(2143); -const core_2 = __nccwpck_require__(5829); -const smithy_client_1 = __nccwpck_require__(3570); -const url_parser_1 = __nccwpck_require__(4681); -const util_base64_1 = __nccwpck_require__(5600); -const util_utf8_1 = __nccwpck_require__(1895); -const httpAuthSchemeProvider_1 = __nccwpck_require__(7145); -const endpointResolver_1 = __nccwpck_require__(1203); -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 ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - 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; - - -/***/ }), - -/***/ 2053: -/***/ ((__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__(6976); -const protocol_http_1 = __nccwpck_require__(4418); -const smithy_client_1 = __nccwpck_require__(3570); -const httpAuthExtensionConfiguration_1 = __nccwpck_require__(8527); -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); -}; -exports.resolveRuntimeExtensions = resolveRuntimeExtensions; - - -/***/ }), - -/***/ 6555: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.defaultSSOHttpAuthSchemeProvider = exports.defaultSSOHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(2143); -const util_middleware_1 = __nccwpck_require__(2390); -const defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "awsssoportal", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSSOHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "GetRoleCredentials": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "ListAccountRoles": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "ListAccounts": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "Logout": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - - -/***/ }), - -/***/ 3584: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(4241); -const util_endpoints_2 = __nccwpck_require__(5473); -const ruleset_1 = __nccwpck_require__(7957); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); -}; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - - -/***/ }), - -/***/ 7957: -/***/ ((__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; - - -/***/ }), - -/***/ 1687: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - GetRoleCredentialsCommand: () => GetRoleCredentialsCommand, - GetRoleCredentialsRequestFilterSensitiveLog: () => GetRoleCredentialsRequestFilterSensitiveLog, - GetRoleCredentialsResponseFilterSensitiveLog: () => GetRoleCredentialsResponseFilterSensitiveLog, - InvalidRequestException: () => InvalidRequestException, - ListAccountRolesCommand: () => ListAccountRolesCommand, - ListAccountRolesRequestFilterSensitiveLog: () => ListAccountRolesRequestFilterSensitiveLog, - ListAccountsCommand: () => ListAccountsCommand, - ListAccountsRequestFilterSensitiveLog: () => ListAccountsRequestFilterSensitiveLog, - LogoutCommand: () => LogoutCommand, - LogoutRequestFilterSensitiveLog: () => LogoutRequestFilterSensitiveLog, - ResourceNotFoundException: () => ResourceNotFoundException, - RoleCredentialsFilterSensitiveLog: () => RoleCredentialsFilterSensitiveLog, - SSO: () => SSO, - SSOClient: () => SSOClient, - SSOServiceException: () => SSOServiceException, - TooManyRequestsException: () => TooManyRequestsException, - UnauthorizedException: () => UnauthorizedException, - __Client: () => import_smithy_client.Client, - paginateListAccountRoles: () => paginateListAccountRoles, - paginateListAccounts: () => paginateListAccounts -}); -module.exports = __toCommonJS(index_exports); - -// src/SSOClient.ts -var import_middleware_host_header = __nccwpck_require__(9514); -var import_middleware_logger = __nccwpck_require__(5675); -var import_middleware_recursion_detection = __nccwpck_require__(7977); -var import_middleware_user_agent = __nccwpck_require__(6634); -var import_config_resolver = __nccwpck_require__(3098); -var import_core = __nccwpck_require__(5829); -var import_middleware_content_length = __nccwpck_require__(2800); -var import_middleware_endpoint = __nccwpck_require__(2918); -var import_middleware_retry = __nccwpck_require__(6039); - -var import_httpAuthSchemeProvider = __nccwpck_require__(6555); - -// src/endpoint/EndpointParameters.ts -var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "awsssoportal" - }); -}, "resolveClientEndpointParameters"); -var commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } -}; - -// src/SSOClient.ts -var import_runtimeConfig = __nccwpck_require__(1012); - -// src/runtimeExtensions.ts -var import_region_config_resolver = __nccwpck_require__(6976); -var import_protocol_http = __nccwpck_require__(4418); -var import_smithy_client = __nccwpck_require__(3570); - -// src/auth/httpAuthExtensionConfiguration.ts -var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; -}, "getHttpAuthExtensionConfiguration"); -var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; -}, "resolveHttpAuthRuntimeConfig"); - -// src/runtimeExtensions.ts -var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign( - (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), - (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), - (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), - getHttpAuthExtensionConfiguration(runtimeConfig) - ); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign( - runtimeConfig, - (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), - (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), - (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), - resolveHttpAuthRuntimeConfig(extensionConfiguration) - ); -}, "resolveRuntimeExtensions"); - -// src/SSOClient.ts -var SSOClient = class extends import_smithy_client.Client { - static { - __name(this, "SSOClient"); - } - /** - * The resolved configuration of SSOClient class. This is resolved and normalized from the {@link SSOClientConfig | constructor configuration interface}. - */ - config; - constructor(...[configuration]) { - const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); - const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use( - (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials - }), "identityProviderConfigProvider") - }) - ); - this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); - } - /** - * Destroy underlying resources, like sockets. It's usually not necessary to do this. - * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. - * Otherwise, sockets might stay open for quite a long time before the server terminates them. - */ - destroy() { - super.destroy(); - } -}; - -// src/SSO.ts - - -// src/commands/GetRoleCredentialsCommand.ts - -var import_middleware_serde = __nccwpck_require__(1238); - - -// src/models/models_0.ts - - -// src/models/SSOServiceException.ts - -var SSOServiceException = class _SSOServiceException extends import_smithy_client.ServiceException { - static { - __name(this, "SSOServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SSOServiceException.prototype); - } -}; - -// src/models/models_0.ts -var InvalidRequestException = class _InvalidRequestException extends SSOServiceException { - static { - __name(this, "InvalidRequestException"); - } - name = "InvalidRequestException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidRequestException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidRequestException.prototype); - } -}; -var ResourceNotFoundException = class _ResourceNotFoundException extends SSOServiceException { - static { - __name(this, "ResourceNotFoundException"); - } - name = "ResourceNotFoundException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ResourceNotFoundException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ResourceNotFoundException.prototype); - } -}; -var TooManyRequestsException = class _TooManyRequestsException extends SSOServiceException { - static { - __name(this, "TooManyRequestsException"); - } - name = "TooManyRequestsException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "TooManyRequestsException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _TooManyRequestsException.prototype); - } -}; -var UnauthorizedException = class _UnauthorizedException extends SSOServiceException { - static { - __name(this, "UnauthorizedException"); - } - name = "UnauthorizedException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnauthorizedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnauthorizedException.prototype); - } -}; -var GetRoleCredentialsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "GetRoleCredentialsRequestFilterSensitiveLog"); -var RoleCredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.secretAccessKey && { secretAccessKey: import_smithy_client.SENSITIVE_STRING }, - ...obj.sessionToken && { sessionToken: import_smithy_client.SENSITIVE_STRING } -}), "RoleCredentialsFilterSensitiveLog"); -var GetRoleCredentialsResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) } -}), "GetRoleCredentialsResponseFilterSensitiveLog"); -var ListAccountRolesRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "ListAccountRolesRequestFilterSensitiveLog"); -var ListAccountsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "ListAccountsRequestFilterSensitiveLog"); -var LogoutRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client.SENSITIVE_STRING } -}), "LogoutRequestFilterSensitiveLog"); - -// src/protocols/Aws_restJson1.ts -var import_core2 = __nccwpck_require__(2143); - - -var se_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/federation/credentials"); - const query = (0, import_smithy_client.map)({ - [_rn]: [, (0, import_smithy_client.expectNonNull)(input[_rN], `roleName`)], - [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)] - }); - let body; - b.m("GET").h(headers).q(query).b(body); - return b.build(); -}, "se_GetRoleCredentialsCommand"); -var se_ListAccountRolesCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/assignment/roles"); - const query = (0, import_smithy_client.map)({ - [_nt]: [, input[_nT]], - [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()], - [_ai]: [, (0, import_smithy_client.expectNonNull)(input[_aI], `accountId`)] - }); - let body; - b.m("GET").h(headers).q(query).b(body); - return b.build(); -}, "se_ListAccountRolesCommand"); -var se_ListAccountsCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/assignment/accounts"); - const query = (0, import_smithy_client.map)({ - [_nt]: [, input[_nT]], - [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()] - }); - let body; - b.m("GET").h(headers).q(query).b(body); - return b.build(); -}, "se_ListAccountsCommand"); -var se_LogoutCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core.requestBuilder)(input, context); - const headers = (0, import_smithy_client.map)({}, import_smithy_client.isSerializableHeaderValue, { - [_xasbt]: input[_aT] - }); - b.bp("/logout"); - let body; - b.m("POST").h(headers).b(body); - return b.build(); -}, "se_LogoutCommand"); -var de_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client.take)(data, { - roleCredentials: import_smithy_client._json - }); - Object.assign(contents, doc); - return contents; -}, "de_GetRoleCredentialsCommand"); -var de_ListAccountRolesCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client.take)(data, { - nextToken: import_smithy_client.expectString, - roleList: import_smithy_client._json - }); - Object.assign(contents, doc); - return contents; -}, "de_ListAccountRolesCommand"); -var de_ListAccountsCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client.expectNonNull)((0, import_smithy_client.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client.take)(data, { - accountList: import_smithy_client._json, - nextToken: import_smithy_client.expectString - }); - Object.assign(contents, doc); - return contents; -}, "de_ListAccountsCommand"); -var de_LogoutCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client.map)({ - $metadata: deserializeMetadata(output) - }); - await (0, import_smithy_client.collectBody)(output.body, context); - return contents; -}, "de_LogoutCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core2.parseJsonErrorBody)(output.body, context) - }; - const errorCode = (0, import_core2.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 - }); - } -}, "de_CommandError"); -var throwDefaultError = (0, import_smithy_client.withBaseException)(SSOServiceException); -var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidRequestException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidRequestExceptionRes"); -var de_ResourceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new ResourceNotFoundException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_ResourceNotFoundExceptionRes"); -var de_TooManyRequestsExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new TooManyRequestsException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_TooManyRequestsExceptionRes"); -var de_UnauthorizedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client.take)(data, { - message: import_smithy_client.expectString - }); - Object.assign(contents, doc); - const exception = new UnauthorizedException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnauthorizedExceptionRes"); -var deserializeMetadata = /* @__PURE__ */ __name((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"] -}), "deserializeMetadata"); -var _aI = "accountId"; -var _aT = "accessToken"; -var _ai = "account_id"; -var _mR = "maxResults"; -var _mr = "max_result"; -var _nT = "nextToken"; -var _nt = "next_token"; -var _rN = "roleName"; -var _rn = "role_name"; -var _xasbt = "x-amz-sso_bearer_token"; - -// src/commands/GetRoleCredentialsCommand.ts -var GetRoleCredentialsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog).ser(se_GetRoleCredentialsCommand).de(de_GetRoleCredentialsCommand).build() { - static { - __name(this, "GetRoleCredentialsCommand"); - } -}; - -// src/commands/ListAccountRolesCommand.ts - - - -var ListAccountRolesCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").f(ListAccountRolesRequestFilterSensitiveLog, void 0).ser(se_ListAccountRolesCommand).de(de_ListAccountRolesCommand).build() { - static { - __name(this, "ListAccountRolesCommand"); - } -}; - -// src/commands/ListAccountsCommand.ts - - - -var ListAccountsCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").f(ListAccountsRequestFilterSensitiveLog, void 0).ser(se_ListAccountsCommand).de(de_ListAccountsCommand).build() { - static { - __name(this, "ListAccountsCommand"); - } -}; - -// src/commands/LogoutCommand.ts - - - -var LogoutCommand = class extends import_smithy_client.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").f(LogoutRequestFilterSensitiveLog, void 0).ser(se_LogoutCommand).de(de_LogoutCommand).build() { - static { - __name(this, "LogoutCommand"); - } -}; - -// src/SSO.ts -var commands = { - GetRoleCredentialsCommand, - ListAccountRolesCommand, - ListAccountsCommand, - LogoutCommand -}; -var SSO = class extends SSOClient { - static { - __name(this, "SSO"); - } -}; -(0, import_smithy_client.createAggregatedClient)(commands, SSO); - -// src/pagination/ListAccountRolesPaginator.ts - -var paginateListAccountRoles = (0, import_core.createPaginator)(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults"); - -// src/pagination/ListAccountsPaginator.ts - -var paginateListAccounts = (0, import_core.createPaginator)(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 1012: -/***/ ((__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__(4665)); -const core_1 = __nccwpck_require__(2143); -const util_user_agent_node_1 = __nccwpck_require__(7330); -const config_resolver_1 = __nccwpck_require__(3098); -const hash_node_1 = __nccwpck_require__(3081); -const middleware_retry_1 = __nccwpck_require__(6039); -const node_config_provider_1 = __nccwpck_require__(3461); -const node_http_handler_1 = __nccwpck_require__(258); -const util_body_length_node_1 = __nccwpck_require__(8075); -const util_retry_1 = __nccwpck_require__(4902); -const runtimeConfig_shared_1 = __nccwpck_require__(7369); -const smithy_client_1 = __nccwpck_require__(3570); -const util_defaults_mode_node_1 = __nccwpck_require__(2429); -const smithy_client_2 = __nccwpck_require__(3570); -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); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ 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, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, - }, config), - 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, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 7369: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(2143); -const core_2 = __nccwpck_require__(5829); -const smithy_client_1 = __nccwpck_require__(3570); -const url_parser_1 = __nccwpck_require__(4681); -const util_base64_1 = __nccwpck_require__(5600); -const util_utf8_1 = __nccwpck_require__(1895); -const httpAuthSchemeProvider_1 = __nccwpck_require__(6555); -const endpointResolver_1 = __nccwpck_require__(3584); -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 ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - 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; - - -/***/ }), - -/***/ 2143: -/***/ ((__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__(6510), exports); -tslib_1.__exportStar(__nccwpck_require__(3017), exports); -tslib_1.__exportStar(__nccwpck_require__(5743), exports); - - -/***/ }), - -/***/ 6510: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/client/index.ts -var index_exports = {}; -__export(index_exports, { - emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, - setCredentialFeature: () => setCredentialFeature, - setFeature: () => setFeature, - setTokenFeature: () => setTokenFeature, - state: () => state -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/client/emitWarningIfUnsupportedVersion.ts -var state = { - warningEmitted: false -}; -var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { - if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { - state.warningEmitted = true; - process.emitWarning( - `NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will -no longer support Node.js 16.x on January 6, 2025. - -To continue receiving updates to AWS services, bug fixes, and security -updates please upgrade to a supported Node.js LTS version. - -More information can be found at: https://a.co/74kJMmI` - ); - } -}, "emitWarningIfUnsupportedVersion"); - -// src/submodules/client/setCredentialFeature.ts -function setCredentialFeature(credentials, feature, value) { - if (!credentials.$source) { - credentials.$source = {}; - } - credentials.$source[feature] = value; - return credentials; -} -__name(setCredentialFeature, "setCredentialFeature"); - -// src/submodules/client/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__aws_sdk_context) { - context.__aws_sdk_context = { - features: {} - }; - } else if (!context.__aws_sdk_context.features) { - context.__aws_sdk_context.features = {}; - } - context.__aws_sdk_context.features[feature] = value; -} -__name(setFeature, "setFeature"); - -// src/submodules/client/setTokenFeature.ts -function setTokenFeature(token, feature, value) { - if (!token.$source) { - token.$source = {}; - } - token.$source[feature] = value; - return token; -} -__name(setTokenFeature, "setTokenFeature"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 3017: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/httpAuthSchemes/index.ts -var index_exports = {}; -__export(index_exports, { - AWSSDKSigV4Signer: () => AWSSDKSigV4Signer, - AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner, - AwsSdkSigV4Signer: () => AwsSdkSigV4Signer, - NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, - NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS, - getBearerTokenEnvKey: () => getBearerTokenEnvKey, - resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config, - resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig, - resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config, - validateSigningProperties: () => validateSigningProperties -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts -var import_protocol_http2 = __nccwpck_require__(4418); - -// src/submodules/httpAuthSchemes/utils/getDateHeader.ts -var import_protocol_http = __nccwpck_require__(4418); -var getDateHeader = /* @__PURE__ */ __name((response) => import_protocol_http.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0, "getDateHeader"); - -// src/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.ts -var getSkewCorrectedDate = /* @__PURE__ */ __name((systemClockOffset) => new Date(Date.now() + systemClockOffset), "getSkewCorrectedDate"); - -// src/submodules/httpAuthSchemes/utils/isClockSkewed.ts -var isClockSkewed = /* @__PURE__ */ __name((clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5, "isClockSkewed"); - -// src/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.ts -var getUpdatedSystemClockOffset = /* @__PURE__ */ __name((clockTime, currentSystemClockOffset) => { - const clockTimeInMs = Date.parse(clockTime); - if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { - return clockTimeInMs - Date.now(); - } - return currentSystemClockOffset; -}, "getUpdatedSystemClockOffset"); - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts -var throwSigningPropertyError = /* @__PURE__ */ __name((name, property) => { - if (!property) { - throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); - } - return property; -}, "throwSigningPropertyError"); -var validateSigningProperties = /* @__PURE__ */ __name(async (signingProperties) => { - const context = throwSigningPropertyError( - "context", - signingProperties.context - ); - const config = throwSigningPropertyError("config", signingProperties.config); - const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; - const signerFunction = throwSigningPropertyError( - "signer", - config.signer - ); - const signer = await signerFunction(authScheme); - const signingRegion = signingProperties?.signingRegion; - const signingRegionSet = signingProperties?.signingRegionSet; - const signingName = signingProperties?.signingName; - return { - config, - signer, - signingRegion, - signingRegionSet, - signingName - }; -}, "validateSigningProperties"); -var AwsSdkSigV4Signer = class { - static { - __name(this, "AwsSdkSigV4Signer"); - } - async sign(httpRequest, identity, signingProperties) { - if (!import_protocol_http2.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const validatedProps = await validateSigningProperties(signingProperties); - const { config, signer } = validatedProps; - let { signingRegion, signingName } = validatedProps; - const handlerExecutionContext = signingProperties.context; - if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { - const [first, second] = handlerExecutionContext.authSchemes; - if (first?.name === "sigv4a" && second?.name === "sigv4") { - signingRegion = second?.signingRegion ?? signingRegion; - signingName = second?.signingName ?? signingName; - } - } - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion, - signingService: signingName - }); - return signedRequest; - } - errorHandler(signingProperties) { - return (error) => { - const serverTime = error.ServerTime ?? getDateHeader(error.$response); - if (serverTime) { - const config = throwSigningPropertyError("config", signingProperties.config); - const initialSystemClockOffset = config.systemClockOffset; - config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); - const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; - if (clockSkewCorrected && error.$metadata) { - error.$metadata.clockSkewCorrected = true; - } - } - throw error; - }; - } - successHandler(httpResponse, signingProperties) { - const dateHeader = getDateHeader(httpResponse); - if (dateHeader) { - const config = throwSigningPropertyError("config", signingProperties.config); - config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); - } - } -}; -var AWSSDKSigV4Signer = AwsSdkSigV4Signer; - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.ts -var import_protocol_http3 = __nccwpck_require__(4418); -var AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer { - static { - __name(this, "AwsSdkSigV4ASigner"); - } - async sign(httpRequest, identity, signingProperties) { - if (!import_protocol_http3.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties( - signingProperties - ); - const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); - const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(","); - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion: multiRegionOverride, - signingService: signingName - }); - return signedRequest; - } -}; - -// src/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.ts -var getArrayForCommaSeparatedString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [], "getArrayForCommaSeparatedString"); - -// src/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.ts -var getBearerTokenEnvKey = /* @__PURE__ */ __name((signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`, "getBearerTokenEnvKey"); - -// src/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.ts -var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; -var NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; -var NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { - /** - * Retrieves auth scheme preference from environment variables - * @param env - Node process environment object - * @returns Array of auth scheme strings if preference is set, undefined otherwise - */ - environmentVariableSelector: /* @__PURE__ */ __name((env, options) => { - if (options?.signingName) { - const bearerTokenKey = getBearerTokenEnvKey(options.signingName); - if (bearerTokenKey in env) return ["httpBearerAuth"]; - } - if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) return void 0; - return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); - }, "environmentVariableSelector"), - /** - * Retrieves auth scheme preference from config file - * @param profile - Config profile object - * @returns Array of auth scheme strings if preference is set, undefined otherwise - */ - configFileSelector: /* @__PURE__ */ __name((profile) => { - if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) return void 0; - return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); - }, "configFileSelector"), - /** - * Default auth scheme preference if not specified in environment or config - */ - default: [] -}; - -// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.ts -var import_core = __nccwpck_require__(5829); -var import_property_provider = __nccwpck_require__(9721); -var resolveAwsSdkSigV4AConfig = /* @__PURE__ */ __name((config) => { - config.sigv4aSigningRegionSet = (0, import_core.normalizeProvider)(config.sigv4aSigningRegionSet); - return config; -}, "resolveAwsSdkSigV4AConfig"); -var NODE_SIGV4A_CONFIG_OPTIONS = { - environmentVariableSelector(env) { - if (env.AWS_SIGV4A_SIGNING_REGION_SET) { - return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); - } - throw new import_property_provider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { - tryNextLink: true - }); - }, - configFileSelector(profile) { - if (profile.sigv4a_signing_region_set) { - return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); - } - throw new import_property_provider.ProviderError("sigv4a_signing_region_set not set in profile.", { - tryNextLink: true - }); - }, - default: void 0 -}; - -// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.ts -var import_client = __nccwpck_require__(6510); -var import_core2 = __nccwpck_require__(5829); -var import_signature_v4 = __nccwpck_require__(1528); -var resolveAwsSdkSigV4Config = /* @__PURE__ */ __name((config) => { - let inputCredentials = config.credentials; - let isUserSupplied = !!config.credentials; - let resolvedCredentials = void 0; - Object.defineProperty(config, "credentials", { - set(credentials) { - if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { - isUserSupplied = true; - } - inputCredentials = credentials; - const memoizedProvider = normalizeCredentialProvider(config, { - credentials: inputCredentials, - credentialDefaultProvider: config.credentialDefaultProvider - }); - const boundProvider = bindCallerConfig(config, memoizedProvider); - if (isUserSupplied && !boundProvider.attributed) { - resolvedCredentials = /* @__PURE__ */ __name(async (options) => boundProvider(options).then( - (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_CODE", "e") - ), "resolvedCredentials"); - resolvedCredentials.memoized = boundProvider.memoized; - resolvedCredentials.configBound = boundProvider.configBound; - resolvedCredentials.attributed = true; - } else { - resolvedCredentials = boundProvider; - } - }, - get() { - return resolvedCredentials; - }, - enumerable: true, - configurable: true - }); - config.credentials = inputCredentials; - const { - // Default for signingEscapePath - signingEscapePath = true, - // Default for systemClockOffset - systemClockOffset = config.systemClockOffset || 0, - // No default for sha256 since it is platform dependent - sha256 - } = config; - let signer; - if (config.signer) { - signer = (0, import_core2.normalizeProvider)(config.signer); - } else if (config.regionInfoProvider) { - signer = /* @__PURE__ */ __name(() => (0, import_core2.normalizeProvider)(config.region)().then( - async (region) => [ - await config.regionInfoProvider(region, { - useFipsEndpoint: await config.useFipsEndpoint(), - useDualstackEndpoint: await config.useDualstackEndpoint() - }) || {}, - region - ] - ).then(([regionInfo, region]) => { - const { signingRegion, signingService } = regionInfo; - config.signingRegion = config.signingRegion || signingRegion || region; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }), "signer"); - } else { - signer = /* @__PURE__ */ __name(async (authScheme) => { - authScheme = Object.assign( - {}, - { - name: "sigv4", - signingName: config.signingName || config.defaultSigningName, - signingRegion: await (0, import_core2.normalizeProvider)(config.region)(), - properties: {} - }, - authScheme - ); - const signingRegion = authScheme.signingRegion; - const signingService = authScheme.signingName; - config.signingRegion = config.signingRegion || signingRegion; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }, "signer"); - } - const resolvedConfig = Object.assign(config, { - systemClockOffset, - signingEscapePath, - signer - }); - return resolvedConfig; -}, "resolveAwsSdkSigV4Config"); -var resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; -function normalizeCredentialProvider(config, { - credentials, - credentialDefaultProvider -}) { - let credentialsProvider; - if (credentials) { - if (!credentials?.memoized) { - credentialsProvider = (0, import_core2.memoizeIdentityProvider)(credentials, import_core2.isIdentityExpired, import_core2.doesIdentityRequireRefresh); - } else { - credentialsProvider = credentials; - } - } else { - if (credentialDefaultProvider) { - credentialsProvider = (0, import_core2.normalizeProvider)( - credentialDefaultProvider( - Object.assign({}, config, { - parentClientConfig: config - }) - ) - ); - } else { - credentialsProvider = /* @__PURE__ */ __name(async () => { - throw new Error( - "@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured." - ); - }, "credentialsProvider"); - } - } - credentialsProvider.memoized = true; - return credentialsProvider; -} -__name(normalizeCredentialProvider, "normalizeCredentialProvider"); -function bindCallerConfig(config, credentialsProvider) { - if (credentialsProvider.configBound) { - return credentialsProvider; - } - const fn = /* @__PURE__ */ __name(async (options) => credentialsProvider({ ...options, callerClientConfig: config }), "fn"); - fn.memoized = credentialsProvider.memoized; - fn.configBound = true; - return fn; -} -__name(bindCallerConfig, "bindCallerConfig"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 5743: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/protocols/index.ts -var index_exports = {}; -__export(index_exports, { - AwsEc2QueryProtocol: () => AwsEc2QueryProtocol, - AwsJson1_0Protocol: () => AwsJson1_0Protocol, - AwsJson1_1Protocol: () => AwsJson1_1Protocol, - AwsJsonRpcProtocol: () => AwsJsonRpcProtocol, - AwsQueryProtocol: () => AwsQueryProtocol, - AwsRestJsonProtocol: () => AwsRestJsonProtocol, - AwsRestXmlProtocol: () => AwsRestXmlProtocol, - JsonCodec: () => JsonCodec, - JsonShapeDeserializer: () => JsonShapeDeserializer, - JsonShapeSerializer: () => JsonShapeSerializer, - XmlCodec: () => XmlCodec, - XmlShapeDeserializer: () => XmlShapeDeserializer, - XmlShapeSerializer: () => XmlShapeSerializer, - _toBool: () => _toBool, - _toNum: () => _toNum, - _toStr: () => _toStr, - awsExpectUnion: () => awsExpectUnion, - loadRestJsonErrorCode: () => loadRestJsonErrorCode, - loadRestXmlErrorCode: () => loadRestXmlErrorCode, - parseJsonBody: () => parseJsonBody, - parseJsonErrorBody: () => parseJsonErrorBody, - parseXmlBody: () => parseXmlBody, - parseXmlErrorBody: () => parseXmlErrorBody -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/protocols/coercing-serializers.ts -var _toStr = /* @__PURE__ */ __name((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; -}, "_toStr"); -var _toBool = /* @__PURE__ */ __name((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; -}, "_toBool"); -var _toNum = /* @__PURE__ */ __name((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; -}, "_toNum"); - -// src/submodules/protocols/json/AwsJsonRpcProtocol.ts -var import_protocols = __nccwpck_require__(2241); -var import_schema3 = __nccwpck_require__(9826); -var import_util_body_length_browser = __nccwpck_require__(713); - -// src/submodules/protocols/ConfigurableSerdeContext.ts -var SerdeContextConfig = class { - static { - __name(this, "SerdeContextConfig"); - } - serdeContext; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } -}; - -// src/submodules/protocols/json/JsonShapeDeserializer.ts -var import_schema = __nccwpck_require__(9826); -var import_serde2 = __nccwpck_require__(7669); -var import_util_base64 = __nccwpck_require__(5600); - -// src/submodules/protocols/json/jsonReviver.ts -var import_serde = __nccwpck_require__(7669); -function jsonReviver(key, value, context) { - if (context?.source) { - const numericString = context.source; - if (typeof value === "number") { - if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { - const isFractional = numericString.includes("."); - if (isFractional) { - return new import_serde.NumericValue(numericString, "bigDecimal"); - } else { - return BigInt(numericString); - } - } - } - } - return value; -} -__name(jsonReviver, "jsonReviver"); - -// src/submodules/protocols/common.ts -var import_smithy_client = __nccwpck_require__(3570); -var collectBodyString = /* @__PURE__ */ __name((streamBody, context) => (0, import_smithy_client.collectBody)(streamBody, context).then((body) => context.utf8Encoder(body)), "collectBodyString"); - -// src/submodules/protocols/json/parseJsonBody.ts -var parseJsonBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - try { - return JSON.parse(encoded); - } catch (e) { - if (e?.name === "SyntaxError") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded - }); - } - throw e; - } - } - return {}; -}), "parseJsonBody"); -var parseJsonErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { - const value = await parseJsonBody(errorBody, context); - value.message = value.message ?? value.Message; - return value; -}, "parseJsonErrorBody"); -var loadRestJsonErrorCode = /* @__PURE__ */ __name((output, data) => { - const findKey = /* @__PURE__ */ __name((object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()), "findKey"); - const sanitizeErrorCode = /* @__PURE__ */ __name((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; - }, "sanitizeErrorCode"); - const headerKey = findKey(output.headers, "x-amzn-errortype"); - if (headerKey !== void 0) { - return sanitizeErrorCode(output.headers[headerKey]); - } - if (data && typeof data === "object") { - const codeKey = findKey(data, "code"); - if (codeKey && data[codeKey] !== void 0) { - return sanitizeErrorCode(data[codeKey]); - } - if (data["__type"] !== void 0) { - return sanitizeErrorCode(data["__type"]); - } - } -}, "loadRestJsonErrorCode"); - -// src/submodules/protocols/json/JsonShapeDeserializer.ts -var JsonShapeDeserializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "JsonShapeDeserializer"); - } - async read(schema, data) { - return this._read( - schema, - typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext) - ); - } - readObject(schema, data) { - return this._read(schema, data); - } - _read(schema, value) { - const isObject = value !== null && typeof value === "object"; - const ns = import_schema.NormalizedSchema.of(schema); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._read(listMember, item)); - } - } - return out; - } else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._read(mapMember, _v); - } - } - return out; - } else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const deserializedValue = this._read(memberSchema, value[fromKey]); - if (deserializedValue != null) { - out[memberName] = deserializedValue; - } - } - return out; - } - if (ns.isBlobSchema() && typeof value === "string") { - return (0, import_util_base64.fromBase64)(value); - } - const mediaType = ns.getMergedTraits().mediaType; - if (ns.isStringSchema() && typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return import_serde2.LazyJsonString.from(value); - } - } - if (ns.isTimestampSchema()) { - const options = this.settings.timestampFormat; - const format = options.useTrait ? ns.getSchema() === import_schema.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; - switch (format) { - case import_schema.SCHEMA.TIMESTAMP_DATE_TIME: - return (0, import_serde2.parseRfc3339DateTimeWithOffset)(value); - case import_schema.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde2.parseRfc7231DateTime)(value); - case import_schema.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return (0, import_serde2.parseEpochTimestamp)(value); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", value); - return new Date(value); - } - } - if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { - return BigInt(value); - } - if (ns.isBigDecimalSchema() && value != void 0) { - if (value instanceof import_serde2.NumericValue) { - return value; - } - return new import_serde2.NumericValue(String(value), "bigDecimal"); - } - if (ns.isNumericSchema() && typeof value === "string") { - switch (value) { - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - case "NaN": - return NaN; - } - } - return value; - } -}; - -// src/submodules/protocols/json/JsonShapeSerializer.ts -var import_schema2 = __nccwpck_require__(9826); -var import_serde4 = __nccwpck_require__(7669); -var import_serde5 = __nccwpck_require__(7669); - -// src/submodules/protocols/json/jsonReplacer.ts -var import_serde3 = __nccwpck_require__(7669); -var NUMERIC_CONTROL_CHAR = String.fromCharCode(925); -var JsonReplacer = class { - static { - __name(this, "JsonReplacer"); - } - /** - * Stores placeholder key to true serialized value lookup. - */ - values = /* @__PURE__ */ new Map(); - counter = 0; - stage = 0; - /** - * Creates a jsonReplacer function that reserves big integer and big decimal values - * for later replacement. - */ - createReplacer() { - if (this.stage === 1) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 1; - return (key, value) => { - if (value instanceof import_serde3.NumericValue) { - const v = `${NUMERIC_CONTROL_CHAR + +"nv" + this.counter++}_` + value.string; - this.values.set(`"${v}"`, value.string); - return v; - } - if (typeof value === "bigint") { - const s = value.toString(); - const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; - this.values.set(`"${v}"`, s); - return v; - } - return value; - }; - } - /** - * Replaces placeholder keys with their true values. - */ - replaceInJson(json) { - if (this.stage === 0) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 2; - if (this.counter === 0) { - return json; - } - for (const [key, value] of this.values) { - json = json.replace(key, value); - } - return json; - } -}; - -// src/submodules/protocols/json/JsonShapeSerializer.ts -var JsonShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "JsonShapeSerializer"); - } - buffer; - rootSchema; - write(schema, value) { - this.rootSchema = import_schema2.NormalizedSchema.of(schema); - this.buffer = this._write(this.rootSchema, value); - } - flush() { - if (this.rootSchema?.isStructSchema() || this.rootSchema?.isDocumentSchema()) { - const replacer = new JsonReplacer(); - return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); - } - return this.buffer; - } - _write(schema, value, container) { - const isObject = value !== null && typeof value === "object"; - const ns = import_schema2.NormalizedSchema.of(schema); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._write(listMember, item)); - } - } - return out; - } else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._write(mapMember, _v); - } - } - return out; - } else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const serializableValue = this._write(memberSchema, value[memberName], ns); - if (serializableValue !== void 0) { - out[targetKey] = serializableValue; - } - } - return out; - } - if (value === null && container?.isStructSchema()) { - return void 0; - } - if (ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string")) { - if (ns === this.rootSchema) { - return value; - } - if (!this.serdeContext?.base64Encoder) { - throw new Error("Missing base64Encoder in serdeContext"); - } - return this.serdeContext?.base64Encoder(value); - } - if (ns.isTimestampSchema() && value instanceof Date) { - const options = this.settings.timestampFormat; - const format = options.useTrait ? ns.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; - switch (format) { - case import_schema2.SCHEMA.TIMESTAMP_DATE_TIME: - return value.toISOString().replace(".000Z", "Z"); - case import_schema2.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde4.dateToUtcString)(value); - case import_schema2.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return value.getTime() / 1e3; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - return value.getTime() / 1e3; - } - } - if (ns.isNumericSchema() && typeof value === "number") { - if (Math.abs(value) === Infinity || isNaN(value)) { - return String(value); - } - } - const mediaType = ns.getMergedTraits().mediaType; - if (ns.isStringSchema() && typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return import_serde5.LazyJsonString.from(value); - } - } - return value; - } -}; - -// src/submodules/protocols/json/JsonCodec.ts -var JsonCodec = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "JsonCodec"); - } - createSerializer() { - const serializer = new JsonShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new JsonShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } -}; - -// src/submodules/protocols/json/AwsJsonRpcProtocol.ts -var AwsJsonRpcProtocol = class extends import_protocols.RpcProtocol { - static { - __name(this, "AwsJsonRpcProtocol"); - } - serializer; - deserializer; - codec; - constructor({ defaultNamespace }) { - super({ - defaultNamespace - }); - this.codec = new JsonCodec({ - timestampFormat: { - useTrait: true, - default: import_schema3.SCHEMA.TIMESTAMP_EPOCH_SECONDS - }, - jsonName: false - }); - this.serializer = this.codec.createSerializer(); - this.deserializer = this.codec.createDeserializer(); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, - "x-amz-target": (this.getJsonRpcVersion() === "1.0" ? `JsonRpc10.` : `JsonProtocol.`) + import_schema3.NormalizedSchema.of(operationSchema).getName() - }); - if ((0, import_schema3.deref)(operationSchema.input) === "unit" || !request.body) { - request.body = "{}"; - } - try { - request.headers["content-length"] = String((0, import_util_body_length_browser.calculateBodyLength)(request.body)); - } catch (e) { - } - return request; - } - getPayloadCodec() { - return this.codec; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const registry = import_schema3.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorIdentifier); - } catch (e) { - const baseExceptionSchema = import_schema3.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), dataObject); - } - throw new Error(errorName); - } - const ns = import_schema3.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output - }); - throw exception; - } -}; - -// src/submodules/protocols/json/AwsJson1_0Protocol.ts -var AwsJson1_0Protocol = class extends AwsJsonRpcProtocol { - static { - __name(this, "AwsJson1_0Protocol"); - } - constructor({ defaultNamespace }) { - super({ - defaultNamespace - }); - } - getShapeId() { - return "aws.protocols#awsJson1_0"; - } - getJsonRpcVersion() { - return "1.0"; - } -}; - -// src/submodules/protocols/json/AwsJson1_1Protocol.ts -var AwsJson1_1Protocol = class extends AwsJsonRpcProtocol { - static { - __name(this, "AwsJson1_1Protocol"); - } - constructor({ defaultNamespace }) { - super({ - defaultNamespace - }); - } - getShapeId() { - return "aws.protocols#awsJson1_1"; - } - getJsonRpcVersion() { - return "1.1"; - } -}; - -// src/submodules/protocols/json/AwsRestJsonProtocol.ts -var import_protocols2 = __nccwpck_require__(2241); -var import_schema4 = __nccwpck_require__(9826); -var import_util_body_length_browser2 = __nccwpck_require__(713); -var AwsRestJsonProtocol = class extends import_protocols2.HttpBindingProtocol { - static { - __name(this, "AwsRestJsonProtocol"); - } - serializer; - deserializer; - codec; - constructor({ defaultNamespace }) { - super({ - defaultNamespace - }); - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS - }, - httpBindings: true, - jsonName: true - }; - this.codec = new JsonCodec(settings); - this.serializer = new import_protocols2.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new import_protocols2.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); - } - getShapeId() { - return "aws.protocols#restJson1"; - } - getPayloadCodec() { - return this.codec; - } - setSerdeContext(serdeContext) { - this.codec.setSerdeContext(serdeContext); - super.setSerdeContext(serdeContext); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = import_schema4.NormalizedSchema.of(operationSchema.input); - const members = inputSchema.getMemberSchemas(); - if (!request.headers["content-type"]) { - const httpPayloadMember = Object.values(members).find((m) => { - return !!m.getMergedTraits().httpPayload; - }); - if (httpPayloadMember) { - const mediaType = httpPayloadMember.getMergedTraits().mediaType; - if (mediaType) { - request.headers["content-type"] = mediaType; - } else if (httpPayloadMember.isStringSchema()) { - request.headers["content-type"] = "text/plain"; - } else if (httpPayloadMember.isBlobSchema()) { - request.headers["content-type"] = "application/octet-stream"; - } else { - request.headers["content-type"] = "application/json"; - } - } else if (!inputSchema.isUnitSchema()) { - const hasBody = Object.values(members).find((m) => { - const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); - return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && httpPrefixHeaders === void 0; - }); - if (hasBody) { - request.headers["content-type"] = "application/json"; - } - } - } - if (request.headers["content-type"] && !request.body) { - request.body = "{}"; - } - if (request.body) { - try { - request.headers["content-length"] = String((0, import_util_body_length_browser2.calculateBodyLength)(request.body)); - } catch (e) { - } - } - return request; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const registry = import_schema4.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorIdentifier); - } catch (e) { - const baseExceptionSchema = import_schema4.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), dataObject); - } - throw new Error(errorName); - } - const ns = import_schema4.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output - }); - throw exception; - } -}; - -// src/submodules/protocols/json/awsExpectUnion.ts -var import_smithy_client2 = __nccwpck_require__(3570); -var awsExpectUnion = /* @__PURE__ */ __name((value) => { - if (value == null) { - return void 0; - } - if (typeof value === "object" && "__type" in value) { - delete value.__type; - } - return (0, import_smithy_client2.expectUnion)(value); -}, "awsExpectUnion"); - -// src/submodules/protocols/query/AwsQueryProtocol.ts -var import_protocols5 = __nccwpck_require__(2241); -var import_schema7 = __nccwpck_require__(9826); -var import_util_body_length_browser3 = __nccwpck_require__(713); - -// src/submodules/protocols/xml/XmlShapeDeserializer.ts -var import_protocols3 = __nccwpck_require__(2241); -var import_schema5 = __nccwpck_require__(9826); -var import_smithy_client3 = __nccwpck_require__(3570); -var import_util_utf8 = __nccwpck_require__(1895); -var import_fast_xml_parser = __nccwpck_require__(7773); -var XmlShapeDeserializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - this.stringDeserializer = new import_protocols3.FromStringShapeDeserializer(settings); - } - static { - __name(this, "XmlShapeDeserializer"); - } - stringDeserializer; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.stringDeserializer.setSerdeContext(serdeContext); - } - /** - * @param schema - describing the data. - * @param bytes - serialized data. - * @param key - used by AwsQuery to step one additional depth into the object before reading it. - */ - read(schema, bytes, key) { - const ns = import_schema5.NormalizedSchema.of(schema); - const memberSchemas = ns.getMemberSchemas(); - const isEventPayload = ns.isStructSchema() && ns.isMemberSchema() && !!Object.values(memberSchemas).find((memberNs) => { - return !!memberNs.getMemberTraits().eventPayload; - }); - if (isEventPayload) { - const output = {}; - const memberName = Object.keys(memberSchemas)[0]; - const eventMemberSchema = memberSchemas[memberName]; - if (eventMemberSchema.isBlobSchema()) { - output[memberName] = bytes; - } else { - output[memberName] = this.read(memberSchemas[memberName], bytes); - } - return output; - } - const xmlString = (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)(bytes); - const parsedObject = this.parseXml(xmlString); - return this.readSchema(schema, key ? parsedObject[key] : parsedObject); - } - readSchema(_schema, value) { - const ns = import_schema5.NormalizedSchema.of(_schema); - const traits = ns.getMergedTraits(); - const schema = ns.getSchema(); - if (ns.isListSchema() && !Array.isArray(value)) { - return this.readSchema(schema, [value]); - } - if (value == null) { - return value; - } - if (typeof value === "object") { - const sparse = !!traits.sparse; - const flat = !!traits.xmlFlattened; - if (ns.isListSchema()) { - const listValue = ns.getValueSchema(); - const buffer2 = []; - const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; - const source = flat ? value : (value[0] ?? value)[sourceKey]; - const sourceArray = Array.isArray(source) ? source : [source]; - for (const v of sourceArray) { - if (v != null || sparse) { - buffer2.push(this.readSchema(listValue, v)); - } - } - return buffer2; - } - const buffer = {}; - if (ns.isMapSchema()) { - const keyNs = ns.getKeySchema(); - const memberNs = ns.getValueSchema(); - let entries; - if (flat) { - entries = Array.isArray(value) ? value : [value]; - } else { - entries = Array.isArray(value.entry) ? value.entry : [value.entry]; - } - const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; - const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; - for (const entry of entries) { - const key = entry[keyProperty]; - const value2 = entry[valueProperty]; - if (value2 != null || sparse) { - buffer[key] = this.readSchema(memberNs, value2); - } - } - return buffer; - } - if (ns.isStructSchema()) { - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMergedTraits(); - const xmlObjectKey = !memberTraits.httpPayload ? memberSchema.getMemberTraits().xmlName ?? memberName : memberTraits.xmlName ?? memberSchema.getName(); - if (value[xmlObjectKey] != null) { - buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); - } - } - return buffer; - } - if (ns.isDocumentSchema()) { - return value; - } - throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); - } else { - if (ns.isListSchema()) { - return []; - } else if (ns.isMapSchema() || ns.isStructSchema()) { - return {}; - } - return this.stringDeserializer.read(ns, value); - } - } - parseXml(xml) { - if (xml.length) { - const parser = new import_fast_xml_parser.XMLParser({ - attributeNamePrefix: "", - htmlEntities: true, - ignoreAttributes: false, - ignoreDeclaration: true, - parseTagValue: false, - trimValues: false, - tagValueProcessor: /* @__PURE__ */ __name((_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, "tagValueProcessor") - }); - parser.addEntity("#xD", "\r"); - parser.addEntity("#10", "\n"); - let parsedObj; - try { - parsedObj = parser.parse(xml, true); - } catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: xml - }); - } - throw e; - } - 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, import_smithy_client3.getValueFromTextNode)(parsedObjToReturn); - } - return {}; - } -}; - -// src/submodules/protocols/query/QueryShapeSerializer.ts -var import_protocols4 = __nccwpck_require__(2241); -var import_schema6 = __nccwpck_require__(9826); -var import_serde6 = __nccwpck_require__(7669); -var import_smithy_client4 = __nccwpck_require__(3570); -var import_util_base642 = __nccwpck_require__(5600); -var QueryShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "QueryShapeSerializer"); - } - buffer; - write(schema, value, prefix = "") { - if (this.buffer === void 0) { - this.buffer = ""; - } - const ns = import_schema6.NormalizedSchema.of(schema); - if (prefix && !prefix.endsWith(".")) { - prefix += "."; - } - if (ns.isBlobSchema()) { - if (typeof value === "string" || value instanceof Uint8Array) { - this.writeKey(prefix); - this.writeValue((this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value)); - } - } else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } - } else if (ns.isBigIntegerSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } - } else if (ns.isBigDecimalSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(value instanceof import_serde6.NumericValue ? value.string : String(value)); - } - } else if (ns.isTimestampSchema()) { - if (value instanceof Date) { - this.writeKey(prefix); - const format = (0, import_protocols4.determineTimestampFormat)(ns, this.settings); - switch (format) { - case import_schema6.SCHEMA.TIMESTAMP_DATE_TIME: - this.writeValue(value.toISOString().replace(".000Z", "Z")); - break; - case import_schema6.SCHEMA.TIMESTAMP_HTTP_DATE: - this.writeValue((0, import_smithy_client4.dateToUtcString)(value)); - break; - case import_schema6.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - this.writeValue(String(value.getTime() / 1e3)); - break; - } - } - } else if (ns.isDocumentSchema()) { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unsupported document type ${ns.getName(true)}`); - } else if (ns.isListSchema()) { - if (Array.isArray(value)) { - if (value.length === 0) { - if (this.settings.serializeEmptyLists) { - this.writeKey(prefix); - this.writeValue(""); - } - } else { - const member = ns.getValueSchema(); - const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const item of value) { - if (item == null) { - continue; - } - const suffix = this.getKey("member", member.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; - this.write(member, item, key); - ++i; - } - } - } - } else if (ns.isMapSchema()) { - if (value && typeof value === "object") { - const keySchema = ns.getKeySchema(); - const memberSchema = ns.getValueSchema(); - const flat = ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const [k, v] of Object.entries(value)) { - if (v == null) { - continue; - } - const keySuffix = this.getKey("key", keySchema.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; - const valueSuffix = this.getKey("value", memberSchema.getMergedTraits().xmlName); - const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; - this.write(keySchema, k, key); - this.write(memberSchema, v, valueKey); - ++i; - } - } - } else if (ns.isStructSchema()) { - if (value && typeof value === "object") { - for (const [memberName, member] of ns.structIterator()) { - if (value[memberName] == null) { - continue; - } - const suffix = this.getKey(memberName, member.getMergedTraits().xmlName); - const key = `${prefix}${suffix}`; - this.write(member, value[memberName], key); - } - } - } else if (ns.isUnitSchema()) { - } else { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); - } - } - flush() { - if (this.buffer === void 0) { - throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); - } - const str = this.buffer; - delete this.buffer; - return str; - } - getKey(memberName, xmlName) { - const key = xmlName ?? memberName; - if (this.settings.capitalizeKeys) { - return key[0].toUpperCase() + key.slice(1); - } - return key; - } - writeKey(key) { - if (key.endsWith(".")) { - key = key.slice(0, key.length - 1); - } - this.buffer += `&${(0, import_protocols4.extendedEncodeURIComponent)(key)}=`; - } - writeValue(value) { - this.buffer += (0, import_protocols4.extendedEncodeURIComponent)(value); - } -}; - -// src/submodules/protocols/query/AwsQueryProtocol.ts -var AwsQueryProtocol = class extends import_protocols5.RpcProtocol { - constructor(options) { - super({ - defaultNamespace: options.defaultNamespace - }); - this.options = options; - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema7.SCHEMA.TIMESTAMP_DATE_TIME - }, - httpBindings: false, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace, - serializeEmptyLists: true - }; - this.serializer = new QueryShapeSerializer(settings); - this.deserializer = new XmlShapeDeserializer(settings); - } - static { - __name(this, "AwsQueryProtocol"); - } - serializer; - deserializer; - getShapeId() { - return "aws.protocols#awsQuery"; - } - setSerdeContext(serdeContext) { - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - } - getPayloadCodec() { - throw new Error("AWSQuery protocol has no payload codec."); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-www-form-urlencoded` - }); - if ((0, import_schema7.deref)(operationSchema.input) === "unit" || !request.body) { - request.body = ""; - } - request.body = `Action=${operationSchema.name.split("#")[1]}&Version=${this.options.version}` + request.body; - if (request.body.endsWith("&")) { - request.body = request.body.slice(-1); - } - try { - request.headers["content-length"] = String((0, import_util_body_length_browser3.calculateBodyLength)(request.body)); - } catch (e) { - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema7.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes2 = await (0, import_protocols5.collectBody)(response.body, context); - if (bytes2.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema7.SCHEMA.DOCUMENT, bytes2)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? operationSchema.name.split("#")[1] + "Result" : void 0; - const bytes = await (0, import_protocols5.collectBody)(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); - } - const output = { - $metadata: this.deserializeMetadata(response), - ...dataObject - }; - return output; - } - /** - * EC2 Query overrides this. - */ - useNestedResult() { - return true; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const errorDataSource = this.loadQueryError(dataObject); - const registry = import_schema7.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.find( - (schema) => import_schema7.NormalizedSchema.of(schema).getMergedTraits().awsQueryError?.[0] === errorName - ); - if (!errorSchema) { - errorSchema = registry.getSchema(errorIdentifier); - } - } catch (e) { - const baseExceptionSchema = import_schema7.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), errorDataSource); - } - throw new Error(errorName); - } - const ns = import_schema7.NormalizedSchema.of(errorSchema); - const message = this.loadQueryErrorMessage(dataObject); - const exception = new errorSchema.ctor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = errorDataSource[target] ?? dataObject[target]; - output[name] = this.deserializer.readSchema(member, value); - } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output - }); - throw exception; - } - /** - * The variations in the error and error message locations are attributed to - * divergence between AWS Query and EC2 Query behavior. - */ - loadQueryErrorCode(output, data) { - const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; - if (code !== void 0) { - return code; - } - if (output.statusCode == 404) { - return "NotFound"; - } - } - loadQueryError(data) { - return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; - } - loadQueryErrorMessage(data) { - const errorData = this.loadQueryError(data); - return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; - } -}; - -// src/submodules/protocols/query/AwsEc2QueryProtocol.ts -var AwsEc2QueryProtocol = class extends AwsQueryProtocol { - constructor(options) { - super(options); - this.options = options; - const ec2Settings = { - capitalizeKeys: true, - flattenLists: true, - serializeEmptyLists: false - }; - Object.assign(this.serializer.settings, ec2Settings); - } - static { - __name(this, "AwsEc2QueryProtocol"); - } - /** - * EC2 Query reads XResponse.XResult instead of XResponse directly. - */ - useNestedResult() { - return false; - } -}; - -// src/submodules/protocols/xml/AwsRestXmlProtocol.ts -var import_protocols6 = __nccwpck_require__(2241); -var import_schema9 = __nccwpck_require__(9826); -var import_util_body_length_browser4 = __nccwpck_require__(713); - -// src/submodules/protocols/xml/parseXmlBody.ts -var import_smithy_client5 = __nccwpck_require__(3570); -var import_fast_xml_parser2 = __nccwpck_require__(7773); -var parseXmlBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - const parser = new import_fast_xml_parser2.XMLParser({ - attributeNamePrefix: "", - htmlEntities: true, - ignoreAttributes: false, - ignoreDeclaration: true, - parseTagValue: false, - trimValues: false, - tagValueProcessor: /* @__PURE__ */ __name((_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, "tagValueProcessor") - }); - parser.addEntity("#xD", "\r"); - parser.addEntity("#10", "\n"); - let parsedObj; - try { - parsedObj = parser.parse(encoded, true); - } catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded - }); - } - throw e; - } - 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, import_smithy_client5.getValueFromTextNode)(parsedObjToReturn); - } - return {}; -}), "parseXmlBody"); -var parseXmlErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { - const value = await parseXmlBody(errorBody, context); - if (value.Error) { - value.Error.message = value.Error.message ?? value.Error.Message; - } - return value; -}, "parseXmlErrorBody"); -var loadRestXmlErrorCode = /* @__PURE__ */ __name((output, data) => { - if (data?.Error?.Code !== void 0) { - return data.Error.Code; - } - if (data?.Code !== void 0) { - return data.Code; - } - if (output.statusCode == 404) { - return "NotFound"; - } -}, "loadRestXmlErrorCode"); - -// src/submodules/protocols/xml/XmlShapeSerializer.ts -var import_xml_builder = __nccwpck_require__(2329); -var import_schema8 = __nccwpck_require__(9826); -var import_serde7 = __nccwpck_require__(7669); -var import_smithy_client6 = __nccwpck_require__(3570); -var import_util_base643 = __nccwpck_require__(5600); -var XmlShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "XmlShapeSerializer"); - } - stringBuffer; - byteBuffer; - buffer; - write(schema, value) { - const ns = import_schema8.NormalizedSchema.of(schema); - if (ns.isStringSchema() && typeof value === "string") { - this.stringBuffer = value; - } else if (ns.isBlobSchema()) { - this.byteBuffer = "byteLength" in value ? value : (this.serdeContext?.base64Decoder ?? import_util_base643.fromBase64)(value); - } else { - this.buffer = this.writeStruct(ns, value, void 0); - const traits = ns.getMergedTraits(); - if (traits.httpPayload && !traits.xmlName) { - this.buffer.withName(ns.getName()); - } - } - } - flush() { - if (this.byteBuffer !== void 0) { - const bytes = this.byteBuffer; - delete this.byteBuffer; - return bytes; - } - if (this.stringBuffer !== void 0) { - const str = this.stringBuffer; - delete this.stringBuffer; - return str; - } - const buffer = this.buffer; - if (this.settings.xmlNamespace) { - if (!buffer?.attributes?.["xmlns"]) { - buffer.addAttribute("xmlns", this.settings.xmlNamespace); - } - } - delete this.buffer; - return buffer.toString(); - } - writeStruct(ns, value, parentXmlns) { - const traits = ns.getMergedTraits(); - const name = ns.isMemberSchema() && !traits.httpPayload ? ns.getMemberTraits().xmlName ?? ns.getMemberName() : traits.xmlName ?? ns.getName(); - if (!name || !ns.isStructSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName( - true - )}.` - ); - } - const structXmlNode = import_xml_builder.XmlNode.of(name); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - if (xmlns) { - structXmlNode.addAttribute(xmlnsAttr, xmlns); - } - for (const [memberName, memberSchema] of ns.structIterator()) { - const val = value[memberName]; - if (val != null) { - if (memberSchema.getMergedTraits().xmlAttribute) { - structXmlNode.addAttribute( - memberSchema.getMergedTraits().xmlName ?? memberName, - this.writeSimple(memberSchema, val) - ); - continue; - } - if (memberSchema.isListSchema()) { - this.writeList(memberSchema, val, structXmlNode, xmlns); - } else if (memberSchema.isMapSchema()) { - this.writeMap(memberSchema, val, structXmlNode, xmlns); - } else if (memberSchema.isStructSchema()) { - structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); - } else { - const memberNode = import_xml_builder.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); - this.writeSimpleInto(memberSchema, val, memberNode, xmlns); - structXmlNode.addChildNode(memberNode); - } - } - } - return structXmlNode; - } - writeList(listMember, array, container, parentXmlns) { - if (!listMember.isMemberSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}` - ); - } - const listTraits = listMember.getMergedTraits(); - const listValueSchema = listMember.getValueSchema(); - const listValueTraits = listValueSchema.getMergedTraits(); - const sparse = !!listValueTraits.sparse; - const flat = !!listTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); - const writeItem = /* @__PURE__ */ __name((container2, value) => { - if (listValueSchema.isListSchema()) { - this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container2, xmlns); - } else if (listValueSchema.isMapSchema()) { - this.writeMap(listValueSchema, value, container2, xmlns); - } else if (listValueSchema.isStructSchema()) { - const struct = this.writeStruct(listValueSchema, value, xmlns); - container2.addChildNode( - struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member") - ); - } else { - const listItemNode = import_xml_builder.XmlNode.of( - flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member" - ); - this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); - container2.addChildNode(listItemNode); - } - }, "writeItem"); - if (flat) { - for (const value of array) { - if (sparse || value != null) { - writeItem(container, value); - } - } - } else { - const listNode = import_xml_builder.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); - if (xmlns) { - listNode.addAttribute(xmlnsAttr, xmlns); - } - for (const value of array) { - if (sparse || value != null) { - writeItem(listNode, value); - } - } - container.addChildNode(listNode); - } - } - writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { - if (!mapMember.isMemberSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}` - ); - } - const mapTraits = mapMember.getMergedTraits(); - const mapKeySchema = mapMember.getKeySchema(); - const mapKeyTraits = mapKeySchema.getMergedTraits(); - const keyTag = mapKeyTraits.xmlName ?? "key"; - const mapValueSchema = mapMember.getValueSchema(); - const mapValueTraits = mapValueSchema.getMergedTraits(); - const valueTag = mapValueTraits.xmlName ?? "value"; - const sparse = !!mapValueTraits.sparse; - const flat = !!mapTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); - const addKeyValue = /* @__PURE__ */ __name((entry, key, val) => { - const keyNode = import_xml_builder.XmlNode.of(keyTag, key); - const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); - if (keyXmlns) { - keyNode.addAttribute(keyXmlnsAttr, keyXmlns); - } - entry.addChildNode(keyNode); - let valueNode = import_xml_builder.XmlNode.of(valueTag); - if (mapValueSchema.isListSchema()) { - this.writeList(mapValueSchema, val, valueNode, xmlns); - } else if (mapValueSchema.isMapSchema()) { - this.writeMap(mapValueSchema, val, valueNode, xmlns, true); - } else if (mapValueSchema.isStructSchema()) { - valueNode = this.writeStruct(mapValueSchema, val, xmlns); - } else { - this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); - } - entry.addChildNode(valueNode); - }, "addKeyValue"); - if (flat) { - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = import_xml_builder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - addKeyValue(entry, key, val); - container.addChildNode(entry); - } - } - } else { - let mapNode; - if (!containerIsMap) { - mapNode = import_xml_builder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - if (xmlns) { - mapNode.addAttribute(xmlnsAttr, xmlns); - } - container.addChildNode(mapNode); - } - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = import_xml_builder.XmlNode.of("entry"); - addKeyValue(entry, key, val); - (containerIsMap ? container : mapNode).addChildNode(entry); - } - } - } - } - writeSimple(_schema, value) { - if (null === value) { - throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); - } - const ns = import_schema8.NormalizedSchema.of(_schema); - let nodeContents = null; - if (value && typeof value === "object") { - if (ns.isBlobSchema()) { - nodeContents = (this.serdeContext?.base64Encoder ?? import_util_base643.toBase64)(value); - } else if (ns.isTimestampSchema() && value instanceof Date) { - const options = this.settings.timestampFormat; - const format = options.useTrait ? ns.getSchema() === import_schema8.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; - switch (format) { - case import_schema8.SCHEMA.TIMESTAMP_DATE_TIME: - nodeContents = value.toISOString().replace(".000Z", "Z"); - break; - case import_schema8.SCHEMA.TIMESTAMP_HTTP_DATE: - nodeContents = (0, import_smithy_client6.dateToUtcString)(value); - break; - case import_schema8.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - nodeContents = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using http date", value); - nodeContents = (0, import_smithy_client6.dateToUtcString)(value); - break; - } - } else if (ns.isBigDecimalSchema() && value) { - if (value instanceof import_serde7.NumericValue) { - return value.string; - } - return String(value); - } else if (ns.isMapSchema() || ns.isListSchema()) { - throw new Error( - "@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead." - ); - } else { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName( - true - )}` - ); - } - } - if (ns.isStringSchema() || ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { - nodeContents = String(value); - } - if (nodeContents === null) { - throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); - } - return nodeContents; - } - writeSimpleInto(_schema, value, into, parentXmlns) { - const nodeContents = this.writeSimple(_schema, value); - const ns = import_schema8.NormalizedSchema.of(_schema); - const content = new import_xml_builder.XmlText(nodeContents); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - if (xmlns) { - into.addAttribute(xmlnsAttr, xmlns); - } - into.addChildNode(content); - } - getXmlnsAttribute(ns, parentXmlns) { - const traits = ns.getMergedTraits(); - const [prefix, xmlns] = traits.xmlNamespace ?? []; - if (xmlns && xmlns !== parentXmlns) { - return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; - } - return [void 0, void 0]; - } -}; - -// src/submodules/protocols/xml/XmlCodec.ts -var XmlCodec = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "XmlCodec"); - } - createSerializer() { - const serializer = new XmlShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new XmlShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } -}; - -// src/submodules/protocols/xml/AwsRestXmlProtocol.ts -var AwsRestXmlProtocol = class extends import_protocols6.HttpBindingProtocol { - static { - __name(this, "AwsRestXmlProtocol"); - } - codec; - serializer; - deserializer; - constructor(options) { - super(options); - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema9.SCHEMA.TIMESTAMP_DATE_TIME - }, - httpBindings: true, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace - }; - this.codec = new XmlCodec(settings); - this.serializer = new import_protocols6.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new import_protocols6.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); - } - getPayloadCodec() { - return this.codec; - } - getShapeId() { - return "aws.protocols#restXml"; - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const ns = import_schema9.NormalizedSchema.of(operationSchema.input); - const members = ns.getMemberSchemas(); - request.path = String(request.path).split("/").filter((segment) => { - return segment !== "{Bucket}"; - }).join("/") || "/"; - if (!request.headers["content-type"]) { - const httpPayloadMember = Object.values(members).find((m) => { - return !!m.getMergedTraits().httpPayload; - }); - if (httpPayloadMember) { - const mediaType = httpPayloadMember.getMergedTraits().mediaType; - if (mediaType) { - request.headers["content-type"] = mediaType; - } else if (httpPayloadMember.isStringSchema()) { - request.headers["content-type"] = "text/plain"; - } else if (httpPayloadMember.isBlobSchema()) { - request.headers["content-type"] = "application/octet-stream"; - } else { - request.headers["content-type"] = "application/xml"; - } - } else if (!ns.isUnitSchema()) { - const hasBody = Object.values(members).find((m) => { - const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); - return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && httpPrefixHeaders === void 0; - }); - if (hasBody) { - request.headers["content-type"] = "application/xml"; - } - } - } - if (request.headers["content-type"] === "application/xml") { - if (typeof request.body === "string") { - request.body = '' + request.body; - } - } - if (request.body) { - try { - request.headers["content-length"] = String((0, import_util_body_length_browser4.calculateBodyLength)(request.body)); - } catch (e) { - } - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - return super.deserializeResponse(operationSchema, context, response); - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const registry = import_schema9.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorIdentifier); - } catch (e) { - const baseExceptionSchema = import_schema9.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), dataObject); - } - throw new Error(errorName); - } - const ns = import_schema9.NormalizedSchema.of(errorSchema); - const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = dataObject.Error?.[target] ?? dataObject[target]; - output[name] = this.codec.createDeserializer().readSchema(member, value); - } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output - }); - throw exception; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 4407: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID, - ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE, - ENV_EXPIRATION: () => ENV_EXPIRATION, - ENV_KEY: () => ENV_KEY, - ENV_SECRET: () => ENV_SECRET, - ENV_SESSION: () => ENV_SESSION, - fromEnv: () => fromEnv -}); -module.exports = __toCommonJS(index_exports); - -// src/fromEnv.ts -var import_client = __nccwpck_require__(6510); -var import_property_provider = __nccwpck_require__(9721); -var ENV_KEY = "AWS_ACCESS_KEY_ID"; -var ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; -var ENV_SESSION = "AWS_SESSION_TOKEN"; -var ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; -var ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; -var ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; -var fromEnv = /* @__PURE__ */ __name((init) => async () => { - init?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); - const accessKeyId = process.env[ENV_KEY]; - const secretAccessKey = process.env[ENV_SECRET]; - const sessionToken = process.env[ENV_SESSION]; - const expiry = process.env[ENV_EXPIRATION]; - const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; - const accountId = process.env[ENV_ACCOUNT_ID]; - if (accessKeyId && secretAccessKey) { - const credentials = { - accessKeyId, - secretAccessKey, - ...sessionToken && { sessionToken }, - ...expiry && { expiration: new Date(expiry) }, - ...credentialScope && { credentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS", "g"); - return credentials; - } - throw new import_property_provider.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init?.logger }); -}, "fromEnv"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 7519: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkUrl = void 0; -const property_provider_1 = __nccwpck_require__(9721); -const LOOPBACK_CIDR_IPv4 = "127.0.0.0/8"; -const LOOPBACK_CIDR_IPv6 = "::1/128"; -const ECS_CONTAINER_HOST = "169.254.170.2"; -const EKS_CONTAINER_HOST_IPv4 = "169.254.170.23"; -const EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]"; -const checkUrl = (url, logger) => { - if (url.protocol === "https:") { - return; - } - if (url.hostname === ECS_CONTAINER_HOST || - url.hostname === EKS_CONTAINER_HOST_IPv4 || - url.hostname === EKS_CONTAINER_HOST_IPv6) { - return; - } - if (url.hostname.includes("[")) { - if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") { - return; - } - } - else { - if (url.hostname === "localhost") { - return; - } - const ipComponents = url.hostname.split("."); - const inRange = (component) => { - const num = parseInt(component, 10); - return 0 <= num && num <= 255; - }; - if (ipComponents[0] === "127" && - inRange(ipComponents[1]) && - inRange(ipComponents[2]) && - inRange(ipComponents[3]) && - ipComponents.length === 4) { - return; - } - } - throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following: - - loopback CIDR 127.0.0.0/8 or [::1/128] - - ECS container host 169.254.170.2 - - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger }); -}; -exports.checkUrl = checkUrl; - - -/***/ }), - -/***/ 9546: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromHttp = void 0; -const tslib_1 = __nccwpck_require__(4351); -const client_1 = __nccwpck_require__(6510); -const node_http_handler_1 = __nccwpck_require__(258); -const property_provider_1 = __nccwpck_require__(9721); -const promises_1 = tslib_1.__importDefault(__nccwpck_require__(3292)); -const checkUrl_1 = __nccwpck_require__(7519); -const requestHelpers_1 = __nccwpck_require__(2707); -const retry_wrapper_1 = __nccwpck_require__(9138); -const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; -const DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; -const AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; -const AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"; -const AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; -const fromHttp = (options = {}) => { - options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp"); - let host; - const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI]; - const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI]; - const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN]; - const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE]; - const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger ? console.warn : options.logger.warn; - if (relative && full) { - warn("@aws-sdk/credential-provider-http: " + - "you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."); - warn("awsContainerCredentialsFullUri will take precedence."); - } - if (token && tokenFile) { - warn("@aws-sdk/credential-provider-http: " + - "you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."); - warn("awsContainerAuthorizationToken will take precedence."); - } - if (full) { - host = full; - } - else if (relative) { - host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`; - } - else { - throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided. -Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger }); - } - const url = new URL(host); - (0, checkUrl_1.checkUrl)(url, options.logger); - const requestHandler = new node_http_handler_1.NodeHttpHandler({ - requestTimeout: options.timeout ?? 1000, - connectionTimeout: options.timeout ?? 1000, - }); - return (0, retry_wrapper_1.retryWrapper)(async () => { - const request = (0, requestHelpers_1.createGetRequest)(url); - if (token) { - request.headers.Authorization = token; - } - else if (tokenFile) { - request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString(); - } - try { - const result = await requestHandler.handle(request); - return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z")); - } - catch (e) { - throw new property_provider_1.CredentialsProviderError(String(e), { logger: options.logger }); - } - }, options.maxRetries ?? 3, options.timeout ?? 1000); -}; -exports.fromHttp = fromHttp; - - -/***/ }), - -/***/ 2707: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createGetRequest = createGetRequest; -exports.getCredentials = getCredentials; -const property_provider_1 = __nccwpck_require__(9721); -const protocol_http_1 = __nccwpck_require__(4418); -const smithy_client_1 = __nccwpck_require__(3570); -const util_stream_1 = __nccwpck_require__(6607); -function createGetRequest(url) { - return new protocol_http_1.HttpRequest({ - protocol: url.protocol, - hostname: url.hostname, - port: Number(url.port), - path: url.pathname, - query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => { - acc[k] = v; - return acc; - }, {}), - fragment: url.hash, - }); -} -async function getCredentials(response, logger) { - const stream = (0, util_stream_1.sdkStreamMixin)(response.body); - const str = await stream.transformToString(); - if (response.statusCode === 200) { - const parsed = JSON.parse(str); - if (typeof parsed.AccessKeyId !== "string" || - typeof parsed.SecretAccessKey !== "string" || - typeof parsed.Token !== "string" || - typeof parsed.Expiration !== "string") { - throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: " + - "{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger }); - } - return { - accessKeyId: parsed.AccessKeyId, - secretAccessKey: parsed.SecretAccessKey, - sessionToken: parsed.Token, - expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration), - }; - } - if (response.statusCode >= 400 && response.statusCode < 500) { - let parsedBody = {}; - try { - parsedBody = JSON.parse(str); - } - catch (e) { } - throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), { - Code: parsedBody.Code, - Message: parsedBody.Message, - }); - } - throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }); -} - - -/***/ }), - -/***/ 9138: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.retryWrapper = void 0; -const retryWrapper = (toRetry, maxRetries, delayMs) => { - return async () => { - for (let i = 0; i < maxRetries; ++i) { - try { - return await toRetry(); - } - catch (e) { - await new Promise((resolve) => setTimeout(resolve, delayMs)); - } - } - return await toRetry(); - }; -}; -exports.retryWrapper = retryWrapper; - - -/***/ }), - -/***/ 5554: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromHttp = void 0; -var fromHttp_1 = __nccwpck_require__(9546); -Object.defineProperty(exports, "fromHttp", ({ enumerable: true, get: function () { return fromHttp_1.fromHttp; } })); - - -/***/ }), - -/***/ 5736: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromIni: () => fromIni -}); -module.exports = __toCommonJS(index_exports); - -// src/fromIni.ts - - -// src/resolveProfileData.ts - - -// src/resolveAssumeRoleCredentials.ts - - -var import_shared_ini_file_loader = __nccwpck_require__(3507); - -// src/resolveCredentialSource.ts -var import_client = __nccwpck_require__(6510); -var import_property_provider = __nccwpck_require__(9721); -var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName, logger) => { - const sourceProvidersMap = { - EcsContainer: /* @__PURE__ */ __name(async (options) => { - const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5554))); - const { fromContainerMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); - return async () => (0, import_property_provider.chain)(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); - }, "EcsContainer"), - Ec2InstanceMetadata: /* @__PURE__ */ __name(async (options) => { - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata"); - const { fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); - return async () => fromInstanceMetadata(options)().then(setNamedProvider); - }, "Ec2InstanceMetadata"), - Environment: /* @__PURE__ */ __name(async (options) => { - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); - const { fromEnv } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(4407))); - return async () => fromEnv(options)().then(setNamedProvider); - }, "Environment") - }; - if (credentialSource in sourceProvidersMap) { - return sourceProvidersMap[credentialSource]; - } else { - throw new import_property_provider.CredentialsProviderError( - `Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, - { logger } - ); - } -}, "resolveCredentialSource"); -var setNamedProvider = /* @__PURE__ */ __name((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"), "setNamedProvider"); - -// src/resolveAssumeRoleCredentials.ts -var isAssumeRoleProfile = /* @__PURE__ */ __name((arg, { profile = "default", logger } = {}) => { - return 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, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger })); -}, "isAssumeRoleProfile"); -var isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger }) => { - const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; - if (withSourceProfile) { - logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`); - } - return withSourceProfile; -}, "isAssumeRoleWithSourceProfile"); -var isCredentialSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger }) => { - const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; - if (withProviderProfile) { - logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`); - } - return withProviderProfile; -}, "isCredentialSourceProfile"); -var resolveAssumeRoleCredentials = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => { - options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)"); - const profileData = profiles[profileName]; - const { source_profile, region } = profileData; - if (!options.roleAssumer) { - const { getDefaultRoleAssumer } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(3764))); - options.roleAssumer = getDefaultRoleAssumer( - { - ...options.clientConfig, - credentialProviderLogger: options.logger, - parentClientConfig: { - ...options?.parentClientConfig, - region: region ?? options?.parentClientConfig?.region - } - }, - options.clientPlugins - ); - } - if (source_profile && source_profile in visitedProfiles) { - throw new import_property_provider.CredentialsProviderError( - `Detected a cycle attempting to resolve credentials for profile ${(0, import_shared_ini_file_loader.getProfileName)(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), - { logger: options.logger } - ); - } - options.logger?.debug( - `@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}` - ); - const sourceCredsProvider = source_profile ? resolveProfileData( - source_profile, - profiles, - options, - { - ...visitedProfiles, - [source_profile]: true - }, - isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {}) - ) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))(); - if (isCredentialSourceWithoutRoleArn(profileData)) { - return sourceCredsProvider.then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); - } else { - const params = { - RoleArn: profileData.role_arn, - RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`, - ExternalId: profileData.external_id, - DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10) - }; - const { mfa_serial } = profileData; - if (mfa_serial) { - if (!options.mfaCodeProvider) { - throw new import_property_provider.CredentialsProviderError( - `Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, - { logger: options.logger, tryNextLink: false } - ); - } - params.SerialNumber = mfa_serial; - params.TokenCode = await options.mfaCodeProvider(mfa_serial); - } - const sourceCreds = await sourceCredsProvider; - return options.roleAssumer(sourceCreds, params).then( - (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o") - ); - } -}, "resolveAssumeRoleCredentials"); -var isCredentialSourceWithoutRoleArn = /* @__PURE__ */ __name((section) => { - return !section.role_arn && !!section.credential_source; -}, "isCredentialSourceWithoutRoleArn"); - -// src/resolveProcessCredentials.ts - -var isProcessProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", "isProcessProfile"); -var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => __toESM(__nccwpck_require__(8638))).then( - ({ fromProcess }) => fromProcess({ - ...options, - profile - })().then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_PROCESS", "v")) -), "resolveProcessCredentials"); - -// src/resolveSsoCredentials.ts - -var resolveSsoCredentials = /* @__PURE__ */ __name(async (profile, profileData, options = {}) => { - const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5284))); - return fromSSO({ - profile, - logger: options.logger, - parentClientConfig: options.parentClientConfig, - clientConfig: options.clientConfig - })().then((creds) => { - if (profileData.sso_session) { - return (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO", "r"); - } else { - return (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t"); - } - }); -}, "resolveSsoCredentials"); -var isSsoProfile = /* @__PURE__ */ __name((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"), "isSsoProfile"); - -// src/resolveStaticCredentials.ts - -var isStaticCredsProfile = /* @__PURE__ */ __name((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 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1, "isStaticCredsProfile"); -var resolveStaticCredentials = /* @__PURE__ */ __name(async (profile, options) => { - options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials"); - const credentials = { - accessKeyId: profile.aws_access_key_id, - secretAccessKey: profile.aws_secret_access_key, - sessionToken: profile.aws_session_token, - ...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }, - ...profile.aws_account_id && { accountId: profile.aws_account_id } - }; - return (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROFILE", "n"); -}, "resolveStaticCredentials"); - -// src/resolveWebIdentityCredentials.ts - -var isWebIdentityProfile = /* @__PURE__ */ __name((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, "isWebIdentityProfile"); -var resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => __toESM(__nccwpck_require__(5603))).then( - ({ fromTokenFile }) => fromTokenFile({ - webIdentityTokenFile: profile.web_identity_token_file, - roleArn: profile.role_arn, - roleSessionName: profile.role_session_name, - roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, - logger: options.logger, - parentClientConfig: options.parentClientConfig - })().then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q")) -), "resolveWebIdentityCredentials"); - -// src/resolveProfileData.ts -var resolveProfileData = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => { - const data = profiles[profileName]; - if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) { - return resolveStaticCredentials(data, options); - } - if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) { - return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles); - } - if (isStaticCredsProfile(data)) { - return resolveStaticCredentials(data, options); - } - if (isWebIdentityProfile(data)) { - return resolveWebIdentityCredentials(data, options); - } - if (isProcessProfile(data)) { - return resolveProcessCredentials(options, profileName); - } - if (isSsoProfile(data)) { - return await resolveSsoCredentials(profileName, data, options); - } - throw new import_property_provider.CredentialsProviderError( - `Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, - { logger: options.logger } - ); -}, "resolveProfileData"); - -// src/fromIni.ts -var fromIni = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { - const init = { - ..._init, - parentClientConfig: { - ...callerClientConfig, - ..._init.parentClientConfig - } - }; - init.logger?.debug("@aws-sdk/credential-provider-ini - fromIni"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - return resolveProfileData( - (0, import_shared_ini_file_loader.getProfileName)({ - profile: _init.profile ?? callerClientConfig?.profile - }), - profiles, - init - ); -}, "fromIni"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 3196: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - credentialsTreatedAsExpired: () => credentialsTreatedAsExpired, - credentialsWillNeedRefresh: () => credentialsWillNeedRefresh, - defaultProvider: () => defaultProvider -}); -module.exports = __toCommonJS(index_exports); - -// src/defaultProvider.ts -var import_credential_provider_env = __nccwpck_require__(4407); - -var import_shared_ini_file_loader = __nccwpck_require__(3507); - -// src/remoteProvider.ts -var import_property_provider = __nccwpck_require__(9721); -var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; -var remoteProvider = /* @__PURE__ */ __name(async (init) => { - const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); - if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { - init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); - const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5554))); - return (0, import_property_provider.chain)(fromHttp(init), fromContainerMetadata(init)); - } - if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { - return async () => { - throw new import_property_provider.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init.logger }); - }; - } - init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); - return fromInstanceMetadata(init); -}, "remoteProvider"); - -// src/defaultProvider.ts -var multipleCredentialSourceWarningEmitted = false; -var defaultProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( - (0, import_property_provider.chain)( - async () => { - const profile = init.profile ?? process.env[import_shared_ini_file_loader.ENV_PROFILE]; - if (profile) { - const envStaticCredentialsAreSet = process.env[import_credential_provider_env.ENV_KEY] && process.env[import_credential_provider_env.ENV_SECRET]; - if (envStaticCredentialsAreSet) { - if (!multipleCredentialSourceWarningEmitted) { - const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" ? init.logger.warn : console.warn; - warnFn( - `@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: - Multiple credential sources detected: - Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. - This SDK will proceed with the AWS_PROFILE value. - - However, a future version may change this behavior to prefer the ENV static credentials. - Please ensure that your environment only sets either the AWS_PROFILE or the - AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. -` - ); - multipleCredentialSourceWarningEmitted = true; - } - } - throw new import_property_provider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { - logger: init.logger, - tryNextLink: true - }); - } - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); - return (0, import_credential_provider_env.fromEnv)(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - throw new import_property_provider.CredentialsProviderError( - "Skipping SSO provider in default chain (inputs do not include SSO fields).", - { logger: init.logger } - ); - } - const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5284))); - return fromSSO(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); - const { fromIni } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5736))); - return fromIni(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); - const { fromProcess } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(8638))); - return fromProcess(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); - const { fromTokenFile } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5603))); - return fromTokenFile(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); - return (await remoteProvider(init))(); - }, - async () => { - throw new import_property_provider.CredentialsProviderError("Could not load credentials from any providers", { - tryNextLink: false, - logger: init.logger - }); - } - ), - credentialsTreatedAsExpired, - credentialsWillNeedRefresh -), "defaultProvider"); -var credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0, "credentialsWillNeedRefresh"); -var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 8638: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromProcess: () => fromProcess -}); -module.exports = __toCommonJS(index_exports); - -// src/fromProcess.ts -var import_shared_ini_file_loader = __nccwpck_require__(3507); - -// src/resolveProcessCredentials.ts -var import_property_provider = __nccwpck_require__(9721); -var import_child_process = __nccwpck_require__(2081); -var import_util = __nccwpck_require__(3837); - -// src/getValidatedProcessCredentials.ts -var import_client = __nccwpck_require__(6510); -var getValidatedProcessCredentials = /* @__PURE__ */ __name((profileName, data, profiles) => { - if (data.Version !== 1) { - throw Error(`Profile ${profileName} credential_process did not return Version 1.`); - } - if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) { - throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); - } - if (data.Expiration) { - const currentTime = /* @__PURE__ */ new Date(); - const expireTime = new Date(data.Expiration); - if (expireTime < currentTime) { - throw Error(`Profile ${profileName} credential_process returned expired credentials.`); - } - } - let accountId = data.AccountId; - if (!accountId && profiles?.[profileName]?.aws_account_id) { - accountId = profiles[profileName].aws_account_id; - } - const credentials = { - accessKeyId: data.AccessKeyId, - secretAccessKey: data.SecretAccessKey, - ...data.SessionToken && { sessionToken: data.SessionToken }, - ...data.Expiration && { expiration: new Date(data.Expiration) }, - ...data.CredentialScope && { credentialScope: data.CredentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROCESS", "w"); - return credentials; -}, "getValidatedProcessCredentials"); - -// src/resolveProcessCredentials.ts -var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger) => { - const profile = profiles[profileName]; - if (profiles[profileName]) { - const credentialProcess = profile["credential_process"]; - if (credentialProcess !== void 0) { - const execPromise = (0, import_util.promisify)(import_child_process.exec); - try { - const { stdout } = await execPromise(credentialProcess); - let data; - try { - data = JSON.parse(stdout.trim()); - } catch { - throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); - } - return getValidatedProcessCredentials(profileName, data, profiles); - } catch (error) { - throw new import_property_provider.CredentialsProviderError(error.message, { logger }); - } - } else { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger }); - } - } else { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { - logger - }); - } -}, "resolveProcessCredentials"); - -// src/fromProcess.ts -var fromProcess = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { - init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - return resolveProcessCredentials( - (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }), - profiles, - init.logger - ); -}, "fromProcess"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 5284: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/loadSso.ts -var loadSso_exports = {}; -__export(loadSso_exports, { - GetRoleCredentialsCommand: () => import_client_sso.GetRoleCredentialsCommand, - SSOClient: () => import_client_sso.SSOClient -}); -var import_client_sso; -var init_loadSso = __esm({ - "src/loadSso.ts"() { - "use strict"; - import_client_sso = __nccwpck_require__(1687); - } -}); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromSSO: () => fromSSO, - isSsoProfile: () => isSsoProfile, - validateSsoProfile: () => validateSsoProfile -}); -module.exports = __toCommonJS(index_exports); - -// src/fromSSO.ts - - - -// src/isSsoProfile.ts -var isSsoProfile = /* @__PURE__ */ __name((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"), "isSsoProfile"); - -// src/resolveSSOCredentials.ts -var import_client = __nccwpck_require__(6510); -var import_token_providers = __nccwpck_require__(7182); -var import_property_provider = __nccwpck_require__(9721); -var import_shared_ini_file_loader = __nccwpck_require__(3507); -var SHOULD_FAIL_CREDENTIAL_CHAIN = false; -var resolveSSOCredentials = /* @__PURE__ */ __name(async ({ - ssoStartUrl, - ssoSession, - ssoAccountId, - ssoRegion, - ssoRoleName, - ssoClient, - clientConfig, - parentClientConfig, - profile, - logger -}) => { - let token; - const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; - if (ssoSession) { - try { - const _token = await (0, import_token_providers.fromSso)({ profile })(); - token = { - accessToken: _token.token, - expiresAt: new Date(_token.expiration).toISOString() - }; - } catch (e) { - throw new import_property_provider.CredentialsProviderError(e.message, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - } else { - try { - token = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoStartUrl); - } catch (e) { - throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - } - if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { - throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - const { accessToken } = token; - const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports)); - const sso = ssoClient || new SSOClient2( - Object.assign({}, clientConfig ?? {}, { - logger: clientConfig?.logger ?? parentClientConfig?.logger, - region: clientConfig?.region ?? ssoRegion - }) - ); - let ssoResp; - try { - ssoResp = await sso.send( - new GetRoleCredentialsCommand2({ - accountId: ssoAccountId, - roleName: ssoRoleName, - accessToken - }) - ); - } catch (e) { - throw new import_property_provider.CredentialsProviderError(e, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - const { - roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} - } = ssoResp; - if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { - throw new import_property_provider.CredentialsProviderError("SSO returns an invalid temporary credential.", { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - const credentials = { - accessKeyId, - secretAccessKey, - sessionToken, - expiration: new Date(expiration), - ...credentialScope && { credentialScope }, - ...accountId && { accountId } - }; - if (ssoSession) { - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO", "s"); - } else { - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO_LEGACY", "u"); - } - return credentials; -}, "resolveSSOCredentials"); - -// src/validateSsoProfile.ts - -var validateSsoProfile = /* @__PURE__ */ __name((profile, logger) => { - 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 import_property_provider.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( - ", " - )} -Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, - { tryNextLink: false, logger } - ); - } - return profile; -}, "validateSsoProfile"); - -// src/fromSSO.ts -var fromSSO = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { - init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; - const { ssoClient } = init; - const profileName = (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }); - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - const profile = profiles[profileName]; - if (!profile) { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger }); - } - if (!isSsoProfile(profile)) { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { - logger: init.logger - }); - } - if (profile?.sso_session) { - const ssoSessions = await (0, import_shared_ini_file_loader.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 import_property_provider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { - tryNextLink: false, - logger: init.logger - }); - } - if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { - throw new import_property_provider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { - tryNextLink: false, - logger: init.logger - }); - } - 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 } = validateSsoProfile( - profile, - init.logger - ); - return resolveSSOCredentials({ - ssoStartUrl: sso_start_url, - ssoSession: sso_session, - ssoAccountId: sso_account_id, - ssoRegion: sso_region, - ssoRoleName: sso_role_name, - ssoClient, - clientConfig: init.clientConfig, - parentClientConfig: init.parentClientConfig, - profile: profileName - }); - } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { - throw new import_property_provider.CredentialsProviderError( - 'Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', - { tryNextLink: false, logger: init.logger } - ); - } else { - return resolveSSOCredentials({ - ssoStartUrl, - ssoSession, - ssoAccountId, - ssoRegion, - ssoRoleName, - ssoClient, - clientConfig: init.clientConfig, - parentClientConfig: init.parentClientConfig, - profile: profileName - }); - } -}, "fromSSO"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 279: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromTokenFile = void 0; -const client_1 = __nccwpck_require__(6510); -const property_provider_1 = __nccwpck_require__(9721); -const fs_1 = __nccwpck_require__(7147); -const fromWebToken_1 = __nccwpck_require__(9527); -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 () => { - init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); - const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; - const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN]; - const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; - if (!webIdentityTokenFile || !roleArn) { - throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { - logger: init.logger, - }); - } - const credentials = await (0, fromWebToken_1.fromWebToken)({ - ...init, - webIdentityToken: (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), - roleArn, - roleSessionName, - })(); - if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { - (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); - } - return credentials; -}; -exports.fromTokenFile = fromTokenFile; - - -/***/ }), - -/***/ 9527: -/***/ (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 () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromWebToken = void 0; -const fromWebToken = (init) => async (awsIdentityProperties) => { - init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); - const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init; - let { roleAssumerWithWebIdentity } = init; - if (!roleAssumerWithWebIdentity) { - const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(3764))); - roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({ - ...init.clientConfig, - credentialProviderLogger: init.logger, - parentClientConfig: { - ...awsIdentityProperties?.callerClientConfig, - ...init.parentClientConfig, - }, - }, init.clientPlugins); - } - return roleAssumerWithWebIdentity({ - RoleArn: roleArn, - RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, - WebIdentityToken: webIdentityToken, - ProviderId: providerId, - PolicyArns: policyArns, - Policy: policy, - DurationSeconds: durationSeconds, - }); -}; -exports.fromWebToken = fromWebToken; - - -/***/ }), - -/***/ 5603: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(279), module.exports); -__reExport(index_exports, __nccwpck_require__(9527), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 9514: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getHostHeaderPlugin: () => getHostHeaderPlugin, - hostHeaderMiddleware: () => hostHeaderMiddleware, - hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions, - resolveHostHeaderConfig: () => resolveHostHeaderConfig -}); -module.exports = __toCommonJS(index_exports); -var import_protocol_http = __nccwpck_require__(4418); -function resolveHostHeaderConfig(input) { - return input; -} -__name(resolveHostHeaderConfig, "resolveHostHeaderConfig"); -var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { - if (!import_protocol_http.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); -}, "hostHeaderMiddleware"); -var hostHeaderMiddlewareOptions = { - name: "hostHeaderMiddleware", - step: "build", - priority: "low", - tags: ["HOST"], - override: true -}; -var getHostHeaderPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); - }, "applyToStack") -}), "getHostHeaderPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 5675: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getLoggerPlugin: () => getLoggerPlugin, - loggerMiddleware: () => loggerMiddleware, - loggerMiddlewareOptions: () => loggerMiddlewareOptions -}); -module.exports = __toCommonJS(index_exports); - -// src/loggerMiddleware.ts -var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => { - try { - const response = await next(args); - const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; - const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; - const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; - const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; - const { $metadata, ...outputWithoutMetadata } = response.output; - logger?.info?.({ - 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 ?? context.inputFilterSensitiveLog; - logger?.error?.({ - clientName, - commandName, - input: inputFilterSensitiveLog(args.input), - error, - metadata: error.$metadata - }); - throw error; - } -}, "loggerMiddleware"); -var loggerMiddlewareOptions = { - name: "loggerMiddleware", - tags: ["LOGGER"], - step: "initialize", - override: true -}; -var getLoggerPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); - }, "applyToStack") -}), "getLoggerPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 7977: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - addRecursionDetectionMiddlewareOptions: () => addRecursionDetectionMiddlewareOptions, - getRecursionDetectionPlugin: () => getRecursionDetectionPlugin, - recursionDetectionMiddleware: () => recursionDetectionMiddleware -}); -module.exports = __toCommonJS(index_exports); -var import_protocol_http = __nccwpck_require__(4418); -var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; -var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; -var ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; -var recursionDetectionMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { - const { request } = args; - if (!import_protocol_http.HttpRequest.isInstance(request) || options.runtime !== "node") { - return next(args); - } - const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME; - if (request.headers.hasOwnProperty(traceIdHeader)) { - return next(args); - } - const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; - const traceId = process.env[ENV_TRACE_ID]; - const nonEmptyString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0, "nonEmptyString"); - if (nonEmptyString(functionName) && nonEmptyString(traceId)) { - request.headers[TRACE_ID_HEADER_NAME] = traceId; - } - return next({ - ...args, - request - }); -}, "recursionDetectionMiddleware"); -var addRecursionDetectionMiddlewareOptions = { - step: "build", - tags: ["RECURSION_DETECTION"], - name: "recursionDetectionMiddleware", - override: true, - priority: "low" -}; -var getRecursionDetectionPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions); - }, "applyToStack") -}), "getRecursionDetectionPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 6634: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - DEFAULT_UA_APP_ID: () => DEFAULT_UA_APP_ID, - getUserAgentMiddlewareOptions: () => getUserAgentMiddlewareOptions, - getUserAgentPlugin: () => getUserAgentPlugin, - resolveUserAgentConfig: () => resolveUserAgentConfig, - userAgentMiddleware: () => userAgentMiddleware -}); -module.exports = __toCommonJS(index_exports); - -// src/configurations.ts -var import_core = __nccwpck_require__(5829); -var DEFAULT_UA_APP_ID = void 0; -function isValidUserAgentAppId(appId) { - if (appId === void 0) { - return true; - } - return typeof appId === "string" && appId.length <= 50; -} -__name(isValidUserAgentAppId, "isValidUserAgentAppId"); -function resolveUserAgentConfig(input) { - const normalizedAppIdProvider = (0, import_core.normalizeProvider)(input.userAgentAppId ?? DEFAULT_UA_APP_ID); - const { customUserAgent } = input; - return Object.assign(input, { - customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, - userAgentAppId: /* @__PURE__ */ __name(async () => { - const appId = await normalizedAppIdProvider(); - if (!isValidUserAgentAppId(appId)) { - const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; - if (typeof appId !== "string") { - logger?.warn("userAgentAppId must be a string or undefined."); - } else if (appId.length > 50) { - logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); - } - } - return appId; - }, "userAgentAppId") - }); -} -__name(resolveUserAgentConfig, "resolveUserAgentConfig"); - -// src/user-agent-middleware.ts -var import_util_endpoints = __nccwpck_require__(4241); -var import_protocol_http = __nccwpck_require__(4418); - -// src/check-features.ts -var import_core2 = __nccwpck_require__(2143); -var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; -async function checkFeatures(context, config, args) { - const request = args.request; - if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { - (0, import_core2.setFeature)(context, "PROTOCOL_RPC_V2_CBOR", "M"); - } - if (typeof config.retryStrategy === "function") { - const retryStrategy = await config.retryStrategy(); - if (typeof retryStrategy.acquireInitialRetryToken === "function") { - if (retryStrategy.constructor?.name?.includes("Adaptive")) { - (0, import_core2.setFeature)(context, "RETRY_MODE_ADAPTIVE", "F"); - } else { - (0, import_core2.setFeature)(context, "RETRY_MODE_STANDARD", "E"); - } - } else { - (0, import_core2.setFeature)(context, "RETRY_MODE_LEGACY", "D"); - } - } - if (typeof config.accountIdEndpointMode === "function") { - const endpointV2 = context.endpointV2; - if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { - (0, import_core2.setFeature)(context, "ACCOUNT_ID_ENDPOINT", "O"); - } - switch (await config.accountIdEndpointMode?.()) { - case "disabled": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); - break; - case "preferred": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); - break; - case "required": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); - break; - } - } - const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; - if (identity?.$source) { - const credentials = identity; - if (credentials.accountId) { - (0, import_core2.setFeature)(context, "RESOLVED_ACCOUNT_ID", "T"); - } - for (const [key, value] of Object.entries(credentials.$source ?? {})) { - (0, import_core2.setFeature)(context, key, value); - } - } -} -__name(checkFeatures, "checkFeatures"); - -// src/constants.ts -var USER_AGENT = "user-agent"; -var X_AMZ_USER_AGENT = "x-amz-user-agent"; -var SPACE = " "; -var UA_NAME_SEPARATOR = "/"; -var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g; -var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g; -var UA_ESCAPE_CHAR = "-"; - -// src/encode-features.ts -var BYTE_LIMIT = 1024; -function encodeFeatures(features) { - let buffer = ""; - for (const key in features) { - const val = features[key]; - if (buffer.length + val.length + 1 <= BYTE_LIMIT) { - if (buffer.length) { - buffer += "," + val; - } else { - buffer += val; - } - continue; - } - break; - } - return buffer; -} -__name(encodeFeatures, "encodeFeatures"); - -// src/user-agent-middleware.ts -var userAgentMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { - const { request } = args; - if (!import_protocol_http.HttpRequest.isInstance(request)) { - return next(args); - } - const { headers } = request; - const userAgent = context?.userAgent?.map(escapeUserAgent) || []; - const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); - await checkFeatures(context, options, args); - const awsContext = context; - defaultUserAgent.push( - `m/${encodeFeatures( - Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features) - )}` - ); - const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; - const appId = await options.userAgentAppId(); - if (appId) { - defaultUserAgent.push(escapeUserAgent([`app/${appId}`])); - } - const prefix = (0, import_util_endpoints.getUserAgentPrefix)(); - const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE); - const normalUAValue = [ - ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), - ...customUserAgent - ].join(SPACE); - if (options.runtime !== "browser") { - if (normalUAValue) { - headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue; - } - headers[USER_AGENT] = sdkUserAgentValue; - } else { - headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; - } - return next({ - ...args, - request - }); -}, "userAgentMiddleware"); -var escapeUserAgent = /* @__PURE__ */ __name((userAgentPair) => { - const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); - const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); - const prefixSeparatorIndex = name.indexOf(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}`; - } - }, ""); -}, "escapeUserAgent"); -var getUserAgentMiddlewareOptions = { - name: "getUserAgentMiddleware", - step: "build", - priority: "low", - tags: ["SET_USER_AGENT", "USER_AGENT"], - override: true -}; -var getUserAgentPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); - }, "applyToStack") -}), "getUserAgentPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 9002: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.defaultSSOOIDCHttpAuthSchemeProvider = exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(2143); -const util_middleware_1 = __nccwpck_require__(2390); -const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sso-oauth", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "CreateToken": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - - -/***/ }), - -/***/ 8012: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(4241); -const util_endpoints_2 = __nccwpck_require__(5473); -const ruleset_1 = __nccwpck_require__(2507); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); -}; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - - -/***/ }), - -/***/ 2507: -/***/ ((__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://oidc-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://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://oidc-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://oidc.{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://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; -exports.ruleSet = _data; - - -/***/ }), - -/***/ 8959: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/sso-oidc/index.ts -var index_exports = {}; -__export(index_exports, { - $Command: () => import_smithy_client6.Command, - AccessDeniedException: () => AccessDeniedException, - AuthorizationPendingException: () => AuthorizationPendingException, - CreateTokenCommand: () => CreateTokenCommand, - CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog, - CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog, - ExpiredTokenException: () => ExpiredTokenException, - InternalServerException: () => InternalServerException, - InvalidClientException: () => InvalidClientException, - InvalidGrantException: () => InvalidGrantException, - InvalidRequestException: () => InvalidRequestException, - InvalidScopeException: () => InvalidScopeException, - SSOOIDC: () => SSOOIDC, - SSOOIDCClient: () => SSOOIDCClient, - SSOOIDCServiceException: () => SSOOIDCServiceException, - SlowDownException: () => SlowDownException, - UnauthorizedClientException: () => UnauthorizedClientException, - UnsupportedGrantTypeException: () => UnsupportedGrantTypeException, - __Client: () => import_smithy_client2.Client -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/sso-oidc/SSOOIDCClient.ts -var import_middleware_host_header = __nccwpck_require__(9514); -var import_middleware_logger = __nccwpck_require__(5675); -var import_middleware_recursion_detection = __nccwpck_require__(7977); -var import_middleware_user_agent = __nccwpck_require__(6634); -var import_config_resolver = __nccwpck_require__(3098); -var import_core = __nccwpck_require__(5829); -var import_middleware_content_length = __nccwpck_require__(2800); -var import_middleware_endpoint = __nccwpck_require__(2918); -var import_middleware_retry = __nccwpck_require__(6039); -var import_smithy_client2 = __nccwpck_require__(3570); -var import_httpAuthSchemeProvider = __nccwpck_require__(9002); - -// src/submodules/sso-oidc/endpoint/EndpointParameters.ts -var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "sso-oauth" - }); -}, "resolveClientEndpointParameters"); -var commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } -}; - -// src/submodules/sso-oidc/SSOOIDCClient.ts -var import_runtimeConfig = __nccwpck_require__(5875); - -// src/submodules/sso-oidc/runtimeExtensions.ts -var import_region_config_resolver = __nccwpck_require__(6976); -var import_protocol_http = __nccwpck_require__(4418); -var import_smithy_client = __nccwpck_require__(3570); - -// src/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.ts -var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; -}, "getHttpAuthExtensionConfiguration"); -var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; -}, "resolveHttpAuthRuntimeConfig"); - -// src/submodules/sso-oidc/runtimeExtensions.ts -var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign( - (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), - (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), - (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), - getHttpAuthExtensionConfiguration(runtimeConfig) - ); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign( - runtimeConfig, - (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), - (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), - (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), - resolveHttpAuthRuntimeConfig(extensionConfiguration) - ); -}, "resolveRuntimeExtensions"); - -// src/submodules/sso-oidc/SSOOIDCClient.ts -var SSOOIDCClient = class extends import_smithy_client2.Client { - static { - __name(this, "SSOOIDCClient"); - } - /** - * The resolved configuration of SSOOIDCClient class. This is resolved and normalized from the {@link SSOOIDCClientConfig | constructor configuration interface}. - */ - config; - constructor(...[configuration]) { - const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); - const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use( - (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials - }), "identityProviderConfigProvider") - }) - ); - this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); - } - /** - * Destroy underlying resources, like sockets. It's usually not necessary to do this. - * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. - * Otherwise, sockets might stay open for quite a long time before the server terminates them. - */ - destroy() { - super.destroy(); - } -}; - -// src/submodules/sso-oidc/SSOOIDC.ts -var import_smithy_client7 = __nccwpck_require__(3570); - -// src/submodules/sso-oidc/commands/CreateTokenCommand.ts -var import_middleware_endpoint2 = __nccwpck_require__(2918); -var import_middleware_serde = __nccwpck_require__(1238); -var import_smithy_client6 = __nccwpck_require__(3570); - -// src/submodules/sso-oidc/models/models_0.ts -var import_smithy_client4 = __nccwpck_require__(3570); - -// src/submodules/sso-oidc/models/SSOOIDCServiceException.ts -var import_smithy_client3 = __nccwpck_require__(3570); -var SSOOIDCServiceException = class _SSOOIDCServiceException extends import_smithy_client3.ServiceException { - static { - __name(this, "SSOOIDCServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype); - } -}; - -// src/submodules/sso-oidc/models/models_0.ts -var AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException { - static { - __name(this, "AccessDeniedException"); - } - name = "AccessDeniedException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be access_denied.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AccessDeniedException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException { - static { - __name(this, "AuthorizationPendingException"); - } - name = "AuthorizationPendingException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * authorization_pending.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "AuthorizationPendingException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AuthorizationPendingException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var CreateTokenRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.clientSecret && { clientSecret: import_smithy_client4.SENSITIVE_STRING }, - ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.codeVerifier && { codeVerifier: import_smithy_client4.SENSITIVE_STRING } -}), "CreateTokenRequestFilterSensitiveLog"); -var CreateTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.idToken && { idToken: import_smithy_client4.SENSITIVE_STRING } -}), "CreateTokenResponseFilterSensitiveLog"); -var ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException { - static { - __name(this, "ExpiredTokenException"); - } - name = "ExpiredTokenException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be expired_token.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var InternalServerException = class _InternalServerException extends SSOOIDCServiceException { - static { - __name(this, "InternalServerException"); - } - name = "InternalServerException"; - $fault = "server"; - /** - *

Single error code. For this exception the value will be server_error.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InternalServerException", - $fault: "server", - ...opts - }); - Object.setPrototypeOf(this, _InternalServerException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException { - static { - __name(this, "InvalidClientException"); - } - name = "InvalidClientException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * invalid_client.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidClientException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException { - static { - __name(this, "InvalidGrantException"); - } - name = "InvalidGrantException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be invalid_grant.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidGrantException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidGrantException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException { - static { - __name(this, "InvalidRequestException"); - } - name = "InvalidRequestException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * invalid_request.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidRequestException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidRequestException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException { - static { - __name(this, "InvalidScopeException"); - } - name = "InvalidScopeException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be invalid_scope.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidScopeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidScopeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var SlowDownException = class _SlowDownException extends SSOOIDCServiceException { - static { - __name(this, "SlowDownException"); - } - name = "SlowDownException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be slow_down.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "SlowDownException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _SlowDownException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException { - static { - __name(this, "UnauthorizedClientException"); - } - name = "UnauthorizedClientException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * unauthorized_client.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnauthorizedClientException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnauthorizedClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -var UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException { - static { - __name(this, "UnsupportedGrantTypeException"); - } - name = "UnsupportedGrantTypeException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * unsupported_grant_type.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnsupportedGrantTypeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; - -// src/submodules/sso-oidc/protocols/Aws_restJson1.ts -var import_core2 = __nccwpck_require__(2143); -var import_core3 = __nccwpck_require__(5829); -var import_smithy_client5 = __nccwpck_require__(3570); -var se_CreateTokenCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core3.requestBuilder)(input, context); - const headers = { - "content-type": "application/json" - }; - b.bp("/token"); - let body; - body = JSON.stringify( - (0, import_smithy_client5.take)(input, { - clientId: [], - clientSecret: [], - code: [], - codeVerifier: [], - deviceCode: [], - grantType: [], - redirectUri: [], - refreshToken: [], - scope: /* @__PURE__ */ __name((_) => (0, import_smithy_client5._json)(_), "scope") - }) - ); - b.m("POST").h(headers).b(body); - return b.build(); -}, "se_CreateTokenCommand"); -var de_CreateTokenCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client5.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client5.expectNonNull)((0, import_smithy_client5.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client5.take)(data, { - accessToken: import_smithy_client5.expectString, - expiresIn: import_smithy_client5.expectInt32, - idToken: import_smithy_client5.expectString, - refreshToken: import_smithy_client5.expectString, - tokenType: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - return contents; -}, "de_CreateTokenCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core2.parseJsonErrorBody)(output.body, context) - }; - const errorCode = (0, import_core2.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 - }); - } -}, "de_CommandError"); -var throwDefaultError = (0, import_smithy_client5.withBaseException)(SSOOIDCServiceException); -var de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new AccessDeniedException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_AccessDeniedExceptionRes"); -var de_AuthorizationPendingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new AuthorizationPendingException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_AuthorizationPendingExceptionRes"); -var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new ExpiredTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_ExpiredTokenExceptionRes"); -var de_InternalServerExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InternalServerException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InternalServerExceptionRes"); -var de_InvalidClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidClientException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidClientExceptionRes"); -var de_InvalidGrantExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidGrantException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidGrantExceptionRes"); -var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidRequestException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidRequestExceptionRes"); -var de_InvalidScopeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidScopeException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidScopeExceptionRes"); -var de_SlowDownExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new SlowDownException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_SlowDownExceptionRes"); -var de_UnauthorizedClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new UnauthorizedClientException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnauthorizedClientExceptionRes"); -var de_UnsupportedGrantTypeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new UnsupportedGrantTypeException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnsupportedGrantTypeExceptionRes"); -var deserializeMetadata = /* @__PURE__ */ __name((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"] -}), "deserializeMetadata"); - -// src/submodules/sso-oidc/commands/CreateTokenCommand.ts -var CreateTokenCommand = class extends import_smithy_client6.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() { - static { - __name(this, "CreateTokenCommand"); - } -}; - -// src/submodules/sso-oidc/SSOOIDC.ts -var commands = { - CreateTokenCommand -}; -var SSOOIDC = class extends SSOOIDCClient { - static { - __name(this, "SSOOIDC"); - } -}; -(0, import_smithy_client7.createAggregatedClient)(commands, SSOOIDC); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 5875: -/***/ ((__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__(4178)); -const core_1 = __nccwpck_require__(2143); -const util_user_agent_node_1 = __nccwpck_require__(7330); -const config_resolver_1 = __nccwpck_require__(3098); -const hash_node_1 = __nccwpck_require__(3081); -const middleware_retry_1 = __nccwpck_require__(6039); -const node_config_provider_1 = __nccwpck_require__(3461); -const node_http_handler_1 = __nccwpck_require__(258); -const util_body_length_node_1 = __nccwpck_require__(8075); -const util_retry_1 = __nccwpck_require__(4902); -const runtimeConfig_shared_1 = __nccwpck_require__(3695); -const smithy_client_1 = __nccwpck_require__(3570); -const util_defaults_mode_node_1 = __nccwpck_require__(2429); -const smithy_client_2 = __nccwpck_require__(3570); -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); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ 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, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, - }, config), - 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, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 3695: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(2143); -const core_2 = __nccwpck_require__(5829); -const smithy_client_1 = __nccwpck_require__(3570); -const url_parser_1 = __nccwpck_require__(4681); -const util_base64_1 = __nccwpck_require__(5600); -const util_utf8_1 = __nccwpck_require__(1895); -const httpAuthSchemeProvider_1 = __nccwpck_require__(9002); -const endpointResolver_1 = __nccwpck_require__(8012); -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 ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - serviceId: config?.serviceId ?? "SSO OIDC", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 6878: -/***/ ((__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__(9514); -const middleware_logger_1 = __nccwpck_require__(5675); -const middleware_recursion_detection_1 = __nccwpck_require__(7977); -const middleware_user_agent_1 = __nccwpck_require__(6634); -const config_resolver_1 = __nccwpck_require__(3098); -const core_1 = __nccwpck_require__(5829); -const middleware_content_length_1 = __nccwpck_require__(2800); -const middleware_endpoint_1 = __nccwpck_require__(2918); -const middleware_retry_1 = __nccwpck_require__(6039); -const smithy_client_1 = __nccwpck_require__(3570); -Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); -const httpAuthSchemeProvider_1 = __nccwpck_require__(3061); -const EndpointParameters_1 = __nccwpck_require__(981); -const runtimeConfig_1 = __nccwpck_require__(302); -const runtimeExtensions_1 = __nccwpck_require__(9913); -class STSClient extends smithy_client_1.Client { - config; - constructor(...[configuration]) { - const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); - const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); - const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); - const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); - const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); - 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, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - }), - })); - this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); - } - destroy() { - super.destroy(); - } -} -exports.STSClient = STSClient; - - -/***/ }), - -/***/ 1746: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - }; -}; -exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - }; -}; -exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; - - -/***/ }), - -/***/ 3061: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(2143); -const util_middleware_1 = __nccwpck_require__(2390); -const STSClient_1 = __nccwpck_require__(6878); -const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sts", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSTSHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "AssumeRoleWithWebIdentity": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; -const resolveStsAuthConfig = (input) => Object.assign(input, { - stsClientCtor: STSClient_1.STSClient, -}); -exports.resolveStsAuthConfig = resolveStsAuthConfig; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, exports.resolveStsAuthConfig)(config); - const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); - return Object.assign(config_1, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - - -/***/ }), - -/***/ 981: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.commonParams = exports.resolveClientEndpointParameters = void 0; -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - useGlobalEndpoint: options.useGlobalEndpoint ?? false, - defaultSigningName: "sts", - }); -}; -exports.resolveClientEndpointParameters = resolveClientEndpointParameters; -exports.commonParams = { - 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" }, -}; - - -/***/ }), - -/***/ 8181: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(4241); -const util_endpoints_2 = __nccwpck_require__(5473); -const ruleset_1 = __nccwpck_require__(5713); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); -}; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - - -/***/ }), - -/***/ 5713: -/***/ ((__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; - - -/***/ }), - -/***/ 3764: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/sts/index.ts -var index_exports = {}; -__export(index_exports, { - AssumeRoleCommand: () => AssumeRoleCommand, - AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog, - AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand, - AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog, - AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog, - ClientInputEndpointParameters: () => import_EndpointParameters3.ClientInputEndpointParameters, - CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog, - ExpiredTokenException: () => ExpiredTokenException, - IDPCommunicationErrorException: () => IDPCommunicationErrorException, - IDPRejectedClaimException: () => IDPRejectedClaimException, - InvalidIdentityTokenException: () => InvalidIdentityTokenException, - MalformedPolicyDocumentException: () => MalformedPolicyDocumentException, - PackedPolicyTooLargeException: () => PackedPolicyTooLargeException, - RegionDisabledException: () => RegionDisabledException, - STS: () => STS, - STSServiceException: () => STSServiceException, - decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, - getDefaultRoleAssumer: () => getDefaultRoleAssumer2, - getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 -}); -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(6878), module.exports); - -// src/submodules/sts/STS.ts -var import_smithy_client6 = __nccwpck_require__(3570); - -// src/submodules/sts/commands/AssumeRoleCommand.ts -var import_middleware_endpoint = __nccwpck_require__(2918); -var import_middleware_serde = __nccwpck_require__(1238); -var import_smithy_client4 = __nccwpck_require__(3570); -var import_EndpointParameters = __nccwpck_require__(981); - -// src/submodules/sts/models/models_0.ts -var import_smithy_client2 = __nccwpck_require__(3570); - -// src/submodules/sts/models/STSServiceException.ts -var import_smithy_client = __nccwpck_require__(3570); -var STSServiceException = class _STSServiceException extends import_smithy_client.ServiceException { - static { - __name(this, "STSServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _STSServiceException.prototype); - } -}; - -// src/submodules/sts/models/models_0.ts -var CredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client2.SENSITIVE_STRING } -}), "CredentialsFilterSensitiveLog"); -var AssumeRoleResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleResponseFilterSensitiveLog"); -var ExpiredTokenException = class _ExpiredTokenException extends STSServiceException { - static { - __name(this, "ExpiredTokenException"); - } - name = "ExpiredTokenException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - } -}; -var MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { - static { - __name(this, "MalformedPolicyDocumentException"); - } - name = "MalformedPolicyDocumentException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "MalformedPolicyDocumentException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); - } -}; -var PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { - static { - __name(this, "PackedPolicyTooLargeException"); - } - name = "PackedPolicyTooLargeException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "PackedPolicyTooLargeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); - } -}; -var RegionDisabledException = class _RegionDisabledException extends STSServiceException { - static { - __name(this, "RegionDisabledException"); - } - name = "RegionDisabledException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "RegionDisabledException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _RegionDisabledException.prototype); - } -}; -var IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { - static { - __name(this, "IDPRejectedClaimException"); - } - name = "IDPRejectedClaimException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "IDPRejectedClaimException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); - } -}; -var InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { - static { - __name(this, "InvalidIdentityTokenException"); - } - name = "InvalidIdentityTokenException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidIdentityTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); - } -}; -var AssumeRoleWithWebIdentityRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client2.SENSITIVE_STRING } -}), "AssumeRoleWithWebIdentityRequestFilterSensitiveLog"); -var AssumeRoleWithWebIdentityResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleWithWebIdentityResponseFilterSensitiveLog"); -var IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { - static { - __name(this, "IDPCommunicationErrorException"); - } - name = "IDPCommunicationErrorException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "IDPCommunicationErrorException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); - } -}; - -// src/submodules/sts/protocols/Aws_query.ts -var import_core = __nccwpck_require__(2143); -var import_protocol_http = __nccwpck_require__(4418); -var import_smithy_client3 = __nccwpck_require__(3570); -var se_AssumeRoleCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleRequest(input, context), - [_A]: _AR, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleCommand"); -var se_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleWithWebIdentityRequest(input, context), - [_A]: _ARWWI, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleWithWebIdentityCommand"); -var de_AssumeRoleCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleResponse(data.AssumeRoleResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleCommand"); -var de_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); - } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleWithWebIdentityCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core.parseXmlErrorBody)(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); - 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); - default: - const parsedBody = parsedOutput.body; - return throwDefaultError({ - output, - parsedBody: parsedBody.Error, - errorCode - }); - } -}, "de_CommandError"); -var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_ExpiredTokenException(body.Error, context); - const exception = new ExpiredTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_ExpiredTokenExceptionRes"); -var de_IDPCommunicationErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_IDPCommunicationErrorException(body.Error, context); - const exception = new IDPCommunicationErrorException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_IDPCommunicationErrorExceptionRes"); -var de_IDPRejectedClaimExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_IDPRejectedClaimException(body.Error, context); - const exception = new IDPRejectedClaimException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_IDPRejectedClaimExceptionRes"); -var de_InvalidIdentityTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_InvalidIdentityTokenException(body.Error, context); - const exception = new InvalidIdentityTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_InvalidIdentityTokenExceptionRes"); -var de_MalformedPolicyDocumentExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_MalformedPolicyDocumentException(body.Error, context); - const exception = new MalformedPolicyDocumentException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_MalformedPolicyDocumentExceptionRes"); -var de_PackedPolicyTooLargeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_PackedPolicyTooLargeException(body.Error, context); - const exception = new PackedPolicyTooLargeException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_PackedPolicyTooLargeExceptionRes"); -var de_RegionDisabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_RegionDisabledException(body.Error, context); - const exception = new RegionDisabledException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_RegionDisabledExceptionRes"); -var se_AssumeRoleRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; - } - if (input[_RSN] != null) { - entries[_RSN] = input[_RSN]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - if (input[_T] != null) { - const memberEntries = se_tagListType(input[_T], context); - if (input[_T]?.length === 0) { - entries.Tags = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `Tags.${key}`; - entries[loc] = value; - }); - } - if (input[_TTK] != null) { - const memberEntries = se_tagKeyListType(input[_TTK], context); - if (input[_TTK]?.length === 0) { - entries.TransitiveTagKeys = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `TransitiveTagKeys.${key}`; - entries[loc] = value; - }); - } - if (input[_EI] != null) { - entries[_EI] = input[_EI]; - } - if (input[_SN] != null) { - entries[_SN] = input[_SN]; - } - if (input[_TC] != null) { - entries[_TC] = input[_TC]; - } - if (input[_SI] != null) { - entries[_SI] = input[_SI]; - } - if (input[_PC] != null) { - const memberEntries = se_ProvidedContextsListType(input[_PC], context); - if (input[_PC]?.length === 0) { - entries.ProvidedContexts = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `ProvidedContexts.${key}`; - entries[loc] = value; - }); - } - return entries; -}, "se_AssumeRoleRequest"); -var se_AssumeRoleWithWebIdentityRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; - } - if (input[_RSN] != null) { - entries[_RSN] = input[_RSN]; - } - if (input[_WIT] != null) { - entries[_WIT] = input[_WIT]; - } - if (input[_PI] != null) { - entries[_PI] = input[_PI]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - return entries; -}, "se_AssumeRoleWithWebIdentityRequest"); -var se_policyDescriptorListType = /* @__PURE__ */ __name((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; -}, "se_policyDescriptorListType"); -var se_PolicyDescriptorType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_a] != null) { - entries[_a] = input[_a]; - } - return entries; -}, "se_PolicyDescriptorType"); -var se_ProvidedContext = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_PAr] != null) { - entries[_PAr] = input[_PAr]; - } - if (input[_CA] != null) { - entries[_CA] = input[_CA]; - } - return entries; -}, "se_ProvidedContext"); -var se_ProvidedContextsListType = /* @__PURE__ */ __name((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; -}, "se_ProvidedContextsListType"); -var se_Tag = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_K] != null) { - entries[_K] = input[_K]; - } - if (input[_Va] != null) { - entries[_Va] = input[_Va]; - } - return entries; -}, "se_Tag"); -var se_tagKeyListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; - } - entries[`member.${counter}`] = entry; - counter++; - } - return entries; -}, "se_tagKeyListType"); -var se_tagListType = /* @__PURE__ */ __name((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; -}, "se_tagListType"); -var de_AssumedRoleUser = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_ARI] != null) { - contents[_ARI] = (0, import_smithy_client3.expectString)(output[_ARI]); - } - if (output[_Ar] != null) { - contents[_Ar] = (0, import_smithy_client3.expectString)(output[_Ar]); - } - return contents; -}, "de_AssumedRoleUser"); -var de_AssumeRoleResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); - } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); - } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); - } - return contents; -}, "de_AssumeRoleResponse"); -var de_AssumeRoleWithWebIdentityResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_SFWIT] != null) { - contents[_SFWIT] = (0, import_smithy_client3.expectString)(output[_SFWIT]); - } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); - } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); - } - if (output[_Pr] != null) { - contents[_Pr] = (0, import_smithy_client3.expectString)(output[_Pr]); - } - if (output[_Au] != null) { - contents[_Au] = (0, import_smithy_client3.expectString)(output[_Au]); - } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); - } - return contents; -}, "de_AssumeRoleWithWebIdentityResponse"); -var de_Credentials = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_AKI] != null) { - contents[_AKI] = (0, import_smithy_client3.expectString)(output[_AKI]); - } - if (output[_SAK] != null) { - contents[_SAK] = (0, import_smithy_client3.expectString)(output[_SAK]); - } - if (output[_ST] != null) { - contents[_ST] = (0, import_smithy_client3.expectString)(output[_ST]); - } - if (output[_E] != null) { - contents[_E] = (0, import_smithy_client3.expectNonNull)((0, import_smithy_client3.parseRfc3339DateTimeWithOffset)(output[_E])); - } - return contents; -}, "de_Credentials"); -var de_ExpiredTokenException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_ExpiredTokenException"); -var de_IDPCommunicationErrorException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_IDPCommunicationErrorException"); -var de_IDPRejectedClaimException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_IDPRejectedClaimException"); -var de_InvalidIdentityTokenException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_InvalidIdentityTokenException"); -var de_MalformedPolicyDocumentException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_MalformedPolicyDocumentException"); -var de_PackedPolicyTooLargeException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_PackedPolicyTooLargeException"); -var de_RegionDisabledException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_RegionDisabledException"); -var deserializeMetadata = /* @__PURE__ */ __name((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"] -}), "deserializeMetadata"); -var throwDefaultError = (0, import_smithy_client3.withBaseException)(STSServiceException); -var buildHttpRpcRequest = /* @__PURE__ */ __name(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 !== void 0) { - contents.hostname = resolvedHostname; - } - if (body !== void 0) { - contents.body = body; - } - return new import_protocol_http.HttpRequest(contents); -}, "buildHttpRpcRequest"); -var SHARED_HEADERS = { - "content-type": "application/x-www-form-urlencoded" -}; -var _ = "2011-06-15"; -var _A = "Action"; -var _AKI = "AccessKeyId"; -var _AR = "AssumeRole"; -var _ARI = "AssumedRoleId"; -var _ARU = "AssumedRoleUser"; -var _ARWWI = "AssumeRoleWithWebIdentity"; -var _Ar = "Arn"; -var _Au = "Audience"; -var _C = "Credentials"; -var _CA = "ContextAssertion"; -var _DS = "DurationSeconds"; -var _E = "Expiration"; -var _EI = "ExternalId"; -var _K = "Key"; -var _P = "Policy"; -var _PA = "PolicyArns"; -var _PAr = "ProviderArn"; -var _PC = "ProvidedContexts"; -var _PI = "ProviderId"; -var _PPS = "PackedPolicySize"; -var _Pr = "Provider"; -var _RA = "RoleArn"; -var _RSN = "RoleSessionName"; -var _SAK = "SecretAccessKey"; -var _SFWIT = "SubjectFromWebIdentityToken"; -var _SI = "SourceIdentity"; -var _SN = "SerialNumber"; -var _ST = "SessionToken"; -var _T = "Tags"; -var _TC = "TokenCode"; -var _TTK = "TransitiveTagKeys"; -var _V = "Version"; -var _Va = "Value"; -var _WIT = "WebIdentityToken"; -var _a = "arn"; -var _m = "message"; -var buildFormUrlencodedString = /* @__PURE__ */ __name((formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client3.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client3.extendedEncodeURIComponent)(value)).join("&"), "buildFormUrlencodedString"); -var loadQueryErrorCode = /* @__PURE__ */ __name((output, data) => { - if (data.Error?.Code !== void 0) { - return data.Error.Code; - } - if (output.statusCode == 404) { - return "NotFound"; - } -}, "loadQueryErrorCode"); - -// src/submodules/sts/commands/AssumeRoleCommand.ts -var AssumeRoleCommand = class extends import_smithy_client4.Command.classBuilder().ep(import_EndpointParameters.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() { - static { - __name(this, "AssumeRoleCommand"); - } -}; - -// src/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.ts -var import_middleware_endpoint2 = __nccwpck_require__(2918); -var import_middleware_serde2 = __nccwpck_require__(1238); -var import_smithy_client5 = __nccwpck_require__(3570); -var import_EndpointParameters2 = __nccwpck_require__(981); -var AssumeRoleWithWebIdentityCommand = class extends import_smithy_client5.Command.classBuilder().ep(import_EndpointParameters2.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde2.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() { - static { - __name(this, "AssumeRoleWithWebIdentityCommand"); - } -}; - -// src/submodules/sts/STS.ts -var import_STSClient = __nccwpck_require__(6878); -var commands = { - AssumeRoleCommand, - AssumeRoleWithWebIdentityCommand -}; -var STS = class extends import_STSClient.STSClient { - static { - __name(this, "STS"); - } -}; -(0, import_smithy_client6.createAggregatedClient)(commands, STS); - -// src/submodules/sts/index.ts -var import_EndpointParameters3 = __nccwpck_require__(981); - -// src/submodules/sts/defaultStsRoleAssumers.ts -var import_client = __nccwpck_require__(6510); -var ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; -var getAccountIdFromAssumedRoleUser = /* @__PURE__ */ __name((assumedRoleUser) => { - if (typeof assumedRoleUser?.Arn === "string") { - const arnComponents = assumedRoleUser.Arn.split(":"); - if (arnComponents.length > 4 && arnComponents[4] !== "") { - return arnComponents[4]; - } - } - return void 0; -}, "getAccountIdFromAssumedRoleUser"); -var resolveRegion = /* @__PURE__ */ __name(async (_region, _parentRegion, credentialProviderLogger) => { - const region = typeof _region === "function" ? await _region() : _region; - const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; - credentialProviderLogger?.debug?.( - "@aws-sdk/client-sts::resolveRegion", - "accepting first of:", - `${region} (provider)`, - `${parentRegion} (parent client)`, - `${ASSUME_ROLE_DEFAULT_REGION} (STS default)` - ); - return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION; -}, "resolveRegion"); -var getDefaultRoleAssumer = /* @__PURE__ */ __name((stsOptions, STSClient3) => { - let stsClient; - let closureSourceCreds; - return async (sourceCreds, params) => { - closureSourceCreds = sourceCreds; - if (!stsClient) { - const { - logger = stsOptions?.parentClientConfig?.logger, - region, - requestHandler = stsOptions?.parentClientConfig?.requestHandler, - credentialProviderLogger - } = stsOptions; - const resolvedRegion = await resolveRegion( - region, - stsOptions?.parentClientConfig?.region, - credentialProviderLogger - ); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient3({ - profile: stsOptions?.parentClientConfig?.profile, - // A hack to make sts client uses the credential in current closure. - credentialDefaultProvider: /* @__PURE__ */ __name(() => async () => closureSourceCreds, "credentialDefaultProvider"), - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger - }); - } - const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleCommand(params)); - if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); - const credentials = { - accessKeyId: Credentials2.AccessKeyId, - secretAccessKey: Credentials2.SecretAccessKey, - sessionToken: Credentials2.SessionToken, - expiration: Credentials2.Expiration, - // TODO(credentialScope): access normally when shape is updated. - ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); - return credentials; - }; -}, "getDefaultRoleAssumer"); -var getDefaultRoleAssumerWithWebIdentity = /* @__PURE__ */ __name((stsOptions, STSClient3) => { - let stsClient; - return async (params) => { - if (!stsClient) { - const { - logger = stsOptions?.parentClientConfig?.logger, - region, - requestHandler = stsOptions?.parentClientConfig?.requestHandler, - credentialProviderLogger - } = stsOptions; - const resolvedRegion = await resolveRegion( - region, - stsOptions?.parentClientConfig?.region, - credentialProviderLogger - ); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient3({ - profile: stsOptions?.parentClientConfig?.profile, - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger - }); - } - const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); - if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); - const credentials = { - accessKeyId: Credentials2.AccessKeyId, - secretAccessKey: Credentials2.SecretAccessKey, - sessionToken: Credentials2.SessionToken, - expiration: Credentials2.Expiration, - // TODO(credentialScope): access normally when shape is updated. - ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, - ...accountId && { accountId } - }; - if (accountId) { - (0, import_client.setCredentialFeature)(credentials, "RESOLVED_ACCOUNT_ID", "T"); - } - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); - return credentials; - }; -}, "getDefaultRoleAssumerWithWebIdentity"); -var isH2 = /* @__PURE__ */ __name((requestHandler) => { - return requestHandler?.metadata?.handlerProtocol === "h2"; -}, "isH2"); - -// src/submodules/sts/defaultRoleAssumers.ts -var import_STSClient2 = __nccwpck_require__(6878); -var getCustomizableStsClientCtor = /* @__PURE__ */ __name((baseCtor, customizations) => { - if (!customizations) return baseCtor; - else - return class CustomizableSTSClient extends baseCtor { - static { - __name(this, "CustomizableSTSClient"); - } - constructor(config) { - super(config); - for (const customization of customizations) { - this.middlewareStack.use(customization); - } - } - }; -}, "getCustomizableStsClientCtor"); -var getDefaultRoleAssumer2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumer"); -var getDefaultRoleAssumerWithWebIdentity2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumerWithWebIdentity"); -var decorateDefaultCredentialProvider = /* @__PURE__ */ __name((provider) => (input) => provider({ - roleAssumer: getDefaultRoleAssumer2(input), - roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input), - ...input -}), "decorateDefaultCredentialProvider"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 302: -/***/ ((__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__(4178)); -const core_1 = __nccwpck_require__(2143); -const util_user_agent_node_1 = __nccwpck_require__(7330); -const config_resolver_1 = __nccwpck_require__(3098); -const core_2 = __nccwpck_require__(5829); -const hash_node_1 = __nccwpck_require__(3081); -const middleware_retry_1 = __nccwpck_require__(6039); -const node_config_provider_1 = __nccwpck_require__(3461); -const node_http_handler_1 = __nccwpck_require__(258); -const util_body_length_node_1 = __nccwpck_require__(8075); -const util_retry_1 = __nccwpck_require__(4902); -const runtimeConfig_shared_1 = __nccwpck_require__(9165); -const smithy_client_1 = __nccwpck_require__(3570); -const util_defaults_mode_node_1 = __nccwpck_require__(2429); -const smithy_client_2 = __nccwpck_require__(3570); -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); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || - (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, - }, config), - 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, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; - - -/***/ }), - -/***/ 9165: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(2143); -const core_2 = __nccwpck_require__(5829); -const smithy_client_1 = __nccwpck_require__(3570); -const url_parser_1 = __nccwpck_require__(4681); -const util_base64_1 = __nccwpck_require__(5600); -const util_utf8_1 = __nccwpck_require__(1895); -const httpAuthSchemeProvider_1 = __nccwpck_require__(3061); -const endpointResolver_1 = __nccwpck_require__(8181); -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 ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - 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; - - -/***/ }), - -/***/ 9913: -/***/ ((__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__(6976); -const protocol_http_1 = __nccwpck_require__(4418); -const smithy_client_1 = __nccwpck_require__(3570); -const httpAuthExtensionConfiguration_1 = __nccwpck_require__(1746); -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); -}; -exports.resolveRuntimeExtensions = resolveRuntimeExtensions; - - -/***/ }), - -/***/ 6976: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, - NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, - REGION_ENV_NAME: () => REGION_ENV_NAME, - REGION_INI_NAME: () => REGION_INI_NAME, - getAwsRegionExtensionConfiguration: () => getAwsRegionExtensionConfiguration, - resolveAwsRegionExtensionConfiguration: () => resolveAwsRegionExtensionConfiguration, - resolveRegionConfig: () => resolveRegionConfig -}); -module.exports = __toCommonJS(index_exports); - -// src/extensions/index.ts -var getAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setRegion(region) { - runtimeConfig.region = region; - }, - region() { - return runtimeConfig.region; - } - }; -}, "getAwsRegionExtensionConfiguration"); -var resolveAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => { - return { - region: awsRegionExtensionConfiguration.region() - }; -}, "resolveAwsRegionExtensionConfiguration"); - -// src/regionConfig/config.ts -var REGION_ENV_NAME = "AWS_REGION"; -var REGION_INI_NAME = "region"; -var NODE_REGION_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => env[REGION_ENV_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"), - default: /* @__PURE__ */ __name(() => { - throw new Error("Region is missing"); - }, "default") -}; -var NODE_REGION_CONFIG_FILE_OPTIONS = { - preferredFile: "credentials" -}; - -// src/regionConfig/isFipsRegion.ts -var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); - -// src/regionConfig/getRealRegion.ts -var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); - -// src/regionConfig/resolveRegionConfig.ts -var resolveRegionConfig = /* @__PURE__ */ __name((input) => { - const { region, useFipsEndpoint } = input; - if (!region) { - throw new Error("Region is missing"); - } - return Object.assign(input, { - region: /* @__PURE__ */ __name(async () => { - if (typeof region === "string") { - return getRealRegion(region); - } - const providedRegion = await region(); - return getRealRegion(providedRegion); - }, "region"), - useFipsEndpoint: /* @__PURE__ */ __name(async () => { - const providedRegion = typeof region === "string" ? region : await region(); - if (isFipsRegion(providedRegion)) { - return true; - } - return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); - }, "useFipsEndpoint") - }); -}, "resolveRegionConfig"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 7182: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromEnvSigningName: () => fromEnvSigningName, - fromSso: () => fromSso, - fromStatic: () => fromStatic, - nodeProvider: () => nodeProvider -}); -module.exports = __toCommonJS(index_exports); - -// src/fromEnvSigningName.ts -var import_client = __nccwpck_require__(6510); -var import_httpAuthSchemes = __nccwpck_require__(3017); -var import_property_provider = __nccwpck_require__(9721); -var fromEnvSigningName = /* @__PURE__ */ __name(({ logger, signingName } = {}) => async () => { - logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); - if (!signingName) { - throw new import_property_provider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); - } - const bearerTokenKey = (0, import_httpAuthSchemes.getBearerTokenEnvKey)(signingName); - if (!(bearerTokenKey in process.env)) { - throw new import_property_provider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); - } - const token = { token: process.env[bearerTokenKey] }; - (0, import_client.setTokenFeature)(token, "BEARER_SERVICE_ENV_VARS", "3"); - return token; -}, "fromEnvSigningName"); - -// src/fromSso.ts - - - -// src/constants.ts -var EXPIRE_WINDOW_MS = 5 * 60 * 1e3; -var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; - -// src/getSsoOidcClient.ts -var getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion, init = {}) => { - const { SSOOIDCClient } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(8959))); - const ssoOidcClient = new SSOOIDCClient( - Object.assign({}, init.clientConfig ?? {}, { - region: ssoRegion ?? init.clientConfig?.region, - logger: init.clientConfig?.logger ?? init.parentClientConfig?.logger - }) - ); - return ssoOidcClient; -}, "getSsoOidcClient"); - -// src/getNewSsoOidcToken.ts -var getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion, init = {}) => { - const { CreateTokenCommand } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(8959))); - const ssoOidcClient = await getSsoOidcClient(ssoRegion, init); - return ssoOidcClient.send( - new CreateTokenCommand({ - clientId: ssoToken.clientId, - clientSecret: ssoToken.clientSecret, - refreshToken: ssoToken.refreshToken, - grantType: "refresh_token" - }) - ); -}, "getNewSsoOidcToken"); - -// src/validateTokenExpiry.ts - -var validateTokenExpiry = /* @__PURE__ */ __name((token) => { - if (token.expiration && token.expiration.getTime() < Date.now()) { - throw new import_property_provider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); - } -}, "validateTokenExpiry"); - -// src/validateTokenKey.ts - -var validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => { - if (typeof value === "undefined") { - throw new import_property_provider.TokenProviderError( - `Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, - false - ); - } -}, "validateTokenKey"); - -// src/writeSSOTokenToFile.ts -var import_shared_ini_file_loader = __nccwpck_require__(3507); -var import_fs = __nccwpck_require__(7147); -var { writeFile } = import_fs.promises; -var writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => { - const tokenFilepath = (0, import_shared_ini_file_loader.getSSOTokenFilepath)(id); - const tokenString = JSON.stringify(ssoToken, null, 2); - return writeFile(tokenFilepath, tokenString); -}, "writeSSOTokenToFile"); - -// src/fromSso.ts -var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0); -var fromSso = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { - const init = { - ..._init, - parentClientConfig: { - ...callerClientConfig, - ..._init.parentClientConfig - } - }; - init.logger?.debug("@aws-sdk/token-providers - fromSso"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - const profileName = (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }); - const profile = profiles[profileName]; - if (!profile) { - throw new import_property_provider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); - } else if (!profile["sso_session"]) { - throw new import_property_provider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); - } - const ssoSessionName = profile["sso_session"]; - const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init); - const ssoSession = ssoSessions[ssoSessionName]; - if (!ssoSession) { - throw new import_property_provider.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 import_property_provider.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, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoSessionName); - } catch (e) { - throw new import_property_provider.TokenProviderError( - `The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, - false - ); - } - validateTokenKey("accessToken", ssoToken.accessToken); - validateTokenKey("expiresAt", ssoToken.expiresAt); - const { accessToken, expiresAt } = ssoToken; - const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; - if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { - return existingToken; - } - if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) { - validateTokenExpiry(existingToken); - return existingToken; - } - validateTokenKey("clientId", ssoToken.clientId, true); - validateTokenKey("clientSecret", ssoToken.clientSecret, true); - validateTokenKey("refreshToken", ssoToken.refreshToken, true); - try { - lastRefreshAttemptTime.setTime(Date.now()); - const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init); - validateTokenKey("accessToken", newSsoOidcToken.accessToken); - validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); - const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3); - try { - await writeSSOTokenToFile(ssoSessionName, { - ...ssoToken, - accessToken: newSsoOidcToken.accessToken, - expiresAt: newTokenExpiration.toISOString(), - refreshToken: newSsoOidcToken.refreshToken - }); - } catch (error) { - } - return { - token: newSsoOidcToken.accessToken, - expiration: newTokenExpiration - }; - } catch (error) { - validateTokenExpiry(existingToken); - return existingToken; - } -}, "fromSso"); - -// src/fromStatic.ts - -var fromStatic = /* @__PURE__ */ __name(({ token, logger }) => async () => { - logger?.debug("@aws-sdk/token-providers - fromStatic"); - if (!token || !token.token) { - throw new import_property_provider.TokenProviderError(`Please pass a valid token to fromStatic`, false); - } - return token; -}, "fromStatic"); - -// src/nodeProvider.ts - -var nodeProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( - (0, import_property_provider.chain)(fromSso(init), async () => { - throw new import_property_provider.TokenProviderError("Could not load token from any providers", false); - }), - (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5, - (token) => token.expiration !== void 0 -), "nodeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 4241: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - ConditionObject: () => import_util_endpoints.ConditionObject, - DeprecatedObject: () => import_util_endpoints.DeprecatedObject, - EndpointError: () => import_util_endpoints.EndpointError, - EndpointObject: () => import_util_endpoints.EndpointObject, - EndpointObjectHeaders: () => import_util_endpoints.EndpointObjectHeaders, - EndpointObjectProperties: () => import_util_endpoints.EndpointObjectProperties, - EndpointParams: () => import_util_endpoints.EndpointParams, - EndpointResolverOptions: () => import_util_endpoints.EndpointResolverOptions, - EndpointRuleObject: () => import_util_endpoints.EndpointRuleObject, - ErrorRuleObject: () => import_util_endpoints.ErrorRuleObject, - EvaluateOptions: () => import_util_endpoints.EvaluateOptions, - Expression: () => import_util_endpoints.Expression, - FunctionArgv: () => import_util_endpoints.FunctionArgv, - FunctionObject: () => import_util_endpoints.FunctionObject, - FunctionReturn: () => import_util_endpoints.FunctionReturn, - ParameterObject: () => import_util_endpoints.ParameterObject, - ReferenceObject: () => import_util_endpoints.ReferenceObject, - ReferenceRecord: () => import_util_endpoints.ReferenceRecord, - RuleSetObject: () => import_util_endpoints.RuleSetObject, - RuleSetRules: () => import_util_endpoints.RuleSetRules, - TreeRuleObject: () => import_util_endpoints.TreeRuleObject, - awsEndpointFunctions: () => awsEndpointFunctions, - getUserAgentPrefix: () => getUserAgentPrefix, - isIpAddress: () => import_util_endpoints.isIpAddress, - partition: () => partition, - resolveDefaultAwsRegionalEndpointsConfig: () => resolveDefaultAwsRegionalEndpointsConfig, - resolveEndpoint: () => import_util_endpoints.resolveEndpoint, - setPartitionInfo: () => setPartitionInfo, - toEndpointV1: () => toEndpointV1, - useDefaultPartitionInfo: () => useDefaultPartitionInfo -}); -module.exports = __toCommonJS(index_exports); - -// src/aws.ts - - -// src/lib/aws/isVirtualHostableS3Bucket.ts - - -// src/lib/isIpAddress.ts -var import_util_endpoints = __nccwpck_require__(5473); - -// src/lib/aws/isVirtualHostableS3Bucket.ts -var isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => { - if (allowSubDomains) { - for (const label of value.split(".")) { - if (!isVirtualHostableS3Bucket(label)) { - return false; - } - } - return true; - } - if (!(0, import_util_endpoints.isValidHostLabel)(value)) { - return false; - } - if (value.length < 3 || value.length > 63) { - return false; - } - if (value !== value.toLowerCase()) { - return false; - } - if ((0, import_util_endpoints.isIpAddress)(value)) { - return false; - } - return true; -}, "isVirtualHostableS3Bucket"); - -// src/lib/aws/parseArn.ts -var ARN_DELIMITER = ":"; -var RESOURCE_DELIMITER = "/"; -var parseArn = /* @__PURE__ */ __name((value) => { - const segments = value.split(ARN_DELIMITER); - if (segments.length < 6) return null; - const [arn, partition2, service, region, accountId, ...resourcePath] = segments; - if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null; - const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); - return { - partition: partition2, - service, - region, - accountId, - resourceId - }; -}, "parseArn"); - -// src/lib/aws/partitions.json -var partitions_default = { - 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|mx)\\-\\w+\\-\\d+$", - regions: { - "af-south-1": { - description: "Africa (Cape Town)" - }, - "ap-east-1": { - description: "Asia Pacific (Hong Kong)" - }, - "ap-east-2": { - description: "Asia Pacific (Taipei)" - }, - "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)" - }, - "ap-southeast-5": { - description: "Asia Pacific (Malaysia)" - }, - "ap-southeast-7": { - description: "Asia Pacific (Thailand)" - }, - "aws-global": { - description: "AWS Standard global region" - }, - "ca-central-1": { - description: "Canada (Central)" - }, - "ca-west-1": { - description: "Canada West (Calgary)" - }, - "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)" - }, - "mx-central-1": { - description: "Mexico (Central)" - }, - "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: { - "aws-iso-e-global": { - description: "AWS ISOE (Europe) global region" - }, - "eu-isoe-west-1": { - description: "EU ISOE West" - } - } - }, { - 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: { - "aws-iso-f-global": { - description: "AWS ISOF global region" - }, - "us-isof-east-1": { - description: "US ISOF EAST" - }, - "us-isof-south-1": { - description: "US ISOF SOUTH" - } - } - }, { - id: "aws-eusc", - outputs: { - dnsSuffix: "amazonaws.eu", - dualStackDnsSuffix: "amazonaws.eu", - implicitGlobalRegion: "eusc-de-east-1", - name: "aws-eusc", - supportsDualStack: false, - supportsFIPS: true - }, - regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", - regions: { - "eusc-de-east-1": { - description: "EU (Germany)" - } - } - }], - version: "1.1" -}; - -// src/lib/aws/partition.ts -var selectedPartitionsInfo = partitions_default; -var selectedUserAgentPrefix = ""; -var partition = /* @__PURE__ */ __name((value) => { - const { partitions } = selectedPartitionsInfo; - for (const partition2 of partitions) { - const { regions, outputs } = partition2; - for (const [region, regionData] of Object.entries(regions)) { - if (region === value) { - return { - ...outputs, - ...regionData - }; - } - } - } - for (const partition2 of partitions) { - const { regionRegex, outputs } = partition2; - if (new RegExp(regionRegex).test(value)) { - return { - ...outputs - }; - } - } - const DEFAULT_PARTITION = partitions.find((partition2) => partition2.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 - }; -}, "partition"); -var setPartitionInfo = /* @__PURE__ */ __name((partitionsInfo, userAgentPrefix = "") => { - selectedPartitionsInfo = partitionsInfo; - selectedUserAgentPrefix = userAgentPrefix; -}, "setPartitionInfo"); -var useDefaultPartitionInfo = /* @__PURE__ */ __name(() => { - setPartitionInfo(partitions_default, ""); -}, "useDefaultPartitionInfo"); -var getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix"); - -// src/aws.ts -var awsEndpointFunctions = { - isVirtualHostableS3Bucket, - parseArn, - partition -}; -import_util_endpoints.customEndpointFunctions.aws = awsEndpointFunctions; - -// src/resolveDefaultAwsRegionalEndpointsConfig.ts -var import_url_parser = __nccwpck_require__(4681); -var resolveDefaultAwsRegionalEndpointsConfig = /* @__PURE__ */ __name((input) => { - if (typeof input.endpointProvider !== "function") { - throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); - } - const { endpoint } = input; - if (endpoint === void 0) { - input.endpoint = async () => { - return toEndpointV1( - input.endpointProvider( - { - Region: typeof input.region === "function" ? await input.region() : input.region, - UseDualStack: typeof input.useDualstackEndpoint === "function" ? await input.useDualstackEndpoint() : input.useDualstackEndpoint, - UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, - Endpoint: void 0 - }, - { logger: input.logger } - ) - ); - }; - } - return input; -}, "resolveDefaultAwsRegionalEndpointsConfig"); -var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => (0, import_url_parser.parseUrl)(endpoint.url), "toEndpointV1"); - -// src/resolveEndpoint.ts - - -// src/types/EndpointError.ts - - -// src/types/EndpointRuleObject.ts - - -// src/types/ErrorRuleObject.ts - - -// src/types/RuleSetObject.ts - - -// src/types/TreeRuleObject.ts - - -// src/types/shared.ts - -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 7330: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - NODE_APP_ID_CONFIG_OPTIONS: () => NODE_APP_ID_CONFIG_OPTIONS, - UA_APP_ID_ENV_NAME: () => UA_APP_ID_ENV_NAME, - UA_APP_ID_INI_NAME: () => UA_APP_ID_INI_NAME, - createDefaultUserAgentProvider: () => createDefaultUserAgentProvider, - crtAvailability: () => crtAvailability, - defaultUserAgent: () => defaultUserAgent -}); -module.exports = __toCommonJS(index_exports); - -// src/defaultUserAgent.ts -var import_os = __nccwpck_require__(2037); -var import_process = __nccwpck_require__(7282); - -// src/crt-availability.ts -var crtAvailability = { - isCrtAvailable: false -}; - -// src/is-crt-available.ts -var isCrtAvailable = /* @__PURE__ */ __name(() => { - if (crtAvailability.isCrtAvailable) { - return ["md/crt-avail"]; - } - return null; -}, "isCrtAvailable"); - -// src/defaultUserAgent.ts -var createDefaultUserAgentProvider = /* @__PURE__ */ __name(({ serviceId, clientVersion }) => { - return async (config) => { - const sections = [ - // sdk-metadata - ["aws-sdk-js", clientVersion], - // ua-metadata - ["ua", "2.1"], - // os-metadata - [`os/${(0, import_os.platform)()}`, (0, import_os.release)()], - // language-metadata - // ECMAScript edition doesn't matter in JS, so no version needed. - ["lang/js"], - ["md/nodejs", `${import_process.versions.node}`] - ]; - const crtAvailable = isCrtAvailable(); - if (crtAvailable) { - sections.push(crtAvailable); - } - if (serviceId) { - sections.push([`api/${serviceId}`, clientVersion]); - } - if (import_process.env.AWS_EXECUTION_ENV) { - sections.push([`exec-env/${import_process.env.AWS_EXECUTION_ENV}`]); - } - const appId = await config?.userAgentAppId?.(); - const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; - return resolvedUserAgent; - }; -}, "createDefaultUserAgentProvider"); -var defaultUserAgent = createDefaultUserAgentProvider; - -// src/nodeAppIdConfigOptions.ts -var import_middleware_user_agent = __nccwpck_require__(6634); -var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; -var UA_APP_ID_INI_NAME = "sdk_ua_app_id"; -var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; -var NODE_APP_ID_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env2) => env2[UA_APP_ID_ENV_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], "configFileSelector"), - default: import_middleware_user_agent.DEFAULT_UA_APP_ID -}; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 9963: -/***/ ((__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__(2825), exports); -tslib_1.__exportStar(__nccwpck_require__(7862), exports); -tslib_1.__exportStar(__nccwpck_require__(785), exports); - - -/***/ }), - -/***/ 2825: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/client/index.ts -var index_exports = {}; -__export(index_exports, { - emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, - setCredentialFeature: () => setCredentialFeature, - setFeature: () => setFeature, - state: () => state -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/client/emitWarningIfUnsupportedVersion.ts -var state = { - warningEmitted: false -}; -var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { - if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { - state.warningEmitted = true; - process.emitWarning( - `NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will -no longer support Node.js 16.x on January 6, 2025. - -To continue receiving updates to AWS services, bug fixes, and security -updates please upgrade to a supported Node.js LTS version. - -More information can be found at: https://a.co/74kJMmI` - ); - } -}, "emitWarningIfUnsupportedVersion"); - -// src/submodules/client/setCredentialFeature.ts -function setCredentialFeature(credentials, feature, value) { - if (!credentials.$source) { - credentials.$source = {}; - } - credentials.$source[feature] = value; - return credentials; -} -__name(setCredentialFeature, "setCredentialFeature"); - -// src/submodules/client/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__aws_sdk_context) { - context.__aws_sdk_context = { - features: {} - }; - } else if (!context.__aws_sdk_context.features) { - context.__aws_sdk_context.features = {}; - } - context.__aws_sdk_context.features[feature] = value; -} -__name(setFeature, "setFeature"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 7862: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/httpAuthSchemes/index.ts -var index_exports = {}; -__export(index_exports, { - AWSSDKSigV4Signer: () => AWSSDKSigV4Signer, - AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner, - AwsSdkSigV4Signer: () => AwsSdkSigV4Signer, - NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, - NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS, - getBearerTokenEnvKey: () => getBearerTokenEnvKey, - resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config, - resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig, - resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config, - validateSigningProperties: () => validateSigningProperties -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts -var import_protocol_http2 = __nccwpck_require__(4418); - -// src/submodules/httpAuthSchemes/utils/getDateHeader.ts -var import_protocol_http = __nccwpck_require__(4418); -var getDateHeader = /* @__PURE__ */ __name((response) => import_protocol_http.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0, "getDateHeader"); - -// src/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.ts -var getSkewCorrectedDate = /* @__PURE__ */ __name((systemClockOffset) => new Date(Date.now() + systemClockOffset), "getSkewCorrectedDate"); - -// src/submodules/httpAuthSchemes/utils/isClockSkewed.ts -var isClockSkewed = /* @__PURE__ */ __name((clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5, "isClockSkewed"); - -// src/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.ts -var getUpdatedSystemClockOffset = /* @__PURE__ */ __name((clockTime, currentSystemClockOffset) => { - const clockTimeInMs = Date.parse(clockTime); - if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { - return clockTimeInMs - Date.now(); - } - return currentSystemClockOffset; -}, "getUpdatedSystemClockOffset"); - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts -var throwSigningPropertyError = /* @__PURE__ */ __name((name, property) => { - if (!property) { - throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); - } - return property; -}, "throwSigningPropertyError"); -var validateSigningProperties = /* @__PURE__ */ __name(async (signingProperties) => { - const context = throwSigningPropertyError( - "context", - signingProperties.context - ); - const config = throwSigningPropertyError("config", signingProperties.config); - const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; - const signerFunction = throwSigningPropertyError( - "signer", - config.signer - ); - const signer = await signerFunction(authScheme); - const signingRegion = signingProperties?.signingRegion; - const signingRegionSet = signingProperties?.signingRegionSet; - const signingName = signingProperties?.signingName; - return { - config, - signer, - signingRegion, - signingRegionSet, - signingName - }; -}, "validateSigningProperties"); -var AwsSdkSigV4Signer = class { - static { - __name(this, "AwsSdkSigV4Signer"); - } - async sign(httpRequest, identity, signingProperties) { - if (!import_protocol_http2.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const validatedProps = await validateSigningProperties(signingProperties); - const { config, signer } = validatedProps; - let { signingRegion, signingName } = validatedProps; - const handlerExecutionContext = signingProperties.context; - if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { - const [first, second] = handlerExecutionContext.authSchemes; - if (first?.name === "sigv4a" && second?.name === "sigv4") { - signingRegion = second?.signingRegion ?? signingRegion; - signingName = second?.signingName ?? signingName; - } - } - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion, - signingService: signingName - }); - return signedRequest; - } - errorHandler(signingProperties) { - return (error) => { - const serverTime = error.ServerTime ?? getDateHeader(error.$response); - if (serverTime) { - const config = throwSigningPropertyError("config", signingProperties.config); - const initialSystemClockOffset = config.systemClockOffset; - config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); - const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; - if (clockSkewCorrected && error.$metadata) { - error.$metadata.clockSkewCorrected = true; - } - } - throw error; - }; - } - successHandler(httpResponse, signingProperties) { - const dateHeader = getDateHeader(httpResponse); - if (dateHeader) { - const config = throwSigningPropertyError("config", signingProperties.config); - config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); - } - } -}; -var AWSSDKSigV4Signer = AwsSdkSigV4Signer; - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.ts -var import_protocol_http3 = __nccwpck_require__(4418); -var AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer { - static { - __name(this, "AwsSdkSigV4ASigner"); - } - async sign(httpRequest, identity, signingProperties) { - if (!import_protocol_http3.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties( - signingProperties - ); - const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); - const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(","); - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion: multiRegionOverride, - signingService: signingName - }); - return signedRequest; - } -}; - -// src/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.ts -var getArrayForCommaSeparatedString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [], "getArrayForCommaSeparatedString"); - -// src/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.ts -var getBearerTokenEnvKey = /* @__PURE__ */ __name((signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`, "getBearerTokenEnvKey"); - -// src/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.ts -var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; -var NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; -var NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { - /** - * Retrieves auth scheme preference from environment variables - * @param env - Node process environment object - * @returns Array of auth scheme strings if preference is set, undefined otherwise - */ - environmentVariableSelector: /* @__PURE__ */ __name((env, options) => { - if (options?.signingName) { - const bearerTokenKey = getBearerTokenEnvKey(options.signingName); - if (bearerTokenKey in env) return ["httpBearerAuth"]; - } - if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) return void 0; - return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); - }, "environmentVariableSelector"), - /** - * Retrieves auth scheme preference from config file - * @param profile - Config profile object - * @returns Array of auth scheme strings if preference is set, undefined otherwise - */ - configFileSelector: /* @__PURE__ */ __name((profile) => { - if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) return void 0; - return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); - }, "configFileSelector"), - /** - * Default auth scheme preference if not specified in environment or config - */ - default: [] -}; - -// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.ts -var import_core = __nccwpck_require__(5829); -var import_property_provider = __nccwpck_require__(9721); -var resolveAwsSdkSigV4AConfig = /* @__PURE__ */ __name((config) => { - config.sigv4aSigningRegionSet = (0, import_core.normalizeProvider)(config.sigv4aSigningRegionSet); - return config; -}, "resolveAwsSdkSigV4AConfig"); -var NODE_SIGV4A_CONFIG_OPTIONS = { - environmentVariableSelector(env) { - if (env.AWS_SIGV4A_SIGNING_REGION_SET) { - return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); - } - throw new import_property_provider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { - tryNextLink: true - }); - }, - configFileSelector(profile) { - if (profile.sigv4a_signing_region_set) { - return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); - } - throw new import_property_provider.ProviderError("sigv4a_signing_region_set not set in profile.", { - tryNextLink: true - }); - }, - default: void 0 -}; - -// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.ts -var import_client = __nccwpck_require__(2825); -var import_core2 = __nccwpck_require__(5829); -var import_signature_v4 = __nccwpck_require__(1528); -var resolveAwsSdkSigV4Config = /* @__PURE__ */ __name((config) => { - let inputCredentials = config.credentials; - let isUserSupplied = !!config.credentials; - let resolvedCredentials = void 0; - Object.defineProperty(config, "credentials", { - set(credentials) { - if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { - isUserSupplied = true; - } - inputCredentials = credentials; - const memoizedProvider = normalizeCredentialProvider(config, { - credentials: inputCredentials, - credentialDefaultProvider: config.credentialDefaultProvider - }); - const boundProvider = bindCallerConfig(config, memoizedProvider); - if (isUserSupplied && !boundProvider.attributed) { - resolvedCredentials = /* @__PURE__ */ __name(async (options) => boundProvider(options).then( - (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_CODE", "e") - ), "resolvedCredentials"); - resolvedCredentials.memoized = boundProvider.memoized; - resolvedCredentials.configBound = boundProvider.configBound; - resolvedCredentials.attributed = true; - } else { - resolvedCredentials = boundProvider; - } - }, - get() { - return resolvedCredentials; - }, - enumerable: true, - configurable: true - }); - config.credentials = inputCredentials; - const { - // Default for signingEscapePath - signingEscapePath = true, - // Default for systemClockOffset - systemClockOffset = config.systemClockOffset || 0, - // No default for sha256 since it is platform dependent - sha256 - } = config; - let signer; - if (config.signer) { - signer = (0, import_core2.normalizeProvider)(config.signer); - } else if (config.regionInfoProvider) { - signer = /* @__PURE__ */ __name(() => (0, import_core2.normalizeProvider)(config.region)().then( - async (region) => [ - await config.regionInfoProvider(region, { - useFipsEndpoint: await config.useFipsEndpoint(), - useDualstackEndpoint: await config.useDualstackEndpoint() - }) || {}, - region - ] - ).then(([regionInfo, region]) => { - const { signingRegion, signingService } = regionInfo; - config.signingRegion = config.signingRegion || signingRegion || region; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }), "signer"); - } else { - signer = /* @__PURE__ */ __name(async (authScheme) => { - authScheme = Object.assign( - {}, - { - name: "sigv4", - signingName: config.signingName || config.defaultSigningName, - signingRegion: await (0, import_core2.normalizeProvider)(config.region)(), - properties: {} - }, - authScheme - ); - const signingRegion = authScheme.signingRegion; - const signingService = authScheme.signingName; - config.signingRegion = config.signingRegion || signingRegion; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }, "signer"); - } - const resolvedConfig = Object.assign(config, { - systemClockOffset, - signingEscapePath, - signer - }); - return resolvedConfig; -}, "resolveAwsSdkSigV4Config"); -var resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; -function normalizeCredentialProvider(config, { - credentials, - credentialDefaultProvider -}) { - let credentialsProvider; - if (credentials) { - if (!credentials?.memoized) { - credentialsProvider = (0, import_core2.memoizeIdentityProvider)(credentials, import_core2.isIdentityExpired, import_core2.doesIdentityRequireRefresh); - } else { - credentialsProvider = credentials; - } - } else { - if (credentialDefaultProvider) { - credentialsProvider = (0, import_core2.normalizeProvider)( - credentialDefaultProvider( - Object.assign({}, config, { - parentClientConfig: config - }) - ) - ); - } else { - credentialsProvider = /* @__PURE__ */ __name(async () => { - throw new Error( - "@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured." - ); - }, "credentialsProvider"); - } - } - credentialsProvider.memoized = true; - return credentialsProvider; -} -__name(normalizeCredentialProvider, "normalizeCredentialProvider"); -function bindCallerConfig(config, credentialsProvider) { - if (credentialsProvider.configBound) { - return credentialsProvider; - } - const fn = /* @__PURE__ */ __name(async (options) => credentialsProvider({ ...options, callerClientConfig: config }), "fn"); - fn.memoized = credentialsProvider.memoized; - fn.configBound = true; - return fn; -} -__name(bindCallerConfig, "bindCallerConfig"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 785: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/submodules/protocols/index.ts -var index_exports = {}; -__export(index_exports, { - AwsEc2QueryProtocol: () => AwsEc2QueryProtocol, - AwsJson1_0Protocol: () => AwsJson1_0Protocol, - AwsJson1_1Protocol: () => AwsJson1_1Protocol, - AwsJsonRpcProtocol: () => AwsJsonRpcProtocol, - AwsQueryProtocol: () => AwsQueryProtocol, - AwsRestJsonProtocol: () => AwsRestJsonProtocol, - AwsRestXmlProtocol: () => AwsRestXmlProtocol, - JsonCodec: () => JsonCodec, - JsonShapeDeserializer: () => JsonShapeDeserializer, - JsonShapeSerializer: () => JsonShapeSerializer, - XmlCodec: () => XmlCodec, - XmlShapeDeserializer: () => XmlShapeDeserializer, - XmlShapeSerializer: () => XmlShapeSerializer, - _toBool: () => _toBool, - _toNum: () => _toNum, - _toStr: () => _toStr, - awsExpectUnion: () => awsExpectUnion, - loadRestJsonErrorCode: () => loadRestJsonErrorCode, - loadRestXmlErrorCode: () => loadRestXmlErrorCode, - parseJsonBody: () => parseJsonBody, - parseJsonErrorBody: () => parseJsonErrorBody, - parseXmlBody: () => parseXmlBody, - parseXmlErrorBody: () => parseXmlErrorBody -}); -module.exports = __toCommonJS(index_exports); - -// src/submodules/protocols/coercing-serializers.ts -var _toStr = /* @__PURE__ */ __name((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; -}, "_toStr"); -var _toBool = /* @__PURE__ */ __name((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; -}, "_toBool"); -var _toNum = /* @__PURE__ */ __name((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; -}, "_toNum"); - -// src/submodules/protocols/json/AwsJsonRpcProtocol.ts -var import_protocols = __nccwpck_require__(2241); -var import_schema3 = __nccwpck_require__(9826); -var import_util_body_length_browser = __nccwpck_require__(713); - -// src/submodules/protocols/ConfigurableSerdeContext.ts -var SerdeContextConfig = class { - static { - __name(this, "SerdeContextConfig"); - } - serdeContext; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } -}; - -// src/submodules/protocols/json/JsonShapeDeserializer.ts -var import_schema = __nccwpck_require__(9826); -var import_serde2 = __nccwpck_require__(7669); -var import_util_base64 = __nccwpck_require__(5600); - -// src/submodules/protocols/json/jsonReviver.ts -var import_serde = __nccwpck_require__(7669); -function jsonReviver(key, value, context) { - if (context?.source) { - const numericString = context.source; - if (typeof value === "number") { - if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { - const isFractional = numericString.includes("."); - if (isFractional) { - return new import_serde.NumericValue(numericString, "bigDecimal"); - } else { - return BigInt(numericString); - } - } - } - } - return value; -} -__name(jsonReviver, "jsonReviver"); - -// src/submodules/protocols/common.ts -var import_smithy_client = __nccwpck_require__(3570); -var collectBodyString = /* @__PURE__ */ __name((streamBody, context) => (0, import_smithy_client.collectBody)(streamBody, context).then((body) => context.utf8Encoder(body)), "collectBodyString"); - -// src/submodules/protocols/json/parseJsonBody.ts -var parseJsonBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - try { - return JSON.parse(encoded); - } catch (e) { - if (e?.name === "SyntaxError") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded - }); - } - throw e; - } - } - return {}; -}), "parseJsonBody"); -var parseJsonErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { - const value = await parseJsonBody(errorBody, context); - value.message = value.message ?? value.Message; - return value; -}, "parseJsonErrorBody"); -var loadRestJsonErrorCode = /* @__PURE__ */ __name((output, data) => { - const findKey = /* @__PURE__ */ __name((object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()), "findKey"); - const sanitizeErrorCode = /* @__PURE__ */ __name((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; - }, "sanitizeErrorCode"); - const headerKey = findKey(output.headers, "x-amzn-errortype"); - if (headerKey !== void 0) { - return sanitizeErrorCode(output.headers[headerKey]); - } - if (data && typeof data === "object") { - const codeKey = findKey(data, "code"); - if (codeKey && data[codeKey] !== void 0) { - return sanitizeErrorCode(data[codeKey]); - } - if (data["__type"] !== void 0) { - return sanitizeErrorCode(data["__type"]); - } - } -}, "loadRestJsonErrorCode"); - -// src/submodules/protocols/json/JsonShapeDeserializer.ts -var JsonShapeDeserializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "JsonShapeDeserializer"); - } - async read(schema, data) { - return this._read( - schema, - typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext) - ); - } - readObject(schema, data) { - return this._read(schema, data); - } - _read(schema, value) { - const isObject = value !== null && typeof value === "object"; - const ns = import_schema.NormalizedSchema.of(schema); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._read(listMember, item)); - } - } - return out; - } else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._read(mapMember, _v); - } - } - return out; - } else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const deserializedValue = this._read(memberSchema, value[fromKey]); - if (deserializedValue != null) { - out[memberName] = deserializedValue; - } - } - return out; - } - if (ns.isBlobSchema() && typeof value === "string") { - return (0, import_util_base64.fromBase64)(value); - } - const mediaType = ns.getMergedTraits().mediaType; - if (ns.isStringSchema() && typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return import_serde2.LazyJsonString.from(value); - } - } - if (ns.isTimestampSchema()) { - const options = this.settings.timestampFormat; - const format = options.useTrait ? ns.getSchema() === import_schema.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; - switch (format) { - case import_schema.SCHEMA.TIMESTAMP_DATE_TIME: - return (0, import_serde2.parseRfc3339DateTimeWithOffset)(value); - case import_schema.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde2.parseRfc7231DateTime)(value); - case import_schema.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return (0, import_serde2.parseEpochTimestamp)(value); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", value); - return new Date(value); - } - } - if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { - return BigInt(value); - } - if (ns.isBigDecimalSchema() && value != void 0) { - if (value instanceof import_serde2.NumericValue) { - return value; - } - return new import_serde2.NumericValue(String(value), "bigDecimal"); - } - if (ns.isNumericSchema() && typeof value === "string") { - switch (value) { - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - case "NaN": - return NaN; - } - } - return value; - } -}; - -// src/submodules/protocols/json/JsonShapeSerializer.ts -var import_schema2 = __nccwpck_require__(9826); -var import_serde4 = __nccwpck_require__(7669); -var import_serde5 = __nccwpck_require__(7669); - -// src/submodules/protocols/json/jsonReplacer.ts -var import_serde3 = __nccwpck_require__(7669); -var NUMERIC_CONTROL_CHAR = String.fromCharCode(925); -var JsonReplacer = class { - static { - __name(this, "JsonReplacer"); - } - /** - * Stores placeholder key to true serialized value lookup. - */ - values = /* @__PURE__ */ new Map(); - counter = 0; - stage = 0; - /** - * Creates a jsonReplacer function that reserves big integer and big decimal values - * for later replacement. - */ - createReplacer() { - if (this.stage === 1) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 1; - return (key, value) => { - if (value instanceof import_serde3.NumericValue) { - const v = `${NUMERIC_CONTROL_CHAR + +"nv" + this.counter++}_` + value.string; - this.values.set(`"${v}"`, value.string); - return v; - } - if (typeof value === "bigint") { - const s = value.toString(); - const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; - this.values.set(`"${v}"`, s); - return v; - } - return value; - }; - } - /** - * Replaces placeholder keys with their true values. - */ - replaceInJson(json) { - if (this.stage === 0) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 2; - if (this.counter === 0) { - return json; - } - for (const [key, value] of this.values) { - json = json.replace(key, value); - } - return json; - } -}; - -// src/submodules/protocols/json/JsonShapeSerializer.ts -var JsonShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "JsonShapeSerializer"); - } - buffer; - rootSchema; - write(schema, value) { - this.rootSchema = import_schema2.NormalizedSchema.of(schema); - this.buffer = this._write(this.rootSchema, value); - } - flush() { - if (this.rootSchema?.isStructSchema() || this.rootSchema?.isDocumentSchema()) { - const replacer = new JsonReplacer(); - return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); - } - return this.buffer; - } - _write(schema, value, container) { - const isObject = value !== null && typeof value === "object"; - const ns = import_schema2.NormalizedSchema.of(schema); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._write(listMember, item)); - } - } - return out; - } else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._write(mapMember, _v); - } - } - return out; - } else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const serializableValue = this._write(memberSchema, value[memberName], ns); - if (serializableValue !== void 0) { - out[targetKey] = serializableValue; - } - } - return out; - } - if (value === null && container?.isStructSchema()) { - return void 0; - } - if (ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string")) { - if (ns === this.rootSchema) { - return value; - } - if (!this.serdeContext?.base64Encoder) { - throw new Error("Missing base64Encoder in serdeContext"); - } - return this.serdeContext?.base64Encoder(value); - } - if (ns.isTimestampSchema() && value instanceof Date) { - const options = this.settings.timestampFormat; - const format = options.useTrait ? ns.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; - switch (format) { - case import_schema2.SCHEMA.TIMESTAMP_DATE_TIME: - return value.toISOString().replace(".000Z", "Z"); - case import_schema2.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde4.dateToUtcString)(value); - case import_schema2.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return value.getTime() / 1e3; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - return value.getTime() / 1e3; - } - } - if (ns.isNumericSchema() && typeof value === "number") { - if (Math.abs(value) === Infinity || isNaN(value)) { - return String(value); - } - } - const mediaType = ns.getMergedTraits().mediaType; - if (ns.isStringSchema() && typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return import_serde5.LazyJsonString.from(value); - } - } - return value; - } -}; - -// src/submodules/protocols/json/JsonCodec.ts -var JsonCodec = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "JsonCodec"); - } - createSerializer() { - const serializer = new JsonShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new JsonShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } -}; - -// src/submodules/protocols/json/AwsJsonRpcProtocol.ts -var AwsJsonRpcProtocol = class extends import_protocols.RpcProtocol { - static { - __name(this, "AwsJsonRpcProtocol"); - } - serializer; - deserializer; - codec; - constructor({ defaultNamespace }) { - super({ - defaultNamespace - }); - this.codec = new JsonCodec({ - timestampFormat: { - useTrait: true, - default: import_schema3.SCHEMA.TIMESTAMP_EPOCH_SECONDS - }, - jsonName: false - }); - this.serializer = this.codec.createSerializer(); - this.deserializer = this.codec.createDeserializer(); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, - "x-amz-target": (this.getJsonRpcVersion() === "1.0" ? `JsonRpc10.` : `JsonProtocol.`) + import_schema3.NormalizedSchema.of(operationSchema).getName() - }); - if ((0, import_schema3.deref)(operationSchema.input) === "unit" || !request.body) { - request.body = "{}"; - } - try { - request.headers["content-length"] = String((0, import_util_body_length_browser.calculateBodyLength)(request.body)); - } catch (e) { - } - return request; - } - getPayloadCodec() { - return this.codec; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const registry = import_schema3.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorIdentifier); - } catch (e) { - const baseExceptionSchema = import_schema3.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), dataObject); - } - throw new Error(errorName); - } - const ns = import_schema3.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output - }); - throw exception; - } -}; - -// src/submodules/protocols/json/AwsJson1_0Protocol.ts -var AwsJson1_0Protocol = class extends AwsJsonRpcProtocol { - static { - __name(this, "AwsJson1_0Protocol"); - } - constructor({ defaultNamespace }) { - super({ - defaultNamespace - }); - } - getShapeId() { - return "aws.protocols#awsJson1_0"; - } - getJsonRpcVersion() { - return "1.0"; - } -}; - -// src/submodules/protocols/json/AwsJson1_1Protocol.ts -var AwsJson1_1Protocol = class extends AwsJsonRpcProtocol { - static { - __name(this, "AwsJson1_1Protocol"); - } - constructor({ defaultNamespace }) { - super({ - defaultNamespace - }); - } - getShapeId() { - return "aws.protocols#awsJson1_1"; - } - getJsonRpcVersion() { - return "1.1"; - } -}; - -// src/submodules/protocols/json/AwsRestJsonProtocol.ts -var import_protocols2 = __nccwpck_require__(2241); -var import_schema4 = __nccwpck_require__(9826); -var import_util_body_length_browser2 = __nccwpck_require__(713); -var AwsRestJsonProtocol = class extends import_protocols2.HttpBindingProtocol { - static { - __name(this, "AwsRestJsonProtocol"); - } - serializer; - deserializer; - codec; - constructor({ defaultNamespace }) { - super({ - defaultNamespace - }); - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS - }, - httpBindings: true, - jsonName: true - }; - this.codec = new JsonCodec(settings); - this.serializer = new import_protocols2.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new import_protocols2.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); - } - getShapeId() { - return "aws.protocols#restJson1"; - } - getPayloadCodec() { - return this.codec; - } - setSerdeContext(serdeContext) { - this.codec.setSerdeContext(serdeContext); - super.setSerdeContext(serdeContext); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = import_schema4.NormalizedSchema.of(operationSchema.input); - const members = inputSchema.getMemberSchemas(); - if (!request.headers["content-type"]) { - const httpPayloadMember = Object.values(members).find((m) => { - return !!m.getMergedTraits().httpPayload; - }); - if (httpPayloadMember) { - const mediaType = httpPayloadMember.getMergedTraits().mediaType; - if (mediaType) { - request.headers["content-type"] = mediaType; - } else if (httpPayloadMember.isStringSchema()) { - request.headers["content-type"] = "text/plain"; - } else if (httpPayloadMember.isBlobSchema()) { - request.headers["content-type"] = "application/octet-stream"; - } else { - request.headers["content-type"] = "application/json"; - } - } else if (!inputSchema.isUnitSchema()) { - const hasBody = Object.values(members).find((m) => { - const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); - return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && httpPrefixHeaders === void 0; - }); - if (hasBody) { - request.headers["content-type"] = "application/json"; - } - } - } - if (request.headers["content-type"] && !request.body) { - request.body = "{}"; - } - if (request.body) { - try { - request.headers["content-length"] = String((0, import_util_body_length_browser2.calculateBodyLength)(request.body)); - } catch (e) { - } - } - return request; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const registry = import_schema4.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorIdentifier); - } catch (e) { - const baseExceptionSchema = import_schema4.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), dataObject); - } - throw new Error(errorName); - } - const ns = import_schema4.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output - }); - throw exception; - } -}; - -// src/submodules/protocols/json/awsExpectUnion.ts -var import_smithy_client2 = __nccwpck_require__(3570); -var awsExpectUnion = /* @__PURE__ */ __name((value) => { - if (value == null) { - return void 0; - } - if (typeof value === "object" && "__type" in value) { - delete value.__type; - } - return (0, import_smithy_client2.expectUnion)(value); -}, "awsExpectUnion"); - -// src/submodules/protocols/query/AwsQueryProtocol.ts -var import_protocols5 = __nccwpck_require__(2241); -var import_schema7 = __nccwpck_require__(9826); -var import_util_body_length_browser3 = __nccwpck_require__(713); - -// src/submodules/protocols/xml/XmlShapeDeserializer.ts -var import_protocols3 = __nccwpck_require__(2241); -var import_schema5 = __nccwpck_require__(9826); -var import_smithy_client3 = __nccwpck_require__(3570); -var import_util_utf8 = __nccwpck_require__(1895); -var import_fast_xml_parser = __nccwpck_require__(2603); -var XmlShapeDeserializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - this.stringDeserializer = new import_protocols3.FromStringShapeDeserializer(settings); - } - static { - __name(this, "XmlShapeDeserializer"); - } - stringDeserializer; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.stringDeserializer.setSerdeContext(serdeContext); - } - /** - * @param schema - describing the data. - * @param bytes - serialized data. - * @param key - used by AwsQuery to step one additional depth into the object before reading it. + * @param schema - describing the data. + * @param bytes - serialized data. + * @param key - used by AwsQuery to step one additional depth into the object before reading it. */ read(schema, bytes, key) { const ns = import_schema5.NormalizedSchema.of(schema); @@ -44257,7 +28929,7 @@ var import_util_body_length_browser4 = __nccwpck_require__(713); // src/submodules/protocols/xml/parseXmlBody.ts var import_smithy_client5 = __nccwpck_require__(3570); -var import_fast_xml_parser2 = __nccwpck_require__(2603); +var import_fast_xml_parser2 = __nccwpck_require__(4577); var parseXmlBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { if (encoded.length) { const parser = new import_fast_xml_parser2.XMLParser({ @@ -44728,7 +29400,7 @@ var AwsRestXmlProtocol = class extends import_protocols6.HttpBindingProtocol { /***/ }), -/***/ 5972: +/***/ 4407: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -44766,7 +29438,7 @@ __export(index_exports, { module.exports = __toCommonJS(index_exports); // src/fromEnv.ts -var import_client = __nccwpck_require__(2825); +var import_client = __nccwpck_require__(6510); var import_property_provider = __nccwpck_require__(9721); var ENV_KEY = "AWS_ACCESS_KEY_ID"; var ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; @@ -44804,7 +29476,7 @@ var fromEnv = /* @__PURE__ */ __name((init) => async () => { /***/ }), -/***/ 3757: +/***/ 7519: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44858,7 +29530,7 @@ exports.checkUrl = checkUrl; /***/ }), -/***/ 6070: +/***/ 9546: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44866,13 +29538,13 @@ exports.checkUrl = checkUrl; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromHttp = void 0; const tslib_1 = __nccwpck_require__(4351); -const client_1 = __nccwpck_require__(2825); +const client_1 = __nccwpck_require__(6510); const node_http_handler_1 = __nccwpck_require__(258); const property_provider_1 = __nccwpck_require__(9721); const promises_1 = tslib_1.__importDefault(__nccwpck_require__(3292)); -const checkUrl_1 = __nccwpck_require__(3757); -const requestHelpers_1 = __nccwpck_require__(9287); -const retry_wrapper_1 = __nccwpck_require__(9921); +const checkUrl_1 = __nccwpck_require__(7519); +const requestHelpers_1 = __nccwpck_require__(2707); +const retry_wrapper_1 = __nccwpck_require__(9138); const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; const DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; const AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; @@ -44934,7 +29606,7 @@ exports.fromHttp = fromHttp; /***/ }), -/***/ 9287: +/***/ 2707: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -44995,7 +29667,7 @@ async function getCredentials(response, logger) { /***/ }), -/***/ 9921: +/***/ 9138: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -45020,20 +29692,20 @@ exports.retryWrapper = retryWrapper; /***/ }), -/***/ 7290: +/***/ 5554: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromHttp = void 0; -var fromHttp_1 = __nccwpck_require__(6070); +var fromHttp_1 = __nccwpck_require__(9546); Object.defineProperty(exports, "fromHttp", ({ enumerable: true, get: function () { return fromHttp_1.fromHttp; } })); /***/ }), -/***/ 4203: +/***/ 5736: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -45086,12 +29758,12 @@ module.exports = __toCommonJS(index_exports); var import_shared_ini_file_loader = __nccwpck_require__(3507); // src/resolveCredentialSource.ts -var import_client = __nccwpck_require__(2825); +var import_client = __nccwpck_require__(6510); var import_property_provider = __nccwpck_require__(9721); var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName, logger) => { const sourceProvidersMap = { EcsContainer: /* @__PURE__ */ __name(async (options) => { - const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7290))); + const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5554))); const { fromContainerMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); logger?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); return async () => (0, import_property_provider.chain)(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); @@ -45103,7 +29775,7 @@ var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileN }, "Ec2InstanceMetadata"), Environment: /* @__PURE__ */ __name(async (options) => { logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); - const { fromEnv } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5972))); + const { fromEnv } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(4407))); return async () => fromEnv(options)().then(setNamedProvider); }, "Environment") }; @@ -45141,7 +29813,7 @@ var resolveAssumeRoleCredentials = /* @__PURE__ */ __name(async (profileName, pr const profileData = profiles[profileName]; const { source_profile, region } = profileData; if (!options.roleAssumer) { - const { getDefaultRoleAssumer } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(2273))); + const { getDefaultRoleAssumer } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(3764))); options.roleAssumer = getDefaultRoleAssumer( { ...options.clientConfig, @@ -45206,7 +29878,7 @@ var isCredentialSourceWithoutRoleArn = /* @__PURE__ */ __name((section) => { // src/resolveProcessCredentials.ts var isProcessProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", "isProcessProfile"); -var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => __toESM(__nccwpck_require__(9969))).then( +var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => __toESM(__nccwpck_require__(8638))).then( ({ fromProcess }) => fromProcess({ ...options, profile @@ -45216,7 +29888,7 @@ var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) // src/resolveSsoCredentials.ts var resolveSsoCredentials = /* @__PURE__ */ __name(async (profile, profileData, options = {}) => { - const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(6414))); + const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5284))); return fromSSO({ profile, logger: options.logger, @@ -45250,7 +29922,7 @@ var resolveStaticCredentials = /* @__PURE__ */ __name(async (profile, options) = // src/resolveWebIdentityCredentials.ts var isWebIdentityProfile = /* @__PURE__ */ __name((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, "isWebIdentityProfile"); -var resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => __toESM(__nccwpck_require__(5646))).then( +var resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => __toESM(__nccwpck_require__(5603))).then( ({ fromTokenFile }) => fromTokenFile({ webIdentityTokenFile: profile.web_identity_token_file, roleArn: profile.role_arn, @@ -45315,7 +29987,7 @@ var fromIni = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig /***/ }), -/***/ 5531: +/***/ 3196: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -45359,7 +30031,7 @@ __export(index_exports, { module.exports = __toCommonJS(index_exports); // src/defaultProvider.ts -var import_credential_provider_env = __nccwpck_require__(5972); +var import_credential_provider_env = __nccwpck_require__(4407); var import_shared_ini_file_loader = __nccwpck_require__(3507); @@ -45370,7 +30042,7 @@ var remoteProvider = /* @__PURE__ */ __name(async (init) => { const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); - const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7290))); + const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5554))); return (0, import_property_provider.chain)(fromHttp(init), fromContainerMetadata(init)); } if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { @@ -45424,553 +30096,40 @@ var defaultProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_ { logger: init.logger } ); } - const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(6414))); - return fromSSO(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); - const { fromIni } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(4203))); - return fromIni(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); - const { fromProcess } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(9969))); - return fromProcess(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); - const { fromTokenFile } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5646))); - return fromTokenFile(init)(); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); - return (await remoteProvider(init))(); - }, - async () => { - throw new import_property_provider.CredentialsProviderError("Could not load credentials from any providers", { - tryNextLink: false, - logger: init.logger - }); - } - ), - credentialsTreatedAsExpired, - credentialsWillNeedRefresh -), "defaultProvider"); -var credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0, "credentialsWillNeedRefresh"); -var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 9969: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromProcess: () => fromProcess -}); -module.exports = __toCommonJS(index_exports); - -// src/fromProcess.ts -var import_shared_ini_file_loader = __nccwpck_require__(3507); - -// src/resolveProcessCredentials.ts -var import_property_provider = __nccwpck_require__(9721); -var import_child_process = __nccwpck_require__(2081); -var import_util = __nccwpck_require__(3837); - -// src/getValidatedProcessCredentials.ts -var import_client = __nccwpck_require__(2825); -var getValidatedProcessCredentials = /* @__PURE__ */ __name((profileName, data, profiles) => { - if (data.Version !== 1) { - throw Error(`Profile ${profileName} credential_process did not return Version 1.`); - } - if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) { - throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); - } - if (data.Expiration) { - const currentTime = /* @__PURE__ */ new Date(); - const expireTime = new Date(data.Expiration); - if (expireTime < currentTime) { - throw Error(`Profile ${profileName} credential_process returned expired credentials.`); - } - } - let accountId = data.AccountId; - if (!accountId && profiles?.[profileName]?.aws_account_id) { - accountId = profiles[profileName].aws_account_id; - } - const credentials = { - accessKeyId: data.AccessKeyId, - secretAccessKey: data.SecretAccessKey, - ...data.SessionToken && { sessionToken: data.SessionToken }, - ...data.Expiration && { expiration: new Date(data.Expiration) }, - ...data.CredentialScope && { credentialScope: data.CredentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROCESS", "w"); - return credentials; -}, "getValidatedProcessCredentials"); - -// src/resolveProcessCredentials.ts -var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger) => { - const profile = profiles[profileName]; - if (profiles[profileName]) { - const credentialProcess = profile["credential_process"]; - if (credentialProcess !== void 0) { - const execPromise = (0, import_util.promisify)(import_child_process.exec); - try { - const { stdout } = await execPromise(credentialProcess); - let data; - try { - data = JSON.parse(stdout.trim()); - } catch { - throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); - } - return getValidatedProcessCredentials(profileName, data, profiles); - } catch (error) { - throw new import_property_provider.CredentialsProviderError(error.message, { logger }); - } - } else { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger }); - } - } else { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { - logger - }); - } -}, "resolveProcessCredentials"); - -// src/fromProcess.ts -var fromProcess = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { - init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - return resolveProcessCredentials( - (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }), - profiles, - init.logger - ); -}, "fromProcess"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 6414: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/loadSso.ts -var loadSso_exports = {}; -__export(loadSso_exports, { - GetRoleCredentialsCommand: () => import_client_sso.GetRoleCredentialsCommand, - SSOClient: () => import_client_sso.SSOClient -}); -var import_client_sso; -var init_loadSso = __esm({ - "src/loadSso.ts"() { - "use strict"; - import_client_sso = __nccwpck_require__(2666); - } -}); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - fromSSO: () => fromSSO, - isSsoProfile: () => isSsoProfile, - validateSsoProfile: () => validateSsoProfile -}); -module.exports = __toCommonJS(index_exports); - -// src/fromSSO.ts - - - -// src/isSsoProfile.ts -var isSsoProfile = /* @__PURE__ */ __name((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"), "isSsoProfile"); - -// src/resolveSSOCredentials.ts -var import_client = __nccwpck_require__(2825); -var import_token_providers = __nccwpck_require__(2843); -var import_property_provider = __nccwpck_require__(9721); -var import_shared_ini_file_loader = __nccwpck_require__(3507); -var SHOULD_FAIL_CREDENTIAL_CHAIN = false; -var resolveSSOCredentials = /* @__PURE__ */ __name(async ({ - ssoStartUrl, - ssoSession, - ssoAccountId, - ssoRegion, - ssoRoleName, - ssoClient, - clientConfig, - parentClientConfig, - profile, - logger -}) => { - let token; - const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; - if (ssoSession) { - try { - const _token = await (0, import_token_providers.fromSso)({ profile })(); - token = { - accessToken: _token.token, - expiresAt: new Date(_token.expiration).toISOString() - }; - } catch (e) { - throw new import_property_provider.CredentialsProviderError(e.message, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - } else { - try { - token = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoStartUrl); - } catch (e) { - throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - } - if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { - throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - const { accessToken } = token; - const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports)); - const sso = ssoClient || new SSOClient2( - Object.assign({}, clientConfig ?? {}, { - logger: clientConfig?.logger ?? parentClientConfig?.logger, - region: clientConfig?.region ?? ssoRegion - }) - ); - let ssoResp; - try { - ssoResp = await sso.send( - new GetRoleCredentialsCommand2({ - accountId: ssoAccountId, - roleName: ssoRoleName, - accessToken - }) - ); - } catch (e) { - throw new import_property_provider.CredentialsProviderError(e, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - const { - roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} - } = ssoResp; - if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { - throw new import_property_provider.CredentialsProviderError("SSO returns an invalid temporary credential.", { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger - }); - } - const credentials = { - accessKeyId, - secretAccessKey, - sessionToken, - expiration: new Date(expiration), - ...credentialScope && { credentialScope }, - ...accountId && { accountId } - }; - if (ssoSession) { - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO", "s"); - } else { - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO_LEGACY", "u"); - } - return credentials; -}, "resolveSSOCredentials"); - -// src/validateSsoProfile.ts - -var validateSsoProfile = /* @__PURE__ */ __name((profile, logger) => { - 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 import_property_provider.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( - ", " - )} -Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, - { tryNextLink: false, logger } - ); - } - return profile; -}, "validateSsoProfile"); - -// src/fromSSO.ts -var fromSSO = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { - init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; - const { ssoClient } = init; - const profileName = (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }); - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - const profile = profiles[profileName]; - if (!profile) { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger }); - } - if (!isSsoProfile(profile)) { - throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { - logger: init.logger - }); - } - if (profile?.sso_session) { - const ssoSessions = await (0, import_shared_ini_file_loader.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 import_property_provider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { - tryNextLink: false, - logger: init.logger - }); - } - if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { - throw new import_property_provider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { - tryNextLink: false, - logger: init.logger - }); - } - 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 } = validateSsoProfile( - profile, - init.logger - ); - return resolveSSOCredentials({ - ssoStartUrl: sso_start_url, - ssoSession: sso_session, - ssoAccountId: sso_account_id, - ssoRegion: sso_region, - ssoRoleName: sso_role_name, - ssoClient, - clientConfig: init.clientConfig, - parentClientConfig: init.parentClientConfig, - profile: profileName - }); - } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { - throw new import_property_provider.CredentialsProviderError( - 'Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', - { tryNextLink: false, logger: init.logger } - ); - } else { - return resolveSSOCredentials({ - ssoStartUrl, - ssoSession, - ssoAccountId, - ssoRegion, - ssoRoleName, - ssoClient, - clientConfig: init.clientConfig, - parentClientConfig: init.parentClientConfig, - profile: profileName - }); - } -}, "fromSSO"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 5614: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromTokenFile = void 0; -const client_1 = __nccwpck_require__(2825); -const property_provider_1 = __nccwpck_require__(9721); -const fs_1 = __nccwpck_require__(7147); -const fromWebToken_1 = __nccwpck_require__(7905); -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 () => { - init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); - const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; - const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN]; - const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; - if (!webIdentityTokenFile || !roleArn) { - throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { - logger: init.logger, - }); - } - const credentials = await (0, fromWebToken_1.fromWebToken)({ - ...init, - webIdentityToken: (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), - roleArn, - roleSessionName, - })(); - if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { - (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); - } - return credentials; -}; -exports.fromTokenFile = fromTokenFile; - - -/***/ }), - -/***/ 7905: -/***/ (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 () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromWebToken = void 0; -const fromWebToken = (init) => async (awsIdentityProperties) => { - init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); - const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init; - let { roleAssumerWithWebIdentity } = init; - if (!roleAssumerWithWebIdentity) { - const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(2273))); - roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({ - ...init.clientConfig, - credentialProviderLogger: init.logger, - parentClientConfig: { - ...awsIdentityProperties?.callerClientConfig, - ...init.parentClientConfig, - }, - }, init.clientPlugins); + const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5284))); + return fromSSO(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); + const { fromIni } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5736))); + return fromIni(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); + const { fromProcess } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(8638))); + return fromProcess(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); + const { fromTokenFile } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5603))); + return fromTokenFile(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); + return (await remoteProvider(init))(); + }, + async () => { + throw new import_property_provider.CredentialsProviderError("Could not load credentials from any providers", { + tryNextLink: false, + logger: init.logger + }); } - return roleAssumerWithWebIdentity({ - RoleArn: roleArn, - RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, - WebIdentityToken: webIdentityToken, - ProviderId: providerId, - PolicyArns: policyArns, - Policy: policy, - DurationSeconds: durationSeconds, - }); -}; -exports.fromWebToken = fromWebToken; - - -/***/ }), - -/***/ 5646: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(5614), module.exports); -__reExport(index_exports, __nccwpck_require__(7905), module.exports); + ), + credentialsTreatedAsExpired, + credentialsWillNeedRefresh +), "defaultProvider"); +var credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0, "credentialsWillNeedRefresh"); +var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -45979,7 +30138,7 @@ __reExport(index_exports, __nccwpck_require__(7905), module.exports); /***/ }), -/***/ 6689: +/***/ 8638: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -46006,426 +30165,91 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - NODE_DISABLE_MULTIREGION_ACCESS_POINT_CONFIG_OPTIONS: () => NODE_DISABLE_MULTIREGION_ACCESS_POINT_CONFIG_OPTIONS, - NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME: () => NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME, - NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME: () => NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME, - NODE_USE_ARN_REGION_CONFIG_OPTIONS: () => NODE_USE_ARN_REGION_CONFIG_OPTIONS, - NODE_USE_ARN_REGION_ENV_NAME: () => NODE_USE_ARN_REGION_ENV_NAME, - NODE_USE_ARN_REGION_INI_NAME: () => NODE_USE_ARN_REGION_INI_NAME, - bucketEndpointMiddleware: () => bucketEndpointMiddleware, - bucketEndpointMiddlewareOptions: () => bucketEndpointMiddlewareOptions, - bucketHostname: () => bucketHostname, - getArnResources: () => getArnResources, - getBucketEndpointPlugin: () => getBucketEndpointPlugin, - getSuffixForArnEndpoint: () => getSuffixForArnEndpoint, - resolveBucketEndpointConfig: () => resolveBucketEndpointConfig, - validateAccountId: () => validateAccountId, - validateDNSHostLabel: () => validateDNSHostLabel, - validateNoDualstack: () => validateNoDualstack, - validateNoFIPS: () => validateNoFIPS, - validateOutpostService: () => validateOutpostService, - validatePartition: () => validatePartition, - validateRegion: () => validateRegion + fromProcess: () => fromProcess }); module.exports = __toCommonJS(index_exports); -// src/NodeDisableMultiregionAccessPointConfigOptions.ts -var import_util_config_provider = __nccwpck_require__(3375); -var NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME = "AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS"; -var NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME = "s3_disable_multiregion_access_points"; -var NODE_DISABLE_MULTIREGION_ACCESS_POINT_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => (0, import_util_config_provider.booleanSelector)(env, NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME, import_util_config_provider.SelectorType.ENV), "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => (0, import_util_config_provider.booleanSelector)(profile, NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME, import_util_config_provider.SelectorType.CONFIG), "configFileSelector"), - default: false -}; - -// src/NodeUseArnRegionConfigOptions.ts - -var NODE_USE_ARN_REGION_ENV_NAME = "AWS_S3_USE_ARN_REGION"; -var NODE_USE_ARN_REGION_INI_NAME = "s3_use_arn_region"; -var NODE_USE_ARN_REGION_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => (0, import_util_config_provider.booleanSelector)(env, NODE_USE_ARN_REGION_ENV_NAME, import_util_config_provider.SelectorType.ENV), "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => (0, import_util_config_provider.booleanSelector)(profile, NODE_USE_ARN_REGION_INI_NAME, import_util_config_provider.SelectorType.CONFIG), "configFileSelector"), - /** - * useArnRegion has specific behavior when undefined instead of false. - * We therefore use undefined as the default value instead of false. - */ - default: void 0 -}; +// src/fromProcess.ts +var import_shared_ini_file_loader = __nccwpck_require__(3507); -// src/bucketEndpointMiddleware.ts -var import_util_arn_parser = __nccwpck_require__(5487); -var import_protocol_http = __nccwpck_require__(4418); +// src/resolveProcessCredentials.ts +var import_property_provider = __nccwpck_require__(9721); +var import_child_process = __nccwpck_require__(2081); +var import_util = __nccwpck_require__(3837); -// src/bucketHostnameUtils.ts -var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; -var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; -var DOTS_PATTERN = /\.\./; -var DOT_PATTERN = /\./; -var S3_HOSTNAME_PATTERN = /^(.+\.)?s3(-fips)?(\.dualstack)?[.-]([a-z0-9-]+)\./; -var S3_US_EAST_1_ALTNAME_PATTERN = /^s3(-external-1)?\.amazonaws\.com$/; -var AWS_PARTITION_SUFFIX = "amazonaws.com"; -var isBucketNameOptions = /* @__PURE__ */ __name((options) => typeof options.bucketName === "string", "isBucketNameOptions"); -var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName"); -var getRegionalSuffix = /* @__PURE__ */ __name((hostname) => { - const parts = hostname.match(S3_HOSTNAME_PATTERN); - return [parts[4], hostname.replace(new RegExp(`^${parts[0]}`), "")]; -}, "getRegionalSuffix"); -var getSuffix = /* @__PURE__ */ __name((hostname) => S3_US_EAST_1_ALTNAME_PATTERN.test(hostname) ? ["us-east-1", AWS_PARTITION_SUFFIX] : getRegionalSuffix(hostname), "getSuffix"); -var getSuffixForArnEndpoint = /* @__PURE__ */ __name((hostname) => S3_US_EAST_1_ALTNAME_PATTERN.test(hostname) ? [hostname.replace(`.${AWS_PARTITION_SUFFIX}`, ""), AWS_PARTITION_SUFFIX] : getRegionalSuffix(hostname), "getSuffixForArnEndpoint"); -var validateArnEndpointOptions = /* @__PURE__ */ __name((options) => { - if (options.pathStyleEndpoint) { - throw new Error("Path-style S3 endpoint is not supported when bucket is an ARN"); - } - if (options.accelerateEndpoint) { - throw new Error("Accelerate endpoint is not supported when bucket is an ARN"); - } - if (!options.tlsCompatible) { - throw new Error("HTTPS is required when bucket is an ARN"); - } -}, "validateArnEndpointOptions"); -var validateService = /* @__PURE__ */ __name((service) => { - if (service !== "s3" && service !== "s3-outposts" && service !== "s3-object-lambda") { - throw new Error("Expect 's3' or 's3-outposts' or 's3-object-lambda' in ARN service component"); - } -}, "validateService"); -var validateS3Service = /* @__PURE__ */ __name((service) => { - if (service !== "s3") { - throw new Error("Expect 's3' in Accesspoint ARN service component"); - } -}, "validateS3Service"); -var validateOutpostService = /* @__PURE__ */ __name((service) => { - if (service !== "s3-outposts") { - throw new Error("Expect 's3-posts' in Outpost ARN service component"); - } -}, "validateOutpostService"); -var validatePartition = /* @__PURE__ */ __name((partition, options) => { - if (partition !== options.clientPartition) { - throw new Error(`Partition in ARN is incompatible, got "${partition}" but expected "${options.clientPartition}"`); - } -}, "validatePartition"); -var validateRegion = /* @__PURE__ */ __name((region, options) => { -}, "validateRegion"); -var validateRegionalClient = /* @__PURE__ */ __name((region) => { - if (["s3-external-1", "aws-global"].includes(region)) { - throw new Error(`Client region ${region} is not regional`); - } -}, "validateRegionalClient"); -var validateAccountId = /* @__PURE__ */ __name((accountId) => { - if (!/[0-9]{12}/.exec(accountId)) { - throw new Error("Access point ARN accountID does not match regex '[0-9]{12}'"); - } -}, "validateAccountId"); -var validateDNSHostLabel = /* @__PURE__ */ __name((label, options = { tlsCompatible: true }) => { - if (label.length >= 64 || !/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(label) || /(\d+\.){3}\d+/.test(label) || /[.-]{2}/.test(label) || options?.tlsCompatible && DOT_PATTERN.test(label)) { - throw new Error(`Invalid DNS label ${label}`); +// src/getValidatedProcessCredentials.ts +var import_client = __nccwpck_require__(6510); +var getValidatedProcessCredentials = /* @__PURE__ */ __name((profileName, data, profiles) => { + if (data.Version !== 1) { + throw Error(`Profile ${profileName} credential_process did not return Version 1.`); } -}, "validateDNSHostLabel"); -var validateCustomEndpoint = /* @__PURE__ */ __name((options) => { - if (options.isCustomEndpoint) { - if (options.dualstackEndpoint) throw new Error("Dualstack endpoint is not supported with custom endpoint"); - if (options.accelerateEndpoint) throw new Error("Accelerate endpoint is not supported with custom endpoint"); + if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) { + throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); } -}, "validateCustomEndpoint"); -var getArnResources = /* @__PURE__ */ __name((resource) => { - const delimiter = resource.includes(":") ? ":" : "/"; - const [resourceType, ...rest] = resource.split(delimiter); - if (resourceType === "accesspoint") { - if (rest.length !== 1 || rest[0] === "") { - throw new Error(`Access Point ARN should have one resource accesspoint${delimiter}{accesspointname}`); - } - return { accesspointName: rest[0] }; - } else if (resourceType === "outpost") { - if (!rest[0] || rest[1] !== "accesspoint" || !rest[2] || rest.length !== 3) { - throw new Error( - `Outpost ARN should have resource outpost${delimiter}{outpostId}${delimiter}accesspoint${delimiter}{accesspointName}` - ); + if (data.Expiration) { + const currentTime = /* @__PURE__ */ new Date(); + const expireTime = new Date(data.Expiration); + if (expireTime < currentTime) { + throw Error(`Profile ${profileName} credential_process returned expired credentials.`); } - const [outpostId, _, accesspointName] = rest; - return { outpostId, accesspointName }; - } else { - throw new Error(`ARN resource should begin with 'accesspoint${delimiter}' or 'outpost${delimiter}'`); - } -}, "getArnResources"); -var validateNoDualstack = /* @__PURE__ */ __name((dualstackEndpoint) => { -}, "validateNoDualstack"); -var validateNoFIPS = /* @__PURE__ */ __name((useFipsEndpoint) => { - if (useFipsEndpoint) throw new Error(`FIPS region is not supported with Outpost.`); -}, "validateNoFIPS"); -var validateMrapAlias = /* @__PURE__ */ __name((name) => { - try { - name.split(".").forEach((label) => { - validateDNSHostLabel(label); - }); - } catch (e) { - throw new Error(`"${name}" is not a DNS compatible name.`); - } -}, "validateMrapAlias"); - -// src/bucketHostname.ts -var bucketHostname = /* @__PURE__ */ __name((options) => { - validateCustomEndpoint(options); - return isBucketNameOptions(options) ? ( - // Construct endpoint when bucketName is a string referring to a bucket name - getEndpointFromBucketName(options) - ) : ( - // Construct endpoint when bucketName is an ARN referring to an S3 resource like Access Point - getEndpointFromArn(options) - ); -}, "bucketHostname"); -var getEndpointFromBucketName = /* @__PURE__ */ __name(({ - accelerateEndpoint = false, - clientRegion: region, - baseHostname, - bucketName, - dualstackEndpoint = false, - fipsEndpoint = false, - pathStyleEndpoint = false, - tlsCompatible = true, - isCustomEndpoint = false -}) => { - const [clientRegion, hostnameSuffix] = isCustomEndpoint ? [region, baseHostname] : getSuffix(baseHostname); - if (pathStyleEndpoint || !isDnsCompatibleBucketName(bucketName) || tlsCompatible && DOT_PATTERN.test(bucketName)) { - return { - bucketEndpoint: false, - hostname: dualstackEndpoint ? `s3.dualstack.${clientRegion}.${hostnameSuffix}` : baseHostname - }; - } - if (accelerateEndpoint) { - baseHostname = `s3-accelerate${dualstackEndpoint ? ".dualstack" : ""}.${hostnameSuffix}`; - } else if (dualstackEndpoint) { - baseHostname = `s3.dualstack.${clientRegion}.${hostnameSuffix}`; - } - return { - bucketEndpoint: true, - hostname: `${bucketName}.${baseHostname}` - }; -}, "getEndpointFromBucketName"); -var getEndpointFromArn = /* @__PURE__ */ __name((options) => { - const { isCustomEndpoint, baseHostname, clientRegion } = options; - const hostnameSuffix = isCustomEndpoint ? baseHostname : getSuffixForArnEndpoint(baseHostname)[1]; - const { - pathStyleEndpoint, - accelerateEndpoint = false, - fipsEndpoint = false, - tlsCompatible = true, - bucketName, - clientPartition = "aws" - } = options; - validateArnEndpointOptions({ pathStyleEndpoint, accelerateEndpoint, tlsCompatible }); - const { service, partition, accountId, region, resource } = bucketName; - validateService(service); - validatePartition(partition, { clientPartition }); - validateAccountId(accountId); - const { accesspointName, outpostId } = getArnResources(resource); - if (service === "s3-object-lambda") { - return getEndpointFromObjectLambdaArn({ ...options, tlsCompatible, bucketName, accesspointName, hostnameSuffix }); - } - if (region === "") { - return getEndpointFromMRAPArn({ ...options, clientRegion, mrapAlias: accesspointName, hostnameSuffix }); - } - if (outpostId) { - return getEndpointFromOutpostArn({ ...options, clientRegion, outpostId, accesspointName, hostnameSuffix }); } - return getEndpointFromAccessPointArn({ ...options, clientRegion, accesspointName, hostnameSuffix }); -}, "getEndpointFromArn"); -var getEndpointFromObjectLambdaArn = /* @__PURE__ */ __name(({ - dualstackEndpoint = false, - fipsEndpoint = false, - tlsCompatible = true, - useArnRegion, - clientRegion, - clientSigningRegion = clientRegion, - accesspointName, - bucketName, - hostnameSuffix -}) => { - const { accountId, region, service } = bucketName; - validateRegionalClient(clientRegion); - const DNSHostLabel = `${accesspointName}-${accountId}`; - validateDNSHostLabel(DNSHostLabel, { tlsCompatible }); - const endpointRegion = useArnRegion ? region : clientRegion; - const signingRegion = useArnRegion ? region : clientSigningRegion; - return { - bucketEndpoint: true, - hostname: `${DNSHostLabel}.${service}${fipsEndpoint ? "-fips" : ""}.${endpointRegion}.${hostnameSuffix}`, - signingRegion, - signingService: service - }; -}, "getEndpointFromObjectLambdaArn"); -var getEndpointFromMRAPArn = /* @__PURE__ */ __name(({ - disableMultiregionAccessPoints, - dualstackEndpoint = false, - isCustomEndpoint, - mrapAlias, - hostnameSuffix -}) => { - if (disableMultiregionAccessPoints === true) { - throw new Error("SDK is attempting to use a MRAP ARN. Please enable to feature."); + let accountId = data.AccountId; + if (!accountId && profiles?.[profileName]?.aws_account_id) { + accountId = profiles[profileName].aws_account_id; } - validateMrapAlias(mrapAlias); - return { - bucketEndpoint: true, - hostname: `${mrapAlias}${isCustomEndpoint ? "" : `.accesspoint.s3-global`}.${hostnameSuffix}`, - signingRegion: "*" - }; -}, "getEndpointFromMRAPArn"); -var getEndpointFromOutpostArn = /* @__PURE__ */ __name(({ - useArnRegion, - clientRegion, - clientSigningRegion = clientRegion, - bucketName, - outpostId, - dualstackEndpoint = false, - fipsEndpoint = false, - tlsCompatible = true, - accesspointName, - isCustomEndpoint, - hostnameSuffix -}) => { - validateRegionalClient(clientRegion); - const DNSHostLabel = `${accesspointName}-${bucketName.accountId}`; - validateDNSHostLabel(DNSHostLabel, { tlsCompatible }); - const endpointRegion = useArnRegion ? bucketName.region : clientRegion; - const signingRegion = useArnRegion ? bucketName.region : clientSigningRegion; - validateOutpostService(bucketName.service); - validateDNSHostLabel(outpostId, { tlsCompatible }); - validateNoFIPS(fipsEndpoint); - const hostnamePrefix = `${DNSHostLabel}.${outpostId}`; - return { - bucketEndpoint: true, - hostname: `${hostnamePrefix}${isCustomEndpoint ? "" : `.s3-outposts.${endpointRegion}`}.${hostnameSuffix}`, - signingRegion, - signingService: "s3-outposts" - }; -}, "getEndpointFromOutpostArn"); -var getEndpointFromAccessPointArn = /* @__PURE__ */ __name(({ - useArnRegion, - clientRegion, - clientSigningRegion = clientRegion, - bucketName, - dualstackEndpoint = false, - fipsEndpoint = false, - tlsCompatible = true, - accesspointName, - isCustomEndpoint, - hostnameSuffix -}) => { - validateRegionalClient(clientRegion); - const hostnamePrefix = `${accesspointName}-${bucketName.accountId}`; - validateDNSHostLabel(hostnamePrefix, { tlsCompatible }); - const endpointRegion = useArnRegion ? bucketName.region : clientRegion; - const signingRegion = useArnRegion ? bucketName.region : clientSigningRegion; - validateS3Service(bucketName.service); - return { - bucketEndpoint: true, - hostname: `${hostnamePrefix}${isCustomEndpoint ? "" : `.s3-accesspoint${fipsEndpoint ? "-fips" : ""}${dualstackEndpoint ? ".dualstack" : ""}.${endpointRegion}`}.${hostnameSuffix}`, - signingRegion + const credentials = { + accessKeyId: data.AccessKeyId, + secretAccessKey: data.SecretAccessKey, + ...data.SessionToken && { sessionToken: data.SessionToken }, + ...data.Expiration && { expiration: new Date(data.Expiration) }, + ...data.CredentialScope && { credentialScope: data.CredentialScope }, + ...accountId && { accountId } }; -}, "getEndpointFromAccessPointArn"); + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROCESS", "w"); + return credentials; +}, "getValidatedProcessCredentials"); -// src/bucketEndpointMiddleware.ts -var bucketEndpointMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { - const { Bucket: bucketName } = args.input; - let replaceBucketInPath = options.bucketEndpoint; - const request = args.request; - if (import_protocol_http.HttpRequest.isInstance(request)) { - if (options.bucketEndpoint) { - request.hostname = bucketName; - } else if ((0, import_util_arn_parser.validate)(bucketName)) { - const bucketArn = (0, import_util_arn_parser.parse)(bucketName); - const clientRegion = await options.region(); - const useDualstackEndpoint = await options.useDualstackEndpoint(); - const useFipsEndpoint = await options.useFipsEndpoint(); - const { partition, signingRegion = clientRegion } = await options.regionInfoProvider(clientRegion, { useDualstackEndpoint, useFipsEndpoint }) || {}; - const useArnRegion = await options.useArnRegion(); - const { - hostname, - bucketEndpoint, - signingRegion: modifiedSigningRegion, - signingService - } = bucketHostname({ - bucketName: bucketArn, - baseHostname: request.hostname, - accelerateEndpoint: options.useAccelerateEndpoint, - dualstackEndpoint: useDualstackEndpoint, - fipsEndpoint: useFipsEndpoint, - pathStyleEndpoint: options.forcePathStyle, - tlsCompatible: request.protocol === "https:", - useArnRegion, - clientPartition: partition, - clientSigningRegion: signingRegion, - clientRegion, - isCustomEndpoint: options.isCustomEndpoint, - disableMultiregionAccessPoints: await options.disableMultiregionAccessPoints() - }); - if (modifiedSigningRegion && modifiedSigningRegion !== signingRegion) { - context["signing_region"] = modifiedSigningRegion; - } - if (signingService && signingService !== "s3") { - context["signing_service"] = signingService; - } - request.hostname = hostname; - replaceBucketInPath = bucketEndpoint; - } else { - const clientRegion = await options.region(); - const dualstackEndpoint = await options.useDualstackEndpoint(); - const fipsEndpoint = await options.useFipsEndpoint(); - const { hostname, bucketEndpoint } = bucketHostname({ - bucketName, - clientRegion, - baseHostname: request.hostname, - accelerateEndpoint: options.useAccelerateEndpoint, - dualstackEndpoint, - fipsEndpoint, - pathStyleEndpoint: options.forcePathStyle, - tlsCompatible: request.protocol === "https:", - isCustomEndpoint: options.isCustomEndpoint - }); - request.hostname = hostname; - replaceBucketInPath = bucketEndpoint; - } - if (replaceBucketInPath) { - request.path = request.path.replace(/^(\/)?[^\/]+/, ""); - if (request.path === "") { - request.path = "/"; +// src/resolveProcessCredentials.ts +var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger) => { + const profile = profiles[profileName]; + if (profiles[profileName]) { + const credentialProcess = profile["credential_process"]; + if (credentialProcess !== void 0) { + const execPromise = (0, import_util.promisify)(import_child_process.exec); + try { + const { stdout } = await execPromise(credentialProcess); + let data; + try { + data = JSON.parse(stdout.trim()); + } catch { + throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); + } + return getValidatedProcessCredentials(profileName, data, profiles); + } catch (error) { + throw new import_property_provider.CredentialsProviderError(error.message, { logger }); } - } - } - return next({ ...args, request }); -}, "bucketEndpointMiddleware"); -var bucketEndpointMiddlewareOptions = { - tags: ["BUCKET_ENDPOINT"], - name: "bucketEndpointMiddleware", - relation: "before", - toMiddleware: "hostHeaderMiddleware", - override: true -}; -var getBucketEndpointPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo(bucketEndpointMiddleware(options), bucketEndpointMiddlewareOptions); - }, "applyToStack") -}), "getBucketEndpointPlugin"); + } else { + throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger }); + } + } else { + throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { + logger + }); + } +}, "resolveProcessCredentials"); -// src/configurations.ts -function resolveBucketEndpointConfig(input) { - const { - bucketEndpoint = false, - forcePathStyle = false, - useAccelerateEndpoint = false, - // useArnRegion has specific behavior when undefined instead of false. - useArnRegion, - disableMultiregionAccessPoints = false - } = input; - return Object.assign(input, { - bucketEndpoint, - forcePathStyle, - useAccelerateEndpoint, - useArnRegion: typeof useArnRegion === "function" ? useArnRegion : () => Promise.resolve(useArnRegion), - disableMultiregionAccessPoints: typeof disableMultiregionAccessPoints === "function" ? disableMultiregionAccessPoints : () => Promise.resolve(disableMultiregionAccessPoints) - }); -} -__name(resolveBucketEndpointConfig, "resolveBucketEndpointConfig"); +// src/fromProcess.ts +var fromProcess = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); + const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); + return resolveProcessCredentials( + (0, import_shared_ini_file_loader.getProfileName)({ + profile: init.profile ?? callerClientConfig?.profile + }), + profiles, + init.logger + ); +}, "fromProcess"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -46434,7 +30258,7 @@ __name(resolveBucketEndpointConfig, "resolveBucketEndpointConfig"); /***/ }), -/***/ 1990: +/***/ 5284: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -46444,6 +30268,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -46458,44 +30285,221 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +// src/loadSso.ts +var loadSso_exports = {}; +__export(loadSso_exports, { + GetRoleCredentialsCommand: () => import_client_sso.GetRoleCredentialsCommand, + SSOClient: () => import_client_sso.SSOClient +}); +var import_client_sso; +var init_loadSso = __esm({ + "src/loadSso.ts"() { + "use strict"; + import_client_sso = __nccwpck_require__(1687); + } +}); + // src/index.ts var index_exports = {}; __export(index_exports, { - addExpectContinueMiddleware: () => addExpectContinueMiddleware, - addExpectContinueMiddlewareOptions: () => addExpectContinueMiddlewareOptions, - getAddExpectContinuePlugin: () => getAddExpectContinuePlugin + fromSSO: () => fromSSO, + isSsoProfile: () => isSsoProfile, + validateSsoProfile: () => validateSsoProfile }); module.exports = __toCommonJS(index_exports); -var import_protocol_http = __nccwpck_require__(4418); -function addExpectContinueMiddleware(options) { - return (next) => async (args) => { - const { request } = args; - if (import_protocol_http.HttpRequest.isInstance(request) && request.body && options.runtime === "node") { - if (options.requestHandler?.constructor?.name !== "FetchHttpHandler") { - request.headers = { - ...request.headers, - Expect: "100-continue" - }; - } + +// src/fromSSO.ts + + + +// src/isSsoProfile.ts +var isSsoProfile = /* @__PURE__ */ __name((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"), "isSsoProfile"); + +// src/resolveSSOCredentials.ts +var import_client = __nccwpck_require__(6510); +var import_token_providers = __nccwpck_require__(7182); +var import_property_provider = __nccwpck_require__(9721); +var import_shared_ini_file_loader = __nccwpck_require__(3507); +var SHOULD_FAIL_CREDENTIAL_CHAIN = false; +var resolveSSOCredentials = /* @__PURE__ */ __name(async ({ + ssoStartUrl, + ssoSession, + ssoAccountId, + ssoRegion, + ssoRoleName, + ssoClient, + clientConfig, + parentClientConfig, + profile, + logger +}) => { + let token; + const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; + if (ssoSession) { + try { + const _token = await (0, import_token_providers.fromSso)({ profile })(); + token = { + accessToken: _token.token, + expiresAt: new Date(_token.expiration).toISOString() + }; + } catch (e) { + throw new import_property_provider.CredentialsProviderError(e.message, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger + }); } - return next({ - ...args, - request + } else { + try { + token = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoStartUrl); + } catch (e) { + throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger + }); + } + } + if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { + throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger + }); + } + const { accessToken } = token; + const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports)); + const sso = ssoClient || new SSOClient2( + Object.assign({}, clientConfig ?? {}, { + logger: clientConfig?.logger ?? parentClientConfig?.logger, + region: clientConfig?.region ?? ssoRegion + }) + ); + let ssoResp; + try { + ssoResp = await sso.send( + new GetRoleCredentialsCommand2({ + accountId: ssoAccountId, + roleName: ssoRoleName, + accessToken + }) + ); + } catch (e) { + throw new import_property_provider.CredentialsProviderError(e, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger + }); + } + const { + roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} + } = ssoResp; + if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { + throw new import_property_provider.CredentialsProviderError("SSO returns an invalid temporary credential.", { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger }); + } + const credentials = { + accessKeyId, + secretAccessKey, + sessionToken, + expiration: new Date(expiration), + ...credentialScope && { credentialScope }, + ...accountId && { accountId } }; -} -__name(addExpectContinueMiddleware, "addExpectContinueMiddleware"); -var addExpectContinueMiddlewareOptions = { - step: "build", - tags: ["SET_EXPECT_HEADER", "EXPECT_HEADER"], - name: "addExpectContinueMiddleware", - override: true -}; -var getAddExpectContinuePlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(addExpectContinueMiddleware(options), addExpectContinueMiddlewareOptions); - }, "applyToStack") -}), "getAddExpectContinuePlugin"); + if (ssoSession) { + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO", "s"); + } else { + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO_LEGACY", "u"); + } + return credentials; +}, "resolveSSOCredentials"); + +// src/validateSsoProfile.ts + +var validateSsoProfile = /* @__PURE__ */ __name((profile, logger) => { + 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 import_property_provider.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( + ", " + )} +Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, + { tryNextLink: false, logger } + ); + } + return profile; +}, "validateSsoProfile"); + +// src/fromSSO.ts +var fromSSO = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; + const { ssoClient } = init; + const profileName = (0, import_shared_ini_file_loader.getProfileName)({ + profile: init.profile ?? callerClientConfig?.profile + }); + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); + const profile = profiles[profileName]; + if (!profile) { + throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger }); + } + if (!isSsoProfile(profile)) { + throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { + logger: init.logger + }); + } + if (profile?.sso_session) { + const ssoSessions = await (0, import_shared_ini_file_loader.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 import_property_provider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { + tryNextLink: false, + logger: init.logger + }); + } + if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { + throw new import_property_provider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { + tryNextLink: false, + logger: init.logger + }); + } + 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 } = validateSsoProfile( + profile, + init.logger + ); + return resolveSSOCredentials({ + ssoStartUrl: sso_start_url, + ssoSession: sso_session, + ssoAccountId: sso_account_id, + ssoRegion: sso_region, + ssoRoleName: sso_role_name, + ssoClient, + clientConfig: init.clientConfig, + parentClientConfig: init.parentClientConfig, + profile: profileName + }); + } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { + throw new import_property_provider.CredentialsProviderError( + 'Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', + { tryNextLink: false, logger: init.logger } + ); + } else { + return resolveSSOCredentials({ + ssoStartUrl, + ssoSession, + ssoAccountId, + ssoRegion, + ssoRoleName, + ssoClient, + clientConfig: init.clientConfig, + parentClientConfig: init.parentClientConfig, + profile: profileName + }); + } +}, "fromSSO"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -46504,570 +30508,306 @@ var getAddExpectContinuePlugin = /* @__PURE__ */ __name((options) => ({ /***/ }), -/***/ 1436: +/***/ 279: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getCrc32ChecksumAlgorithmFunction = void 0; -const tslib_1 = __nccwpck_require__(4351); -const crc32_1 = __nccwpck_require__(8408); -const util_1 = __nccwpck_require__(4871); -const zlib = tslib_1.__importStar(__nccwpck_require__(9796)); -class NodeCrc32 { - checksum = 0; - update(data) { - this.checksum = zlib.crc32(data, this.checksum); - } - async digest() { - return (0, util_1.numToUint8)(this.checksum); - } - reset() { - this.checksum = 0; +exports.fromTokenFile = void 0; +const client_1 = __nccwpck_require__(6510); +const property_provider_1 = __nccwpck_require__(9721); +const fs_1 = __nccwpck_require__(7147); +const fromWebToken_1 = __nccwpck_require__(9527); +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 () => { + init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); + const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; + const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN]; + const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; + if (!webIdentityTokenFile || !roleArn) { + throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { + logger: init.logger, + }); } -} -const getCrc32ChecksumAlgorithmFunction = () => { - if (typeof zlib.crc32 === "undefined") { - return crc32_1.AwsCrc32; + const credentials = await (0, fromWebToken_1.fromWebToken)({ + ...init, + webIdentityToken: (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), + roleArn, + roleSessionName, + })(); + if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { + (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); } - return NodeCrc32; + return credentials; }; -exports.getCrc32ChecksumAlgorithmFunction = getCrc32ChecksumAlgorithmFunction; +exports.fromTokenFile = fromTokenFile; /***/ }), -/***/ 3799: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9527: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - CONFIG_REQUEST_CHECKSUM_CALCULATION: () => CONFIG_REQUEST_CHECKSUM_CALCULATION, - CONFIG_RESPONSE_CHECKSUM_VALIDATION: () => CONFIG_RESPONSE_CHECKSUM_VALIDATION, - ChecksumAlgorithm: () => ChecksumAlgorithm, - ChecksumLocation: () => ChecksumLocation, - DEFAULT_CHECKSUM_ALGORITHM: () => DEFAULT_CHECKSUM_ALGORITHM, - DEFAULT_REQUEST_CHECKSUM_CALCULATION: () => DEFAULT_REQUEST_CHECKSUM_CALCULATION, - DEFAULT_RESPONSE_CHECKSUM_VALIDATION: () => DEFAULT_RESPONSE_CHECKSUM_VALIDATION, - ENV_REQUEST_CHECKSUM_CALCULATION: () => ENV_REQUEST_CHECKSUM_CALCULATION, - ENV_RESPONSE_CHECKSUM_VALIDATION: () => ENV_RESPONSE_CHECKSUM_VALIDATION, - NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS: () => NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS, - NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS: () => NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS, - RequestChecksumCalculation: () => RequestChecksumCalculation, - ResponseChecksumValidation: () => ResponseChecksumValidation, - crc64NvmeCrtContainer: () => crc64NvmeCrtContainer, - flexibleChecksumsMiddleware: () => flexibleChecksumsMiddleware, - flexibleChecksumsMiddlewareOptions: () => flexibleChecksumsMiddlewareOptions, - getFlexibleChecksumsPlugin: () => getFlexibleChecksumsPlugin, - resolveFlexibleChecksumsConfig: () => resolveFlexibleChecksumsConfig +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; }); -module.exports = __toCommonJS(index_exports); - -// src/constants.ts -var RequestChecksumCalculation = { - /** - * When set, a checksum will be calculated for all request payloads of operations - * modeled with the {@link httpChecksum} trait where `requestChecksumRequired` is `true` - * AND/OR a `requestAlgorithmMember` is modeled. - * {@link https://smithy.io/2.0/aws/aws-core.html#aws-protocols-httpchecksum-trait httpChecksum} - */ - WHEN_SUPPORTED: "WHEN_SUPPORTED", - /** - * When set, a checksum will only be calculated for request payloads of operations - * modeled with the {@link httpChecksum} trait where `requestChecksumRequired` is `true` - * OR where a `requestAlgorithmMember` is modeled and the user sets it. - * {@link https://smithy.io/2.0/aws/aws-core.html#aws-protocols-httpchecksum-trait httpChecksum} - */ - WHEN_REQUIRED: "WHEN_REQUIRED" -}; -var DEFAULT_REQUEST_CHECKSUM_CALCULATION = RequestChecksumCalculation.WHEN_SUPPORTED; -var ResponseChecksumValidation = { - /** - * When set, checksum validation MUST be performed on all response payloads of operations - * modeled with the {@link httpChecksum} trait where `responseAlgorithms` is modeled, - * except when no modeled checksum algorithms are supported by an SDK. - * {@link https://smithy.io/2.0/aws/aws-core.html#aws-protocols-httpchecksum-trait httpChecksum} - */ - WHEN_SUPPORTED: "WHEN_SUPPORTED", - /** - * When set, checksum validation MUST NOT be performed on response payloads of operations UNLESS - * the SDK supports the modeled checksum algorithms AND the user has set the `requestValidationModeMember` to `ENABLED`. - * It is currently impossible to model an operation as requiring a response checksum, - * but this setting leaves the door open for future updates. - */ - WHEN_REQUIRED: "WHEN_REQUIRED" -}; -var DEFAULT_RESPONSE_CHECKSUM_VALIDATION = RequestChecksumCalculation.WHEN_SUPPORTED; -var ChecksumAlgorithm = /* @__PURE__ */ ((ChecksumAlgorithm3) => { - ChecksumAlgorithm3["MD5"] = "MD5"; - ChecksumAlgorithm3["CRC32"] = "CRC32"; - ChecksumAlgorithm3["CRC32C"] = "CRC32C"; - ChecksumAlgorithm3["CRC64NVME"] = "CRC64NVME"; - ChecksumAlgorithm3["SHA1"] = "SHA1"; - ChecksumAlgorithm3["SHA256"] = "SHA256"; - return ChecksumAlgorithm3; -})(ChecksumAlgorithm || {}); -var ChecksumLocation = /* @__PURE__ */ ((ChecksumLocation2) => { - ChecksumLocation2["HEADER"] = "header"; - ChecksumLocation2["TRAILER"] = "trailer"; - return ChecksumLocation2; -})(ChecksumLocation || {}); -var DEFAULT_CHECKSUM_ALGORITHM = "CRC32" /* CRC32 */; - -// src/stringUnionSelector.ts -var stringUnionSelector = /* @__PURE__ */ __name((obj, key, union, type) => { - if (!(key in obj)) return void 0; - const value = obj[key].toUpperCase(); - if (!Object.values(union).includes(value)) { - throw new TypeError(`Cannot load ${type} '${key}'. Expected one of ${Object.values(union)}, got '${obj[key]}'.`); - } - return value; -}, "stringUnionSelector"); - -// src/NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS.ts -var ENV_REQUEST_CHECKSUM_CALCULATION = "AWS_REQUEST_CHECKSUM_CALCULATION"; -var CONFIG_REQUEST_CHECKSUM_CALCULATION = "request_checksum_calculation"; -var NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => stringUnionSelector(env, ENV_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, "env" /* ENV */), "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => stringUnionSelector(profile, CONFIG_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, "shared config entry" /* CONFIG */), "configFileSelector"), - default: DEFAULT_REQUEST_CHECKSUM_CALCULATION -}; - -// src/NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS.ts -var ENV_RESPONSE_CHECKSUM_VALIDATION = "AWS_RESPONSE_CHECKSUM_VALIDATION"; -var CONFIG_RESPONSE_CHECKSUM_VALIDATION = "response_checksum_validation"; -var NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => stringUnionSelector(env, ENV_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, "env" /* ENV */), "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => stringUnionSelector(profile, CONFIG_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, "shared config entry" /* CONFIG */), "configFileSelector"), - default: DEFAULT_RESPONSE_CHECKSUM_VALIDATION -}; - -// src/crc64-nvme-crt-container.ts -var crc64NvmeCrtContainer = { - CrtCrc64Nvme: null +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromWebToken = void 0; +const fromWebToken = (init) => async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); + const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init; + let { roleAssumerWithWebIdentity } = init; + if (!roleAssumerWithWebIdentity) { + const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(3764))); + roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({ + ...init.clientConfig, + credentialProviderLogger: init.logger, + parentClientConfig: { + ...awsIdentityProperties?.callerClientConfig, + ...init.parentClientConfig, + }, + }, init.clientPlugins); + } + return roleAssumerWithWebIdentity({ + RoleArn: roleArn, + RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, + WebIdentityToken: webIdentityToken, + ProviderId: providerId, + PolicyArns: policyArns, + Policy: policy, + DurationSeconds: durationSeconds, + }); }; +exports.fromWebToken = fromWebToken; -// src/flexibleChecksumsMiddleware.ts -var import_core = __nccwpck_require__(8171); -var import_protocol_http = __nccwpck_require__(4418); -var import_util_stream = __nccwpck_require__(6607); -// src/types.ts -var CLIENT_SUPPORTED_ALGORITHMS = [ - "CRC32" /* CRC32 */, - "CRC32C" /* CRC32C */, - "CRC64NVME" /* CRC64NVME */, - "SHA1" /* SHA1 */, - "SHA256" /* SHA256 */ -]; -var PRIORITY_ORDER_ALGORITHMS = [ - "SHA256" /* SHA256 */, - "SHA1" /* SHA1 */, - "CRC32" /* CRC32 */, - "CRC32C" /* CRC32C */, - "CRC64NVME" /* CRC64NVME */ -]; +/***/ }), -// src/getChecksumAlgorithmForRequest.ts -var getChecksumAlgorithmForRequest = /* @__PURE__ */ __name((input, { requestChecksumRequired, requestAlgorithmMember, requestChecksumCalculation }) => { - if (!requestAlgorithmMember) { - return requestChecksumCalculation === RequestChecksumCalculation.WHEN_SUPPORTED || requestChecksumRequired ? DEFAULT_CHECKSUM_ALGORITHM : void 0; - } - if (!input[requestAlgorithmMember]) { - return void 0; - } - const checksumAlgorithm = input[requestAlgorithmMember]; - if (!CLIENT_SUPPORTED_ALGORITHMS.includes(checksumAlgorithm)) { - throw new Error( - `The checksum algorithm "${checksumAlgorithm}" is not supported by the client. Select one of ${CLIENT_SUPPORTED_ALGORITHMS}.` - ); - } - return checksumAlgorithm; -}, "getChecksumAlgorithmForRequest"); +/***/ 5603: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// src/getChecksumLocationName.ts -var getChecksumLocationName = /* @__PURE__ */ __name((algorithm) => algorithm === "MD5" /* MD5 */ ? "content-md5" : `x-amz-checksum-${algorithm.toLowerCase()}`, "getChecksumLocationName"); +"use strict"; -// src/hasHeader.ts -var hasHeader = /* @__PURE__ */ __name((header, headers) => { - const soughtHeader = header.toLowerCase(); - for (const headerName of Object.keys(headers)) { - if (soughtHeader === headerName.toLowerCase()) { - return true; - } +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return false; -}, "hasHeader"); + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/hasHeaderWithPrefix.ts -var hasHeaderWithPrefix = /* @__PURE__ */ __name((headerPrefix, headers) => { - const soughtHeaderPrefix = headerPrefix.toLowerCase(); - for (const headerName of Object.keys(headers)) { - if (headerName.toLowerCase().startsWith(soughtHeaderPrefix)) { - return true; - } - } - return false; -}, "hasHeaderWithPrefix"); +// src/index.ts +var index_exports = {}; +module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(279), module.exports); +__reExport(index_exports, __nccwpck_require__(9527), module.exports); +// Annotate the CommonJS export names for ESM import in node: -// src/isStreaming.ts -var import_is_array_buffer = __nccwpck_require__(780); -var isStreaming = /* @__PURE__ */ __name((body) => body !== void 0 && typeof body !== "string" && !ArrayBuffer.isView(body) && !(0, import_is_array_buffer.isArrayBuffer)(body), "isStreaming"); +0 && (0); -// src/selectChecksumAlgorithmFunction.ts -var import_crc32c = __nccwpck_require__(7035); -var import_getCrc32ChecksumAlgorithmFunction = __nccwpck_require__(1436); -var selectChecksumAlgorithmFunction = /* @__PURE__ */ __name((checksumAlgorithm, config) => { - switch (checksumAlgorithm) { - case "MD5" /* MD5 */: - return config.md5; - case "CRC32" /* CRC32 */: - return (0, import_getCrc32ChecksumAlgorithmFunction.getCrc32ChecksumAlgorithmFunction)(); - case "CRC32C" /* CRC32C */: - return import_crc32c.AwsCrc32c; - case "CRC64NVME" /* CRC64NVME */: - if (typeof crc64NvmeCrtContainer.CrtCrc64Nvme !== "function") { - throw new Error( - `Please check whether you have installed the "@aws-sdk/crc64-nvme-crt" package explicitly. -You must also register the package by calling [require("@aws-sdk/crc64-nvme-crt");] or an ESM equivalent such as [import "@aws-sdk/crc64-nvme-crt";]. -For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt` - ); - } - return crc64NvmeCrtContainer.CrtCrc64Nvme; - case "SHA1" /* SHA1 */: - return config.sha1; - case "SHA256" /* SHA256 */: - return config.sha256; - default: - throw new Error(`Unsupported checksum algorithm: ${checksumAlgorithm}`); - } -}, "selectChecksumAlgorithmFunction"); -// src/stringHasher.ts -var import_util_utf8 = __nccwpck_require__(1895); -var stringHasher = /* @__PURE__ */ __name((checksumAlgorithmFn, body) => { - const hash = new checksumAlgorithmFn(); - hash.update((0, import_util_utf8.toUint8Array)(body || "")); - return hash.digest(); -}, "stringHasher"); -// src/flexibleChecksumsMiddleware.ts -var flexibleChecksumsMiddlewareOptions = { - name: "flexibleChecksumsMiddleware", - step: "build", - tags: ["BODY_CHECKSUM"], - override: true -}; -var flexibleChecksumsMiddleware = /* @__PURE__ */ __name((config, middlewareConfig) => (next, context) => async (args) => { - if (!import_protocol_http.HttpRequest.isInstance(args.request)) { - return next(args); - } - if (hasHeaderWithPrefix("x-amz-checksum-", args.request.headers)) { - return next(args); - } - const { request, input } = args; - const { body: requestBody, headers } = request; - const { base64Encoder, streamHasher } = config; - const { requestChecksumRequired, requestAlgorithmMember } = middlewareConfig; - const requestChecksumCalculation = await config.requestChecksumCalculation(); - const requestAlgorithmMemberName = requestAlgorithmMember?.name; - const requestAlgorithmMemberHttpHeader = requestAlgorithmMember?.httpHeader; - if (requestAlgorithmMemberName && !input[requestAlgorithmMemberName]) { - if (requestChecksumCalculation === RequestChecksumCalculation.WHEN_SUPPORTED || requestChecksumRequired) { - input[requestAlgorithmMemberName] = DEFAULT_CHECKSUM_ALGORITHM; - if (requestAlgorithmMemberHttpHeader) { - headers[requestAlgorithmMemberHttpHeader] = DEFAULT_CHECKSUM_ALGORITHM; - } - } - } - const checksumAlgorithm = getChecksumAlgorithmForRequest(input, { - requestChecksumRequired, - requestAlgorithmMember: requestAlgorithmMember?.name, - requestChecksumCalculation - }); - let updatedBody = requestBody; - let updatedHeaders = headers; - if (checksumAlgorithm) { - switch (checksumAlgorithm) { - case "CRC32" /* CRC32 */: - (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32", "U"); - break; - case "CRC32C" /* CRC32C */: - (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32C", "V"); - break; - case "CRC64NVME" /* CRC64NVME */: - (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_CRC64", "W"); - break; - case "SHA1" /* SHA1 */: - (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_SHA1", "X"); - break; - case "SHA256" /* SHA256 */: - (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_SHA256", "Y"); - break; - } - const checksumLocationName = getChecksumLocationName(checksumAlgorithm); - const checksumAlgorithmFn = selectChecksumAlgorithmFunction(checksumAlgorithm, config); - if (isStreaming(requestBody)) { - const { getAwsChunkedEncodingStream, bodyLengthChecker } = config; - updatedBody = getAwsChunkedEncodingStream( - typeof config.requestStreamBufferSize === "number" && config.requestStreamBufferSize >= 8 * 1024 ? (0, import_util_stream.createBufferedReadable)(requestBody, config.requestStreamBufferSize, context.logger) : requestBody, - { - base64Encoder, - bodyLengthChecker, - checksumLocationName, - checksumAlgorithmFn, - streamHasher - } - ); - updatedHeaders = { - ...headers, - "content-encoding": headers["content-encoding"] ? `${headers["content-encoding"]},aws-chunked` : "aws-chunked", - "transfer-encoding": "chunked", - "x-amz-decoded-content-length": headers["content-length"], - "x-amz-content-sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER", - "x-amz-trailer": checksumLocationName - }; - delete updatedHeaders["content-length"]; - } else if (!hasHeader(checksumLocationName, headers)) { - const rawChecksum = await stringHasher(checksumAlgorithmFn, requestBody); - updatedHeaders = { - ...headers, - [checksumLocationName]: base64Encoder(rawChecksum) - }; - } - } - const result = await next({ - ...args, - request: { - ...request, - headers: updatedHeaders, - body: updatedBody - } - }); - return result; -}, "flexibleChecksumsMiddleware"); +/***/ }), -// src/flexibleChecksumsInputMiddleware.ts +/***/ 9514: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var flexibleChecksumsInputMiddlewareOptions = { - name: "flexibleChecksumsInputMiddleware", - toMiddleware: "serializerMiddleware", - relation: "before", - tags: ["BODY_CHECKSUM"], - override: true +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var flexibleChecksumsInputMiddleware = /* @__PURE__ */ __name((config, middlewareConfig) => (next, context) => async (args) => { - const input = args.input; - const { requestValidationModeMember } = middlewareConfig; - const requestChecksumCalculation = await config.requestChecksumCalculation(); - const responseChecksumValidation = await config.responseChecksumValidation(); - switch (requestChecksumCalculation) { - case RequestChecksumCalculation.WHEN_REQUIRED: - (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED", "a"); - break; - case RequestChecksumCalculation.WHEN_SUPPORTED: - (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED", "Z"); - break; - } - switch (responseChecksumValidation) { - case ResponseChecksumValidation.WHEN_REQUIRED: - (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED", "c"); - break; - case ResponseChecksumValidation.WHEN_SUPPORTED: - (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED", "b"); - break; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - if (requestValidationModeMember && !input[requestValidationModeMember]) { - if (responseChecksumValidation === ResponseChecksumValidation.WHEN_SUPPORTED) { - input[requestValidationModeMember] = "ENABLED"; - } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + getHostHeaderPlugin: () => getHostHeaderPlugin, + hostHeaderMiddleware: () => hostHeaderMiddleware, + hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions, + resolveHostHeaderConfig: () => resolveHostHeaderConfig +}); +module.exports = __toCommonJS(index_exports); +var import_protocol_http = __nccwpck_require__(4418); +function resolveHostHeaderConfig(input) { + return input; +} +__name(resolveHostHeaderConfig, "resolveHostHeaderConfig"); +var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { + if (!import_protocol_http.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); -}, "flexibleChecksumsInputMiddleware"); - -// src/flexibleChecksumsResponseMiddleware.ts - +}, "hostHeaderMiddleware"); +var hostHeaderMiddlewareOptions = { + name: "hostHeaderMiddleware", + step: "build", + priority: "low", + tags: ["HOST"], + override: true +}; +var getHostHeaderPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); + }, "applyToStack") +}), "getHostHeaderPlugin"); +// Annotate the CommonJS export names for ESM import in node: -// src/getChecksumAlgorithmListForResponse.ts -var getChecksumAlgorithmListForResponse = /* @__PURE__ */ __name((responseAlgorithms = []) => { - const validChecksumAlgorithms = []; - for (const algorithm of PRIORITY_ORDER_ALGORITHMS) { - if (!responseAlgorithms.includes(algorithm) || !CLIENT_SUPPORTED_ALGORITHMS.includes(algorithm)) { - continue; - } - validChecksumAlgorithms.push(algorithm); - } - return validChecksumAlgorithms; -}, "getChecksumAlgorithmListForResponse"); +0 && (0); -// src/isChecksumWithPartNumber.ts -var isChecksumWithPartNumber = /* @__PURE__ */ __name((checksum) => { - const lastHyphenIndex = checksum.lastIndexOf("-"); - if (lastHyphenIndex !== -1) { - const numberPart = checksum.slice(lastHyphenIndex + 1); - if (!numberPart.startsWith("0")) { - const number = parseInt(numberPart, 10); - if (!isNaN(number) && number >= 1 && number <= 1e4) { - return true; - } - } - } - return false; -}, "isChecksumWithPartNumber"); -// src/validateChecksumFromResponse.ts +/***/ }), -// src/getChecksum.ts -var getChecksum = /* @__PURE__ */ __name(async (body, { checksumAlgorithmFn, base64Encoder }) => base64Encoder(await stringHasher(checksumAlgorithmFn, body)), "getChecksum"); +/***/ 5675: +/***/ ((module) => { -// src/validateChecksumFromResponse.ts -var validateChecksumFromResponse = /* @__PURE__ */ __name(async (response, { config, responseAlgorithms, logger }) => { - const checksumAlgorithms = getChecksumAlgorithmListForResponse(responseAlgorithms); - const { body: responseBody, headers: responseHeaders } = response; - for (const algorithm of checksumAlgorithms) { - const responseHeader = getChecksumLocationName(algorithm); - const checksumFromResponse = responseHeaders[responseHeader]; - if (checksumFromResponse) { - let checksumAlgorithmFn; - try { - checksumAlgorithmFn = selectChecksumAlgorithmFunction(algorithm, config); - } catch (error) { - if (algorithm === "CRC64NVME" /* CRC64NVME */) { - logger?.warn(`Skipping ${"CRC64NVME" /* CRC64NVME */} checksum validation: ${error.message}`); - continue; - } - throw error; - } - const { base64Encoder } = config; - if (isStreaming(responseBody)) { - response.body = (0, import_util_stream.createChecksumStream)({ - expectedChecksum: checksumFromResponse, - checksumSourceLocation: responseHeader, - checksum: new checksumAlgorithmFn(), - source: responseBody, - base64Encoder - }); - return; - } - const checksum = await getChecksum(responseBody, { checksumAlgorithmFn, base64Encoder }); - if (checksum === checksumFromResponse) { - break; - } - throw new Error( - `Checksum mismatch: expected "${checksum}" but received "${checksumFromResponse}" in response header "${responseHeader}".` - ); - } - } -}, "validateChecksumFromResponse"); +"use strict"; -// src/flexibleChecksumsResponseMiddleware.ts -var flexibleChecksumsResponseMiddlewareOptions = { - name: "flexibleChecksumsResponseMiddleware", - toMiddleware: "deserializerMiddleware", - relation: "after", - tags: ["BODY_CHECKSUM"], - override: true +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var flexibleChecksumsResponseMiddleware = /* @__PURE__ */ __name((config, middlewareConfig) => (next, context) => async (args) => { - if (!import_protocol_http.HttpRequest.isInstance(args.request)) { - return next(args); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - const input = args.input; - const result = await next(args); - const response = result.response; - const { requestValidationModeMember, responseAlgorithms } = middlewareConfig; - if (requestValidationModeMember && input[requestValidationModeMember] === "ENABLED") { - const { clientName, commandName } = context; - const isS3WholeObjectMultipartGetResponseChecksum = clientName === "S3Client" && commandName === "GetObjectCommand" && getChecksumAlgorithmListForResponse(responseAlgorithms).every((algorithm) => { - const responseHeader = getChecksumLocationName(algorithm); - const checksumFromResponse = response.headers[responseHeader]; - return !checksumFromResponse || isChecksumWithPartNumber(checksumFromResponse); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + getLoggerPlugin: () => getLoggerPlugin, + loggerMiddleware: () => loggerMiddleware, + loggerMiddlewareOptions: () => loggerMiddlewareOptions +}); +module.exports = __toCommonJS(index_exports); + +// src/loggerMiddleware.ts +var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => { + try { + const response = await next(args); + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; + const { $metadata, ...outputWithoutMetadata } = response.output; + logger?.info?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + output: outputFilterSensitiveLog(outputWithoutMetadata), + metadata: $metadata }); - if (isS3WholeObjectMultipartGetResponseChecksum) { - return result; - } - await validateChecksumFromResponse(response, { - config, - responseAlgorithms, - logger: context.logger + return response; + } catch (error) { + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + logger?.error?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + error, + metadata: error.$metadata }); + throw error; } - return result; -}, "flexibleChecksumsResponseMiddleware"); - -// src/getFlexibleChecksumsPlugin.ts -var getFlexibleChecksumsPlugin = /* @__PURE__ */ __name((config, middlewareConfig) => ({ +}, "loggerMiddleware"); +var loggerMiddlewareOptions = { + name: "loggerMiddleware", + tags: ["LOGGER"], + step: "initialize", + override: true +}; +var getLoggerPlugin = /* @__PURE__ */ __name((options) => ({ applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(flexibleChecksumsMiddleware(config, middlewareConfig), flexibleChecksumsMiddlewareOptions); - clientStack.addRelativeTo( - flexibleChecksumsInputMiddleware(config, middlewareConfig), - flexibleChecksumsInputMiddlewareOptions - ); - clientStack.addRelativeTo( - flexibleChecksumsResponseMiddleware(config, middlewareConfig), - flexibleChecksumsResponseMiddlewareOptions - ); + clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); }, "applyToStack") -}), "getFlexibleChecksumsPlugin"); - -// src/resolveFlexibleChecksumsConfig.ts -var import_util_middleware = __nccwpck_require__(2390); -var resolveFlexibleChecksumsConfig = /* @__PURE__ */ __name((input) => { - const { requestChecksumCalculation, responseChecksumValidation, requestStreamBufferSize } = input; - return Object.assign(input, { - requestChecksumCalculation: (0, import_util_middleware.normalizeProvider)(requestChecksumCalculation ?? DEFAULT_REQUEST_CHECKSUM_CALCULATION), - responseChecksumValidation: (0, import_util_middleware.normalizeProvider)(responseChecksumValidation ?? DEFAULT_RESPONSE_CHECKSUM_VALIDATION), - requestStreamBufferSize: Number(requestStreamBufferSize ?? 0) - }); -}, "resolveFlexibleChecksumsConfig"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 8171: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +}), "getLoggerPlugin"); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -tslib_1.__exportStar(__nccwpck_require__(8574), exports); -tslib_1.__exportStar(__nccwpck_require__(1523), exports); -tslib_1.__exportStar(__nccwpck_require__(5986), exports); /***/ }), -/***/ 8574: -/***/ ((module) => { +/***/ 7977: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -47090,75 +30830,59 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/client/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, - setCredentialFeature: () => setCredentialFeature, - setFeature: () => setFeature, - setTokenFeature: () => setTokenFeature, - state: () => state + addRecursionDetectionMiddlewareOptions: () => addRecursionDetectionMiddlewareOptions, + getRecursionDetectionPlugin: () => getRecursionDetectionPlugin, + recursionDetectionMiddleware: () => recursionDetectionMiddleware }); module.exports = __toCommonJS(index_exports); - -// src/submodules/client/emitWarningIfUnsupportedVersion.ts -var state = { - warningEmitted: false -}; -var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { - if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { - state.warningEmitted = true; - process.emitWarning( - `NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will -no longer support Node.js 16.x on January 6, 2025. - -To continue receiving updates to AWS services, bug fixes, and security -updates please upgrade to a supported Node.js LTS version. - -More information can be found at: https://a.co/74kJMmI` - ); - } -}, "emitWarningIfUnsupportedVersion"); - -// src/submodules/client/setCredentialFeature.ts -function setCredentialFeature(credentials, feature, value) { - if (!credentials.$source) { - credentials.$source = {}; +var import_protocol_http = __nccwpck_require__(4418); +var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; +var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; +var ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; +var recursionDetectionMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { + const { request } = args; + if (!import_protocol_http.HttpRequest.isInstance(request) || options.runtime !== "node") { + return next(args); } - credentials.$source[feature] = value; - return credentials; -} -__name(setCredentialFeature, "setCredentialFeature"); - -// src/submodules/client/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__aws_sdk_context) { - context.__aws_sdk_context = { - features: {} - }; - } else if (!context.__aws_sdk_context.features) { - context.__aws_sdk_context.features = {}; + const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME; + if (request.headers.hasOwnProperty(traceIdHeader)) { + return next(args); } - context.__aws_sdk_context.features[feature] = value; -} -__name(setFeature, "setFeature"); - -// src/submodules/client/setTokenFeature.ts -function setTokenFeature(token, feature, value) { - if (!token.$source) { - token.$source = {}; + const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; + const traceId = process.env[ENV_TRACE_ID]; + const nonEmptyString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0, "nonEmptyString"); + if (nonEmptyString(functionName) && nonEmptyString(traceId)) { + request.headers[TRACE_ID_HEADER_NAME] = traceId; } - token.$source[feature] = value; - return token; -} -__name(setTokenFeature, "setTokenFeature"); + return next({ + ...args, + request + }); +}, "recursionDetectionMiddleware"); +var addRecursionDetectionMiddlewareOptions = { + step: "build", + tags: ["RECURSION_DETECTION"], + name: "recursionDetectionMiddleware", + override: true, + priority: "low" +}; +var getRecursionDetectionPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions); + }, "applyToStack") +}), "getRecursionDetectionPlugin"); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 1523: +/***/ 6634: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -47182,371 +30906,317 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/httpAuthSchemes/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - AWSSDKSigV4Signer: () => AWSSDKSigV4Signer, - AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner, - AwsSdkSigV4Signer: () => AwsSdkSigV4Signer, - NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, - NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS, - getBearerTokenEnvKey: () => getBearerTokenEnvKey, - resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config, - resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig, - resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config, - validateSigningProperties: () => validateSigningProperties + DEFAULT_UA_APP_ID: () => DEFAULT_UA_APP_ID, + getUserAgentMiddlewareOptions: () => getUserAgentMiddlewareOptions, + getUserAgentPlugin: () => getUserAgentPlugin, + resolveUserAgentConfig: () => resolveUserAgentConfig, + userAgentMiddleware: () => userAgentMiddleware }); module.exports = __toCommonJS(index_exports); -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts -var import_protocol_http2 = __nccwpck_require__(4418); +// src/configurations.ts +var import_core = __nccwpck_require__(5829); +var DEFAULT_UA_APP_ID = void 0; +function isValidUserAgentAppId(appId) { + if (appId === void 0) { + return true; + } + return typeof appId === "string" && appId.length <= 50; +} +__name(isValidUserAgentAppId, "isValidUserAgentAppId"); +function resolveUserAgentConfig(input) { + const normalizedAppIdProvider = (0, import_core.normalizeProvider)(input.userAgentAppId ?? DEFAULT_UA_APP_ID); + const { customUserAgent } = input; + return Object.assign(input, { + customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, + userAgentAppId: /* @__PURE__ */ __name(async () => { + const appId = await normalizedAppIdProvider(); + if (!isValidUserAgentAppId(appId)) { + const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; + if (typeof appId !== "string") { + logger?.warn("userAgentAppId must be a string or undefined."); + } else if (appId.length > 50) { + logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); + } + } + return appId; + }, "userAgentAppId") + }); +} +__name(resolveUserAgentConfig, "resolveUserAgentConfig"); -// src/submodules/httpAuthSchemes/utils/getDateHeader.ts +// src/user-agent-middleware.ts +var import_util_endpoints = __nccwpck_require__(4241); var import_protocol_http = __nccwpck_require__(4418); -var getDateHeader = /* @__PURE__ */ __name((response) => import_protocol_http.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0, "getDateHeader"); - -// src/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.ts -var getSkewCorrectedDate = /* @__PURE__ */ __name((systemClockOffset) => new Date(Date.now() + systemClockOffset), "getSkewCorrectedDate"); - -// src/submodules/httpAuthSchemes/utils/isClockSkewed.ts -var isClockSkewed = /* @__PURE__ */ __name((clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5, "isClockSkewed"); - -// src/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.ts -var getUpdatedSystemClockOffset = /* @__PURE__ */ __name((clockTime, currentSystemClockOffset) => { - const clockTimeInMs = Date.parse(clockTime); - if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { - return clockTimeInMs - Date.now(); - } - return currentSystemClockOffset; -}, "getUpdatedSystemClockOffset"); -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.ts -var throwSigningPropertyError = /* @__PURE__ */ __name((name, property) => { - if (!property) { - throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); - } - return property; -}, "throwSigningPropertyError"); -var validateSigningProperties = /* @__PURE__ */ __name(async (signingProperties) => { - const context = throwSigningPropertyError( - "context", - signingProperties.context - ); - const config = throwSigningPropertyError("config", signingProperties.config); - const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; - const signerFunction = throwSigningPropertyError( - "signer", - config.signer - ); - const signer = await signerFunction(authScheme); - const signingRegion = signingProperties?.signingRegion; - const signingRegionSet = signingProperties?.signingRegionSet; - const signingName = signingProperties?.signingName; - return { - config, - signer, - signingRegion, - signingRegionSet, - signingName - }; -}, "validateSigningProperties"); -var AwsSdkSigV4Signer = class { - static { - __name(this, "AwsSdkSigV4Signer"); +// src/check-features.ts +var import_core2 = __nccwpck_require__(2143); +var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; +async function checkFeatures(context, config, args) { + const request = args.request; + if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { + (0, import_core2.setFeature)(context, "PROTOCOL_RPC_V2_CBOR", "M"); } - async sign(httpRequest, identity, signingProperties) { - if (!import_protocol_http2.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const validatedProps = await validateSigningProperties(signingProperties); - const { config, signer } = validatedProps; - let { signingRegion, signingName } = validatedProps; - const handlerExecutionContext = signingProperties.context; - if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { - const [first, second] = handlerExecutionContext.authSchemes; - if (first?.name === "sigv4a" && second?.name === "sigv4") { - signingRegion = second?.signingRegion ?? signingRegion; - signingName = second?.signingName ?? signingName; + if (typeof config.retryStrategy === "function") { + const retryStrategy = await config.retryStrategy(); + if (typeof retryStrategy.acquireInitialRetryToken === "function") { + if (retryStrategy.constructor?.name?.includes("Adaptive")) { + (0, import_core2.setFeature)(context, "RETRY_MODE_ADAPTIVE", "F"); + } else { + (0, import_core2.setFeature)(context, "RETRY_MODE_STANDARD", "E"); } + } else { + (0, import_core2.setFeature)(context, "RETRY_MODE_LEGACY", "D"); } - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion, - signingService: signingName - }); - return signedRequest; - } - errorHandler(signingProperties) { - return (error) => { - const serverTime = error.ServerTime ?? getDateHeader(error.$response); - if (serverTime) { - const config = throwSigningPropertyError("config", signingProperties.config); - const initialSystemClockOffset = config.systemClockOffset; - config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); - const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; - if (clockSkewCorrected && error.$metadata) { - error.$metadata.clockSkewCorrected = true; - } - } - throw error; - }; } - successHandler(httpResponse, signingProperties) { - const dateHeader = getDateHeader(httpResponse); - if (dateHeader) { - const config = throwSigningPropertyError("config", signingProperties.config); - config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); + if (typeof config.accountIdEndpointMode === "function") { + const endpointV2 = context.endpointV2; + if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { + (0, import_core2.setFeature)(context, "ACCOUNT_ID_ENDPOINT", "O"); } - } -}; -var AWSSDKSigV4Signer = AwsSdkSigV4Signer; - -// src/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.ts -var import_protocol_http3 = __nccwpck_require__(4418); -var AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer { - static { - __name(this, "AwsSdkSigV4ASigner"); - } - async sign(httpRequest, identity, signingProperties) { - if (!import_protocol_http3.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + switch (await config.accountIdEndpointMode?.()) { + case "disabled": + (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); + break; + case "preferred": + (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); + break; + case "required": + (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); + break; } - const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties( - signingProperties - ); - const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); - const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(","); - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion: multiRegionOverride, - signingService: signingName - }); - return signedRequest; } -}; - -// src/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.ts -var getArrayForCommaSeparatedString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [], "getArrayForCommaSeparatedString"); - -// src/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.ts -var getBearerTokenEnvKey = /* @__PURE__ */ __name((signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`, "getBearerTokenEnvKey"); - -// src/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.ts -var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; -var NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; -var NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { - /** - * Retrieves auth scheme preference from environment variables - * @param env - Node process environment object - * @returns Array of auth scheme strings if preference is set, undefined otherwise - */ - environmentVariableSelector: /* @__PURE__ */ __name((env, options) => { - if (options?.signingName) { - const bearerTokenKey = getBearerTokenEnvKey(options.signingName); - if (bearerTokenKey in env) return ["httpBearerAuth"]; - } - if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) return void 0; - return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); - }, "environmentVariableSelector"), - /** - * Retrieves auth scheme preference from config file - * @param profile - Config profile object - * @returns Array of auth scheme strings if preference is set, undefined otherwise - */ - configFileSelector: /* @__PURE__ */ __name((profile) => { - if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) return void 0; - return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); - }, "configFileSelector"), - /** - * Default auth scheme preference if not specified in environment or config - */ - default: [] -}; - -// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.ts -var import_core = __nccwpck_require__(5829); -var import_property_provider = __nccwpck_require__(9721); -var resolveAwsSdkSigV4AConfig = /* @__PURE__ */ __name((config) => { - config.sigv4aSigningRegionSet = (0, import_core.normalizeProvider)(config.sigv4aSigningRegionSet); - return config; -}, "resolveAwsSdkSigV4AConfig"); -var NODE_SIGV4A_CONFIG_OPTIONS = { - environmentVariableSelector(env) { - if (env.AWS_SIGV4A_SIGNING_REGION_SET) { - return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); + const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; + if (identity?.$source) { + const credentials = identity; + if (credentials.accountId) { + (0, import_core2.setFeature)(context, "RESOLVED_ACCOUNT_ID", "T"); } - throw new import_property_provider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { - tryNextLink: true - }); - }, - configFileSelector(profile) { - if (profile.sigv4a_signing_region_set) { - return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); + for (const [key, value] of Object.entries(credentials.$source ?? {})) { + (0, import_core2.setFeature)(context, key, value); } - throw new import_property_provider.ProviderError("sigv4a_signing_region_set not set in profile.", { - tryNextLink: true - }); - }, - default: void 0 -}; + } +} +__name(checkFeatures, "checkFeatures"); -// src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.ts -var import_client = __nccwpck_require__(8574); -var import_core2 = __nccwpck_require__(5829); -var import_signature_v4 = __nccwpck_require__(1528); -var resolveAwsSdkSigV4Config = /* @__PURE__ */ __name((config) => { - let inputCredentials = config.credentials; - let isUserSupplied = !!config.credentials; - let resolvedCredentials = void 0; - Object.defineProperty(config, "credentials", { - set(credentials) { - if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { - isUserSupplied = true; - } - inputCredentials = credentials; - const memoizedProvider = normalizeCredentialProvider(config, { - credentials: inputCredentials, - credentialDefaultProvider: config.credentialDefaultProvider - }); - const boundProvider = bindCallerConfig(config, memoizedProvider); - if (isUserSupplied && !boundProvider.attributed) { - resolvedCredentials = /* @__PURE__ */ __name(async (options) => boundProvider(options).then( - (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_CODE", "e") - ), "resolvedCredentials"); - resolvedCredentials.memoized = boundProvider.memoized; - resolvedCredentials.configBound = boundProvider.configBound; - resolvedCredentials.attributed = true; +// src/constants.ts +var USER_AGENT = "user-agent"; +var X_AMZ_USER_AGENT = "x-amz-user-agent"; +var SPACE = " "; +var UA_NAME_SEPARATOR = "/"; +var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g; +var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g; +var UA_ESCAPE_CHAR = "-"; + +// src/encode-features.ts +var BYTE_LIMIT = 1024; +function encodeFeatures(features) { + let buffer = ""; + for (const key in features) { + const val = features[key]; + if (buffer.length + val.length + 1 <= BYTE_LIMIT) { + if (buffer.length) { + buffer += "," + val; } else { - resolvedCredentials = boundProvider; + buffer += val; } - }, - get() { - return resolvedCredentials; - }, - enumerable: true, - configurable: true - }); - config.credentials = inputCredentials; - const { - // Default for signingEscapePath - signingEscapePath = true, - // Default for systemClockOffset - systemClockOffset = config.systemClockOffset || 0, - // No default for sha256 since it is platform dependent - sha256 - } = config; - let signer; - if (config.signer) { - signer = (0, import_core2.normalizeProvider)(config.signer); - } else if (config.regionInfoProvider) { - signer = /* @__PURE__ */ __name(() => (0, import_core2.normalizeProvider)(config.region)().then( - async (region) => [ - await config.regionInfoProvider(region, { - useFipsEndpoint: await config.useFipsEndpoint(), - useDualstackEndpoint: await config.useDualstackEndpoint() - }) || {}, - region - ] - ).then(([regionInfo, region]) => { - const { signingRegion, signingService } = regionInfo; - config.signingRegion = config.signingRegion || signingRegion || region; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }), "signer"); - } else { - signer = /* @__PURE__ */ __name(async (authScheme) => { - authScheme = Object.assign( - {}, - { - name: "sigv4", - signingName: config.signingName || config.defaultSigningName, - signingRegion: await (0, import_core2.normalizeProvider)(config.region)(), - properties: {} - }, - authScheme - ); - const signingRegion = authScheme.signingRegion; - const signingService = authScheme.signingName; - config.signingRegion = config.signingRegion || signingRegion; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }, "signer"); + continue; + } + break; + } + return buffer; +} +__name(encodeFeatures, "encodeFeatures"); + +// src/user-agent-middleware.ts +var userAgentMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { + const { request } = args; + if (!import_protocol_http.HttpRequest.isInstance(request)) { + return next(args); + } + const { headers } = request; + const userAgent = context?.userAgent?.map(escapeUserAgent) || []; + const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); + await checkFeatures(context, options, args); + const awsContext = context; + defaultUserAgent.push( + `m/${encodeFeatures( + Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features) + )}` + ); + const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; + const appId = await options.userAgentAppId(); + if (appId) { + defaultUserAgent.push(escapeUserAgent([`app/${appId}`])); } - const resolvedConfig = Object.assign(config, { - systemClockOffset, - signingEscapePath, - signer - }); - return resolvedConfig; -}, "resolveAwsSdkSigV4Config"); -var resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; -function normalizeCredentialProvider(config, { - credentials, - credentialDefaultProvider -}) { - let credentialsProvider; - if (credentials) { - if (!credentials?.memoized) { - credentialsProvider = (0, import_core2.memoizeIdentityProvider)(credentials, import_core2.isIdentityExpired, import_core2.doesIdentityRequireRefresh); - } else { - credentialsProvider = credentials; + const prefix = (0, import_util_endpoints.getUserAgentPrefix)(); + const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE); + const normalUAValue = [ + ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), + ...customUserAgent + ].join(SPACE); + if (options.runtime !== "browser") { + if (normalUAValue) { + headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue; } + headers[USER_AGENT] = sdkUserAgentValue; } else { - if (credentialDefaultProvider) { - credentialsProvider = (0, import_core2.normalizeProvider)( - credentialDefaultProvider( - Object.assign({}, config, { - parentClientConfig: config - }) - ) - ); - } else { - credentialsProvider = /* @__PURE__ */ __name(async () => { - throw new Error( - "@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured." - ); - }, "credentialsProvider"); - } + headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; } - credentialsProvider.memoized = true; - return credentialsProvider; -} -__name(normalizeCredentialProvider, "normalizeCredentialProvider"); -function bindCallerConfig(config, credentialsProvider) { - if (credentialsProvider.configBound) { - return credentialsProvider; + return next({ + ...args, + request + }); +}, "userAgentMiddleware"); +var escapeUserAgent = /* @__PURE__ */ __name((userAgentPair) => { + const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); + const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); + const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); + const prefix = name.substring(0, prefixSeparatorIndex); + let uaName = name.substring(prefixSeparatorIndex + 1); + if (prefix === "api") { + uaName = uaName.toLowerCase(); } - const fn = /* @__PURE__ */ __name(async (options) => credentialsProvider({ ...options, callerClientConfig: config }), "fn"); - fn.memoized = credentialsProvider.memoized; - fn.configBound = true; - return fn; -} -__name(bindCallerConfig, "bindCallerConfig"); + 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}`; + } + }, ""); +}, "escapeUserAgent"); +var getUserAgentMiddlewareOptions = { + name: "getUserAgentMiddleware", + step: "build", + priority: "low", + tags: ["SET_USER_AGENT", "USER_AGENT"], + override: true +}; +var getUserAgentPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); + }, "applyToStack") +}), "getUserAgentPlugin"); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + +/***/ }), + +/***/ 9002: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthSchemeConfig = exports.defaultSSOOIDCHttpAuthSchemeProvider = exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0; +const core_1 = __nccwpck_require__(2143); +const util_middleware_1 = __nccwpck_require__(2390); +const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sso-oauth", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "CreateToken": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; +}; +exports.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; + + +/***/ }), + +/***/ 8012: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = __nccwpck_require__(4241); +const util_endpoints_2 = __nccwpck_require__(5473); +const ruleset_1 = __nccwpck_require__(2507); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; + + +/***/ }), + +/***/ 2507: +/***/ ((__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://oidc-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://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://oidc-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://oidc.{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://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; +exports.ruleSet = _data; + + /***/ }), -/***/ 5986: +/***/ 8959: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -47570,2044 +31240,2285 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/index.ts +// src/submodules/sso-oidc/index.ts var index_exports = {}; __export(index_exports, { - AwsEc2QueryProtocol: () => AwsEc2QueryProtocol, - AwsJson1_0Protocol: () => AwsJson1_0Protocol, - AwsJson1_1Protocol: () => AwsJson1_1Protocol, - AwsJsonRpcProtocol: () => AwsJsonRpcProtocol, - AwsQueryProtocol: () => AwsQueryProtocol, - AwsRestJsonProtocol: () => AwsRestJsonProtocol, - AwsRestXmlProtocol: () => AwsRestXmlProtocol, - JsonCodec: () => JsonCodec, - JsonShapeDeserializer: () => JsonShapeDeserializer, - JsonShapeSerializer: () => JsonShapeSerializer, - XmlCodec: () => XmlCodec, - XmlShapeDeserializer: () => XmlShapeDeserializer, - XmlShapeSerializer: () => XmlShapeSerializer, - _toBool: () => _toBool, - _toNum: () => _toNum, - _toStr: () => _toStr, - awsExpectUnion: () => awsExpectUnion, - loadRestJsonErrorCode: () => loadRestJsonErrorCode, - loadRestXmlErrorCode: () => loadRestXmlErrorCode, - parseJsonBody: () => parseJsonBody, - parseJsonErrorBody: () => parseJsonErrorBody, - parseXmlBody: () => parseXmlBody, - parseXmlErrorBody: () => parseXmlErrorBody + $Command: () => import_smithy_client6.Command, + AccessDeniedException: () => AccessDeniedException, + AuthorizationPendingException: () => AuthorizationPendingException, + CreateTokenCommand: () => CreateTokenCommand, + CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog, + CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog, + ExpiredTokenException: () => ExpiredTokenException, + InternalServerException: () => InternalServerException, + InvalidClientException: () => InvalidClientException, + InvalidGrantException: () => InvalidGrantException, + InvalidRequestException: () => InvalidRequestException, + InvalidScopeException: () => InvalidScopeException, + SSOOIDC: () => SSOOIDC, + SSOOIDCClient: () => SSOOIDCClient, + SSOOIDCServiceException: () => SSOOIDCServiceException, + SlowDownException: () => SlowDownException, + UnauthorizedClientException: () => UnauthorizedClientException, + UnsupportedGrantTypeException: () => UnsupportedGrantTypeException, + __Client: () => import_smithy_client2.Client }); module.exports = __toCommonJS(index_exports); -// src/submodules/protocols/coercing-serializers.ts -var _toStr = /* @__PURE__ */ __name((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; -}, "_toStr"); -var _toBool = /* @__PURE__ */ __name((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; -}, "_toBool"); -var _toNum = /* @__PURE__ */ __name((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; -}, "_toNum"); - -// src/submodules/protocols/json/AwsJsonRpcProtocol.ts -var import_protocols = __nccwpck_require__(2241); -var import_schema3 = __nccwpck_require__(9826); -var import_util_body_length_browser = __nccwpck_require__(713); - -// src/submodules/protocols/ConfigurableSerdeContext.ts -var SerdeContextConfig = class { - static { - __name(this, "SerdeContextConfig"); - } - serdeContext; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } -}; - -// src/submodules/protocols/json/JsonShapeDeserializer.ts -var import_schema = __nccwpck_require__(9826); -var import_serde2 = __nccwpck_require__(7669); -var import_util_base64 = __nccwpck_require__(5600); - -// src/submodules/protocols/json/jsonReviver.ts -var import_serde = __nccwpck_require__(7669); -function jsonReviver(key, value, context) { - if (context?.source) { - const numericString = context.source; - if (typeof value === "number") { - if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { - const isFractional = numericString.includes("."); - if (isFractional) { - return new import_serde.NumericValue(numericString, "bigDecimal"); - } else { - return BigInt(numericString); - } - } - } - } - return value; -} -__name(jsonReviver, "jsonReviver"); - -// src/submodules/protocols/common.ts -var import_smithy_client = __nccwpck_require__(3570); -var collectBodyString = /* @__PURE__ */ __name((streamBody, context) => (0, import_smithy_client.collectBody)(streamBody, context).then((body) => context.utf8Encoder(body)), "collectBodyString"); - -// src/submodules/protocols/json/parseJsonBody.ts -var parseJsonBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - try { - return JSON.parse(encoded); - } catch (e) { - if (e?.name === "SyntaxError") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded - }); - } - throw e; - } - } - return {}; -}), "parseJsonBody"); -var parseJsonErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { - const value = await parseJsonBody(errorBody, context); - value.message = value.message ?? value.Message; - return value; -}, "parseJsonErrorBody"); -var loadRestJsonErrorCode = /* @__PURE__ */ __name((output, data) => { - const findKey = /* @__PURE__ */ __name((object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()), "findKey"); - const sanitizeErrorCode = /* @__PURE__ */ __name((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; - }, "sanitizeErrorCode"); - const headerKey = findKey(output.headers, "x-amzn-errortype"); - if (headerKey !== void 0) { - return sanitizeErrorCode(output.headers[headerKey]); - } - if (data && typeof data === "object") { - const codeKey = findKey(data, "code"); - if (codeKey && data[codeKey] !== void 0) { - return sanitizeErrorCode(data[codeKey]); - } - if (data["__type"] !== void 0) { - return sanitizeErrorCode(data["__type"]); - } - } -}, "loadRestJsonErrorCode"); +// src/submodules/sso-oidc/SSOOIDCClient.ts +var import_middleware_host_header = __nccwpck_require__(9514); +var import_middleware_logger = __nccwpck_require__(5675); +var import_middleware_recursion_detection = __nccwpck_require__(7977); +var import_middleware_user_agent = __nccwpck_require__(6634); +var import_config_resolver = __nccwpck_require__(3098); +var import_core = __nccwpck_require__(5829); +var import_middleware_content_length = __nccwpck_require__(2800); +var import_middleware_endpoint = __nccwpck_require__(2918); +var import_middleware_retry = __nccwpck_require__(6039); +var import_smithy_client2 = __nccwpck_require__(3570); +var import_httpAuthSchemeProvider = __nccwpck_require__(9002); -// src/submodules/protocols/json/JsonShapeDeserializer.ts -var JsonShapeDeserializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "JsonShapeDeserializer"); - } - async read(schema, data) { - return this._read( - schema, - typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext) - ); - } - readObject(schema, data) { - return this._read(schema, data); - } - _read(schema, value) { - const isObject = value !== null && typeof value === "object"; - const ns = import_schema.NormalizedSchema.of(schema); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._read(listMember, item)); - } - } - return out; - } else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._read(mapMember, _v); - } - } - return out; - } else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const deserializedValue = this._read(memberSchema, value[fromKey]); - if (deserializedValue != null) { - out[memberName] = deserializedValue; - } - } - return out; - } - if (ns.isBlobSchema() && typeof value === "string") { - return (0, import_util_base64.fromBase64)(value); - } - const mediaType = ns.getMergedTraits().mediaType; - if (ns.isStringSchema() && typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return import_serde2.LazyJsonString.from(value); - } - } - if (ns.isTimestampSchema()) { - const options = this.settings.timestampFormat; - const format = options.useTrait ? ns.getSchema() === import_schema.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; - switch (format) { - case import_schema.SCHEMA.TIMESTAMP_DATE_TIME: - return (0, import_serde2.parseRfc3339DateTimeWithOffset)(value); - case import_schema.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde2.parseRfc7231DateTime)(value); - case import_schema.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return (0, import_serde2.parseEpochTimestamp)(value); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", value); - return new Date(value); - } - } - if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { - return BigInt(value); - } - if (ns.isBigDecimalSchema() && value != void 0) { - if (value instanceof import_serde2.NumericValue) { - return value; - } - return new import_serde2.NumericValue(String(value), "bigDecimal"); - } - if (ns.isNumericSchema() && typeof value === "string") { - switch (value) { - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - case "NaN": - return NaN; +// src/submodules/sso-oidc/endpoint/EndpointParameters.ts +var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "sso-oauth" + }); +}, "resolveClientEndpointParameters"); +var commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } +}; + +// src/submodules/sso-oidc/SSOOIDCClient.ts +var import_runtimeConfig = __nccwpck_require__(5875); + +// src/submodules/sso-oidc/runtimeExtensions.ts +var import_region_config_resolver = __nccwpck_require__(6976); +var import_protocol_http = __nccwpck_require__(4418); +var import_smithy_client = __nccwpck_require__(3570); + +// src/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.ts +var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; } - return value; - } -}; + }; +}, "getHttpAuthExtensionConfiguration"); +var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials() + }; +}, "resolveHttpAuthRuntimeConfig"); -// src/submodules/protocols/json/JsonShapeSerializer.ts -var import_schema2 = __nccwpck_require__(9826); -var import_serde4 = __nccwpck_require__(7669); +// src/submodules/sso-oidc/runtimeExtensions.ts +var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign( + (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), + (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), + (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), + getHttpAuthExtensionConfiguration(runtimeConfig) + ); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign( + runtimeConfig, + (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), + (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), + (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), + resolveHttpAuthRuntimeConfig(extensionConfiguration) + ); +}, "resolveRuntimeExtensions"); -// src/submodules/protocols/json/jsonReplacer.ts -var import_serde3 = __nccwpck_require__(7669); -var NUMERIC_CONTROL_CHAR = String.fromCharCode(925); -var JsonReplacer = class { +// src/submodules/sso-oidc/SSOOIDCClient.ts +var SSOOIDCClient = class extends import_smithy_client2.Client { static { - __name(this, "JsonReplacer"); + __name(this, "SSOOIDCClient"); } /** - * Stores placeholder key to true serialized value lookup. - */ - values = /* @__PURE__ */ new Map(); - counter = 0; - stage = 0; - /** - * Creates a jsonReplacer function that reserves big integer and big decimal values - * for later replacement. + * The resolved configuration of SSOOIDCClient class. This is resolved and normalized from the {@link SSOOIDCClientConfig | constructor configuration interface}. */ - createReplacer() { - if (this.stage === 1) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 1; - return (key, value) => { - if (value instanceof import_serde3.NumericValue) { - const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; - this.values.set(`"${v}"`, value.string); - return v; - } - if (typeof value === "bigint") { - const s = value.toString(); - const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; - this.values.set(`"${v}"`, s); - return v; - } - return value; - }; + config; + constructor(...[configuration]) { + const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); + const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); + const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); + const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use( + (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { + httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials + }), "identityProviderConfigProvider") + }) + ); + this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); } /** - * Replaces placeholder keys with their true values. + * Destroy underlying resources, like sockets. It's usually not necessary to do this. + * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. + * Otherwise, sockets might stay open for quite a long time before the server terminates them. */ - replaceInJson(json) { - if (this.stage === 0) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 2; - if (this.counter === 0) { - return json; - } - for (const [key, value] of this.values) { - json = json.replace(key, value); - } - return json; + destroy() { + super.destroy(); } }; -// src/submodules/protocols/json/JsonShapeSerializer.ts -var JsonShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } +// src/submodules/sso-oidc/SSOOIDC.ts +var import_smithy_client7 = __nccwpck_require__(3570); + +// src/submodules/sso-oidc/commands/CreateTokenCommand.ts +var import_middleware_endpoint2 = __nccwpck_require__(2918); +var import_middleware_serde = __nccwpck_require__(1238); +var import_smithy_client6 = __nccwpck_require__(3570); + +// src/submodules/sso-oidc/models/models_0.ts +var import_smithy_client4 = __nccwpck_require__(3570); + +// src/submodules/sso-oidc/models/SSOOIDCServiceException.ts +var import_smithy_client3 = __nccwpck_require__(3570); +var SSOOIDCServiceException = class _SSOOIDCServiceException extends import_smithy_client3.ServiceException { static { - __name(this, "JsonShapeSerializer"); - } - buffer; - rootSchema; - write(schema, value) { - this.rootSchema = import_schema2.NormalizedSchema.of(schema); - this.buffer = this._write(this.rootSchema, value); - } - flush() { - if (this.rootSchema?.isStructSchema() || this.rootSchema?.isDocumentSchema()) { - const replacer = new JsonReplacer(); - return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); - } - return this.buffer; + __name(this, "SSOOIDCServiceException"); } - _write(schema, value, container) { - const isObject = value !== null && typeof value === "object"; - const ns = import_schema2.NormalizedSchema.of(schema); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._write(listMember, item)); - } - } - return out; - } else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._write(mapMember, _v); - } - } - return out; - } else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const serializableValue = this._write(memberSchema, value[memberName], ns); - if (serializableValue !== void 0) { - out[targetKey] = serializableValue; - } - } - return out; - } - if (value === null && container?.isStructSchema()) { - return void 0; - } - if (ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string")) { - if (ns === this.rootSchema) { - return value; - } - if (!this.serdeContext?.base64Encoder) { - throw new Error("Missing base64Encoder in serdeContext"); - } - return this.serdeContext?.base64Encoder(value); - } - if (ns.isTimestampSchema() && value instanceof Date) { - const options = this.settings.timestampFormat; - const format = options.useTrait ? ns.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; - switch (format) { - case import_schema2.SCHEMA.TIMESTAMP_DATE_TIME: - return value.toISOString().replace(".000Z", "Z"); - case import_schema2.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde4.dateToUtcString)(value); - case import_schema2.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return value.getTime() / 1e3; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - return value.getTime() / 1e3; - } - } - if (ns.isNumericSchema() && typeof value === "number") { - if (Math.abs(value) === Infinity || isNaN(value)) { - return String(value); - } - } - if (ns.isStringSchema()) { - if (typeof value === "undefined" && ns.isIdempotencyToken()) { - return (0, import_serde4.generateIdempotencyToken)(); - } - const mediaType = ns.getMergedTraits().mediaType; - if (typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return import_serde4.LazyJsonString.from(value); - } - } - } - return value; + /** + * @internal + */ + constructor(options) { + super(options); + Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype); } }; -// src/submodules/protocols/json/JsonCodec.ts -var JsonCodec = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } +// src/submodules/sso-oidc/models/models_0.ts +var AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException { static { - __name(this, "JsonCodec"); - } - createSerializer() { - const serializer = new JsonShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; + __name(this, "AccessDeniedException"); } - createDeserializer() { - const deserializer = new JsonShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; + name = "AccessDeniedException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be access_denied.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _AccessDeniedException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } }; - -// src/submodules/protocols/json/AwsJsonRpcProtocol.ts -var AwsJsonRpcProtocol = class extends import_protocols.RpcProtocol { +var AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException { static { - __name(this, "AwsJsonRpcProtocol"); + __name(this, "AuthorizationPendingException"); } - serializer; - deserializer; - serviceTarget; - codec; - constructor({ defaultNamespace, serviceTarget }) { + name = "AuthorizationPendingException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * authorization_pending.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { super({ - defaultNamespace + name: "AuthorizationPendingException", + $fault: "client", + ...opts }); - this.serviceTarget = serviceTarget; - this.codec = new JsonCodec({ - timestampFormat: { - useTrait: true, - default: import_schema3.SCHEMA.TIMESTAMP_EPOCH_SECONDS - }, - jsonName: false + Object.setPrototypeOf(this, _AuthorizationPendingException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +var CreateTokenRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.clientSecret && { clientSecret: import_smithy_client4.SENSITIVE_STRING }, + ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, + ...obj.codeVerifier && { codeVerifier: import_smithy_client4.SENSITIVE_STRING } +}), "CreateTokenRequestFilterSensitiveLog"); +var CreateTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.accessToken && { accessToken: import_smithy_client4.SENSITIVE_STRING }, + ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, + ...obj.idToken && { idToken: import_smithy_client4.SENSITIVE_STRING } +}), "CreateTokenResponseFilterSensitiveLog"); +var ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException { + static { + __name(this, "ExpiredTokenException"); + } + name = "ExpiredTokenException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be expired_token.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts }); - this.serializer = this.codec.createSerializer(); - this.deserializer = this.codec.createDeserializer(); + Object.setPrototypeOf(this, _ExpiredTokenException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, - "x-amz-target": `${this.serviceTarget}.${import_schema3.NormalizedSchema.of(operationSchema).getName()}` +}; +var InternalServerException = class _InternalServerException extends SSOOIDCServiceException { + static { + __name(this, "InternalServerException"); + } + name = "InternalServerException"; + $fault = "server"; + /** + *

Single error code. For this exception the value will be server_error.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts }); - if ((0, import_schema3.deref)(operationSchema.input) === "unit" || !request.body) { - request.body = "{}"; - } - try { - request.headers["content-length"] = String((0, import_util_body_length_browser.calculateBodyLength)(request.body)); - } catch (e) { - } - return request; + Object.setPrototypeOf(this, _InternalServerException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - getPayloadCodec() { - return this.codec; +}; +var InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException { + static { + __name(this, "InvalidClientException"); } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const registry = import_schema3.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorIdentifier); - } catch (e) { - const baseExceptionSchema = import_schema3.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), dataObject); - } - throw new Error(errorName); - } - const ns = import_schema3.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output + name = "InvalidClientException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * invalid_client.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidClientException", + $fault: "client", + ...opts }); - throw exception; + Object.setPrototypeOf(this, _InvalidClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } }; - -// src/submodules/protocols/json/AwsJson1_0Protocol.ts -var AwsJson1_0Protocol = class extends AwsJsonRpcProtocol { +var InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException { static { - __name(this, "AwsJson1_0Protocol"); + __name(this, "InvalidGrantException"); } - constructor({ defaultNamespace, serviceTarget }) { + name = "InvalidGrantException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be invalid_grant.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { super({ - defaultNamespace, - serviceTarget + name: "InvalidGrantException", + $fault: "client", + ...opts }); + Object.setPrototypeOf(this, _InvalidGrantException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - getShapeId() { - return "aws.protocols#awsJson1_0"; - } - getJsonRpcVersion() { - return "1.0"; +}; +var InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException { + static { + __name(this, "InvalidRequestException"); } + name = "InvalidRequestException"; + $fault = "client"; /** - * @override + *

Single error code. For this exception the value will be + * invalid_request.

+ * @public */ - getDefaultContentType() { - return "application/x-amz-json-1.0"; + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidRequestException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } }; - -// src/submodules/protocols/json/AwsJson1_1Protocol.ts -var AwsJson1_1Protocol = class extends AwsJsonRpcProtocol { +var InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException { static { - __name(this, "AwsJson1_1Protocol"); + __name(this, "InvalidScopeException"); } - constructor({ defaultNamespace, serviceTarget }) { + name = "InvalidScopeException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be invalid_scope.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { super({ - defaultNamespace, - serviceTarget + name: "InvalidScopeException", + $fault: "client", + ...opts }); + Object.setPrototypeOf(this, _InvalidScopeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - getShapeId() { - return "aws.protocols#awsJson1_1"; - } - getJsonRpcVersion() { - return "1.1"; +}; +var SlowDownException = class _SlowDownException extends SSOOIDCServiceException { + static { + __name(this, "SlowDownException"); } + name = "SlowDownException"; + $fault = "client"; /** - * @override + *

Single error code. For this exception the value will be slow_down.

+ * @public */ - getDefaultContentType() { - return "application/x-amz-json-1.1"; + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "SlowDownException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _SlowDownException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } }; - -// src/submodules/protocols/json/AwsRestJsonProtocol.ts -var import_protocols2 = __nccwpck_require__(2241); -var import_schema4 = __nccwpck_require__(9826); -var import_util_body_length_browser2 = __nccwpck_require__(713); -var AwsRestJsonProtocol = class extends import_protocols2.HttpBindingProtocol { +var UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException { static { - __name(this, "AwsRestJsonProtocol"); + __name(this, "UnauthorizedClientException"); } - serializer; - deserializer; - codec; - constructor({ defaultNamespace }) { + name = "UnauthorizedClientException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * unauthorized_client.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { super({ - defaultNamespace + name: "UnauthorizedClientException", + $fault: "client", + ...opts }); - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS - }, - httpBindings: true, - jsonName: true - }; - this.codec = new JsonCodec(settings); - this.serializer = new import_protocols2.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new import_protocols2.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + Object.setPrototypeOf(this, _UnauthorizedClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - getShapeId() { - return "aws.protocols#restJson1"; +}; +var UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException { + static { + __name(this, "UnsupportedGrantTypeException"); } - getPayloadCodec() { - return this.codec; + name = "UnsupportedGrantTypeException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * unsupported_grant_type.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "UnsupportedGrantTypeException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - setSerdeContext(serdeContext) { - this.codec.setSerdeContext(serdeContext); - super.setSerdeContext(serdeContext); +}; + +// src/submodules/sso-oidc/protocols/Aws_restJson1.ts +var import_core2 = __nccwpck_require__(2143); +var import_core3 = __nccwpck_require__(5829); +var import_smithy_client5 = __nccwpck_require__(3570); +var se_CreateTokenCommand = /* @__PURE__ */ __name(async (input, context) => { + const b = (0, import_core3.requestBuilder)(input, context); + const headers = { + "content-type": "application/json" + }; + b.bp("/token"); + let body; + body = JSON.stringify( + (0, import_smithy_client5.take)(input, { + clientId: [], + clientSecret: [], + code: [], + codeVerifier: [], + deviceCode: [], + grantType: [], + redirectUri: [], + refreshToken: [], + scope: /* @__PURE__ */ __name((_) => (0, import_smithy_client5._json)(_), "scope") + }) + ); + b.m("POST").h(headers).b(body); + return b.build(); +}, "se_CreateTokenCommand"); +var de_CreateTokenCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = import_schema4.NormalizedSchema.of(operationSchema.input); - const members = inputSchema.getMemberSchemas(); - if (!request.headers["content-type"]) { - const httpPayloadMember = Object.values(members).find((m) => { - return !!m.getMergedTraits().httpPayload; + const contents = (0, import_smithy_client5.map)({ + $metadata: deserializeMetadata(output) + }); + const data = (0, import_smithy_client5.expectNonNull)((0, import_smithy_client5.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); + const doc = (0, import_smithy_client5.take)(data, { + accessToken: import_smithy_client5.expectString, + expiresIn: import_smithy_client5.expectInt32, + idToken: import_smithy_client5.expectString, + refreshToken: import_smithy_client5.expectString, + tokenType: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + return contents; +}, "de_CreateTokenCommand"); +var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { + const parsedOutput = { + ...output, + body: await (0, import_core2.parseJsonErrorBody)(output.body, context) + }; + const errorCode = (0, import_core2.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 }); - if (httpPayloadMember) { - const mediaType = httpPayloadMember.getMergedTraits().mediaType; - if (mediaType) { - request.headers["content-type"] = mediaType; - } else if (httpPayloadMember.isStringSchema()) { - request.headers["content-type"] = "text/plain"; - } else if (httpPayloadMember.isBlobSchema()) { - request.headers["content-type"] = "application/octet-stream"; - } else { - request.headers["content-type"] = this.getDefaultContentType(); - } - } else if (!inputSchema.isUnitSchema()) { - const hasBody = Object.values(members).find((m) => { - const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); - return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && httpPrefixHeaders === void 0; - }); - if (hasBody) { - request.headers["content-type"] = this.getDefaultContentType(); - } - } - } - if (request.headers["content-type"] && !request.body) { - request.body = "{}"; - } - if (request.body) { - try { - request.headers["content-length"] = String((0, import_util_body_length_browser2.calculateBodyLength)(request.body)); - } catch (e) { - } - } - return request; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const registry = import_schema4.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorIdentifier); - } catch (e) { - const baseExceptionSchema = import_schema4.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), dataObject); - } - throw new Error(errorName); - } - const ns = import_schema4.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output - }); - throw exception; } - /** - * @override - */ - getDefaultContentType() { - return "application/json"; +}, "de_CommandError"); +var throwDefaultError = (0, import_smithy_client5.withBaseException)(SSOOIDCServiceException); +var de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new AccessDeniedException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_AccessDeniedExceptionRes"); +var de_AuthorizationPendingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new AuthorizationPendingException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_AuthorizationPendingExceptionRes"); +var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new ExpiredTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_ExpiredTokenExceptionRes"); +var de_InternalServerExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InternalServerException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InternalServerExceptionRes"); +var de_InvalidClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidClientException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidClientExceptionRes"); +var de_InvalidGrantExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidGrantException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidGrantExceptionRes"); +var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidRequestException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidRequestExceptionRes"); +var de_InvalidScopeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidScopeException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidScopeExceptionRes"); +var de_SlowDownExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new SlowDownException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_SlowDownExceptionRes"); +var de_UnauthorizedClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new UnauthorizedClientException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_UnauthorizedClientExceptionRes"); +var de_UnsupportedGrantTypeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new UnsupportedGrantTypeException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_UnsupportedGrantTypeExceptionRes"); +var deserializeMetadata = /* @__PURE__ */ __name((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"] +}), "deserializeMetadata"); + +// src/submodules/sso-oidc/commands/CreateTokenCommand.ts +var CreateTokenCommand = class extends import_smithy_client6.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() { + static { + __name(this, "CreateTokenCommand"); } }; -// src/submodules/protocols/json/awsExpectUnion.ts -var import_smithy_client2 = __nccwpck_require__(3570); -var awsExpectUnion = /* @__PURE__ */ __name((value) => { - if (value == null) { - return void 0; - } - if (typeof value === "object" && "__type" in value) { - delete value.__type; +// src/submodules/sso-oidc/SSOOIDC.ts +var commands = { + CreateTokenCommand +}; +var SSOOIDC = class extends SSOOIDCClient { + static { + __name(this, "SSOOIDC"); } - return (0, import_smithy_client2.expectUnion)(value); -}, "awsExpectUnion"); +}; +(0, import_smithy_client7.createAggregatedClient)(commands, SSOOIDC); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); -// src/submodules/protocols/query/AwsQueryProtocol.ts -var import_protocols5 = __nccwpck_require__(2241); -var import_schema7 = __nccwpck_require__(9826); -var import_util_body_length_browser3 = __nccwpck_require__(713); -// src/submodules/protocols/xml/XmlShapeDeserializer.ts -var import_protocols3 = __nccwpck_require__(2241); -var import_schema5 = __nccwpck_require__(9826); -var import_smithy_client3 = __nccwpck_require__(3570); -var import_util_utf8 = __nccwpck_require__(1895); -var import_fast_xml_parser = __nccwpck_require__(4678); -var XmlShapeDeserializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - this.stringDeserializer = new import_protocols3.FromStringShapeDeserializer(settings); - } - static { - __name(this, "XmlShapeDeserializer"); - } - stringDeserializer; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.stringDeserializer.setSerdeContext(serdeContext); - } - /** - * @param schema - describing the data. - * @param bytes - serialized data. - * @param key - used by AwsQuery to step one additional depth into the object before reading it. - */ - read(schema, bytes, key) { - const ns = import_schema5.NormalizedSchema.of(schema); - const memberSchemas = ns.getMemberSchemas(); - const isEventPayload = ns.isStructSchema() && ns.isMemberSchema() && !!Object.values(memberSchemas).find((memberNs) => { - return !!memberNs.getMemberTraits().eventPayload; - }); - if (isEventPayload) { - const output = {}; - const memberName = Object.keys(memberSchemas)[0]; - const eventMemberSchema = memberSchemas[memberName]; - if (eventMemberSchema.isBlobSchema()) { - output[memberName] = bytes; - } else { - output[memberName] = this.read(memberSchemas[memberName], bytes); - } - return output; - } - const xmlString = (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)(bytes); - const parsedObject = this.parseXml(xmlString); - return this.readSchema(schema, key ? parsedObject[key] : parsedObject); - } - readSchema(_schema, value) { - const ns = import_schema5.NormalizedSchema.of(_schema); - const traits = ns.getMergedTraits(); - if (ns.isListSchema() && !Array.isArray(value)) { - return this.readSchema(ns, [value]); - } - if (value == null) { - return value; - } - if (typeof value === "object") { - const sparse = !!traits.sparse; - const flat = !!traits.xmlFlattened; - if (ns.isListSchema()) { - const listValue = ns.getValueSchema(); - const buffer2 = []; - const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; - const source = flat ? value : (value[0] ?? value)[sourceKey]; - const sourceArray = Array.isArray(source) ? source : [source]; - for (const v of sourceArray) { - if (v != null || sparse) { - buffer2.push(this.readSchema(listValue, v)); - } - } - return buffer2; - } - const buffer = {}; - if (ns.isMapSchema()) { - const keyNs = ns.getKeySchema(); - const memberNs = ns.getValueSchema(); - let entries; - if (flat) { - entries = Array.isArray(value) ? value : [value]; - } else { - entries = Array.isArray(value.entry) ? value.entry : [value.entry]; - } - const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; - const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; - for (const entry of entries) { - const key = entry[keyProperty]; - const value2 = entry[valueProperty]; - if (value2 != null || sparse) { - buffer[key] = this.readSchema(memberNs, value2); - } - } - return buffer; - } - if (ns.isStructSchema()) { - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMergedTraits(); - const xmlObjectKey = !memberTraits.httpPayload ? memberSchema.getMemberTraits().xmlName ?? memberName : memberTraits.xmlName ?? memberSchema.getName(); - if (value[xmlObjectKey] != null) { - buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); - } - } - return buffer; - } - if (ns.isDocumentSchema()) { - return value; - } - throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); - } - if (ns.isListSchema()) { - return []; - } - if (ns.isMapSchema() || ns.isStructSchema()) { - return {}; - } - return this.stringDeserializer.read(ns, value); - } - parseXml(xml) { - if (xml.length) { - const parser = new import_fast_xml_parser.XMLParser({ - attributeNamePrefix: "", - htmlEntities: true, - ignoreAttributes: false, - ignoreDeclaration: true, - parseTagValue: false, - trimValues: false, - tagValueProcessor: /* @__PURE__ */ __name((_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, "tagValueProcessor") - }); - parser.addEntity("#xD", "\r"); - parser.addEntity("#10", "\n"); - let parsedObj; - try { - parsedObj = parser.parse(xml, true); - } catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: xml - }); - } - throw e; - } - 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, import_smithy_client3.getValueFromTextNode)(parsedObjToReturn); - } - return {}; - } +/***/ }), + +/***/ 5875: +/***/ ((__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__(4178)); +const core_1 = __nccwpck_require__(2143); +const util_user_agent_node_1 = __nccwpck_require__(7330); +const config_resolver_1 = __nccwpck_require__(3098); +const hash_node_1 = __nccwpck_require__(3081); +const middleware_retry_1 = __nccwpck_require__(6039); +const node_config_provider_1 = __nccwpck_require__(3461); +const node_http_handler_1 = __nccwpck_require__(258); +const util_body_length_node_1 = __nccwpck_require__(8075); +const util_retry_1 = __nccwpck_require__(4902); +const runtimeConfig_shared_1 = __nccwpck_require__(3695); +const smithy_client_1 = __nccwpck_require__(3570); +const util_defaults_mode_node_1 = __nccwpck_require__(2429); +const smithy_client_2 = __nccwpck_require__(3570); +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); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ 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, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, + }, config), + 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, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; }; +exports.getRuntimeConfig = getRuntimeConfig; -// src/submodules/protocols/query/QueryShapeSerializer.ts -var import_protocols4 = __nccwpck_require__(2241); -var import_schema6 = __nccwpck_require__(9826); -var import_serde5 = __nccwpck_require__(7669); -var import_smithy_client4 = __nccwpck_require__(3570); -var import_util_base642 = __nccwpck_require__(5600); -var QueryShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "QueryShapeSerializer"); - } - buffer; - write(schema, value, prefix = "") { - if (this.buffer === void 0) { - this.buffer = ""; + +/***/ }), + +/***/ 3695: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const core_1 = __nccwpck_require__(2143); +const core_2 = __nccwpck_require__(5829); +const smithy_client_1 = __nccwpck_require__(3570); +const url_parser_1 = __nccwpck_require__(4681); +const util_base64_1 = __nccwpck_require__(5600); +const util_utf8_1 = __nccwpck_require__(1895); +const httpAuthSchemeProvider_1 = __nccwpck_require__(9002); +const endpointResolver_1 = __nccwpck_require__(8012); +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 ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + serviceId: config?.serviceId ?? "SSO OIDC", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; + + +/***/ }), + +/***/ 6878: +/***/ ((__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__(9514); +const middleware_logger_1 = __nccwpck_require__(5675); +const middleware_recursion_detection_1 = __nccwpck_require__(7977); +const middleware_user_agent_1 = __nccwpck_require__(6634); +const config_resolver_1 = __nccwpck_require__(3098); +const core_1 = __nccwpck_require__(5829); +const middleware_content_length_1 = __nccwpck_require__(2800); +const middleware_endpoint_1 = __nccwpck_require__(2918); +const middleware_retry_1 = __nccwpck_require__(6039); +const smithy_client_1 = __nccwpck_require__(3570); +Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); +const httpAuthSchemeProvider_1 = __nccwpck_require__(3061); +const EndpointParameters_1 = __nccwpck_require__(981); +const runtimeConfig_1 = __nccwpck_require__(302); +const runtimeExtensions_1 = __nccwpck_require__(9913); +class STSClient extends smithy_client_1.Client { + config; + constructor(...[configuration]) { + const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); + const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); + const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); + const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); + const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); + const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); + 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, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); } - const ns = import_schema6.NormalizedSchema.of(schema); - if (prefix && !prefix.endsWith(".")) { - prefix += "."; + destroy() { + super.destroy(); } - if (ns.isBlobSchema()) { - if (typeof value === "string" || value instanceof Uint8Array) { - this.writeKey(prefix); - this.writeValue((this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value)); - } - } else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } else if (ns.isIdempotencyToken()) { - this.writeKey(prefix); - this.writeValue((0, import_serde5.generateIdempotencyToken)()); - } - } else if (ns.isBigIntegerSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } - } else if (ns.isBigDecimalSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(value instanceof import_serde5.NumericValue ? value.string : String(value)); - } - } else if (ns.isTimestampSchema()) { - if (value instanceof Date) { - this.writeKey(prefix); - const format = (0, import_protocols4.determineTimestampFormat)(ns, this.settings); - switch (format) { - case import_schema6.SCHEMA.TIMESTAMP_DATE_TIME: - this.writeValue(value.toISOString().replace(".000Z", "Z")); - break; - case import_schema6.SCHEMA.TIMESTAMP_HTTP_DATE: - this.writeValue((0, import_smithy_client4.dateToUtcString)(value)); - break; - case import_schema6.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - this.writeValue(String(value.getTime() / 1e3)); +} +exports.STSClient = STSClient; + + +/***/ }), + +/***/ 1746: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; +exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; + + +/***/ }), + +/***/ 3061: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; +const core_1 = __nccwpck_require__(2143); +const util_middleware_1 = __nccwpck_require__(2390); +const STSClient_1 = __nccwpck_require__(6878); +const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sts", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSTSHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "AssumeRoleWithWebIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); break; } - } - } else if (ns.isDocumentSchema()) { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unsupported document type ${ns.getName(true)}`); - } else if (ns.isListSchema()) { - if (Array.isArray(value)) { - if (value.length === 0) { - if (this.settings.serializeEmptyLists) { - this.writeKey(prefix); - this.writeValue(""); - } - } else { - const member = ns.getValueSchema(); - const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const item of value) { - if (item == null) { - continue; - } - const suffix = this.getKey("member", member.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; - this.write(member, item, key); - ++i; - } - } - } - } else if (ns.isMapSchema()) { - if (value && typeof value === "object") { - const keySchema = ns.getKeySchema(); - const memberSchema = ns.getValueSchema(); - const flat = ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const [k, v] of Object.entries(value)) { - if (v == null) { - continue; - } - const keySuffix = this.getKey("key", keySchema.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; - const valueSuffix = this.getKey("value", memberSchema.getMergedTraits().xmlName); - const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; - this.write(keySchema, k, key); - this.write(memberSchema, v, valueKey); - ++i; - } - } - } else if (ns.isStructSchema()) { - if (value && typeof value === "object") { - for (const [memberName, member] of ns.structIterator()) { - if (value[memberName] == null && !member.isIdempotencyToken()) { - continue; - } - const suffix = this.getKey(memberName, member.getMergedTraits().xmlName); - const key = `${prefix}${suffix}`; - this.write(member, value[memberName], key); + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); } - } - } else if (ns.isUnitSchema()) { - } else { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); - } - } - flush() { - if (this.buffer === void 0) { - throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); - } - const str = this.buffer; - delete this.buffer; - return str; - } - getKey(memberName, xmlName) { - const key = xmlName ?? memberName; - if (this.settings.capitalizeKeys) { - return key[0].toUpperCase() + key.slice(1); } - return key; + return options; +}; +exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; +const resolveStsAuthConfig = (input) => Object.assign(input, { + stsClientCtor: STSClient_1.STSClient, +}); +exports.resolveStsAuthConfig = resolveStsAuthConfig; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, exports.resolveStsAuthConfig)(config); + const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); + return Object.assign(config_1, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; + + +/***/ }), + +/***/ 981: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.commonParams = exports.resolveClientEndpointParameters = void 0; +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + useGlobalEndpoint: options.useGlobalEndpoint ?? false, + defaultSigningName: "sts", + }); +}; +exports.resolveClientEndpointParameters = resolveClientEndpointParameters; +exports.commonParams = { + 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" }, +}; + + +/***/ }), + +/***/ 8181: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = __nccwpck_require__(4241); +const util_endpoints_2 = __nccwpck_require__(5473); +const ruleset_1 = __nccwpck_require__(5713); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; + + +/***/ }), + +/***/ 5713: +/***/ ((__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; + + +/***/ }), + +/***/ 3764: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - writeKey(key) { - if (key.endsWith(".")) { - key = key.slice(0, key.length - 1); - } - this.buffer += `&${(0, import_protocols4.extendedEncodeURIComponent)(key)}=`; + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/submodules/sts/index.ts +var index_exports = {}; +__export(index_exports, { + AssumeRoleCommand: () => AssumeRoleCommand, + AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog, + AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand, + AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog, + AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog, + ClientInputEndpointParameters: () => import_EndpointParameters3.ClientInputEndpointParameters, + CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog, + ExpiredTokenException: () => ExpiredTokenException, + IDPCommunicationErrorException: () => IDPCommunicationErrorException, + IDPRejectedClaimException: () => IDPRejectedClaimException, + InvalidIdentityTokenException: () => InvalidIdentityTokenException, + MalformedPolicyDocumentException: () => MalformedPolicyDocumentException, + PackedPolicyTooLargeException: () => PackedPolicyTooLargeException, + RegionDisabledException: () => RegionDisabledException, + STS: () => STS, + STSServiceException: () => STSServiceException, + decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, + getDefaultRoleAssumer: () => getDefaultRoleAssumer2, + getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 +}); +module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(6878), module.exports); + +// src/submodules/sts/STS.ts +var import_smithy_client6 = __nccwpck_require__(3570); + +// src/submodules/sts/commands/AssumeRoleCommand.ts +var import_middleware_endpoint = __nccwpck_require__(2918); +var import_middleware_serde = __nccwpck_require__(1238); +var import_smithy_client4 = __nccwpck_require__(3570); +var import_EndpointParameters = __nccwpck_require__(981); + +// src/submodules/sts/models/models_0.ts +var import_smithy_client2 = __nccwpck_require__(3570); + +// src/submodules/sts/models/STSServiceException.ts +var import_smithy_client = __nccwpck_require__(3570); +var STSServiceException = class _STSServiceException extends import_smithy_client.ServiceException { + static { + __name(this, "STSServiceException"); } - writeValue(value) { - this.buffer += (0, import_protocols4.extendedEncodeURIComponent)(value); + /** + * @internal + */ + constructor(options) { + super(options); + Object.setPrototypeOf(this, _STSServiceException.prototype); } }; -// src/submodules/protocols/query/AwsQueryProtocol.ts -var AwsQueryProtocol = class extends import_protocols5.RpcProtocol { - constructor(options) { +// src/submodules/sts/models/models_0.ts +var CredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client2.SENSITIVE_STRING } +}), "CredentialsFilterSensitiveLog"); +var AssumeRoleResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } +}), "AssumeRoleResponseFilterSensitiveLog"); +var ExpiredTokenException = class _ExpiredTokenException extends STSServiceException { + static { + __name(this, "ExpiredTokenException"); + } + name = "ExpiredTokenException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { super({ - defaultNamespace: options.defaultNamespace + name: "ExpiredTokenException", + $fault: "client", + ...opts }); - this.options = options; - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema7.SCHEMA.TIMESTAMP_DATE_TIME - }, - httpBindings: false, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace, - serializeEmptyLists: true - }; - this.serializer = new QueryShapeSerializer(settings); - this.deserializer = new XmlShapeDeserializer(settings); + Object.setPrototypeOf(this, _ExpiredTokenException.prototype); } +}; +var MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { static { - __name(this, "AwsQueryProtocol"); - } - serializer; - deserializer; - getShapeId() { - return "aws.protocols#awsQuery"; + __name(this, "MalformedPolicyDocumentException"); } - setSerdeContext(serdeContext) { - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); + name = "MalformedPolicyDocumentException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "MalformedPolicyDocumentException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); } - getPayloadCodec() { - throw new Error("AWSQuery protocol has no payload codec."); +}; +var PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { + static { + __name(this, "PackedPolicyTooLargeException"); } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-www-form-urlencoded` + name = "PackedPolicyTooLargeException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "PackedPolicyTooLargeException", + $fault: "client", + ...opts }); - if ((0, import_schema7.deref)(operationSchema.input) === "unit" || !request.body) { - request.body = ""; - } - request.body = `Action=${operationSchema.name.split("#")[1]}&Version=${this.options.version}` + request.body; - if (request.body.endsWith("&")) { - request.body = request.body.slice(-1); - } - try { - request.headers["content-length"] = String((0, import_util_body_length_browser3.calculateBodyLength)(request.body)); - } catch (e) { - } - return request; + Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema7.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes2 = await (0, import_protocols5.collectBody)(response.body, context); - if (bytes2.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema7.SCHEMA.DOCUMENT, bytes2)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? operationSchema.name.split("#")[1] + "Result" : void 0; - const bytes = await (0, import_protocols5.collectBody)(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); - } - const output = { - $metadata: this.deserializeMetadata(response), - ...dataObject - }; - return output; +}; +var RegionDisabledException = class _RegionDisabledException extends STSServiceException { + static { + __name(this, "RegionDisabledException"); } + name = "RegionDisabledException"; + $fault = "client"; /** - * EC2 Query overrides this. + * @internal */ - useNestedResult() { - return true; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const errorDataSource = this.loadQueryError(dataObject); - const registry = import_schema7.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.find( - (schema) => import_schema7.NormalizedSchema.of(schema).getMergedTraits().awsQueryError?.[0] === errorName - ); - if (!errorSchema) { - errorSchema = registry.getSchema(errorIdentifier); - } - } catch (e) { - const baseExceptionSchema = import_schema7.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), errorDataSource); - } - throw new Error(errorName); - } - const ns = import_schema7.NormalizedSchema.of(errorSchema); - const message = this.loadQueryErrorMessage(dataObject); - const exception = new errorSchema.ctor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = errorDataSource[target] ?? dataObject[target]; - output[name] = this.deserializer.readSchema(member, value); - } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output + constructor(opts) { + super({ + name: "RegionDisabledException", + $fault: "client", + ...opts }); - throw exception; + Object.setPrototypeOf(this, _RegionDisabledException.prototype); + } +}; +var IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { + static { + __name(this, "IDPRejectedClaimException"); } + name = "IDPRejectedClaimException"; + $fault = "client"; /** - * The variations in the error and error message locations are attributed to - * divergence between AWS Query and EC2 Query behavior. + * @internal */ - loadQueryErrorCode(output, data) { - const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; - if (code !== void 0) { - return code; - } - if (output.statusCode == 404) { - return "NotFound"; - } - } - loadQueryError(data) { - return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; + constructor(opts) { + super({ + name: "IDPRejectedClaimException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); } - loadQueryErrorMessage(data) { - const errorData = this.loadQueryError(data); - return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; +}; +var InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { + static { + __name(this, "InvalidIdentityTokenException"); } + name = "InvalidIdentityTokenException"; + $fault = "client"; /** - * @override + * @internal */ - getDefaultContentType() { - return "application/x-www-form-urlencoded"; + constructor(opts) { + super({ + name: "InvalidIdentityTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); } }; - -// src/submodules/protocols/query/AwsEc2QueryProtocol.ts -var AwsEc2QueryProtocol = class extends AwsQueryProtocol { - constructor(options) { - super(options); - this.options = options; - const ec2Settings = { - capitalizeKeys: true, - flattenLists: true, - serializeEmptyLists: false - }; - Object.assign(this.serializer.settings, ec2Settings); - } +var AssumeRoleWithWebIdentityRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client2.SENSITIVE_STRING } +}), "AssumeRoleWithWebIdentityRequestFilterSensitiveLog"); +var AssumeRoleWithWebIdentityResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } +}), "AssumeRoleWithWebIdentityResponseFilterSensitiveLog"); +var IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { static { - __name(this, "AwsEc2QueryProtocol"); + __name(this, "IDPCommunicationErrorException"); } + name = "IDPCommunicationErrorException"; + $fault = "client"; /** - * EC2 Query reads XResponse.XResult instead of XResponse directly. + * @internal */ - useNestedResult() { - return false; - } -}; - -// src/submodules/protocols/xml/AwsRestXmlProtocol.ts -var import_protocols6 = __nccwpck_require__(2241); -var import_schema9 = __nccwpck_require__(9826); -var import_util_body_length_browser4 = __nccwpck_require__(713); - -// src/submodules/protocols/xml/parseXmlBody.ts -var import_smithy_client5 = __nccwpck_require__(3570); -var import_fast_xml_parser2 = __nccwpck_require__(4678); -var parseXmlBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - const parser = new import_fast_xml_parser2.XMLParser({ - attributeNamePrefix: "", - htmlEntities: true, - ignoreAttributes: false, - ignoreDeclaration: true, - parseTagValue: false, - trimValues: false, - tagValueProcessor: /* @__PURE__ */ __name((_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, "tagValueProcessor") + constructor(opts) { + super({ + name: "IDPCommunicationErrorException", + $fault: "client", + ...opts }); - parser.addEntity("#xD", "\r"); - parser.addEntity("#10", "\n"); - let parsedObj; - try { - parsedObj = parser.parse(encoded, true); - } catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded - }); - } - throw e; - } - 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, import_smithy_client5.getValueFromTextNode)(parsedObjToReturn); - } - return {}; -}), "parseXmlBody"); -var parseXmlErrorBody = /* @__PURE__ */ __name(async (errorBody, context) => { - const value = await parseXmlBody(errorBody, context); - if (value.Error) { - value.Error.message = value.Error.message ?? value.Error.Message; - } - return value; -}, "parseXmlErrorBody"); -var loadRestXmlErrorCode = /* @__PURE__ */ __name((output, data) => { - if (data?.Error?.Code !== void 0) { - return data.Error.Code; - } - if (data?.Code !== void 0) { - return data.Code; - } - if (output.statusCode == 404) { - return "NotFound"; + Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); } -}, "loadRestXmlErrorCode"); +}; -// src/submodules/protocols/xml/XmlShapeSerializer.ts -var import_xml_builder = __nccwpck_require__(1003); -var import_schema8 = __nccwpck_require__(9826); -var import_serde6 = __nccwpck_require__(7669); -var import_smithy_client6 = __nccwpck_require__(3570); -var import_util_base643 = __nccwpck_require__(5600); -var XmlShapeSerializer = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; - } - static { - __name(this, "XmlShapeSerializer"); - } - stringBuffer; - byteBuffer; - buffer; - write(schema, value) { - const ns = import_schema8.NormalizedSchema.of(schema); - if (ns.isStringSchema() && typeof value === "string") { - this.stringBuffer = value; - } else if (ns.isBlobSchema()) { - this.byteBuffer = "byteLength" in value ? value : (this.serdeContext?.base64Decoder ?? import_util_base643.fromBase64)(value); - } else { - this.buffer = this.writeStruct(ns, value, void 0); - const traits = ns.getMergedTraits(); - if (traits.httpPayload && !traits.xmlName) { - this.buffer.withName(ns.getName()); - } - } - } - flush() { - if (this.byteBuffer !== void 0) { - const bytes = this.byteBuffer; - delete this.byteBuffer; - return bytes; - } - if (this.stringBuffer !== void 0) { - const str = this.stringBuffer; - delete this.stringBuffer; - return str; - } - const buffer = this.buffer; - if (this.settings.xmlNamespace) { - if (!buffer?.attributes?.["xmlns"]) { - buffer.addAttribute("xmlns", this.settings.xmlNamespace); - } - } - delete this.buffer; - return buffer.toString(); - } - writeStruct(ns, value, parentXmlns) { - const traits = ns.getMergedTraits(); - const name = ns.isMemberSchema() && !traits.httpPayload ? ns.getMemberTraits().xmlName ?? ns.getMemberName() : traits.xmlName ?? ns.getName(); - if (!name || !ns.isStructSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName( - true - )}.` - ); - } - const structXmlNode = import_xml_builder.XmlNode.of(name); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - if (xmlns) { - structXmlNode.addAttribute(xmlnsAttr, xmlns); - } - for (const [memberName, memberSchema] of ns.structIterator()) { - const val = value[memberName]; - if (val != null || memberSchema.isIdempotencyToken()) { - if (memberSchema.getMergedTraits().xmlAttribute) { - structXmlNode.addAttribute( - memberSchema.getMergedTraits().xmlName ?? memberName, - this.writeSimple(memberSchema, val) - ); - continue; - } - if (memberSchema.isListSchema()) { - this.writeList(memberSchema, val, structXmlNode, xmlns); - } else if (memberSchema.isMapSchema()) { - this.writeMap(memberSchema, val, structXmlNode, xmlns); - } else if (memberSchema.isStructSchema()) { - structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); - } else { - const memberNode = import_xml_builder.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); - this.writeSimpleInto(memberSchema, val, memberNode, xmlns); - structXmlNode.addChildNode(memberNode); - } - } - } - return structXmlNode; +// src/submodules/sts/protocols/Aws_query.ts +var import_core = __nccwpck_require__(2143); +var import_protocol_http = __nccwpck_require__(4418); +var import_smithy_client3 = __nccwpck_require__(3570); +var se_AssumeRoleCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_AssumeRoleRequest(input, context), + [_A]: _AR, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_AssumeRoleCommand"); +var se_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_AssumeRoleWithWebIdentityRequest(input, context), + [_A]: _ARWWI, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_AssumeRoleWithWebIdentityCommand"); +var de_AssumeRoleCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - writeList(listMember, array, container, parentXmlns) { - if (!listMember.isMemberSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}` - ); - } - const listTraits = listMember.getMergedTraits(); - const listValueSchema = listMember.getValueSchema(); - const listValueTraits = listValueSchema.getMergedTraits(); - const sparse = !!listValueTraits.sparse; - const flat = !!listTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); - const writeItem = /* @__PURE__ */ __name((container2, value) => { - if (listValueSchema.isListSchema()) { - this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container2, xmlns); - } else if (listValueSchema.isMapSchema()) { - this.writeMap(listValueSchema, value, container2, xmlns); - } else if (listValueSchema.isStructSchema()) { - const struct = this.writeStruct(listValueSchema, value, xmlns); - container2.addChildNode( - struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member") - ); - } else { - const listItemNode = import_xml_builder.XmlNode.of( - flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member" - ); - this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); - container2.addChildNode(listItemNode); - } - }, "writeItem"); - if (flat) { - for (const value of array) { - if (sparse || value != null) { - writeItem(container, value); - } - } - } else { - const listNode = import_xml_builder.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); - if (xmlns) { - listNode.addAttribute(xmlnsAttr, xmlns); - } - for (const value of array) { - if (sparse || value != null) { - writeItem(listNode, value); - } - } - container.addChildNode(listNode); - } + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_AssumeRoleResponse(data.AssumeRoleResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_AssumeRoleCommand"); +var de_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { - if (!mapMember.isMemberSchema()) { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}` - ); - } - const mapTraits = mapMember.getMergedTraits(); - const mapKeySchema = mapMember.getKeySchema(); - const mapKeyTraits = mapKeySchema.getMergedTraits(); - const keyTag = mapKeyTraits.xmlName ?? "key"; - const mapValueSchema = mapMember.getValueSchema(); - const mapValueTraits = mapValueSchema.getMergedTraits(); - const valueTag = mapValueTraits.xmlName ?? "value"; - const sparse = !!mapValueTraits.sparse; - const flat = !!mapTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); - const addKeyValue = /* @__PURE__ */ __name((entry, key, val) => { - const keyNode = import_xml_builder.XmlNode.of(keyTag, key); - const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); - if (keyXmlns) { - keyNode.addAttribute(keyXmlnsAttr, keyXmlns); - } - entry.addChildNode(keyNode); - let valueNode = import_xml_builder.XmlNode.of(valueTag); - if (mapValueSchema.isListSchema()) { - this.writeList(mapValueSchema, val, valueNode, xmlns); - } else if (mapValueSchema.isMapSchema()) { - this.writeMap(mapValueSchema, val, valueNode, xmlns, true); - } else if (mapValueSchema.isStructSchema()) { - valueNode = this.writeStruct(mapValueSchema, val, xmlns); - } else { - this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); - } - entry.addChildNode(valueNode); - }, "addKeyValue"); - if (flat) { - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = import_xml_builder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - addKeyValue(entry, key, val); - container.addChildNode(entry); - } - } - } else { - let mapNode; - if (!containerIsMap) { - mapNode = import_xml_builder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - if (xmlns) { - mapNode.addAttribute(xmlnsAttr, xmlns); - } - container.addChildNode(mapNode); - } - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = import_xml_builder.XmlNode.of("entry"); - addKeyValue(entry, key, val); - (containerIsMap ? container : mapNode).addChildNode(entry); - } - } - } + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_AssumeRoleWithWebIdentityCommand"); +var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { + const parsedOutput = { + ...output, + body: await (0, import_core.parseXmlErrorBody)(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); + 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); + default: + const parsedBody = parsedOutput.body; + return throwDefaultError({ + output, + parsedBody: parsedBody.Error, + errorCode + }); } - writeSimple(_schema, value) { - if (null === value) { - throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); - } - const ns = import_schema8.NormalizedSchema.of(_schema); - let nodeContents = null; - if (value && typeof value === "object") { - if (ns.isBlobSchema()) { - nodeContents = (this.serdeContext?.base64Encoder ?? import_util_base643.toBase64)(value); - } else if (ns.isTimestampSchema() && value instanceof Date) { - const options = this.settings.timestampFormat; - const format = options.useTrait ? ns.getSchema() === import_schema8.SCHEMA.TIMESTAMP_DEFAULT ? options.default : ns.getSchema() ?? options.default : options.default; - switch (format) { - case import_schema8.SCHEMA.TIMESTAMP_DATE_TIME: - nodeContents = value.toISOString().replace(".000Z", "Z"); - break; - case import_schema8.SCHEMA.TIMESTAMP_HTTP_DATE: - nodeContents = (0, import_smithy_client6.dateToUtcString)(value); - break; - case import_schema8.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - nodeContents = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using http date", value); - nodeContents = (0, import_smithy_client6.dateToUtcString)(value); - break; - } - } else if (ns.isBigDecimalSchema() && value) { - if (value instanceof import_serde6.NumericValue) { - return value.string; - } - return String(value); - } else if (ns.isMapSchema() || ns.isListSchema()) { - throw new Error( - "@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead." - ); - } else { - throw new Error( - `@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName( - true - )}` - ); - } - } - if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { - nodeContents = String(value); - } - if (ns.isStringSchema()) { - if (value === void 0 && ns.isIdempotencyToken()) { - nodeContents = (0, import_serde6.generateIdempotencyToken)(); - } else { - nodeContents = String(value); - } - } - if (nodeContents === null) { - throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); +}, "de_CommandError"); +var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_ExpiredTokenException(body.Error, context); + const exception = new ExpiredTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_ExpiredTokenExceptionRes"); +var de_IDPCommunicationErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_IDPCommunicationErrorException(body.Error, context); + const exception = new IDPCommunicationErrorException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_IDPCommunicationErrorExceptionRes"); +var de_IDPRejectedClaimExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_IDPRejectedClaimException(body.Error, context); + const exception = new IDPRejectedClaimException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_IDPRejectedClaimExceptionRes"); +var de_InvalidIdentityTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_InvalidIdentityTokenException(body.Error, context); + const exception = new InvalidIdentityTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_InvalidIdentityTokenExceptionRes"); +var de_MalformedPolicyDocumentExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_MalformedPolicyDocumentException(body.Error, context); + const exception = new MalformedPolicyDocumentException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_MalformedPolicyDocumentExceptionRes"); +var de_PackedPolicyTooLargeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_PackedPolicyTooLargeException(body.Error, context); + const exception = new PackedPolicyTooLargeException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_PackedPolicyTooLargeExceptionRes"); +var de_RegionDisabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_RegionDisabledException(body.Error, context); + const exception = new RegionDisabledException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_RegionDisabledExceptionRes"); +var se_AssumeRoleRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_RA] != null) { + entries[_RA] = input[_RA]; + } + if (input[_RSN] != null) { + entries[_RSN] = input[_RSN]; + } + if (input[_PA] != null) { + const memberEntries = se_policyDescriptorListType(input[_PA], context); + if (input[_PA]?.length === 0) { + entries.PolicyArns = []; } - return nodeContents; + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `PolicyArns.${key}`; + entries[loc] = value; + }); } - writeSimpleInto(_schema, value, into, parentXmlns) { - const nodeContents = this.writeSimple(_schema, value); - const ns = import_schema8.NormalizedSchema.of(_schema); - const content = new import_xml_builder.XmlText(nodeContents); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - if (xmlns) { - into.addAttribute(xmlnsAttr, xmlns); + if (input[_P] != null) { + entries[_P] = input[_P]; + } + if (input[_DS] != null) { + entries[_DS] = input[_DS]; + } + if (input[_T] != null) { + const memberEntries = se_tagListType(input[_T], context); + if (input[_T]?.length === 0) { + entries.Tags = []; } - into.addChildNode(content); + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `Tags.${key}`; + entries[loc] = value; + }); } - getXmlnsAttribute(ns, parentXmlns) { - const traits = ns.getMergedTraits(); - const [prefix, xmlns] = traits.xmlNamespace ?? []; - if (xmlns && xmlns !== parentXmlns) { - return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; + if (input[_TTK] != null) { + const memberEntries = se_tagKeyListType(input[_TTK], context); + if (input[_TTK]?.length === 0) { + entries.TransitiveTagKeys = []; } - return [void 0, void 0]; + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `TransitiveTagKeys.${key}`; + entries[loc] = value; + }); } -}; - -// src/submodules/protocols/xml/XmlCodec.ts -var XmlCodec = class extends SerdeContextConfig { - constructor(settings) { - super(); - this.settings = settings; + if (input[_EI] != null) { + entries[_EI] = input[_EI]; } - static { - __name(this, "XmlCodec"); + if (input[_SN] != null) { + entries[_SN] = input[_SN]; } - createSerializer() { - const serializer = new XmlShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; + if (input[_TC] != null) { + entries[_TC] = input[_TC]; } - createDeserializer() { - const deserializer = new XmlShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; + if (input[_SI] != null) { + entries[_SI] = input[_SI]; } -}; - -// src/submodules/protocols/xml/AwsRestXmlProtocol.ts -var AwsRestXmlProtocol = class extends import_protocols6.HttpBindingProtocol { - static { - __name(this, "AwsRestXmlProtocol"); + if (input[_PC] != null) { + const memberEntries = se_ProvidedContextsListType(input[_PC], context); + if (input[_PC]?.length === 0) { + entries.ProvidedContexts = []; + } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `ProvidedContexts.${key}`; + entries[loc] = value; + }); } - codec; - serializer; - deserializer; - constructor(options) { - super(options); - const settings = { - timestampFormat: { - useTrait: true, - default: import_schema9.SCHEMA.TIMESTAMP_DATE_TIME - }, - httpBindings: true, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace - }; - this.codec = new XmlCodec(settings); - this.serializer = new import_protocols6.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new import_protocols6.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + return entries; +}, "se_AssumeRoleRequest"); +var se_AssumeRoleWithWebIdentityRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_RA] != null) { + entries[_RA] = input[_RA]; } - getPayloadCodec() { - return this.codec; + if (input[_RSN] != null) { + entries[_RSN] = input[_RSN]; } - getShapeId() { - return "aws.protocols#restXml"; + if (input[_WIT] != null) { + entries[_WIT] = input[_WIT]; } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const ns = import_schema9.NormalizedSchema.of(operationSchema.input); - const members = ns.getMemberSchemas(); - request.path = String(request.path).split("/").filter((segment) => { - return segment !== "{Bucket}"; - }).join("/") || "/"; - if (!request.headers["content-type"]) { - const httpPayloadMember = Object.values(members).find((m) => { - return !!m.getMergedTraits().httpPayload; - }); - if (httpPayloadMember) { - const mediaType = httpPayloadMember.getMergedTraits().mediaType; - if (mediaType) { - request.headers["content-type"] = mediaType; - } else if (httpPayloadMember.isStringSchema()) { - request.headers["content-type"] = "text/plain"; - } else if (httpPayloadMember.isBlobSchema()) { - request.headers["content-type"] = "application/octet-stream"; - } else { - request.headers["content-type"] = this.getDefaultContentType(); - } - } else if (!ns.isUnitSchema()) { - const hasBody = Object.values(members).find((m) => { - const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); - return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && httpPrefixHeaders === void 0; - }); - if (hasBody) { - request.headers["content-type"] = this.getDefaultContentType(); - } - } - } - if (request.headers["content-type"] === this.getDefaultContentType()) { - if (typeof request.body === "string") { - request.body = '' + request.body; - } + if (input[_PI] != null) { + entries[_PI] = input[_PI]; + } + if (input[_PA] != null) { + const memberEntries = se_policyDescriptorListType(input[_PA], context); + if (input[_PA]?.length === 0) { + entries.PolicyArns = []; } - if (request.body) { - try { - request.headers["content-length"] = String((0, import_util_body_length_browser4.calculateBodyLength)(request.body)); - } catch (e) { - } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `PolicyArns.${key}`; + entries[loc] = value; + }); + } + if (input[_P] != null) { + entries[_P] = input[_P]; + } + if (input[_DS] != null) { + entries[_DS] = input[_DS]; + } + return entries; +}, "se_AssumeRoleWithWebIdentityRequest"); +var se_policyDescriptorListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; } - return request; + const memberEntries = se_PolicyDescriptorType(entry, context); + Object.entries(memberEntries).forEach(([key, value]) => { + entries[`member.${counter}.${key}`] = value; + }); + counter++; } - async deserializeResponse(operationSchema, context, response) { - return super.deserializeResponse(operationSchema, context, response); + return entries; +}, "se_policyDescriptorListType"); +var se_PolicyDescriptorType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_a] != null) { + entries[_a] = input[_a]; } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); + return entries; +}, "se_PolicyDescriptorType"); +var se_ProvidedContext = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_PAr] != null) { + entries[_PAr] = input[_PAr]; + } + if (input[_CA] != null) { + entries[_CA] = input[_CA]; + } + return entries; +}, "se_ProvidedContext"); +var se_ProvidedContextsListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; } - const registry = import_schema9.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorIdentifier); - } catch (e) { - const baseExceptionSchema = import_schema9.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace).getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = baseExceptionSchema.ctor; - throw Object.assign(new ErrorCtor(errorName), dataObject); - } - throw new Error(errorName); + const memberEntries = se_ProvidedContext(entry, context); + Object.entries(memberEntries).forEach(([key, value]) => { + entries[`member.${counter}.${key}`] = value; + }); + counter++; + } + return entries; +}, "se_ProvidedContextsListType"); +var se_Tag = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_K] != null) { + entries[_K] = input[_K]; + } + if (input[_Va] != null) { + entries[_Va] = input[_Va]; + } + return entries; +}, "se_Tag"); +var se_tagKeyListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; } - const ns = import_schema9.NormalizedSchema.of(errorSchema); - const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new errorSchema.ctor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = dataObject.Error?.[target] ?? dataObject[target]; - output[name] = this.codec.createDeserializer().readSchema(member, value); + entries[`member.${counter}`] = entry; + counter++; + } + return entries; +}, "se_tagKeyListType"); +var se_tagListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { + continue; } - Object.assign(exception, { - $metadata: metadata, - $response: response, - $fault: ns.getMergedTraits().error, - message, - ...output + const memberEntries = se_Tag(entry, context); + Object.entries(memberEntries).forEach(([key, value]) => { + entries[`member.${counter}.${key}`] = value; }); - throw exception; + counter++; } - /** - * @override - */ - getDefaultContentType() { - return "application/xml"; + return entries; +}, "se_tagListType"); +var de_AssumedRoleUser = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_ARI] != null) { + contents[_ARI] = (0, import_smithy_client3.expectString)(output[_ARI]); + } + if (output[_Ar] != null) { + contents[_Ar] = (0, import_smithy_client3.expectString)(output[_Ar]); + } + return contents; +}, "de_AssumedRoleUser"); +var de_AssumeRoleResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C], context); + } + if (output[_ARU] != null) { + contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); + } + if (output[_PPS] != null) { + contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); + } + if (output[_SI] != null) { + contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); + } + return contents; +}, "de_AssumeRoleResponse"); +var de_AssumeRoleWithWebIdentityResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C], context); + } + if (output[_SFWIT] != null) { + contents[_SFWIT] = (0, import_smithy_client3.expectString)(output[_SFWIT]); + } + if (output[_ARU] != null) { + contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); + } + if (output[_PPS] != null) { + contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); + } + if (output[_Pr] != null) { + contents[_Pr] = (0, import_smithy_client3.expectString)(output[_Pr]); + } + if (output[_Au] != null) { + contents[_Au] = (0, import_smithy_client3.expectString)(output[_Au]); + } + if (output[_SI] != null) { + contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); + } + return contents; +}, "de_AssumeRoleWithWebIdentityResponse"); +var de_Credentials = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_AKI] != null) { + contents[_AKI] = (0, import_smithy_client3.expectString)(output[_AKI]); + } + if (output[_SAK] != null) { + contents[_SAK] = (0, import_smithy_client3.expectString)(output[_SAK]); + } + if (output[_ST] != null) { + contents[_ST] = (0, import_smithy_client3.expectString)(output[_ST]); + } + if (output[_E] != null) { + contents[_E] = (0, import_smithy_client3.expectNonNull)((0, import_smithy_client3.parseRfc3339DateTimeWithOffset)(output[_E])); + } + return contents; +}, "de_Credentials"); +var de_ExpiredTokenException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_ExpiredTokenException"); +var de_IDPCommunicationErrorException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_IDPCommunicationErrorException"); +var de_IDPRejectedClaimException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_IDPRejectedClaimException"); +var de_InvalidIdentityTokenException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_InvalidIdentityTokenException"); +var de_MalformedPolicyDocumentException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_MalformedPolicyDocumentException"); +var de_PackedPolicyTooLargeException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_PackedPolicyTooLargeException"); +var de_RegionDisabledException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_RegionDisabledException"); +var deserializeMetadata = /* @__PURE__ */ __name((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"] +}), "deserializeMetadata"); +var throwDefaultError = (0, import_smithy_client3.withBaseException)(STSServiceException); +var buildHttpRpcRequest = /* @__PURE__ */ __name(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 !== void 0) { + contents.hostname = resolvedHostname; + } + if (body !== void 0) { + contents.body = body; } + return new import_protocol_http.HttpRequest(contents); +}, "buildHttpRpcRequest"); +var SHARED_HEADERS = { + "content-type": "application/x-www-form-urlencoded" }; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 1003: -/***/ ((module) => { - -"use strict"; +var _ = "2011-06-15"; +var _A = "Action"; +var _AKI = "AccessKeyId"; +var _AR = "AssumeRole"; +var _ARI = "AssumedRoleId"; +var _ARU = "AssumedRoleUser"; +var _ARWWI = "AssumeRoleWithWebIdentity"; +var _Ar = "Arn"; +var _Au = "Audience"; +var _C = "Credentials"; +var _CA = "ContextAssertion"; +var _DS = "DurationSeconds"; +var _E = "Expiration"; +var _EI = "ExternalId"; +var _K = "Key"; +var _P = "Policy"; +var _PA = "PolicyArns"; +var _PAr = "ProviderArn"; +var _PC = "ProvidedContexts"; +var _PI = "ProviderId"; +var _PPS = "PackedPolicySize"; +var _Pr = "Provider"; +var _RA = "RoleArn"; +var _RSN = "RoleSessionName"; +var _SAK = "SecretAccessKey"; +var _SFWIT = "SubjectFromWebIdentityToken"; +var _SI = "SourceIdentity"; +var _SN = "SerialNumber"; +var _ST = "SessionToken"; +var _T = "Tags"; +var _TC = "TokenCode"; +var _TTK = "TransitiveTagKeys"; +var _V = "Version"; +var _Va = "Value"; +var _WIT = "WebIdentityToken"; +var _a = "arn"; +var _m = "message"; +var buildFormUrlencodedString = /* @__PURE__ */ __name((formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client3.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client3.extendedEncodeURIComponent)(value)).join("&"), "buildFormUrlencodedString"); +var loadQueryErrorCode = /* @__PURE__ */ __name((output, data) => { + if (data.Error?.Code !== void 0) { + return data.Error.Code; + } + if (output.statusCode == 404) { + return "NotFound"; + } +}, "loadQueryErrorCode"); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/submodules/sts/commands/AssumeRoleCommand.ts +var AssumeRoleCommand = class extends import_smithy_client4.Command.classBuilder().ep(import_EndpointParameters.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() { + static { + __name(this, "AssumeRoleCommand"); } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - XmlNode: () => XmlNode, - XmlText: () => XmlText -}); -module.exports = __toCommonJS(index_exports); - -// src/escape-attribute.ts -function escapeAttribute(value) { - return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); -} -__name(escapeAttribute, "escapeAttribute"); -// src/escape-element.ts -function escapeElement(value) { - return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">").replace(/\r/g, " ").replace(/\n/g, " ").replace(/\u0085/g, "…").replace(/\u2028/, "
"); -} -__name(escapeElement, "escapeElement"); - -// src/XmlText.ts -var XmlText = class { - constructor(value) { - this.value = value; - } +// src/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.ts +var import_middleware_endpoint2 = __nccwpck_require__(2918); +var import_middleware_serde2 = __nccwpck_require__(1238); +var import_smithy_client5 = __nccwpck_require__(3570); +var import_EndpointParameters2 = __nccwpck_require__(981); +var AssumeRoleWithWebIdentityCommand = class extends import_smithy_client5.Command.classBuilder().ep(import_EndpointParameters2.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde2.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() { static { - __name(this, "XmlText"); - } - toString() { - return escapeElement("" + this.value); + __name(this, "AssumeRoleWithWebIdentityCommand"); } }; -// src/XmlNode.ts -var XmlNode = class _XmlNode { - constructor(name, children = []) { - this.name = name; - this.children = children; - } +// src/submodules/sts/STS.ts +var import_STSClient = __nccwpck_require__(6878); +var commands = { + AssumeRoleCommand, + AssumeRoleWithWebIdentityCommand +}; +var STS = class extends import_STSClient.STSClient { static { - __name(this, "XmlNode"); + __name(this, "STS"); } - attributes = {}; - static of(name, childText, withName) { - const node = new _XmlNode(name); - if (childText !== void 0) { - node.addChildNode(new XmlText(childText)); - } - if (withName !== void 0) { - node.withName(withName); +}; +(0, import_smithy_client6.createAggregatedClient)(commands, STS); + +// src/submodules/sts/index.ts +var import_EndpointParameters3 = __nccwpck_require__(981); + +// src/submodules/sts/defaultStsRoleAssumers.ts +var import_client = __nccwpck_require__(6510); +var ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; +var getAccountIdFromAssumedRoleUser = /* @__PURE__ */ __name((assumedRoleUser) => { + if (typeof assumedRoleUser?.Arn === "string") { + const arnComponents = assumedRoleUser.Arn.split(":"); + if (arnComponents.length > 4 && arnComponents[4] !== "") { + return arnComponents[4]; } - return node; - } - withName(name) { - this.name = name; - return this; - } - addAttribute(name, value) { - this.attributes[name] = value; - return this; - } - addChildNode(child) { - this.children.push(child); - return this; - } - removeAttribute(name) { - delete this.attributes[name]; - return this; - } - /** - * @internal - * Alias of {@link XmlNode#withName(string)} for codegen brevity. - */ - n(name) { - this.name = name; - return this; - } - /** - * @internal - * Alias of {@link XmlNode#addChildNode(string)} for codegen brevity. - */ - c(child) { - this.children.push(child); - return this; } - /** - * @internal - * Checked version of {@link XmlNode#addAttribute(string)} for codegen brevity. - */ - a(name, value) { - if (value != null) { - this.attributes[name] = value; + return void 0; +}, "getAccountIdFromAssumedRoleUser"); +var resolveRegion = /* @__PURE__ */ __name(async (_region, _parentRegion, credentialProviderLogger) => { + const region = typeof _region === "function" ? await _region() : _region; + const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; + credentialProviderLogger?.debug?.( + "@aws-sdk/client-sts::resolveRegion", + "accepting first of:", + `${region} (provider)`, + `${parentRegion} (parent client)`, + `${ASSUME_ROLE_DEFAULT_REGION} (STS default)` + ); + return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION; +}, "resolveRegion"); +var getDefaultRoleAssumer = /* @__PURE__ */ __name((stsOptions, STSClient3) => { + let stsClient; + let closureSourceCreds; + return async (sourceCreds, params) => { + closureSourceCreds = sourceCreds; + if (!stsClient) { + const { + logger = stsOptions?.parentClientConfig?.logger, + region, + requestHandler = stsOptions?.parentClientConfig?.requestHandler, + credentialProviderLogger + } = stsOptions; + const resolvedRegion = await resolveRegion( + region, + stsOptions?.parentClientConfig?.region, + credentialProviderLogger + ); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient3({ + profile: stsOptions?.parentClientConfig?.profile, + // A hack to make sts client uses the credential in current closure. + credentialDefaultProvider: /* @__PURE__ */ __name(() => async () => closureSourceCreds, "credentialDefaultProvider"), + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, + logger + }); } - return this; - } - /** - * Create a child node. - * Used in serialization of string fields. - * @internal - */ - cc(input, field, withName = field) { - if (input[field] != null) { - const node = _XmlNode.of(field, input[field]).withName(withName); - this.c(node); + const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleCommand(params)); + if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); } - } - /** - * Creates list child nodes. - * @internal - */ - l(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - nodes.map((node) => { - node.withName(memberName); - this.c(node); + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); + const credentials = { + accessKeyId: Credentials2.AccessKeyId, + secretAccessKey: Credentials2.SecretAccessKey, + sessionToken: Credentials2.SessionToken, + expiration: Credentials2.Expiration, + // TODO(credentialScope): access normally when shape is updated. + ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, + ...accountId && { accountId } + }; + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); + return credentials; + }; +}, "getDefaultRoleAssumer"); +var getDefaultRoleAssumerWithWebIdentity = /* @__PURE__ */ __name((stsOptions, STSClient3) => { + let stsClient; + return async (params) => { + if (!stsClient) { + const { + logger = stsOptions?.parentClientConfig?.logger, + region, + requestHandler = stsOptions?.parentClientConfig?.requestHandler, + credentialProviderLogger + } = stsOptions; + const resolvedRegion = await resolveRegion( + region, + stsOptions?.parentClientConfig?.region, + credentialProviderLogger + ); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient3({ + profile: stsOptions?.parentClientConfig?.profile, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, + logger }); } - } - /** - * Creates list child nodes with container. - * @internal - */ - lc(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - const containerNode = new _XmlNode(memberName); - nodes.map((node) => { - containerNode.c(node); - }); - this.c(containerNode); + const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); + if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); } - } - toString() { - const hasChildren = Boolean(this.children.length); - let xmlText = `<${this.name}`; - const attributes = this.attributes; - for (const attributeName of Object.keys(attributes)) { - const attribute = attributes[attributeName]; - if (attribute != null) { - xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; - } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); + const credentials = { + accessKeyId: Credentials2.AccessKeyId, + secretAccessKey: Credentials2.SecretAccessKey, + sessionToken: Credentials2.SessionToken, + expiration: Credentials2.Expiration, + // TODO(credentialScope): access normally when shape is updated. + ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, + ...accountId && { accountId } + }; + if (accountId) { + (0, import_client.setCredentialFeature)(credentials, "RESOLVED_ACCOUNT_ID", "T"); } - return xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`; - } -}; -// Annotate the CommonJS export names for ESM import in node: + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); + return credentials; + }; +}, "getDefaultRoleAssumerWithWebIdentity"); +var isH2 = /* @__PURE__ */ __name((requestHandler) => { + return requestHandler?.metadata?.handlerProtocol === "h2"; +}, "isH2"); +// src/submodules/sts/defaultRoleAssumers.ts +var import_STSClient2 = __nccwpck_require__(6878); +var getCustomizableStsClientCtor = /* @__PURE__ */ __name((baseCtor, customizations) => { + if (!customizations) return baseCtor; + else + return class CustomizableSTSClient extends baseCtor { + static { + __name(this, "CustomizableSTSClient"); + } + constructor(config) { + super(config); + for (const customization of customizations) { + this.middlewareStack.use(customization); + } + } + }; +}, "getCustomizableStsClientCtor"); +var getDefaultRoleAssumer2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumer"); +var getDefaultRoleAssumerWithWebIdentity2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumerWithWebIdentity"); +var decorateDefaultCredentialProvider = /* @__PURE__ */ __name((provider) => (input) => provider({ + roleAssumer: getDefaultRoleAssumer2(input), + roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input), + ...input +}), "decorateDefaultCredentialProvider"); +// Annotate the CommonJS export names for ESM import in node: 0 && (0); - /***/ }), -/***/ 2545: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 302: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getHostHeaderPlugin: () => getHostHeaderPlugin, - hostHeaderMiddleware: () => hostHeaderMiddleware, - hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions, - resolveHostHeaderConfig: () => resolveHostHeaderConfig -}); -module.exports = __toCommonJS(index_exports); -var import_protocol_http = __nccwpck_require__(4418); -function resolveHostHeaderConfig(input) { - return input; -} -__name(resolveHostHeaderConfig, "resolveHostHeaderConfig"); -var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { - if (!import_protocol_http.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); -}, "hostHeaderMiddleware"); -var hostHeaderMiddlewareOptions = { - name: "hostHeaderMiddleware", - step: "build", - priority: "low", - tags: ["HOST"], - override: true +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__(4178)); +const core_1 = __nccwpck_require__(2143); +const util_user_agent_node_1 = __nccwpck_require__(7330); +const config_resolver_1 = __nccwpck_require__(3098); +const core_2 = __nccwpck_require__(5829); +const hash_node_1 = __nccwpck_require__(3081); +const middleware_retry_1 = __nccwpck_require__(6039); +const node_config_provider_1 = __nccwpck_require__(3461); +const node_http_handler_1 = __nccwpck_require__(258); +const util_body_length_node_1 = __nccwpck_require__(8075); +const util_retry_1 = __nccwpck_require__(4902); +const runtimeConfig_shared_1 = __nccwpck_require__(9165); +const smithy_client_1 = __nccwpck_require__(3570); +const util_defaults_mode_node_1 = __nccwpck_require__(2429); +const smithy_client_2 = __nccwpck_require__(3570); +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); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || + (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, + }, config), + 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, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; }; -var getHostHeaderPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); - }, "applyToStack") -}), "getHostHeaderPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +exports.getRuntimeConfig = getRuntimeConfig; /***/ }), -/***/ 2098: -/***/ ((module) => { +/***/ 9165: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - getLocationConstraintPlugin: () => getLocationConstraintPlugin, - locationConstraintMiddleware: () => locationConstraintMiddleware, - locationConstraintMiddlewareOptions: () => locationConstraintMiddlewareOptions -}); -module.exports = __toCommonJS(index_exports); -function locationConstraintMiddleware(options) { - return (next) => async (args) => { - const { CreateBucketConfiguration } = args.input; - const region = await options.region(); - if (!CreateBucketConfiguration?.LocationConstraint && !CreateBucketConfiguration?.Location) { - args = { - ...args, - input: { - ...args.input, - CreateBucketConfiguration: region === "us-east-1" ? void 0 : { LocationConstraint: region } - } - }; - } - return next(args); - }; -} -__name(locationConstraintMiddleware, "locationConstraintMiddleware"); -var locationConstraintMiddlewareOptions = { - step: "initialize", - tags: ["LOCATION_CONSTRAINT", "CREATE_BUCKET_CONFIGURATION"], - name: "locationConstraintMiddleware", - override: true +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const core_1 = __nccwpck_require__(2143); +const core_2 = __nccwpck_require__(5829); +const smithy_client_1 = __nccwpck_require__(3570); +const url_parser_1 = __nccwpck_require__(4681); +const util_base64_1 = __nccwpck_require__(5600); +const util_utf8_1 = __nccwpck_require__(1895); +const httpAuthSchemeProvider_1 = __nccwpck_require__(3061); +const endpointResolver_1 = __nccwpck_require__(8181); +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 ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + 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, + }; }; -var getLocationConstraintPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(locationConstraintMiddleware(config), locationConstraintMiddlewareOptions); - }, "applyToStack") -}), "getLocationConstraintPlugin"); -// Annotate the CommonJS export names for ESM import in node: +exports.getRuntimeConfig = getRuntimeConfig; -0 && (0); +/***/ }), + +/***/ 9913: +/***/ ((__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__(6976); +const protocol_http_1 = __nccwpck_require__(4418); +const smithy_client_1 = __nccwpck_require__(3570); +const httpAuthExtensionConfiguration_1 = __nccwpck_require__(1746); +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); +}; +exports.resolveRuntimeExtensions = resolveRuntimeExtensions; /***/ }), -/***/ 14: +/***/ 6976: /***/ ((module) => { "use strict"; @@ -49634,54 +33545,76 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - getLoggerPlugin: () => getLoggerPlugin, - loggerMiddleware: () => loggerMiddleware, - loggerMiddlewareOptions: () => loggerMiddlewareOptions + NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, + NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, + REGION_ENV_NAME: () => REGION_ENV_NAME, + REGION_INI_NAME: () => REGION_INI_NAME, + getAwsRegionExtensionConfiguration: () => getAwsRegionExtensionConfiguration, + resolveAwsRegionExtensionConfiguration: () => resolveAwsRegionExtensionConfiguration, + resolveRegionConfig: () => resolveRegionConfig }); module.exports = __toCommonJS(index_exports); -// src/loggerMiddleware.ts -var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => { - try { - const response = await next(args); - const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; - const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; - const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; - const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; - const { $metadata, ...outputWithoutMetadata } = response.output; - logger?.info?.({ - 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 ?? context.inputFilterSensitiveLog; - logger?.error?.({ - clientName, - commandName, - input: inputFilterSensitiveLog(args.input), - error, - metadata: error.$metadata - }); - throw error; - } -}, "loggerMiddleware"); -var loggerMiddlewareOptions = { - name: "loggerMiddleware", - tags: ["LOGGER"], - step: "initialize", - override: true +// src/extensions/index.ts +var getAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setRegion(region) { + runtimeConfig.region = region; + }, + region() { + return runtimeConfig.region; + } + }; +}, "getAwsRegionExtensionConfiguration"); +var resolveAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => { + return { + region: awsRegionExtensionConfiguration.region() + }; +}, "resolveAwsRegionExtensionConfiguration"); + +// src/regionConfig/config.ts +var REGION_ENV_NAME = "AWS_REGION"; +var REGION_INI_NAME = "region"; +var NODE_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: /* @__PURE__ */ __name((env) => env[REGION_ENV_NAME], "environmentVariableSelector"), + configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"), + default: /* @__PURE__ */ __name(() => { + throw new Error("Region is missing"); + }, "default") }; -var getLoggerPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); - }, "applyToStack") -}), "getLoggerPlugin"); +var NODE_REGION_CONFIG_FILE_OPTIONS = { + preferredFile: "credentials" +}; + +// src/regionConfig/isFipsRegion.ts +var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); + +// src/regionConfig/getRealRegion.ts +var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); + +// src/regionConfig/resolveRegionConfig.ts +var resolveRegionConfig = /* @__PURE__ */ __name((input) => { + const { region, useFipsEndpoint } = input; + if (!region) { + throw new Error("Region is missing"); + } + return Object.assign(input, { + region: /* @__PURE__ */ __name(async () => { + if (typeof region === "string") { + return getRealRegion(region); + } + const providedRegion = await region(); + return getRealRegion(providedRegion); + }, "region"), + useFipsEndpoint: /* @__PURE__ */ __name(async () => { + const providedRegion = typeof region === "string" ? region : await region(); + if (isFipsRegion(providedRegion)) { + return true; + } + return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); + }, "useFipsEndpoint") + }); +}, "resolveRegionConfig"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -49690,14 +33623,16 @@ var getLoggerPlugin = /* @__PURE__ */ __name((options) => ({ /***/ }), -/***/ 5525: +/***/ 7182: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -49712,726 +33647,797 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - addRecursionDetectionMiddlewareOptions: () => addRecursionDetectionMiddlewareOptions, - getRecursionDetectionPlugin: () => getRecursionDetectionPlugin, - recursionDetectionMiddleware: () => recursionDetectionMiddleware + fromEnvSigningName: () => fromEnvSigningName, + fromSso: () => fromSso, + fromStatic: () => fromStatic, + nodeProvider: () => nodeProvider }); module.exports = __toCommonJS(index_exports); -var import_protocol_http = __nccwpck_require__(4418); -var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; -var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; -var ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; -var recursionDetectionMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { - const { request } = args; - if (!import_protocol_http.HttpRequest.isInstance(request) || options.runtime !== "node") { - return next(args); - } - const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME; - if (request.headers.hasOwnProperty(traceIdHeader)) { - return next(args); + +// src/fromEnvSigningName.ts +var import_client = __nccwpck_require__(6510); +var import_httpAuthSchemes = __nccwpck_require__(3017); +var import_property_provider = __nccwpck_require__(9721); +var fromEnvSigningName = /* @__PURE__ */ __name(({ logger, signingName } = {}) => async () => { + logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); + if (!signingName) { + throw new import_property_provider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); } - const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; - const traceId = process.env[ENV_TRACE_ID]; - const nonEmptyString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0, "nonEmptyString"); - if (nonEmptyString(functionName) && nonEmptyString(traceId)) { - request.headers[TRACE_ID_HEADER_NAME] = traceId; + const bearerTokenKey = (0, import_httpAuthSchemes.getBearerTokenEnvKey)(signingName); + if (!(bearerTokenKey in process.env)) { + throw new import_property_provider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); } - return next({ - ...args, - request - }); -}, "recursionDetectionMiddleware"); -var addRecursionDetectionMiddlewareOptions = { - step: "build", - tags: ["RECURSION_DETECTION"], - name: "recursionDetectionMiddleware", - override: true, - priority: "low" -}; -var getRecursionDetectionPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions); - }, "applyToStack") -}), "getRecursionDetectionPlugin"); -// Annotate the CommonJS export names for ESM import in node: + const token = { token: process.env[bearerTokenKey] }; + (0, import_client.setTokenFeature)(token, "BEARER_SERVICE_ENV_VARS", "3"); + return token; +}, "fromEnvSigningName"); -0 && (0); +// src/fromSso.ts -/***/ }), +// src/constants.ts +var EXPIRE_WINDOW_MS = 5 * 60 * 1e3; +var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; -/***/ 1139: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// src/getSsoOidcClient.ts +var getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion, init = {}) => { + const { SSOOIDCClient } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(8959))); + const ssoOidcClient = new SSOOIDCClient( + Object.assign({}, init.clientConfig ?? {}, { + region: ssoRegion ?? init.clientConfig?.region, + logger: init.clientConfig?.logger ?? init.parentClientConfig?.logger + }) + ); + return ssoOidcClient; +}, "getSsoOidcClient"); -"use strict"; +// src/getNewSsoOidcToken.ts +var getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion, init = {}) => { + const { CreateTokenCommand } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(8959))); + const ssoOidcClient = await getSsoOidcClient(ssoRegion, init); + return ssoOidcClient.send( + new CreateTokenCommand({ + clientId: ssoToken.clientId, + clientSecret: ssoToken.clientSecret, + refreshToken: ssoToken.refreshToken, + grantType: "refresh_token" + }) + ); +}, "getNewSsoOidcToken"); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/validateTokenExpiry.ts + +var validateTokenExpiry = /* @__PURE__ */ __name((token) => { + if (token.expiration && token.expiration.getTime() < Date.now()) { + throw new import_property_provider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +}, "validateTokenExpiry"); -// src/index.ts -var index_exports = {}; -__export(index_exports, { - NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS: () => NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS, - S3ExpressIdentityCache: () => S3ExpressIdentityCache, - S3ExpressIdentityCacheEntry: () => S3ExpressIdentityCacheEntry, - S3ExpressIdentityProviderImpl: () => S3ExpressIdentityProviderImpl, - SignatureV4S3Express: () => SignatureV4S3Express, - checkContentLengthHeader: () => checkContentLengthHeader, - checkContentLengthHeaderMiddlewareOptions: () => checkContentLengthHeaderMiddlewareOptions, - getCheckContentLengthHeaderPlugin: () => getCheckContentLengthHeaderPlugin, - getRegionRedirectMiddlewarePlugin: () => getRegionRedirectMiddlewarePlugin, - getS3ExpiresMiddlewarePlugin: () => getS3ExpiresMiddlewarePlugin, - getS3ExpressHttpSigningPlugin: () => getS3ExpressHttpSigningPlugin, - getS3ExpressPlugin: () => getS3ExpressPlugin, - getThrow200ExceptionsPlugin: () => getThrow200ExceptionsPlugin, - getValidateBucketNamePlugin: () => getValidateBucketNamePlugin, - regionRedirectEndpointMiddleware: () => regionRedirectEndpointMiddleware, - regionRedirectEndpointMiddlewareOptions: () => regionRedirectEndpointMiddlewareOptions, - regionRedirectMiddleware: () => regionRedirectMiddleware, - regionRedirectMiddlewareOptions: () => regionRedirectMiddlewareOptions, - resolveS3Config: () => resolveS3Config, - s3ExpiresMiddleware: () => s3ExpiresMiddleware, - s3ExpiresMiddlewareOptions: () => s3ExpiresMiddlewareOptions, - s3ExpressHttpSigningMiddleware: () => s3ExpressHttpSigningMiddleware, - s3ExpressHttpSigningMiddlewareOptions: () => s3ExpressHttpSigningMiddlewareOptions, - s3ExpressMiddleware: () => s3ExpressMiddleware, - s3ExpressMiddlewareOptions: () => s3ExpressMiddlewareOptions, - throw200ExceptionsMiddleware: () => throw200ExceptionsMiddleware, - throw200ExceptionsMiddlewareOptions: () => throw200ExceptionsMiddlewareOptions, - validateBucketNameMiddleware: () => validateBucketNameMiddleware, - validateBucketNameMiddlewareOptions: () => validateBucketNameMiddlewareOptions -}); -module.exports = __toCommonJS(index_exports); +// src/validateTokenKey.ts -// src/check-content-length-header.ts -var import_protocol_http = __nccwpck_require__(4418); -var import_smithy_client = __nccwpck_require__(3570); -var CONTENT_LENGTH_HEADER = "content-length"; -var DECODED_CONTENT_LENGTH_HEADER = "x-amz-decoded-content-length"; -function checkContentLengthHeader() { - return (next, context) => async (args) => { - const { request } = args; - if (import_protocol_http.HttpRequest.isInstance(request)) { - if (!(CONTENT_LENGTH_HEADER in request.headers) && !(DECODED_CONTENT_LENGTH_HEADER in request.headers)) { - const message = `Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.`; - if (typeof context?.logger?.warn === "function" && !(context.logger instanceof import_smithy_client.NoOpLogger)) { - context.logger.warn(message); - } else { - console.warn(message); - } - } +var validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => { + if (typeof value === "undefined") { + throw new import_property_provider.TokenProviderError( + `Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, + false + ); + } +}, "validateTokenKey"); + +// src/writeSSOTokenToFile.ts +var import_shared_ini_file_loader = __nccwpck_require__(3507); +var import_fs = __nccwpck_require__(7147); +var { writeFile } = import_fs.promises; +var writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => { + const tokenFilepath = (0, import_shared_ini_file_loader.getSSOTokenFilepath)(id); + const tokenString = JSON.stringify(ssoToken, null, 2); + return writeFile(tokenFilepath, tokenString); +}, "writeSSOTokenToFile"); + +// src/fromSso.ts +var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0); +var fromSso = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { + const init = { + ..._init, + parentClientConfig: { + ...callerClientConfig, + ..._init.parentClientConfig } - return next({ ...args }); }; -} -__name(checkContentLengthHeader, "checkContentLengthHeader"); -var checkContentLengthHeaderMiddlewareOptions = { - step: "finalizeRequest", - tags: ["CHECK_CONTENT_LENGTH_HEADER"], - name: "getCheckContentLengthHeaderPlugin", - override: true -}; -var getCheckContentLengthHeaderPlugin = /* @__PURE__ */ __name((unused) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(checkContentLengthHeader(), checkContentLengthHeaderMiddlewareOptions); - }, "applyToStack") -}), "getCheckContentLengthHeaderPlugin"); - -// src/region-redirect-endpoint-middleware.ts -var regionRedirectEndpointMiddleware = /* @__PURE__ */ __name((config) => { - return (next, context) => async (args) => { - const originalRegion = await config.region(); - const regionProviderRef = config.region; - let unlock = /* @__PURE__ */ __name(() => { - }, "unlock"); - if (context.__s3RegionRedirect) { - Object.defineProperty(config, "region", { - writable: false, - value: /* @__PURE__ */ __name(async () => { - return context.__s3RegionRedirect; - }, "value") - }); - unlock = /* @__PURE__ */ __name(() => Object.defineProperty(config, "region", { - writable: true, - value: regionProviderRef - }), "unlock"); + init.logger?.debug("@aws-sdk/token-providers - fromSso"); + const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); + const profileName = (0, import_shared_ini_file_loader.getProfileName)({ + profile: init.profile ?? callerClientConfig?.profile + }); + const profile = profiles[profileName]; + if (!profile) { + throw new import_property_provider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); + } else if (!profile["sso_session"]) { + throw new import_property_provider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); + } + const ssoSessionName = profile["sso_session"]; + const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init); + const ssoSession = ssoSessions[ssoSessionName]; + if (!ssoSession) { + throw new import_property_provider.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 import_property_provider.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, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoSessionName); + } catch (e) { + throw new import_property_provider.TokenProviderError( + `The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, + false + ); + } + validateTokenKey("accessToken", ssoToken.accessToken); + validateTokenKey("expiresAt", ssoToken.expiresAt); + const { accessToken, expiresAt } = ssoToken; + const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; + if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { + return existingToken; + } + if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) { + validateTokenExpiry(existingToken); + return existingToken; + } + validateTokenKey("clientId", ssoToken.clientId, true); + validateTokenKey("clientSecret", ssoToken.clientSecret, true); + validateTokenKey("refreshToken", ssoToken.refreshToken, true); + try { + lastRefreshAttemptTime.setTime(Date.now()); + const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init); + validateTokenKey("accessToken", newSsoOidcToken.accessToken); + validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); + const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3); try { - const result = await next(args); - if (context.__s3RegionRedirect) { - unlock(); - const region = await config.region(); - if (originalRegion !== region) { - throw new Error("Region was not restored following S3 region redirect."); - } - } - return result; - } catch (e) { - unlock(); - throw e; + await writeSSOTokenToFile(ssoSessionName, { + ...ssoToken, + accessToken: newSsoOidcToken.accessToken, + expiresAt: newTokenExpiration.toISOString(), + refreshToken: newSsoOidcToken.refreshToken + }); + } catch (error) { } - }; -}, "regionRedirectEndpointMiddleware"); -var regionRedirectEndpointMiddlewareOptions = { - tags: ["REGION_REDIRECT", "S3"], - name: "regionRedirectEndpointMiddleware", - override: true, - relation: "before", - toMiddleware: "endpointV2Middleware" -}; + return { + token: newSsoOidcToken.accessToken, + expiration: newTokenExpiration + }; + } catch (error) { + validateTokenExpiry(existingToken); + return existingToken; + } +}, "fromSso"); + +// src/fromStatic.ts + +var fromStatic = /* @__PURE__ */ __name(({ token, logger }) => async () => { + logger?.debug("@aws-sdk/token-providers - fromStatic"); + if (!token || !token.token) { + throw new import_property_provider.TokenProviderError(`Please pass a valid token to fromStatic`, false); + } + return token; +}, "fromStatic"); + +// src/nodeProvider.ts + +var nodeProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( + (0, import_property_provider.chain)(fromSso(init), async () => { + throw new import_property_provider.TokenProviderError("Could not load token from any providers", false); + }), + (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5, + (token) => token.expiration !== void 0 +), "nodeProvider"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), -// src/region-redirect-middleware.ts -function regionRedirectMiddleware(clientConfig) { - return (next, context) => async (args) => { - try { - return await next(args); - } catch (err) { - if (clientConfig.followRegionRedirects) { - if (err?.$metadata?.httpStatusCode === 301 || // err.name === "PermanentRedirect" && --> removing the error name check, as that allows for HEAD operations (which have the 301 status code, but not the same error name) to be covered for region redirection as well - err?.$metadata?.httpStatusCode === 400 && err?.name === "IllegalLocationConstraintException") { - try { - const actualRegion = err.$response.headers["x-amz-bucket-region"]; - context.logger?.debug(`Redirecting from ${await clientConfig.region()} to ${actualRegion}`); - context.__s3RegionRedirect = actualRegion; - } catch (e) { - throw new Error("Region redirect failed: " + e); - } - return next(args); - } - } - throw err; - } - }; -} -__name(regionRedirectMiddleware, "regionRedirectMiddleware"); -var regionRedirectMiddlewareOptions = { - step: "initialize", - tags: ["REGION_REDIRECT", "S3"], - name: "regionRedirectMiddleware", - override: true +/***/ 4241: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var getRegionRedirectMiddlewarePlugin = /* @__PURE__ */ __name((clientConfig) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(regionRedirectMiddleware(clientConfig), regionRedirectMiddlewareOptions); - clientStack.addRelativeTo(regionRedirectEndpointMiddleware(clientConfig), regionRedirectEndpointMiddlewareOptions); - }, "applyToStack") -}), "getRegionRedirectMiddlewarePlugin"); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/s3-expires-middleware.ts +// src/index.ts +var index_exports = {}; +__export(index_exports, { + ConditionObject: () => import_util_endpoints.ConditionObject, + DeprecatedObject: () => import_util_endpoints.DeprecatedObject, + EndpointError: () => import_util_endpoints.EndpointError, + EndpointObject: () => import_util_endpoints.EndpointObject, + EndpointObjectHeaders: () => import_util_endpoints.EndpointObjectHeaders, + EndpointObjectProperties: () => import_util_endpoints.EndpointObjectProperties, + EndpointParams: () => import_util_endpoints.EndpointParams, + EndpointResolverOptions: () => import_util_endpoints.EndpointResolverOptions, + EndpointRuleObject: () => import_util_endpoints.EndpointRuleObject, + ErrorRuleObject: () => import_util_endpoints.ErrorRuleObject, + EvaluateOptions: () => import_util_endpoints.EvaluateOptions, + Expression: () => import_util_endpoints.Expression, + FunctionArgv: () => import_util_endpoints.FunctionArgv, + FunctionObject: () => import_util_endpoints.FunctionObject, + FunctionReturn: () => import_util_endpoints.FunctionReturn, + ParameterObject: () => import_util_endpoints.ParameterObject, + ReferenceObject: () => import_util_endpoints.ReferenceObject, + ReferenceRecord: () => import_util_endpoints.ReferenceRecord, + RuleSetObject: () => import_util_endpoints.RuleSetObject, + RuleSetRules: () => import_util_endpoints.RuleSetRules, + TreeRuleObject: () => import_util_endpoints.TreeRuleObject, + awsEndpointFunctions: () => awsEndpointFunctions, + getUserAgentPrefix: () => getUserAgentPrefix, + isIpAddress: () => import_util_endpoints.isIpAddress, + partition: () => partition, + resolveDefaultAwsRegionalEndpointsConfig: () => resolveDefaultAwsRegionalEndpointsConfig, + resolveEndpoint: () => import_util_endpoints.resolveEndpoint, + setPartitionInfo: () => setPartitionInfo, + toEndpointV1: () => toEndpointV1, + useDefaultPartitionInfo: () => useDefaultPartitionInfo +}); +module.exports = __toCommonJS(index_exports); +// src/aws.ts -var s3ExpiresMiddleware = /* @__PURE__ */ __name((config) => { - return (next, context) => async (args) => { - const result = await next(args); - const { response } = result; - if (import_protocol_http.HttpResponse.isInstance(response)) { - if (response.headers.expires) { - response.headers.expiresstring = response.headers.expires; - try { - (0, import_smithy_client.parseRfc7231DateTime)(response.headers.expires); - } catch (e) { - context.logger?.warn( - `AWS SDK Warning for ${context.clientName}::${context.commandName} response parsing (${response.headers.expires}): ${e}` - ); - delete response.headers.expires; - } + +// src/lib/aws/isVirtualHostableS3Bucket.ts + + +// src/lib/isIpAddress.ts +var import_util_endpoints = __nccwpck_require__(5473); + +// src/lib/aws/isVirtualHostableS3Bucket.ts +var isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => { + if (allowSubDomains) { + for (const label of value.split(".")) { + if (!isVirtualHostableS3Bucket(label)) { + return false; } } - return result; - }; -}, "s3ExpiresMiddleware"); -var s3ExpiresMiddlewareOptions = { - tags: ["S3"], - name: "s3ExpiresMiddleware", - override: true, - relation: "after", - toMiddleware: "deserializerMiddleware" -}; -var getS3ExpiresMiddlewarePlugin = /* @__PURE__ */ __name((clientConfig) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo(s3ExpiresMiddleware(clientConfig), s3ExpiresMiddlewareOptions); - }, "applyToStack") -}), "getS3ExpiresMiddlewarePlugin"); - -// src/s3-express/classes/S3ExpressIdentityCache.ts -var S3ExpressIdentityCache = class _S3ExpressIdentityCache { - constructor(data = {}) { - this.data = data; + return true; } - static { - __name(this, "S3ExpressIdentityCache"); + if (!(0, import_util_endpoints.isValidHostLabel)(value)) { + return false; } - lastPurgeTime = Date.now(); - static EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS = 3e4; - get(key) { - const entry = this.data[key]; - if (!entry) { - return; - } - return entry; + if (value.length < 3 || value.length > 63) { + return false; } - set(key, entry) { - this.data[key] = entry; - return entry; + if (value !== value.toLowerCase()) { + return false; } - delete(key) { - delete this.data[key]; + if ((0, import_util_endpoints.isIpAddress)(value)) { + return false; } - async purgeExpired() { - const now = Date.now(); - if (this.lastPurgeTime + _S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS > now) { - return; + return true; +}, "isVirtualHostableS3Bucket"); + +// src/lib/aws/parseArn.ts +var ARN_DELIMITER = ":"; +var RESOURCE_DELIMITER = "/"; +var parseArn = /* @__PURE__ */ __name((value) => { + const segments = value.split(ARN_DELIMITER); + if (segments.length < 6) return null; + const [arn, partition2, service, region, accountId, ...resourcePath] = segments; + if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null; + const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); + return { + partition: partition2, + service, + region, + accountId, + resourceId + }; +}, "parseArn"); + +// src/lib/aws/partitions.json +var partitions_default = { + 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|mx)\\-\\w+\\-\\d+$", + regions: { + "af-south-1": { + description: "Africa (Cape Town)" + }, + "ap-east-1": { + description: "Asia Pacific (Hong Kong)" + }, + "ap-east-2": { + description: "Asia Pacific (Taipei)" + }, + "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)" + }, + "ap-southeast-5": { + description: "Asia Pacific (Malaysia)" + }, + "ap-southeast-7": { + description: "Asia Pacific (Thailand)" + }, + "aws-global": { + description: "AWS Standard global region" + }, + "ca-central-1": { + description: "Canada (Central)" + }, + "ca-west-1": { + description: "Canada West (Calgary)" + }, + "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)" + }, + "mx-central-1": { + description: "Mexico (Central)" + }, + "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)" + } } - for (const key in this.data) { - const entry = this.data[key]; - if (!entry.isRefreshing) { - const credential = await entry.identity; - if (credential.expiration) { - if (credential.expiration.getTime() < now) { - delete this.data[key]; - } - } + }, { + 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)" } } - } -}; - -// src/s3-express/classes/S3ExpressIdentityCacheEntry.ts -var S3ExpressIdentityCacheEntry = class { - /** - * @param identity - stored identity. - * @param accessed - timestamp of last access in epoch ms. - * @param isRefreshing - this key is currently in the process of being refreshed (background). - */ - constructor(_identity, isRefreshing = false, accessed = Date.now()) { - this._identity = _identity; - this.isRefreshing = isRefreshing; - this.accessed = accessed; - } - static { - __name(this, "S3ExpressIdentityCacheEntry"); - } - get identity() { - this.accessed = Date.now(); - return this._identity; - } + }, { + 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: { + "aws-iso-e-global": { + description: "AWS ISOE (Europe) global region" + }, + "eu-isoe-west-1": { + description: "EU ISOE West" + } + } + }, { + 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: { + "aws-iso-f-global": { + description: "AWS ISOF global region" + }, + "us-isof-east-1": { + description: "US ISOF EAST" + }, + "us-isof-south-1": { + description: "US ISOF SOUTH" + } + } + }, { + id: "aws-eusc", + outputs: { + dnsSuffix: "amazonaws.eu", + dualStackDnsSuffix: "amazonaws.eu", + implicitGlobalRegion: "eusc-de-east-1", + name: "aws-eusc", + supportsDualStack: false, + supportsFIPS: true + }, + regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", + regions: { + "eusc-de-east-1": { + description: "EU (Germany)" + } + } + }], + version: "1.1" }; -// src/s3-express/classes/S3ExpressIdentityProviderImpl.ts -var S3ExpressIdentityProviderImpl = class _S3ExpressIdentityProviderImpl { - constructor(createSessionFn, cache = new S3ExpressIdentityCache()) { - this.createSessionFn = createSessionFn; - this.cache = cache; - } - static { - __name(this, "S3ExpressIdentityProviderImpl"); - } - static REFRESH_WINDOW_MS = 6e4; - async getS3ExpressIdentity(awsIdentity, identityProperties) { - const key = identityProperties.Bucket; - const { cache } = this; - const entry = cache.get(key); - if (entry) { - return entry.identity.then((identity) => { - const isExpired = (identity.expiration?.getTime() ?? 0) < Date.now(); - if (isExpired) { - return cache.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity; - } - const isExpiringSoon = (identity.expiration?.getTime() ?? 0) < Date.now() + _S3ExpressIdentityProviderImpl.REFRESH_WINDOW_MS; - if (isExpiringSoon && !entry.isRefreshing) { - entry.isRefreshing = true; - this.getIdentity(key).then((id) => { - cache.set(key, new S3ExpressIdentityCacheEntry(Promise.resolve(id))); - }); - } - return identity; - }); +// src/lib/aws/partition.ts +var selectedPartitionsInfo = partitions_default; +var selectedUserAgentPrefix = ""; +var partition = /* @__PURE__ */ __name((value) => { + const { partitions } = selectedPartitionsInfo; + for (const partition2 of partitions) { + const { regions, outputs } = partition2; + for (const [region, regionData] of Object.entries(regions)) { + if (region === value) { + return { + ...outputs, + ...regionData + }; + } } - return cache.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity; } - async getIdentity(key) { - await this.cache.purgeExpired().catch((error) => { - console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n" + error); - }); - const session = await this.createSessionFn(key); - if (!session.Credentials?.AccessKeyId || !session.Credentials?.SecretAccessKey) { - throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey."); + for (const partition2 of partitions) { + const { regionRegex, outputs } = partition2; + if (new RegExp(regionRegex).test(value)) { + return { + ...outputs + }; } - const identity = { - accessKeyId: session.Credentials.AccessKeyId, - secretAccessKey: session.Credentials.SecretAccessKey, - sessionToken: session.Credentials.SessionToken, - expiration: session.Credentials.Expiration ? new Date(session.Credentials.Expiration) : void 0 - }; - return identity; } -}; - -// src/s3-express/classes/SignatureV4S3Express.ts -var import_signature_v4 = __nccwpck_require__(1528); + const DEFAULT_PARTITION = partitions.find((partition2) => partition2.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 + }; +}, "partition"); +var setPartitionInfo = /* @__PURE__ */ __name((partitionsInfo, userAgentPrefix = "") => { + selectedPartitionsInfo = partitionsInfo; + selectedUserAgentPrefix = userAgentPrefix; +}, "setPartitionInfo"); +var useDefaultPartitionInfo = /* @__PURE__ */ __name(() => { + setPartitionInfo(partitions_default, ""); +}, "useDefaultPartitionInfo"); +var getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix"); -// src/s3-express/constants.ts -var import_util_config_provider = __nccwpck_require__(3375); -var S3_EXPRESS_BUCKET_TYPE = "Directory"; -var S3_EXPRESS_BACKEND = "S3Express"; -var S3_EXPRESS_AUTH_SCHEME = "sigv4-s3express"; -var SESSION_TOKEN_QUERY_PARAM = "X-Amz-S3session-Token"; -var SESSION_TOKEN_HEADER = SESSION_TOKEN_QUERY_PARAM.toLowerCase(); -var NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME = "AWS_S3_DISABLE_EXPRESS_SESSION_AUTH"; -var NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME = "s3_disable_express_session_auth"; -var NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => (0, import_util_config_provider.booleanSelector)(env, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME, import_util_config_provider.SelectorType.ENV), "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => (0, import_util_config_provider.booleanSelector)(profile, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME, import_util_config_provider.SelectorType.CONFIG), "configFileSelector"), - default: false +// src/aws.ts +var awsEndpointFunctions = { + isVirtualHostableS3Bucket, + parseArn, + partition }; +import_util_endpoints.customEndpointFunctions.aws = awsEndpointFunctions; -// src/s3-express/classes/SignatureV4S3Express.ts -var SignatureV4S3Express = class extends import_signature_v4.SignatureV4 { - static { - __name(this, "SignatureV4S3Express"); - } - /** - * Signs with alternate provided credentials instead of those provided in the - * constructor. - * - * Additionally omits the credential sessionToken and assigns it to the - * alternate header field for S3 Express. - */ - async signWithCredentials(requestToSign, credentials, options) { - const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials); - requestToSign.headers[SESSION_TOKEN_HEADER] = credentials.sessionToken; - const privateAccess = this; - setSingleOverride(privateAccess, credentialsWithoutSessionToken); - return privateAccess.signRequest(requestToSign, options ?? {}); +// src/resolveDefaultAwsRegionalEndpointsConfig.ts +var import_url_parser = __nccwpck_require__(4681); +var resolveDefaultAwsRegionalEndpointsConfig = /* @__PURE__ */ __name((input) => { + if (typeof input.endpointProvider !== "function") { + throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); } - /** - * Similar to {@link SignatureV4S3Express#signWithCredentials} but for presigning. - */ - async presignWithCredentials(requestToSign, credentials, options) { - const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials); - delete requestToSign.headers[SESSION_TOKEN_HEADER]; - requestToSign.headers[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken; - requestToSign.query = requestToSign.query ?? {}; - requestToSign.query[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken; - const privateAccess = this; - setSingleOverride(privateAccess, credentialsWithoutSessionToken); - return this.presign(requestToSign, options); + const { endpoint } = input; + if (endpoint === void 0) { + input.endpoint = async () => { + return toEndpointV1( + input.endpointProvider( + { + Region: typeof input.region === "function" ? await input.region() : input.region, + UseDualStack: typeof input.useDualstackEndpoint === "function" ? await input.useDualstackEndpoint() : input.useDualstackEndpoint, + UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, + Endpoint: void 0 + }, + { logger: input.logger } + ) + ); + }; } -}; -function getCredentialsWithoutSessionToken(credentials) { - const credentialsWithoutSessionToken = { - accessKeyId: credentials.accessKeyId, - secretAccessKey: credentials.secretAccessKey, - expiration: credentials.expiration - }; - return credentialsWithoutSessionToken; -} -__name(getCredentialsWithoutSessionToken, "getCredentialsWithoutSessionToken"); -function setSingleOverride(privateAccess, credentialsWithoutSessionToken) { - const id = setTimeout(() => { - throw new Error("SignatureV4S3Express credential override was created but not called."); - }, 10); - const currentCredentialProvider = privateAccess.credentialProvider; - const overrideCredentialsProviderOnce = /* @__PURE__ */ __name(() => { - clearTimeout(id); - privateAccess.credentialProvider = currentCredentialProvider; - return Promise.resolve(credentialsWithoutSessionToken); - }, "overrideCredentialsProviderOnce"); - privateAccess.credentialProvider = overrideCredentialsProviderOnce; -} -__name(setSingleOverride, "setSingleOverride"); + return input; +}, "resolveDefaultAwsRegionalEndpointsConfig"); +var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => (0, import_url_parser.parseUrl)(endpoint.url), "toEndpointV1"); -// src/s3-express/functions/s3ExpressMiddleware.ts -var import_core = __nccwpck_require__(9559); +// src/resolveEndpoint.ts -var s3ExpressMiddleware = /* @__PURE__ */ __name((options) => { - return (next, context) => async (args) => { - if (context.endpointV2) { - const endpoint = context.endpointV2; - const isS3ExpressAuth = endpoint.properties?.authSchemes?.[0]?.name === S3_EXPRESS_AUTH_SCHEME; - const isS3ExpressBucket = endpoint.properties?.backend === S3_EXPRESS_BACKEND || endpoint.properties?.bucketType === S3_EXPRESS_BUCKET_TYPE; - if (isS3ExpressBucket) { - (0, import_core.setFeature)(context, "S3_EXPRESS_BUCKET", "J"); - context.isS3ExpressBucket = true; - } - if (isS3ExpressAuth) { - const requestBucket = args.input.Bucket; - if (requestBucket) { - const s3ExpressIdentity = await options.s3ExpressIdentityProvider.getS3ExpressIdentity( - await options.credentials(), - { - Bucket: requestBucket - } - ); - context.s3ExpressIdentity = s3ExpressIdentity; - if (import_protocol_http.HttpRequest.isInstance(args.request) && s3ExpressIdentity.sessionToken) { - args.request.headers[SESSION_TOKEN_HEADER] = s3ExpressIdentity.sessionToken; - } - } - } - } - return next(args); - }; -}, "s3ExpressMiddleware"); -var s3ExpressMiddlewareOptions = { - name: "s3ExpressMiddleware", - step: "build", - tags: ["S3", "S3_EXPRESS"], - override: true -}; -var getS3ExpressPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(s3ExpressMiddleware(options), s3ExpressMiddlewareOptions); - }, "applyToStack") -}), "getS3ExpressPlugin"); -// src/s3-express/functions/s3ExpressHttpSigningMiddleware.ts -var import_core2 = __nccwpck_require__(5829); +// src/types/EndpointError.ts -var import_util_middleware = __nccwpck_require__(2390); -// src/s3-express/functions/signS3Express.ts -var signS3Express = /* @__PURE__ */ __name(async (s3ExpressIdentity, signingOptions, request, sigV4MultiRegionSigner) => { - const signedRequest = await sigV4MultiRegionSigner.signWithCredentials(request, s3ExpressIdentity, {}); - if (signedRequest.headers["X-Amz-Security-Token"] || signedRequest.headers["x-amz-security-token"]) { - throw new Error("X-Amz-Security-Token must not be set for s3-express requests."); - } - return signedRequest; -}, "signS3Express"); +// src/types/EndpointRuleObject.ts -// src/s3-express/functions/s3ExpressHttpSigningMiddleware.ts -var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { - throw error; -}, "defaultErrorHandler"); -var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { -}, "defaultSuccessHandler"); -var s3ExpressHttpSigningMiddlewareOptions = import_core2.httpSigningMiddlewareOptions; -var s3ExpressHttpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { - if (!import_protocol_http.HttpRequest.isInstance(args.request)) { - return next(args); - } - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); - } - const { - httpAuthOption: { signingProperties = {} }, - identity, - signer - } = scheme; - let request; - if (context.s3ExpressIdentity) { - request = await signS3Express( - context.s3ExpressIdentity, - signingProperties, - args.request, - await config.signer() - ); - } else { - request = await signer.sign(args.request, identity, signingProperties); - } - const output = await next({ - ...args, - request - }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); - (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); - return output; -}, "s3ExpressHttpSigningMiddleware"); -var getS3ExpressHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo( - s3ExpressHttpSigningMiddleware(config), - import_core2.httpSigningMiddlewareOptions - ); - }, "applyToStack") -}), "getS3ExpressHttpSigningPlugin"); -// src/s3Configuration.ts -var resolveS3Config = /* @__PURE__ */ __name((input, { - session -}) => { - const [s3ClientProvider, CreateSessionCommandCtor] = session; - const { - forcePathStyle, - useAccelerateEndpoint, - disableMultiregionAccessPoints, - followRegionRedirects, - s3ExpressIdentityProvider, - bucketEndpoint - } = input; - return Object.assign(input, { - forcePathStyle: forcePathStyle ?? false, - useAccelerateEndpoint: useAccelerateEndpoint ?? false, - disableMultiregionAccessPoints: disableMultiregionAccessPoints ?? false, - followRegionRedirects: followRegionRedirects ?? false, - s3ExpressIdentityProvider: s3ExpressIdentityProvider ?? new S3ExpressIdentityProviderImpl( - async (key) => s3ClientProvider().send( - new CreateSessionCommandCtor({ - Bucket: key - }) - ) - ), - bucketEndpoint: bucketEndpoint ?? false - }); -}, "resolveS3Config"); +// src/types/ErrorRuleObject.ts -// src/throw-200-exceptions.ts -var import_util_stream = __nccwpck_require__(6607); -var THROW_IF_EMPTY_BODY = { - CopyObjectCommand: true, - UploadPartCopyCommand: true, - CompleteMultipartUploadCommand: true +// src/types/RuleSetObject.ts + + +// src/types/TreeRuleObject.ts + + +// src/types/shared.ts + +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 7330: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var MAX_BYTES_TO_INSPECT = 3e3; -var throw200ExceptionsMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { - const result = await next(args); - const { response } = result; - if (!import_protocol_http.HttpResponse.isInstance(response)) { - return result; - } - const { statusCode, body: sourceBody } = response; - if (statusCode < 200 || statusCode >= 300) { - return result; - } - const isSplittableStream = typeof sourceBody?.stream === "function" || typeof sourceBody?.pipe === "function" || typeof sourceBody?.tee === "function"; - if (!isSplittableStream) { - return result; - } - let bodyCopy = sourceBody; - let body = sourceBody; - if (sourceBody && typeof sourceBody === "object" && !(sourceBody instanceof Uint8Array)) { - [bodyCopy, body] = await (0, import_util_stream.splitStream)(sourceBody); - } - response.body = body; - const bodyBytes = await collectBody(bodyCopy, { - streamCollector: /* @__PURE__ */ __name(async (stream) => { - return (0, import_util_stream.headStream)(stream, MAX_BYTES_TO_INSPECT); - }, "streamCollector") - }); - if (typeof bodyCopy?.destroy === "function") { - bodyCopy.destroy(); - } - const bodyStringTail = config.utf8Encoder(bodyBytes.subarray(bodyBytes.length - 16)); - if (bodyBytes.length === 0 && THROW_IF_EMPTY_BODY[context.commandName]) { - const err = new Error("S3 aborted request"); - err.name = "InternalError"; - throw err; - } - if (bodyStringTail && bodyStringTail.endsWith("")) { - response.statusCode = 400; - } - return result; -}, "throw200ExceptionsMiddleware"); -var collectBody = /* @__PURE__ */ __name((streamBody = new Uint8Array(), context) => { - if (streamBody instanceof Uint8Array) { - return Promise.resolve(streamBody); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return context.streamCollector(streamBody) || Promise.resolve(new Uint8Array()); -}, "collectBody"); -var throw200ExceptionsMiddlewareOptions = { - relation: "after", - toMiddleware: "deserializerMiddleware", - tags: ["THROW_200_EXCEPTIONS", "S3"], - name: "throw200ExceptionsMiddleware", - override: true + return to; }; -var getThrow200ExceptionsPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.addRelativeTo(throw200ExceptionsMiddleware(config), throw200ExceptionsMiddlewareOptions); - }, "applyToStack") -}), "getThrow200ExceptionsPlugin"); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/validate-bucket-name.ts -var import_util_arn_parser = __nccwpck_require__(5487); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + NODE_APP_ID_CONFIG_OPTIONS: () => NODE_APP_ID_CONFIG_OPTIONS, + UA_APP_ID_ENV_NAME: () => UA_APP_ID_ENV_NAME, + UA_APP_ID_INI_NAME: () => UA_APP_ID_INI_NAME, + createDefaultUserAgentProvider: () => createDefaultUserAgentProvider, + crtAvailability: () => crtAvailability, + defaultUserAgent: () => defaultUserAgent +}); +module.exports = __toCommonJS(index_exports); -// src/bucket-endpoint-middleware.ts -function bucketEndpointMiddleware(options) { - return (next, context) => async (args) => { - if (options.bucketEndpoint) { - const endpoint = context.endpointV2; - if (endpoint) { - const bucket = args.input.Bucket; - if (typeof bucket === "string") { - try { - const bucketEndpointUrl = new URL(bucket); - context.endpointV2 = { - ...endpoint, - url: bucketEndpointUrl - }; - } catch (e) { - const warning = `@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${bucket} could not be parsed as URL.`; - if (context.logger?.constructor?.name === "NoOpLogger") { - console.warn(warning); - } else { - context.logger?.warn?.(warning); - } - throw e; - } - } - } - } - return next(args); - }; -} -__name(bucketEndpointMiddleware, "bucketEndpointMiddleware"); -var bucketEndpointMiddlewareOptions = { - name: "bucketEndpointMiddleware", - override: true, - relation: "after", - toMiddleware: "endpointV2Middleware" +// src/defaultUserAgent.ts +var import_os = __nccwpck_require__(2037); +var import_process = __nccwpck_require__(7282); + +// src/crt-availability.ts +var crtAvailability = { + isCrtAvailable: false }; -// src/validate-bucket-name.ts -function validateBucketNameMiddleware({ bucketEndpoint }) { - return (next) => async (args) => { - const { - input: { Bucket } - } = args; - if (!bucketEndpoint && typeof Bucket === "string" && !(0, import_util_arn_parser.validate)(Bucket) && Bucket.indexOf("/") >= 0) { - const err = new Error(`Bucket name shouldn't contain '/', received '${Bucket}'`); - err.name = "InvalidBucketName"; - throw err; +// src/is-crt-available.ts +var isCrtAvailable = /* @__PURE__ */ __name(() => { + if (crtAvailability.isCrtAvailable) { + return ["md/crt-avail"]; + } + return null; +}, "isCrtAvailable"); + +// src/defaultUserAgent.ts +var createDefaultUserAgentProvider = /* @__PURE__ */ __name(({ serviceId, clientVersion }) => { + return async (config) => { + const sections = [ + // sdk-metadata + ["aws-sdk-js", clientVersion], + // ua-metadata + ["ua", "2.1"], + // os-metadata + [`os/${(0, import_os.platform)()}`, (0, import_os.release)()], + // language-metadata + // ECMAScript edition doesn't matter in JS, so no version needed. + ["lang/js"], + ["md/nodejs", `${import_process.versions.node}`] + ]; + const crtAvailable = isCrtAvailable(); + if (crtAvailable) { + sections.push(crtAvailable); } - return next({ ...args }); + if (serviceId) { + sections.push([`api/${serviceId}`, clientVersion]); + } + if (import_process.env.AWS_EXECUTION_ENV) { + sections.push([`exec-env/${import_process.env.AWS_EXECUTION_ENV}`]); + } + const appId = await config?.userAgentAppId?.(); + const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; + return resolvedUserAgent; }; -} -__name(validateBucketNameMiddleware, "validateBucketNameMiddleware"); -var validateBucketNameMiddlewareOptions = { - step: "initialize", - tags: ["VALIDATE_BUCKET_NAME"], - name: "validateBucketNameMiddleware", - override: true +}, "createDefaultUserAgentProvider"); +var defaultUserAgent = createDefaultUserAgentProvider; + +// src/nodeAppIdConfigOptions.ts +var import_middleware_user_agent = __nccwpck_require__(6634); +var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; +var UA_APP_ID_INI_NAME = "sdk_ua_app_id"; +var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; +var NODE_APP_ID_CONFIG_OPTIONS = { + environmentVariableSelector: /* @__PURE__ */ __name((env2) => env2[UA_APP_ID_ENV_NAME], "environmentVariableSelector"), + configFileSelector: /* @__PURE__ */ __name((profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], "configFileSelector"), + default: import_middleware_user_agent.DEFAULT_UA_APP_ID }; -var getValidateBucketNamePlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(validateBucketNameMiddleware(options), validateBucketNameMiddlewareOptions); - clientStack.addRelativeTo(bucketEndpointMiddleware(options), bucketEndpointMiddlewareOptions); - }, "applyToStack") -}), "getValidateBucketNamePlugin"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -50440,21 +34446,21 @@ var getValidateBucketNamePlugin = /* @__PURE__ */ __name((options) => ({ /***/ }), -/***/ 9559: +/***/ 9963: /***/ ((__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__(9263), exports); -tslib_1.__exportStar(__nccwpck_require__(7379), exports); -tslib_1.__exportStar(__nccwpck_require__(6764), exports); +tslib_1.__exportStar(__nccwpck_require__(2825), exports); +tslib_1.__exportStar(__nccwpck_require__(7862), exports); +tslib_1.__exportStar(__nccwpck_require__(785), exports); /***/ }), -/***/ 9263: +/***/ 2825: /***/ ((module) => { "use strict"; @@ -50546,7 +34552,7 @@ __name(setTokenFeature, "setTokenFeature"); /***/ }), -/***/ 7379: +/***/ 7862: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -50779,7 +34785,7 @@ var NODE_SIGV4A_CONFIG_OPTIONS = { }; // src/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.ts -var import_client = __nccwpck_require__(9263); +var import_client = __nccwpck_require__(2825); var import_core2 = __nccwpck_require__(5829); var import_signature_v4 = __nccwpck_require__(1528); var resolveAwsSdkSigV4Config = /* @__PURE__ */ __name((config) => { @@ -50934,7 +34940,7 @@ __name(bindCallerConfig, "bindCallerConfig"); /***/ }), -/***/ 6764: +/***/ 785: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -51709,7 +35715,7 @@ var import_protocols3 = __nccwpck_require__(2241); var import_schema5 = __nccwpck_require__(9826); var import_smithy_client3 = __nccwpck_require__(3570); var import_util_utf8 = __nccwpck_require__(1895); -var import_fast_xml_parser = __nccwpck_require__(6388); +var import_fast_xml_parser = __nccwpck_require__(4577); var XmlShapeDeserializer = class extends SerdeContextConfig { constructor(settings) { super(); @@ -52193,7 +36199,7 @@ var import_util_body_length_browser4 = __nccwpck_require__(713); // src/submodules/protocols/xml/parseXmlBody.ts var import_smithy_client5 = __nccwpck_require__(3570); -var import_fast_xml_parser2 = __nccwpck_require__(6388); +var import_fast_xml_parser2 = __nccwpck_require__(4577); var parseXmlBody = /* @__PURE__ */ __name((streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { if (encoded.length) { const parser = new import_fast_xml_parser2.XMLParser({ @@ -52249,7 +36255,7 @@ var loadRestXmlErrorCode = /* @__PURE__ */ __name((output, data) => { }, "loadRestXmlErrorCode"); // src/submodules/protocols/xml/XmlShapeSerializer.ts -var import_xml_builder = __nccwpck_require__(5721); +var import_xml_builder = __nccwpck_require__(3816); var import_schema8 = __nccwpck_require__(9826); var import_serde6 = __nccwpck_require__(7669); var import_smithy_client6 = __nccwpck_require__(3570); @@ -52677,14 +36683,499 @@ var AwsRestXmlProtocol = class extends import_protocols6.HttpBindingProtocol { /***/ }), -/***/ 5721: -/***/ ((module) => { +/***/ 3816: +/***/ ((module) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + XmlNode: () => XmlNode, + XmlText: () => XmlText +}); +module.exports = __toCommonJS(index_exports); + +// src/escape-attribute.ts +function escapeAttribute(value) { + return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} +__name(escapeAttribute, "escapeAttribute"); + +// src/escape-element.ts +function escapeElement(value) { + return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">").replace(/\r/g, " ").replace(/\n/g, " ").replace(/\u0085/g, "…").replace(/\u2028/, "
"); +} +__name(escapeElement, "escapeElement"); + +// src/XmlText.ts +var XmlText = class { + constructor(value) { + this.value = value; + } + static { + __name(this, "XmlText"); + } + toString() { + return escapeElement("" + this.value); + } +}; + +// src/XmlNode.ts +var XmlNode = class _XmlNode { + constructor(name, children = []) { + this.name = name; + this.children = children; + } + static { + __name(this, "XmlNode"); + } + attributes = {}; + static of(name, childText, withName) { + const node = new _XmlNode(name); + if (childText !== void 0) { + node.addChildNode(new XmlText(childText)); + } + if (withName !== void 0) { + node.withName(withName); + } + return node; + } + withName(name) { + this.name = name; + return this; + } + addAttribute(name, value) { + this.attributes[name] = value; + return this; + } + addChildNode(child) { + this.children.push(child); + return this; + } + removeAttribute(name) { + delete this.attributes[name]; + return this; + } + /** + * @internal + * Alias of {@link XmlNode#withName(string)} for codegen brevity. + */ + n(name) { + this.name = name; + return this; + } + /** + * @internal + * Alias of {@link XmlNode#addChildNode(string)} for codegen brevity. + */ + c(child) { + this.children.push(child); + return this; + } + /** + * @internal + * Checked version of {@link XmlNode#addAttribute(string)} for codegen brevity. + */ + a(name, value) { + if (value != null) { + this.attributes[name] = value; + } + return this; + } + /** + * Create a child node. + * Used in serialization of string fields. + * @internal + */ + cc(input, field, withName = field) { + if (input[field] != null) { + const node = _XmlNode.of(field, input[field]).withName(withName); + this.c(node); + } + } + /** + * Creates list child nodes. + * @internal + */ + l(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + nodes.map((node) => { + node.withName(memberName); + this.c(node); + }); + } + } + /** + * Creates list child nodes with container. + * @internal + */ + lc(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + const containerNode = new _XmlNode(memberName); + nodes.map((node) => { + containerNode.c(node); + }); + this.c(containerNode); + } + } + toString() { + const hasChildren = Boolean(this.children.length); + let xmlText = `<${this.name}`; + const attributes = this.attributes; + for (const attributeName of Object.keys(attributes)) { + const attribute = attributes[attributeName]; + if (attribute != null) { + xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; + } + } + return xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`; + } +}; +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 5972: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID, + ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE, + ENV_EXPIRATION: () => ENV_EXPIRATION, + ENV_KEY: () => ENV_KEY, + ENV_SECRET: () => ENV_SECRET, + ENV_SESSION: () => ENV_SESSION, + fromEnv: () => fromEnv +}); +module.exports = __toCommonJS(index_exports); + +// src/fromEnv.ts +var import_client = __nccwpck_require__(2825); +var import_property_provider = __nccwpck_require__(9721); +var ENV_KEY = "AWS_ACCESS_KEY_ID"; +var ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; +var ENV_SESSION = "AWS_SESSION_TOKEN"; +var ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; +var ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; +var ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; +var fromEnv = /* @__PURE__ */ __name((init) => async () => { + init?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); + const accessKeyId = process.env[ENV_KEY]; + const secretAccessKey = process.env[ENV_SECRET]; + const sessionToken = process.env[ENV_SESSION]; + const expiry = process.env[ENV_EXPIRATION]; + const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; + const accountId = process.env[ENV_ACCOUNT_ID]; + if (accessKeyId && secretAccessKey) { + const credentials = { + accessKeyId, + secretAccessKey, + ...sessionToken && { sessionToken }, + ...expiry && { expiration: new Date(expiry) }, + ...credentialScope && { credentialScope }, + ...accountId && { accountId } + }; + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS", "g"); + return credentials; + } + throw new import_property_provider.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init?.logger }); +}, "fromEnv"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 3757: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.checkUrl = void 0; +const property_provider_1 = __nccwpck_require__(9721); +const LOOPBACK_CIDR_IPv4 = "127.0.0.0/8"; +const LOOPBACK_CIDR_IPv6 = "::1/128"; +const ECS_CONTAINER_HOST = "169.254.170.2"; +const EKS_CONTAINER_HOST_IPv4 = "169.254.170.23"; +const EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]"; +const checkUrl = (url, logger) => { + if (url.protocol === "https:") { + return; + } + if (url.hostname === ECS_CONTAINER_HOST || + url.hostname === EKS_CONTAINER_HOST_IPv4 || + url.hostname === EKS_CONTAINER_HOST_IPv6) { + return; + } + if (url.hostname.includes("[")) { + if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") { + return; + } + } + else { + if (url.hostname === "localhost") { + return; + } + const ipComponents = url.hostname.split("."); + const inRange = (component) => { + const num = parseInt(component, 10); + return 0 <= num && num <= 255; + }; + if (ipComponents[0] === "127" && + inRange(ipComponents[1]) && + inRange(ipComponents[2]) && + inRange(ipComponents[3]) && + ipComponents.length === 4) { + return; + } + } + throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following: + - loopback CIDR 127.0.0.0/8 or [::1/128] + - ECS container host 169.254.170.2 + - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger }); +}; +exports.checkUrl = checkUrl; + + +/***/ }), + +/***/ 6070: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromHttp = void 0; +const tslib_1 = __nccwpck_require__(4351); +const client_1 = __nccwpck_require__(2825); +const node_http_handler_1 = __nccwpck_require__(258); +const property_provider_1 = __nccwpck_require__(9721); +const promises_1 = tslib_1.__importDefault(__nccwpck_require__(3292)); +const checkUrl_1 = __nccwpck_require__(3757); +const requestHelpers_1 = __nccwpck_require__(9287); +const retry_wrapper_1 = __nccwpck_require__(9921); +const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; +const DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; +const AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; +const AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"; +const AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; +const fromHttp = (options = {}) => { + options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp"); + let host; + const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI]; + const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI]; + const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN]; + const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE]; + const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger ? console.warn : options.logger.warn; + if (relative && full) { + warn("@aws-sdk/credential-provider-http: " + + "you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."); + warn("awsContainerCredentialsFullUri will take precedence."); + } + if (token && tokenFile) { + warn("@aws-sdk/credential-provider-http: " + + "you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."); + warn("awsContainerAuthorizationToken will take precedence."); + } + if (full) { + host = full; + } + else if (relative) { + host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`; + } + else { + throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided. +Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger }); + } + const url = new URL(host); + (0, checkUrl_1.checkUrl)(url, options.logger); + const requestHandler = new node_http_handler_1.NodeHttpHandler({ + requestTimeout: options.timeout ?? 1000, + connectionTimeout: options.timeout ?? 1000, + }); + return (0, retry_wrapper_1.retryWrapper)(async () => { + const request = (0, requestHelpers_1.createGetRequest)(url); + if (token) { + request.headers.Authorization = token; + } + else if (tokenFile) { + request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString(); + } + try { + const result = await requestHandler.handle(request); + return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z")); + } + catch (e) { + throw new property_provider_1.CredentialsProviderError(String(e), { logger: options.logger }); + } + }, options.maxRetries ?? 3, options.timeout ?? 1000); +}; +exports.fromHttp = fromHttp; + + +/***/ }), + +/***/ 9287: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createGetRequest = createGetRequest; +exports.getCredentials = getCredentials; +const property_provider_1 = __nccwpck_require__(9721); +const protocol_http_1 = __nccwpck_require__(4418); +const smithy_client_1 = __nccwpck_require__(3570); +const util_stream_1 = __nccwpck_require__(6607); +function createGetRequest(url) { + return new protocol_http_1.HttpRequest({ + protocol: url.protocol, + hostname: url.hostname, + port: Number(url.port), + path: url.pathname, + query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => { + acc[k] = v; + return acc; + }, {}), + fragment: url.hash, + }); +} +async function getCredentials(response, logger) { + const stream = (0, util_stream_1.sdkStreamMixin)(response.body); + const str = await stream.transformToString(); + if (response.statusCode === 200) { + const parsed = JSON.parse(str); + if (typeof parsed.AccessKeyId !== "string" || + typeof parsed.SecretAccessKey !== "string" || + typeof parsed.Token !== "string" || + typeof parsed.Expiration !== "string") { + throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: " + + "{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger }); + } + return { + accessKeyId: parsed.AccessKeyId, + secretAccessKey: parsed.SecretAccessKey, + sessionToken: parsed.Token, + expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration), + }; + } + if (response.statusCode >= 400 && response.statusCode < 500) { + let parsedBody = {}; + try { + parsedBody = JSON.parse(str); + } + catch (e) { } + throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), { + Code: parsedBody.Code, + Message: parsedBody.Message, + }); + } + throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }); +} + + +/***/ }), + +/***/ 9921: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.retryWrapper = void 0; +const retryWrapper = (toRetry, maxRetries, delayMs) => { + return async () => { + for (let i = 0; i < maxRetries; ++i) { + try { + return await toRetry(); + } + catch (e) { + await new Promise((resolve) => setTimeout(resolve, delayMs)); + } + } + return await toRetry(); + }; +}; +exports.retryWrapper = retryWrapper; + + +/***/ }), + +/***/ 7290: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromHttp = void 0; +var fromHttp_1 = __nccwpck_require__(6070); +Object.defineProperty(exports, "fromHttp", ({ enumerable: true, get: function () { return fromHttp_1.fromHttp; } })); + + +/***/ }), + +/***/ 4203: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -52699,154 +37190,256 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - XmlNode: () => XmlNode, - XmlText: () => XmlText + fromIni: () => fromIni }); module.exports = __toCommonJS(index_exports); -// src/escape-attribute.ts -function escapeAttribute(value) { - return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); -} -__name(escapeAttribute, "escapeAttribute"); +// src/fromIni.ts -// src/escape-element.ts -function escapeElement(value) { - return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">").replace(/\r/g, " ").replace(/\n/g, " ").replace(/\u0085/g, "…").replace(/\u2028/, "
"); -} -__name(escapeElement, "escapeElement"); -// src/XmlText.ts -var XmlText = class { - constructor(value) { - this.value = value; - } - static { - __name(this, "XmlText"); - } - toString() { - return escapeElement("" + this.value); - } -}; +// src/resolveProfileData.ts -// src/XmlNode.ts -var XmlNode = class _XmlNode { - constructor(name, children = []) { - this.name = name; - this.children = children; - } - static { - __name(this, "XmlNode"); + +// src/resolveAssumeRoleCredentials.ts + + +var import_shared_ini_file_loader = __nccwpck_require__(3507); + +// src/resolveCredentialSource.ts +var import_client = __nccwpck_require__(2825); +var import_property_provider = __nccwpck_require__(9721); +var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName, logger) => { + const sourceProvidersMap = { + EcsContainer: /* @__PURE__ */ __name(async (options) => { + const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7290))); + const { fromContainerMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); + return async () => (0, import_property_provider.chain)(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); + }, "EcsContainer"), + Ec2InstanceMetadata: /* @__PURE__ */ __name(async (options) => { + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata"); + const { fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); + return async () => fromInstanceMetadata(options)().then(setNamedProvider); + }, "Ec2InstanceMetadata"), + Environment: /* @__PURE__ */ __name(async (options) => { + logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); + const { fromEnv } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5972))); + return async () => fromEnv(options)().then(setNamedProvider); + }, "Environment") + }; + if (credentialSource in sourceProvidersMap) { + return sourceProvidersMap[credentialSource]; + } else { + throw new import_property_provider.CredentialsProviderError( + `Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, + { logger } + ); } - attributes = {}; - static of(name, childText, withName) { - const node = new _XmlNode(name); - if (childText !== void 0) { - node.addChildNode(new XmlText(childText)); - } - if (withName !== void 0) { - node.withName(withName); - } - return node; +}, "resolveCredentialSource"); +var setNamedProvider = /* @__PURE__ */ __name((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"), "setNamedProvider"); + +// src/resolveAssumeRoleCredentials.ts +var isAssumeRoleProfile = /* @__PURE__ */ __name((arg, { profile = "default", logger } = {}) => { + return 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, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger })); +}, "isAssumeRoleProfile"); +var isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger }) => { + const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; + if (withSourceProfile) { + logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`); } - withName(name) { - this.name = name; - return this; + return withSourceProfile; +}, "isAssumeRoleWithSourceProfile"); +var isCredentialSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger }) => { + const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; + if (withProviderProfile) { + logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`); } - addAttribute(name, value) { - this.attributes[name] = value; - return this; + return withProviderProfile; +}, "isCredentialSourceProfile"); +var resolveAssumeRoleCredentials = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => { + options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)"); + const profileData = profiles[profileName]; + const { source_profile, region } = profileData; + if (!options.roleAssumer) { + const { getDefaultRoleAssumer } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(2273))); + options.roleAssumer = getDefaultRoleAssumer( + { + ...options.clientConfig, + credentialProviderLogger: options.logger, + parentClientConfig: { + ...options?.parentClientConfig, + region: region ?? options?.parentClientConfig?.region + } + }, + options.clientPlugins + ); } - addChildNode(child) { - this.children.push(child); - return this; + if (source_profile && source_profile in visitedProfiles) { + throw new import_property_provider.CredentialsProviderError( + `Detected a cycle attempting to resolve credentials for profile ${(0, import_shared_ini_file_loader.getProfileName)(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), + { logger: options.logger } + ); } - removeAttribute(name) { - delete this.attributes[name]; - return this; + options.logger?.debug( + `@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}` + ); + const sourceCredsProvider = source_profile ? resolveProfileData( + source_profile, + profiles, + options, + { + ...visitedProfiles, + [source_profile]: true + }, + isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {}) + ) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))(); + if (isCredentialSourceWithoutRoleArn(profileData)) { + return sourceCredsProvider.then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); + } else { + const params = { + RoleArn: profileData.role_arn, + RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`, + ExternalId: profileData.external_id, + DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10) + }; + const { mfa_serial } = profileData; + if (mfa_serial) { + if (!options.mfaCodeProvider) { + throw new import_property_provider.CredentialsProviderError( + `Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, + { logger: options.logger, tryNextLink: false } + ); + } + params.SerialNumber = mfa_serial; + params.TokenCode = await options.mfaCodeProvider(mfa_serial); + } + const sourceCreds = await sourceCredsProvider; + return options.roleAssumer(sourceCreds, params).then( + (creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o") + ); } - /** - * @internal - * Alias of {@link XmlNode#withName(string)} for codegen brevity. - */ - n(name) { - this.name = name; - return this; +}, "resolveAssumeRoleCredentials"); +var isCredentialSourceWithoutRoleArn = /* @__PURE__ */ __name((section) => { + return !section.role_arn && !!section.credential_source; +}, "isCredentialSourceWithoutRoleArn"); + +// src/resolveProcessCredentials.ts + +var isProcessProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", "isProcessProfile"); +var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => __toESM(__nccwpck_require__(9969))).then( + ({ fromProcess }) => fromProcess({ + ...options, + profile + })().then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_PROCESS", "v")) +), "resolveProcessCredentials"); + +// src/resolveSsoCredentials.ts + +var resolveSsoCredentials = /* @__PURE__ */ __name(async (profile, profileData, options = {}) => { + const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(6414))); + return fromSSO({ + profile, + logger: options.logger, + parentClientConfig: options.parentClientConfig, + clientConfig: options.clientConfig + })().then((creds) => { + if (profileData.sso_session) { + return (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO", "r"); + } else { + return (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t"); + } + }); +}, "resolveSsoCredentials"); +var isSsoProfile = /* @__PURE__ */ __name((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"), "isSsoProfile"); + +// src/resolveStaticCredentials.ts + +var isStaticCredsProfile = /* @__PURE__ */ __name((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 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1, "isStaticCredsProfile"); +var resolveStaticCredentials = /* @__PURE__ */ __name(async (profile, options) => { + options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials"); + const credentials = { + accessKeyId: profile.aws_access_key_id, + secretAccessKey: profile.aws_secret_access_key, + sessionToken: profile.aws_session_token, + ...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }, + ...profile.aws_account_id && { accountId: profile.aws_account_id } + }; + return (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROFILE", "n"); +}, "resolveStaticCredentials"); + +// src/resolveWebIdentityCredentials.ts + +var isWebIdentityProfile = /* @__PURE__ */ __name((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, "isWebIdentityProfile"); +var resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => __toESM(__nccwpck_require__(5646))).then( + ({ fromTokenFile }) => fromTokenFile({ + webIdentityTokenFile: profile.web_identity_token_file, + roleArn: profile.role_arn, + roleSessionName: profile.role_session_name, + roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, + logger: options.logger, + parentClientConfig: options.parentClientConfig + })().then((creds) => (0, import_client.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q")) +), "resolveWebIdentityCredentials"); + +// src/resolveProfileData.ts +var resolveProfileData = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => { + const data = profiles[profileName]; + if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) { + return resolveStaticCredentials(data, options); } - /** - * @internal - * Alias of {@link XmlNode#addChildNode(string)} for codegen brevity. - */ - c(child) { - this.children.push(child); - return this; + if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) { + return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles); } - /** - * @internal - * Checked version of {@link XmlNode#addAttribute(string)} for codegen brevity. - */ - a(name, value) { - if (value != null) { - this.attributes[name] = value; - } - return this; + if (isStaticCredsProfile(data)) { + return resolveStaticCredentials(data, options); } - /** - * Create a child node. - * Used in serialization of string fields. - * @internal - */ - cc(input, field, withName = field) { - if (input[field] != null) { - const node = _XmlNode.of(field, input[field]).withName(withName); - this.c(node); - } + if (isWebIdentityProfile(data)) { + return resolveWebIdentityCredentials(data, options); } - /** - * Creates list child nodes. - * @internal - */ - l(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - nodes.map((node) => { - node.withName(memberName); - this.c(node); - }); - } + if (isProcessProfile(data)) { + return resolveProcessCredentials(options, profileName); } - /** - * Creates list child nodes with container. - * @internal - */ - lc(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - const containerNode = new _XmlNode(memberName); - nodes.map((node) => { - containerNode.c(node); - }); - this.c(containerNode); - } + if (isSsoProfile(data)) { + return await resolveSsoCredentials(profileName, data, options); } - toString() { - const hasChildren = Boolean(this.children.length); - let xmlText = `<${this.name}`; - const attributes = this.attributes; - for (const attributeName of Object.keys(attributes)) { - const attribute = attributes[attributeName]; - if (attribute != null) { - xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; - } + throw new import_property_provider.CredentialsProviderError( + `Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, + { logger: options.logger } + ); +}, "resolveProfileData"); + +// src/fromIni.ts +var fromIni = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { + const init = { + ..._init, + parentClientConfig: { + ...callerClientConfig, + ..._init.parentClientConfig } - return xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`; - } -}; + }; + init.logger?.debug("@aws-sdk/credential-provider-ini - fromIni"); + const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); + return resolveProfileData( + (0, import_shared_ini_file_loader.getProfileName)({ + profile: _init.profile ?? callerClientConfig?.profile + }), + profiles, + init + ); +}, "fromIni"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -52855,14 +37448,16 @@ var XmlNode = class _XmlNode { /***/ }), -/***/ 9718: -/***/ ((module) => { +/***/ 5531: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -52877,79 +37472,125 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { - getSsecPlugin: () => getSsecPlugin, - isValidBase64EncodedSSECustomerKey: () => isValidBase64EncodedSSECustomerKey, - ssecMiddleware: () => ssecMiddleware, - ssecMiddlewareOptions: () => ssecMiddlewareOptions + credentialsTreatedAsExpired: () => credentialsTreatedAsExpired, + credentialsWillNeedRefresh: () => credentialsWillNeedRefresh, + defaultProvider: () => defaultProvider }); module.exports = __toCommonJS(index_exports); -function ssecMiddleware(options) { - return (next) => async (args) => { - const input = { ...args.input }; - const properties = [ - { - target: "SSECustomerKey", - hash: "SSECustomerKeyMD5" - }, - { - target: "CopySourceSSECustomerKey", - hash: "CopySourceSSECustomerKeyMD5" - } - ]; - for (const prop of properties) { - const value = input[prop.target]; - if (value) { - let valueForHash; - if (typeof value === "string") { - if (isValidBase64EncodedSSECustomerKey(value, options)) { - valueForHash = options.base64Decoder(value); - } else { - valueForHash = options.utf8Decoder(value); - input[prop.target] = options.base64Encoder(valueForHash); + +// src/defaultProvider.ts +var import_credential_provider_env = __nccwpck_require__(5972); + +var import_shared_ini_file_loader = __nccwpck_require__(3507); + +// src/remoteProvider.ts +var import_property_provider = __nccwpck_require__(9721); +var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; +var remoteProvider = /* @__PURE__ */ __name(async (init) => { + const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); + if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { + init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); + const { fromHttp } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7290))); + return (0, import_property_provider.chain)(fromHttp(init), fromContainerMetadata(init)); + } + if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { + return async () => { + throw new import_property_provider.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init.logger }); + }; + } + init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); + return fromInstanceMetadata(init); +}, "remoteProvider"); + +// src/defaultProvider.ts +var multipleCredentialSourceWarningEmitted = false; +var defaultProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( + (0, import_property_provider.chain)( + async () => { + const profile = init.profile ?? process.env[import_shared_ini_file_loader.ENV_PROFILE]; + if (profile) { + const envStaticCredentialsAreSet = process.env[import_credential_provider_env.ENV_KEY] && process.env[import_credential_provider_env.ENV_SECRET]; + if (envStaticCredentialsAreSet) { + if (!multipleCredentialSourceWarningEmitted) { + const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" ? init.logger.warn : console.warn; + warnFn( + `@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: + Multiple credential sources detected: + Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. + This SDK will proceed with the AWS_PROFILE value. + + However, a future version may change this behavior to prefer the ENV static credentials. + Please ensure that your environment only sets either the AWS_PROFILE or the + AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. +` + ); + multipleCredentialSourceWarningEmitted = true; } - } else { - valueForHash = ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value); - input[prop.target] = options.base64Encoder(valueForHash); } - const hash = new options.md5(); - hash.update(valueForHash); - input[prop.hash] = options.base64Encoder(await hash.digest()); + throw new import_property_provider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { + logger: init.logger, + tryNextLink: true + }); } - } - return next({ - ...args, - input - }); - }; -} -__name(ssecMiddleware, "ssecMiddleware"); -var ssecMiddlewareOptions = { - name: "ssecMiddleware", - step: "initialize", - tags: ["SSE"], - override: true -}; -var getSsecPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(ssecMiddleware(config), ssecMiddlewareOptions); - }, "applyToStack") -}), "getSsecPlugin"); -function isValidBase64EncodedSSECustomerKey(str, options) { - const base64Regex = /^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; - if (!base64Regex.test(str)) return false; - try { - const decodedBytes = options.base64Decoder(str); - return decodedBytes.length === 32; - } catch { - return false; - } -} -__name(isValidBase64EncodedSSECustomerKey, "isValidBase64EncodedSSECustomerKey"); + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); + return (0, import_credential_provider_env.fromEnv)(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + throw new import_property_provider.CredentialsProviderError( + "Skipping SSO provider in default chain (inputs do not include SSO fields).", + { logger: init.logger } + ); + } + const { fromSSO } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(6414))); + return fromSSO(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); + const { fromIni } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(4203))); + return fromIni(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); + const { fromProcess } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(9969))); + return fromProcess(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); + const { fromTokenFile } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(5646))); + return fromTokenFile(init)(); + }, + async () => { + init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); + return (await remoteProvider(init))(); + }, + async () => { + throw new import_property_provider.CredentialsProviderError("Could not load credentials from any providers", { + tryNextLink: false, + logger: init.logger + }); + } + ), + credentialsTreatedAsExpired, + credentialsWillNeedRefresh +), "defaultProvider"); +var credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0, "credentialsWillNeedRefresh"); +var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -52958,7 +37599,7 @@ __name(isValidBase64EncodedSSECustomerKey, "isValidBase64EncodedSSECustomerKey") /***/ }), -/***/ 4688: +/***/ 9969: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -52985,200 +37626,341 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - DEFAULT_UA_APP_ID: () => DEFAULT_UA_APP_ID, - getUserAgentMiddlewareOptions: () => getUserAgentMiddlewareOptions, - getUserAgentPlugin: () => getUserAgentPlugin, - resolveUserAgentConfig: () => resolveUserAgentConfig, - userAgentMiddleware: () => userAgentMiddleware + fromProcess: () => fromProcess }); module.exports = __toCommonJS(index_exports); -// src/configurations.ts -var import_core = __nccwpck_require__(5829); -var DEFAULT_UA_APP_ID = void 0; -function isValidUserAgentAppId(appId) { - if (appId === void 0) { - return true; - } - return typeof appId === "string" && appId.length <= 50; -} -__name(isValidUserAgentAppId, "isValidUserAgentAppId"); -function resolveUserAgentConfig(input) { - const normalizedAppIdProvider = (0, import_core.normalizeProvider)(input.userAgentAppId ?? DEFAULT_UA_APP_ID); - const { customUserAgent } = input; - return Object.assign(input, { - customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, - userAgentAppId: /* @__PURE__ */ __name(async () => { - const appId = await normalizedAppIdProvider(); - if (!isValidUserAgentAppId(appId)) { - const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; - if (typeof appId !== "string") { - logger?.warn("userAgentAppId must be a string or undefined."); - } else if (appId.length > 50) { - logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); - } - } - return appId; - }, "userAgentAppId") - }); -} -__name(resolveUserAgentConfig, "resolveUserAgentConfig"); +// src/fromProcess.ts +var import_shared_ini_file_loader = __nccwpck_require__(3507); -// src/user-agent-middleware.ts -var import_util_endpoints = __nccwpck_require__(3350); -var import_protocol_http = __nccwpck_require__(4418); +// src/resolveProcessCredentials.ts +var import_property_provider = __nccwpck_require__(9721); +var import_child_process = __nccwpck_require__(2081); +var import_util = __nccwpck_require__(3837); -// src/check-features.ts -var import_core2 = __nccwpck_require__(9963); -var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; -async function checkFeatures(context, config, args) { - const request = args.request; - if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { - (0, import_core2.setFeature)(context, "PROTOCOL_RPC_V2_CBOR", "M"); +// src/getValidatedProcessCredentials.ts +var import_client = __nccwpck_require__(2825); +var getValidatedProcessCredentials = /* @__PURE__ */ __name((profileName, data, profiles) => { + if (data.Version !== 1) { + throw Error(`Profile ${profileName} credential_process did not return Version 1.`); } - if (typeof config.retryStrategy === "function") { - const retryStrategy = await config.retryStrategy(); - if (typeof retryStrategy.acquireInitialRetryToken === "function") { - if (retryStrategy.constructor?.name?.includes("Adaptive")) { - (0, import_core2.setFeature)(context, "RETRY_MODE_ADAPTIVE", "F"); - } else { - (0, import_core2.setFeature)(context, "RETRY_MODE_STANDARD", "E"); + if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) { + throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); + } + if (data.Expiration) { + const currentTime = /* @__PURE__ */ new Date(); + const expireTime = new Date(data.Expiration); + if (expireTime < currentTime) { + throw Error(`Profile ${profileName} credential_process returned expired credentials.`); + } + } + let accountId = data.AccountId; + if (!accountId && profiles?.[profileName]?.aws_account_id) { + accountId = profiles[profileName].aws_account_id; + } + const credentials = { + accessKeyId: data.AccessKeyId, + secretAccessKey: data.SecretAccessKey, + ...data.SessionToken && { sessionToken: data.SessionToken }, + ...data.Expiration && { expiration: new Date(data.Expiration) }, + ...data.CredentialScope && { credentialScope: data.CredentialScope }, + ...accountId && { accountId } + }; + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_PROCESS", "w"); + return credentials; +}, "getValidatedProcessCredentials"); + +// src/resolveProcessCredentials.ts +var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger) => { + const profile = profiles[profileName]; + if (profiles[profileName]) { + const credentialProcess = profile["credential_process"]; + if (credentialProcess !== void 0) { + const execPromise = (0, import_util.promisify)(import_child_process.exec); + try { + const { stdout } = await execPromise(credentialProcess); + let data; + try { + data = JSON.parse(stdout.trim()); + } catch { + throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); + } + return getValidatedProcessCredentials(profileName, data, profiles); + } catch (error) { + throw new import_property_provider.CredentialsProviderError(error.message, { logger }); } } else { - (0, import_core2.setFeature)(context, "RETRY_MODE_LEGACY", "D"); + throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger }); } + } else { + throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { + logger + }); } - if (typeof config.accountIdEndpointMode === "function") { - const endpointV2 = context.endpointV2; - if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { - (0, import_core2.setFeature)(context, "ACCOUNT_ID_ENDPOINT", "O"); - } - switch (await config.accountIdEndpointMode?.()) { - case "disabled": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); - break; - case "preferred": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); - break; - case "required": - (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); - break; - } +}, "resolveProcessCredentials"); + +// src/fromProcess.ts +var fromProcess = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); + const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); + return resolveProcessCredentials( + (0, import_shared_ini_file_loader.getProfileName)({ + profile: init.profile ?? callerClientConfig?.profile + }), + profiles, + init.logger + ); +}, "fromProcess"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 6414: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; - if (identity?.$source) { - const credentials = identity; - if (credentials.accountId) { - (0, import_core2.setFeature)(context, "RESOLVED_ACCOUNT_ID", "T"); - } - for (const [key, value] of Object.entries(credentials.$source ?? {})) { - (0, import_core2.setFeature)(context, key, value); - } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/loadSso.ts +var loadSso_exports = {}; +__export(loadSso_exports, { + GetRoleCredentialsCommand: () => import_client_sso.GetRoleCredentialsCommand, + SSOClient: () => import_client_sso.SSOClient +}); +var import_client_sso; +var init_loadSso = __esm({ + "src/loadSso.ts"() { + "use strict"; + import_client_sso = __nccwpck_require__(2666); } -} -__name(checkFeatures, "checkFeatures"); +}); -// src/constants.ts -var USER_AGENT = "user-agent"; -var X_AMZ_USER_AGENT = "x-amz-user-agent"; -var SPACE = " "; -var UA_NAME_SEPARATOR = "/"; -var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g; -var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g; -var UA_ESCAPE_CHAR = "-"; +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromSSO: () => fromSSO, + isSsoProfile: () => isSsoProfile, + validateSsoProfile: () => validateSsoProfile +}); +module.exports = __toCommonJS(index_exports); -// src/encode-features.ts -var BYTE_LIMIT = 1024; -function encodeFeatures(features) { - let buffer = ""; - for (const key in features) { - const val = features[key]; - if (buffer.length + val.length + 1 <= BYTE_LIMIT) { - if (buffer.length) { - buffer += "," + val; - } else { - buffer += val; - } - continue; +// src/fromSSO.ts + + + +// src/isSsoProfile.ts +var isSsoProfile = /* @__PURE__ */ __name((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"), "isSsoProfile"); + +// src/resolveSSOCredentials.ts +var import_client = __nccwpck_require__(2825); +var import_token_providers = __nccwpck_require__(2843); +var import_property_provider = __nccwpck_require__(9721); +var import_shared_ini_file_loader = __nccwpck_require__(3507); +var SHOULD_FAIL_CREDENTIAL_CHAIN = false; +var resolveSSOCredentials = /* @__PURE__ */ __name(async ({ + ssoStartUrl, + ssoSession, + ssoAccountId, + ssoRegion, + ssoRoleName, + ssoClient, + clientConfig, + parentClientConfig, + profile, + logger +}) => { + let token; + const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; + if (ssoSession) { + try { + const _token = await (0, import_token_providers.fromSso)({ profile })(); + token = { + accessToken: _token.token, + expiresAt: new Date(_token.expiration).toISOString() + }; + } catch (e) { + throw new import_property_provider.CredentialsProviderError(e.message, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger + }); + } + } else { + try { + token = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoStartUrl); + } catch (e) { + throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger + }); } - break; } - return buffer; -} -__name(encodeFeatures, "encodeFeatures"); - -// src/user-agent-middleware.ts -var userAgentMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { - const { request } = args; - if (!import_protocol_http.HttpRequest.isInstance(request)) { - return next(args); + if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { + throw new import_property_provider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger + }); } - const { headers } = request; - const userAgent = context?.userAgent?.map(escapeUserAgent) || []; - const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); - await checkFeatures(context, options, args); - const awsContext = context; - defaultUserAgent.push( - `m/${encodeFeatures( - Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features) - )}` + const { accessToken } = token; + const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports)); + const sso = ssoClient || new SSOClient2( + Object.assign({}, clientConfig ?? {}, { + logger: clientConfig?.logger ?? parentClientConfig?.logger, + region: clientConfig?.region ?? ssoRegion + }) ); - const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; - const appId = await options.userAgentAppId(); - if (appId) { - defaultUserAgent.push(escapeUserAgent([`app/${appId}`])); + let ssoResp; + try { + ssoResp = await sso.send( + new GetRoleCredentialsCommand2({ + accountId: ssoAccountId, + roleName: ssoRoleName, + accessToken + }) + ); + } catch (e) { + throw new import_property_provider.CredentialsProviderError(e, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger + }); } - const prefix = (0, import_util_endpoints.getUserAgentPrefix)(); - const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE); - const normalUAValue = [ - ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), - ...customUserAgent - ].join(SPACE); - if (options.runtime !== "browser") { - if (normalUAValue) { - headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue; - } - headers[USER_AGENT] = sdkUserAgentValue; + const { + roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} + } = ssoResp; + if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { + throw new import_property_provider.CredentialsProviderError("SSO returns an invalid temporary credential.", { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger + }); + } + const credentials = { + accessKeyId, + secretAccessKey, + sessionToken, + expiration: new Date(expiration), + ...credentialScope && { credentialScope }, + ...accountId && { accountId } + }; + if (ssoSession) { + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO", "s"); } else { - headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_SSO_LEGACY", "u"); } - return next({ - ...args, - request - }); -}, "userAgentMiddleware"); -var escapeUserAgent = /* @__PURE__ */ __name((userAgentPair) => { - const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); - const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); - const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); - const prefix = name.substring(0, prefixSeparatorIndex); - let uaName = name.substring(prefixSeparatorIndex + 1); - if (prefix === "api") { - uaName = uaName.toLowerCase(); + return credentials; +}, "resolveSSOCredentials"); + +// src/validateSsoProfile.ts + +var validateSsoProfile = /* @__PURE__ */ __name((profile, logger) => { + 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 import_property_provider.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( + ", " + )} +Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, + { tryNextLink: false, logger } + ); } - 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}`; + return profile; +}, "validateSsoProfile"); + +// src/fromSSO.ts +var fromSSO = /* @__PURE__ */ __name((init = {}) => async ({ callerClientConfig } = {}) => { + init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; + const { ssoClient } = init; + const profileName = (0, import_shared_ini_file_loader.getProfileName)({ + profile: init.profile ?? callerClientConfig?.profile + }); + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); + const profile = profiles[profileName]; + if (!profile) { + throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger }); } - }, ""); -}, "escapeUserAgent"); -var getUserAgentMiddlewareOptions = { - name: "getUserAgentMiddleware", - step: "build", - priority: "low", - tags: ["SET_USER_AGENT", "USER_AGENT"], - override: true -}; -var getUserAgentPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: /* @__PURE__ */ __name((clientStack) => { - clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); - }, "applyToStack") -}), "getUserAgentPlugin"); + if (!isSsoProfile(profile)) { + throw new import_property_provider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { + logger: init.logger + }); + } + if (profile?.sso_session) { + const ssoSessions = await (0, import_shared_ini_file_loader.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 import_property_provider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { + tryNextLink: false, + logger: init.logger + }); + } + if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { + throw new import_property_provider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { + tryNextLink: false, + logger: init.logger + }); + } + 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 } = validateSsoProfile( + profile, + init.logger + ); + return resolveSSOCredentials({ + ssoStartUrl: sso_start_url, + ssoSession: sso_session, + ssoAccountId: sso_account_id, + ssoRegion: sso_region, + ssoRoleName: sso_role_name, + ssoClient, + clientConfig: init.clientConfig, + parentClientConfig: init.parentClientConfig, + profile: profileName + }); + } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { + throw new import_property_provider.CredentialsProviderError( + 'Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', + { tryNextLink: false, logger: init.logger } + ); + } else { + return resolveSSOCredentials({ + ssoStartUrl, + ssoSession, + ssoAccountId, + ssoRegion, + ssoRoleName, + ssoClient, + clientConfig: init.clientConfig, + parentClientConfig: init.parentClientConfig, + profile: profileName + }); + } +}, "fromSSO"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -53187,112 +37969,150 @@ var getUserAgentPlugin = /* @__PURE__ */ __name((config) => ({ /***/ }), -/***/ 9414: +/***/ 5614: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.defaultSSOOIDCHttpAuthSchemeProvider = exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(9963); -const util_middleware_1 = __nccwpck_require__(2390); -const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sso-oauth", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "CreateToken": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } +exports.fromTokenFile = void 0; +const client_1 = __nccwpck_require__(2825); +const property_provider_1 = __nccwpck_require__(9721); +const fs_1 = __nccwpck_require__(7147); +const fromWebToken_1 = __nccwpck_require__(7905); +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 () => { + init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); + const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; + const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN]; + const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; + if (!webIdentityTokenFile || !roleArn) { + throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { + logger: init.logger, + }); } - return options; -}; -exports.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); + const credentials = await (0, fromWebToken_1.fromWebToken)({ + ...init, + webIdentityToken: (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), + roleArn, + roleSessionName, + })(); + if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { + (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); + } + return credentials; }; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; +exports.fromTokenFile = fromTokenFile; /***/ }), -/***/ 5: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7905: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(3350); -const util_endpoints_2 = __nccwpck_require__(5473); -const ruleset_1 = __nccwpck_require__(932); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +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; }); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromWebToken = void 0; +const fromWebToken = (init) => async (awsIdentityProperties) => { + init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); + const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init; + let { roleAssumerWithWebIdentity } = init; + if (!roleAssumerWithWebIdentity) { + const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(2273))); + roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({ + ...init.clientConfig, + credentialProviderLogger: init.logger, + parentClientConfig: { + ...awsIdentityProperties?.callerClientConfig, + ...init.parentClientConfig, + }, + }, init.clientPlugins); + } + return roleAssumerWithWebIdentity({ + RoleArn: roleArn, + RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, + WebIdentityToken: webIdentityToken, + ProviderId: providerId, + PolicyArns: policyArns, + Policy: policy, + DurationSeconds: durationSeconds, + }); }; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; +exports.fromWebToken = fromWebToken; /***/ }), -/***/ 932: -/***/ ((__unused_webpack_module, exports) => { +/***/ 5646: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "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://oidc-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://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://oidc-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://oidc.{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://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; -exports.ruleSet = _data; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(5614), module.exports); +__reExport(index_exports, __nccwpck_require__(7905), module.exports); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 7334: +/***/ 6689: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -53316,1203 +38136,1129 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/sso-oidc/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - $Command: () => import_smithy_client6.Command, - AccessDeniedException: () => AccessDeniedException, - AuthorizationPendingException: () => AuthorizationPendingException, - CreateTokenCommand: () => CreateTokenCommand, - CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog, - CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog, - ExpiredTokenException: () => ExpiredTokenException, - InternalServerException: () => InternalServerException, - InvalidClientException: () => InvalidClientException, - InvalidGrantException: () => InvalidGrantException, - InvalidRequestException: () => InvalidRequestException, - InvalidScopeException: () => InvalidScopeException, - SSOOIDC: () => SSOOIDC, - SSOOIDCClient: () => SSOOIDCClient, - SSOOIDCServiceException: () => SSOOIDCServiceException, - SlowDownException: () => SlowDownException, - UnauthorizedClientException: () => UnauthorizedClientException, - UnsupportedGrantTypeException: () => UnsupportedGrantTypeException, - __Client: () => import_smithy_client2.Client + NODE_DISABLE_MULTIREGION_ACCESS_POINT_CONFIG_OPTIONS: () => NODE_DISABLE_MULTIREGION_ACCESS_POINT_CONFIG_OPTIONS, + NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME: () => NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME, + NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME: () => NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME, + NODE_USE_ARN_REGION_CONFIG_OPTIONS: () => NODE_USE_ARN_REGION_CONFIG_OPTIONS, + NODE_USE_ARN_REGION_ENV_NAME: () => NODE_USE_ARN_REGION_ENV_NAME, + NODE_USE_ARN_REGION_INI_NAME: () => NODE_USE_ARN_REGION_INI_NAME, + bucketEndpointMiddleware: () => bucketEndpointMiddleware, + bucketEndpointMiddlewareOptions: () => bucketEndpointMiddlewareOptions, + bucketHostname: () => bucketHostname, + getArnResources: () => getArnResources, + getBucketEndpointPlugin: () => getBucketEndpointPlugin, + getSuffixForArnEndpoint: () => getSuffixForArnEndpoint, + resolveBucketEndpointConfig: () => resolveBucketEndpointConfig, + validateAccountId: () => validateAccountId, + validateDNSHostLabel: () => validateDNSHostLabel, + validateNoDualstack: () => validateNoDualstack, + validateNoFIPS: () => validateNoFIPS, + validateOutpostService: () => validateOutpostService, + validatePartition: () => validatePartition, + validateRegion: () => validateRegion }); module.exports = __toCommonJS(index_exports); -// src/submodules/sso-oidc/SSOOIDCClient.ts -var import_middleware_host_header = __nccwpck_require__(2545); -var import_middleware_logger = __nccwpck_require__(14); -var import_middleware_recursion_detection = __nccwpck_require__(5525); -var import_middleware_user_agent = __nccwpck_require__(4688); -var import_config_resolver = __nccwpck_require__(3098); -var import_core = __nccwpck_require__(5829); -var import_middleware_content_length = __nccwpck_require__(2800); -var import_middleware_endpoint = __nccwpck_require__(2918); -var import_middleware_retry = __nccwpck_require__(6039); -var import_smithy_client2 = __nccwpck_require__(3570); -var import_httpAuthSchemeProvider = __nccwpck_require__(9414); - -// src/submodules/sso-oidc/endpoint/EndpointParameters.ts -var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "sso-oauth" - }); -}, "resolveClientEndpointParameters"); -var commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } +// src/NodeDisableMultiregionAccessPointConfigOptions.ts +var import_util_config_provider = __nccwpck_require__(3375); +var NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME = "AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS"; +var NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME = "s3_disable_multiregion_access_points"; +var NODE_DISABLE_MULTIREGION_ACCESS_POINT_CONFIG_OPTIONS = { + environmentVariableSelector: /* @__PURE__ */ __name((env) => (0, import_util_config_provider.booleanSelector)(env, NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME, import_util_config_provider.SelectorType.ENV), "environmentVariableSelector"), + configFileSelector: /* @__PURE__ */ __name((profile) => (0, import_util_config_provider.booleanSelector)(profile, NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME, import_util_config_provider.SelectorType.CONFIG), "configFileSelector"), + default: false }; -// src/submodules/sso-oidc/SSOOIDCClient.ts -var import_runtimeConfig = __nccwpck_require__(7277); - -// src/submodules/sso-oidc/runtimeExtensions.ts -var import_region_config_resolver = __nccwpck_require__(8156); -var import_protocol_http = __nccwpck_require__(4418); -var import_smithy_client = __nccwpck_require__(3570); - -// src/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.ts -var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; -}, "getHttpAuthExtensionConfiguration"); -var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; -}, "resolveHttpAuthRuntimeConfig"); - -// src/submodules/sso-oidc/runtimeExtensions.ts -var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign( - (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), - (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), - (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), - getHttpAuthExtensionConfiguration(runtimeConfig) - ); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign( - runtimeConfig, - (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), - (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), - (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), - resolveHttpAuthRuntimeConfig(extensionConfiguration) - ); -}, "resolveRuntimeExtensions"); +// src/NodeUseArnRegionConfigOptions.ts -// src/submodules/sso-oidc/SSOOIDCClient.ts -var SSOOIDCClient = class extends import_smithy_client2.Client { - static { - __name(this, "SSOOIDCClient"); - } - /** - * The resolved configuration of SSOOIDCClient class. This is resolved and normalized from the {@link SSOOIDCClientConfig | constructor configuration interface}. - */ - config; - constructor(...[configuration]) { - const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); - const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use( - (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials - }), "identityProviderConfigProvider") - }) - ); - this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); - } +var NODE_USE_ARN_REGION_ENV_NAME = "AWS_S3_USE_ARN_REGION"; +var NODE_USE_ARN_REGION_INI_NAME = "s3_use_arn_region"; +var NODE_USE_ARN_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: /* @__PURE__ */ __name((env) => (0, import_util_config_provider.booleanSelector)(env, NODE_USE_ARN_REGION_ENV_NAME, import_util_config_provider.SelectorType.ENV), "environmentVariableSelector"), + configFileSelector: /* @__PURE__ */ __name((profile) => (0, import_util_config_provider.booleanSelector)(profile, NODE_USE_ARN_REGION_INI_NAME, import_util_config_provider.SelectorType.CONFIG), "configFileSelector"), /** - * Destroy underlying resources, like sockets. It's usually not necessary to do this. - * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. - * Otherwise, sockets might stay open for quite a long time before the server terminates them. + * useArnRegion has specific behavior when undefined instead of false. + * We therefore use undefined as the default value instead of false. */ - destroy() { - super.destroy(); - } + default: void 0 }; -// src/submodules/sso-oidc/SSOOIDC.ts -var import_smithy_client7 = __nccwpck_require__(3570); - -// src/submodules/sso-oidc/commands/CreateTokenCommand.ts -var import_middleware_endpoint2 = __nccwpck_require__(2918); -var import_middleware_serde = __nccwpck_require__(1238); -var import_smithy_client6 = __nccwpck_require__(3570); - -// src/submodules/sso-oidc/models/models_0.ts -var import_smithy_client4 = __nccwpck_require__(3570); +// src/bucketEndpointMiddleware.ts +var import_util_arn_parser = __nccwpck_require__(5487); +var import_protocol_http = __nccwpck_require__(4418); -// src/submodules/sso-oidc/models/SSOOIDCServiceException.ts -var import_smithy_client3 = __nccwpck_require__(3570); -var SSOOIDCServiceException = class _SSOOIDCServiceException extends import_smithy_client3.ServiceException { - static { - __name(this, "SSOOIDCServiceException"); +// src/bucketHostnameUtils.ts +var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; +var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; +var DOTS_PATTERN = /\.\./; +var DOT_PATTERN = /\./; +var S3_HOSTNAME_PATTERN = /^(.+\.)?s3(-fips)?(\.dualstack)?[.-]([a-z0-9-]+)\./; +var S3_US_EAST_1_ALTNAME_PATTERN = /^s3(-external-1)?\.amazonaws\.com$/; +var AWS_PARTITION_SUFFIX = "amazonaws.com"; +var isBucketNameOptions = /* @__PURE__ */ __name((options) => typeof options.bucketName === "string", "isBucketNameOptions"); +var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName"); +var getRegionalSuffix = /* @__PURE__ */ __name((hostname) => { + const parts = hostname.match(S3_HOSTNAME_PATTERN); + return [parts[4], hostname.replace(new RegExp(`^${parts[0]}`), "")]; +}, "getRegionalSuffix"); +var getSuffix = /* @__PURE__ */ __name((hostname) => S3_US_EAST_1_ALTNAME_PATTERN.test(hostname) ? ["us-east-1", AWS_PARTITION_SUFFIX] : getRegionalSuffix(hostname), "getSuffix"); +var getSuffixForArnEndpoint = /* @__PURE__ */ __name((hostname) => S3_US_EAST_1_ALTNAME_PATTERN.test(hostname) ? [hostname.replace(`.${AWS_PARTITION_SUFFIX}`, ""), AWS_PARTITION_SUFFIX] : getRegionalSuffix(hostname), "getSuffixForArnEndpoint"); +var validateArnEndpointOptions = /* @__PURE__ */ __name((options) => { + if (options.pathStyleEndpoint) { + throw new Error("Path-style S3 endpoint is not supported when bucket is an ARN"); } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype); + if (options.accelerateEndpoint) { + throw new Error("Accelerate endpoint is not supported when bucket is an ARN"); } -}; - -// src/submodules/sso-oidc/models/models_0.ts -var AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException { - static { - __name(this, "AccessDeniedException"); + if (!options.tlsCompatible) { + throw new Error("HTTPS is required when bucket is an ARN"); } - name = "AccessDeniedException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be access_denied.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AccessDeniedException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; +}, "validateArnEndpointOptions"); +var validateService = /* @__PURE__ */ __name((service) => { + if (service !== "s3" && service !== "s3-outposts" && service !== "s3-object-lambda") { + throw new Error("Expect 's3' or 's3-outposts' or 's3-object-lambda' in ARN service component"); } -}; -var AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException { - static { - __name(this, "AuthorizationPendingException"); +}, "validateService"); +var validateS3Service = /* @__PURE__ */ __name((service) => { + if (service !== "s3") { + throw new Error("Expect 's3' in Accesspoint ARN service component"); } - name = "AuthorizationPendingException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * authorization_pending.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "AuthorizationPendingException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AuthorizationPendingException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; +}, "validateS3Service"); +var validateOutpostService = /* @__PURE__ */ __name((service) => { + if (service !== "s3-outposts") { + throw new Error("Expect 's3-posts' in Outpost ARN service component"); + } +}, "validateOutpostService"); +var validatePartition = /* @__PURE__ */ __name((partition, options) => { + if (partition !== options.clientPartition) { + throw new Error(`Partition in ARN is incompatible, got "${partition}" but expected "${options.clientPartition}"`); } -}; -var CreateTokenRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.clientSecret && { clientSecret: import_smithy_client4.SENSITIVE_STRING }, - ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.codeVerifier && { codeVerifier: import_smithy_client4.SENSITIVE_STRING } -}), "CreateTokenRequestFilterSensitiveLog"); -var CreateTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.accessToken && { accessToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, - ...obj.idToken && { idToken: import_smithy_client4.SENSITIVE_STRING } -}), "CreateTokenResponseFilterSensitiveLog"); -var ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException { - static { - __name(this, "ExpiredTokenException"); +}, "validatePartition"); +var validateRegion = /* @__PURE__ */ __name((region, options) => { +}, "validateRegion"); +var validateRegionalClient = /* @__PURE__ */ __name((region) => { + if (["s3-external-1", "aws-global"].includes(region)) { + throw new Error(`Client region ${region} is not regional`); } - name = "ExpiredTokenException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be expired_token.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; +}, "validateRegionalClient"); +var validateAccountId = /* @__PURE__ */ __name((accountId) => { + if (!/[0-9]{12}/.exec(accountId)) { + throw new Error("Access point ARN accountID does not match regex '[0-9]{12}'"); } -}; -var InternalServerException = class _InternalServerException extends SSOOIDCServiceException { - static { - __name(this, "InternalServerException"); +}, "validateAccountId"); +var validateDNSHostLabel = /* @__PURE__ */ __name((label, options = { tlsCompatible: true }) => { + if (label.length >= 64 || !/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(label) || /(\d+\.){3}\d+/.test(label) || /[.-]{2}/.test(label) || options?.tlsCompatible && DOT_PATTERN.test(label)) { + throw new Error(`Invalid DNS label ${label}`); } - name = "InternalServerException"; - $fault = "server"; - /** - *

Single error code. For this exception the value will be server_error.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InternalServerException", - $fault: "server", - ...opts - }); - Object.setPrototypeOf(this, _InternalServerException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; +}, "validateDNSHostLabel"); +var validateCustomEndpoint = /* @__PURE__ */ __name((options) => { + if (options.isCustomEndpoint) { + if (options.dualstackEndpoint) throw new Error("Dualstack endpoint is not supported with custom endpoint"); + if (options.accelerateEndpoint) throw new Error("Accelerate endpoint is not supported with custom endpoint"); } -}; -var InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException { - static { - __name(this, "InvalidClientException"); +}, "validateCustomEndpoint"); +var getArnResources = /* @__PURE__ */ __name((resource) => { + const delimiter = resource.includes(":") ? ":" : "/"; + const [resourceType, ...rest] = resource.split(delimiter); + if (resourceType === "accesspoint") { + if (rest.length !== 1 || rest[0] === "") { + throw new Error(`Access Point ARN should have one resource accesspoint${delimiter}{accesspointname}`); + } + return { accesspointName: rest[0] }; + } else if (resourceType === "outpost") { + if (!rest[0] || rest[1] !== "accesspoint" || !rest[2] || rest.length !== 3) { + throw new Error( + `Outpost ARN should have resource outpost${delimiter}{outpostId}${delimiter}accesspoint${delimiter}{accesspointName}` + ); + } + const [outpostId, _, accesspointName] = rest; + return { outpostId, accesspointName }; + } else { + throw new Error(`ARN resource should begin with 'accesspoint${delimiter}' or 'outpost${delimiter}'`); } - name = "InvalidClientException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * invalid_client.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidClientException", - $fault: "client", - ...opts +}, "getArnResources"); +var validateNoDualstack = /* @__PURE__ */ __name((dualstackEndpoint) => { +}, "validateNoDualstack"); +var validateNoFIPS = /* @__PURE__ */ __name((useFipsEndpoint) => { + if (useFipsEndpoint) throw new Error(`FIPS region is not supported with Outpost.`); +}, "validateNoFIPS"); +var validateMrapAlias = /* @__PURE__ */ __name((name) => { + try { + name.split(".").forEach((label) => { + validateDNSHostLabel(label); }); - Object.setPrototypeOf(this, _InvalidClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + } catch (e) { + throw new Error(`"${name}" is not a DNS compatible name.`); } -}; -var InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException { - static { - __name(this, "InvalidGrantException"); +}, "validateMrapAlias"); + +// src/bucketHostname.ts +var bucketHostname = /* @__PURE__ */ __name((options) => { + validateCustomEndpoint(options); + return isBucketNameOptions(options) ? ( + // Construct endpoint when bucketName is a string referring to a bucket name + getEndpointFromBucketName(options) + ) : ( + // Construct endpoint when bucketName is an ARN referring to an S3 resource like Access Point + getEndpointFromArn(options) + ); +}, "bucketHostname"); +var getEndpointFromBucketName = /* @__PURE__ */ __name(({ + accelerateEndpoint = false, + clientRegion: region, + baseHostname, + bucketName, + dualstackEndpoint = false, + fipsEndpoint = false, + pathStyleEndpoint = false, + tlsCompatible = true, + isCustomEndpoint = false +}) => { + const [clientRegion, hostnameSuffix] = isCustomEndpoint ? [region, baseHostname] : getSuffix(baseHostname); + if (pathStyleEndpoint || !isDnsCompatibleBucketName(bucketName) || tlsCompatible && DOT_PATTERN.test(bucketName)) { + return { + bucketEndpoint: false, + hostname: dualstackEndpoint ? `s3.dualstack.${clientRegion}.${hostnameSuffix}` : baseHostname + }; } - name = "InvalidGrantException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be invalid_grant.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidGrantException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidGrantException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + if (accelerateEndpoint) { + baseHostname = `s3-accelerate${dualstackEndpoint ? ".dualstack" : ""}.${hostnameSuffix}`; + } else if (dualstackEndpoint) { + baseHostname = `s3.dualstack.${clientRegion}.${hostnameSuffix}`; } -}; -var InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException { - static { - __name(this, "InvalidRequestException"); + return { + bucketEndpoint: true, + hostname: `${bucketName}.${baseHostname}` + }; +}, "getEndpointFromBucketName"); +var getEndpointFromArn = /* @__PURE__ */ __name((options) => { + const { isCustomEndpoint, baseHostname, clientRegion } = options; + const hostnameSuffix = isCustomEndpoint ? baseHostname : getSuffixForArnEndpoint(baseHostname)[1]; + const { + pathStyleEndpoint, + accelerateEndpoint = false, + fipsEndpoint = false, + tlsCompatible = true, + bucketName, + clientPartition = "aws" + } = options; + validateArnEndpointOptions({ pathStyleEndpoint, accelerateEndpoint, tlsCompatible }); + const { service, partition, accountId, region, resource } = bucketName; + validateService(service); + validatePartition(partition, { clientPartition }); + validateAccountId(accountId); + const { accesspointName, outpostId } = getArnResources(resource); + if (service === "s3-object-lambda") { + return getEndpointFromObjectLambdaArn({ ...options, tlsCompatible, bucketName, accesspointName, hostnameSuffix }); } - name = "InvalidRequestException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * invalid_request.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidRequestException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidRequestException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + if (region === "") { + return getEndpointFromMRAPArn({ ...options, clientRegion, mrapAlias: accesspointName, hostnameSuffix }); } -}; -var InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException { - static { - __name(this, "InvalidScopeException"); + if (outpostId) { + return getEndpointFromOutpostArn({ ...options, clientRegion, outpostId, accesspointName, hostnameSuffix }); } - name = "InvalidScopeException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be invalid_scope.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidScopeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidScopeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; + return getEndpointFromAccessPointArn({ ...options, clientRegion, accesspointName, hostnameSuffix }); +}, "getEndpointFromArn"); +var getEndpointFromObjectLambdaArn = /* @__PURE__ */ __name(({ + dualstackEndpoint = false, + fipsEndpoint = false, + tlsCompatible = true, + useArnRegion, + clientRegion, + clientSigningRegion = clientRegion, + accesspointName, + bucketName, + hostnameSuffix +}) => { + const { accountId, region, service } = bucketName; + validateRegionalClient(clientRegion); + const DNSHostLabel = `${accesspointName}-${accountId}`; + validateDNSHostLabel(DNSHostLabel, { tlsCompatible }); + const endpointRegion = useArnRegion ? region : clientRegion; + const signingRegion = useArnRegion ? region : clientSigningRegion; + return { + bucketEndpoint: true, + hostname: `${DNSHostLabel}.${service}${fipsEndpoint ? "-fips" : ""}.${endpointRegion}.${hostnameSuffix}`, + signingRegion, + signingService: service + }; +}, "getEndpointFromObjectLambdaArn"); +var getEndpointFromMRAPArn = /* @__PURE__ */ __name(({ + disableMultiregionAccessPoints, + dualstackEndpoint = false, + isCustomEndpoint, + mrapAlias, + hostnameSuffix +}) => { + if (disableMultiregionAccessPoints === true) { + throw new Error("SDK is attempting to use a MRAP ARN. Please enable to feature."); + } + validateMrapAlias(mrapAlias); + return { + bucketEndpoint: true, + hostname: `${mrapAlias}${isCustomEndpoint ? "" : `.accesspoint.s3-global`}.${hostnameSuffix}`, + signingRegion: "*" + }; +}, "getEndpointFromMRAPArn"); +var getEndpointFromOutpostArn = /* @__PURE__ */ __name(({ + useArnRegion, + clientRegion, + clientSigningRegion = clientRegion, + bucketName, + outpostId, + dualstackEndpoint = false, + fipsEndpoint = false, + tlsCompatible = true, + accesspointName, + isCustomEndpoint, + hostnameSuffix +}) => { + validateRegionalClient(clientRegion); + const DNSHostLabel = `${accesspointName}-${bucketName.accountId}`; + validateDNSHostLabel(DNSHostLabel, { tlsCompatible }); + const endpointRegion = useArnRegion ? bucketName.region : clientRegion; + const signingRegion = useArnRegion ? bucketName.region : clientSigningRegion; + validateOutpostService(bucketName.service); + validateDNSHostLabel(outpostId, { tlsCompatible }); + validateNoFIPS(fipsEndpoint); + const hostnamePrefix = `${DNSHostLabel}.${outpostId}`; + return { + bucketEndpoint: true, + hostname: `${hostnamePrefix}${isCustomEndpoint ? "" : `.s3-outposts.${endpointRegion}`}.${hostnameSuffix}`, + signingRegion, + signingService: "s3-outposts" + }; +}, "getEndpointFromOutpostArn"); +var getEndpointFromAccessPointArn = /* @__PURE__ */ __name(({ + useArnRegion, + clientRegion, + clientSigningRegion = clientRegion, + bucketName, + dualstackEndpoint = false, + fipsEndpoint = false, + tlsCompatible = true, + accesspointName, + isCustomEndpoint, + hostnameSuffix +}) => { + validateRegionalClient(clientRegion); + const hostnamePrefix = `${accesspointName}-${bucketName.accountId}`; + validateDNSHostLabel(hostnamePrefix, { tlsCompatible }); + const endpointRegion = useArnRegion ? bucketName.region : clientRegion; + const signingRegion = useArnRegion ? bucketName.region : clientSigningRegion; + validateS3Service(bucketName.service); + return { + bucketEndpoint: true, + hostname: `${hostnamePrefix}${isCustomEndpoint ? "" : `.s3-accesspoint${fipsEndpoint ? "-fips" : ""}${dualstackEndpoint ? ".dualstack" : ""}.${endpointRegion}`}.${hostnameSuffix}`, + signingRegion + }; +}, "getEndpointFromAccessPointArn"); + +// src/bucketEndpointMiddleware.ts +var bucketEndpointMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { + const { Bucket: bucketName } = args.input; + let replaceBucketInPath = options.bucketEndpoint; + const request = args.request; + if (import_protocol_http.HttpRequest.isInstance(request)) { + if (options.bucketEndpoint) { + request.hostname = bucketName; + } else if ((0, import_util_arn_parser.validate)(bucketName)) { + const bucketArn = (0, import_util_arn_parser.parse)(bucketName); + const clientRegion = await options.region(); + const useDualstackEndpoint = await options.useDualstackEndpoint(); + const useFipsEndpoint = await options.useFipsEndpoint(); + const { partition, signingRegion = clientRegion } = await options.regionInfoProvider(clientRegion, { useDualstackEndpoint, useFipsEndpoint }) || {}; + const useArnRegion = await options.useArnRegion(); + const { + hostname, + bucketEndpoint, + signingRegion: modifiedSigningRegion, + signingService + } = bucketHostname({ + bucketName: bucketArn, + baseHostname: request.hostname, + accelerateEndpoint: options.useAccelerateEndpoint, + dualstackEndpoint: useDualstackEndpoint, + fipsEndpoint: useFipsEndpoint, + pathStyleEndpoint: options.forcePathStyle, + tlsCompatible: request.protocol === "https:", + useArnRegion, + clientPartition: partition, + clientSigningRegion: signingRegion, + clientRegion, + isCustomEndpoint: options.isCustomEndpoint, + disableMultiregionAccessPoints: await options.disableMultiregionAccessPoints() + }); + if (modifiedSigningRegion && modifiedSigningRegion !== signingRegion) { + context["signing_region"] = modifiedSigningRegion; + } + if (signingService && signingService !== "s3") { + context["signing_service"] = signingService; + } + request.hostname = hostname; + replaceBucketInPath = bucketEndpoint; + } else { + const clientRegion = await options.region(); + const dualstackEndpoint = await options.useDualstackEndpoint(); + const fipsEndpoint = await options.useFipsEndpoint(); + const { hostname, bucketEndpoint } = bucketHostname({ + bucketName, + clientRegion, + baseHostname: request.hostname, + accelerateEndpoint: options.useAccelerateEndpoint, + dualstackEndpoint, + fipsEndpoint, + pathStyleEndpoint: options.forcePathStyle, + tlsCompatible: request.protocol === "https:", + isCustomEndpoint: options.isCustomEndpoint + }); + request.hostname = hostname; + replaceBucketInPath = bucketEndpoint; + } + if (replaceBucketInPath) { + request.path = request.path.replace(/^(\/)?[^\/]+/, ""); + if (request.path === "") { + request.path = "/"; + } + } } + return next({ ...args, request }); +}, "bucketEndpointMiddleware"); +var bucketEndpointMiddlewareOptions = { + tags: ["BUCKET_ENDPOINT"], + name: "bucketEndpointMiddleware", + relation: "before", + toMiddleware: "hostHeaderMiddleware", + override: true +}; +var getBucketEndpointPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo(bucketEndpointMiddleware(options), bucketEndpointMiddlewareOptions); + }, "applyToStack") +}), "getBucketEndpointPlugin"); + +// src/configurations.ts +function resolveBucketEndpointConfig(input) { + const { + bucketEndpoint = false, + forcePathStyle = false, + useAccelerateEndpoint = false, + // useArnRegion has specific behavior when undefined instead of false. + useArnRegion, + disableMultiregionAccessPoints = false + } = input; + return Object.assign(input, { + bucketEndpoint, + forcePathStyle, + useAccelerateEndpoint, + useArnRegion: typeof useArnRegion === "function" ? useArnRegion : () => Promise.resolve(useArnRegion), + disableMultiregionAccessPoints: typeof disableMultiregionAccessPoints === "function" ? disableMultiregionAccessPoints : () => Promise.resolve(disableMultiregionAccessPoints) + }); +} +__name(resolveBucketEndpointConfig, "resolveBucketEndpointConfig"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 1990: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var SlowDownException = class _SlowDownException extends SSOOIDCServiceException { - static { - __name(this, "SlowDownException"); - } - name = "SlowDownException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be slow_down.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "SlowDownException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _SlowDownException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; -var UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException { - static { - __name(this, "UnauthorizedClientException"); - } - name = "UnauthorizedClientException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * unauthorized_client.

- * @public - */ - error; - /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public - */ - error_description; - /** - * @internal - */ - constructor(opts) { - super({ - name: "UnauthorizedClientException", - $fault: "client", - ...opts +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + addExpectContinueMiddleware: () => addExpectContinueMiddleware, + addExpectContinueMiddlewareOptions: () => addExpectContinueMiddlewareOptions, + getAddExpectContinuePlugin: () => getAddExpectContinuePlugin +}); +module.exports = __toCommonJS(index_exports); +var import_protocol_http = __nccwpck_require__(4418); +function addExpectContinueMiddleware(options) { + return (next) => async (args) => { + const { request } = args; + if (import_protocol_http.HttpRequest.isInstance(request) && request.body && options.runtime === "node") { + if (options.requestHandler?.constructor?.name !== "FetchHttpHandler") { + request.headers = { + ...request.headers, + Expect: "100-continue" + }; + } + } + return next({ + ...args, + request }); - Object.setPrototypeOf(this, _UnauthorizedClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } + }; +} +__name(addExpectContinueMiddleware, "addExpectContinueMiddleware"); +var addExpectContinueMiddlewareOptions = { + step: "build", + tags: ["SET_EXPECT_HEADER", "EXPECT_HEADER"], + name: "addExpectContinueMiddleware", + override: true }; -var UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException { - static { - __name(this, "UnsupportedGrantTypeException"); +var getAddExpectContinuePlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(addExpectContinueMiddleware(options), addExpectContinueMiddlewareOptions); + }, "applyToStack") +}), "getAddExpectContinuePlugin"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 1436: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getCrc32ChecksumAlgorithmFunction = void 0; +const tslib_1 = __nccwpck_require__(4351); +const crc32_1 = __nccwpck_require__(8408); +const util_1 = __nccwpck_require__(4871); +const zlib = tslib_1.__importStar(__nccwpck_require__(9796)); +class NodeCrc32 { + checksum = 0; + update(data) { + this.checksum = zlib.crc32(data, this.checksum); + } + async digest() { + return (0, util_1.numToUint8)(this.checksum); + } + reset() { + this.checksum = 0; + } +} +const getCrc32ChecksumAlgorithmFunction = () => { + if (typeof zlib.crc32 === "undefined") { + return crc32_1.AwsCrc32; + } + return NodeCrc32; +}; +exports.getCrc32ChecksumAlgorithmFunction = getCrc32ChecksumAlgorithmFunction; + + +/***/ }), + +/***/ 3799: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - name = "UnsupportedGrantTypeException"; - $fault = "client"; - /** - *

Single error code. For this exception the value will be - * unsupported_grant_type.

- * @public - */ - error; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + CONFIG_REQUEST_CHECKSUM_CALCULATION: () => CONFIG_REQUEST_CHECKSUM_CALCULATION, + CONFIG_RESPONSE_CHECKSUM_VALIDATION: () => CONFIG_RESPONSE_CHECKSUM_VALIDATION, + ChecksumAlgorithm: () => ChecksumAlgorithm, + ChecksumLocation: () => ChecksumLocation, + DEFAULT_CHECKSUM_ALGORITHM: () => DEFAULT_CHECKSUM_ALGORITHM, + DEFAULT_REQUEST_CHECKSUM_CALCULATION: () => DEFAULT_REQUEST_CHECKSUM_CALCULATION, + DEFAULT_RESPONSE_CHECKSUM_VALIDATION: () => DEFAULT_RESPONSE_CHECKSUM_VALIDATION, + ENV_REQUEST_CHECKSUM_CALCULATION: () => ENV_REQUEST_CHECKSUM_CALCULATION, + ENV_RESPONSE_CHECKSUM_VALIDATION: () => ENV_RESPONSE_CHECKSUM_VALIDATION, + NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS: () => NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS, + NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS: () => NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS, + RequestChecksumCalculation: () => RequestChecksumCalculation, + ResponseChecksumValidation: () => ResponseChecksumValidation, + crc64NvmeCrtContainer: () => crc64NvmeCrtContainer, + flexibleChecksumsMiddleware: () => flexibleChecksumsMiddleware, + flexibleChecksumsMiddlewareOptions: () => flexibleChecksumsMiddlewareOptions, + getFlexibleChecksumsPlugin: () => getFlexibleChecksumsPlugin, + resolveFlexibleChecksumsConfig: () => resolveFlexibleChecksumsConfig +}); +module.exports = __toCommonJS(index_exports); + +// src/constants.ts +var RequestChecksumCalculation = { /** - *

Human-readable text providing additional information, used to assist the client developer - * in understanding the error that occurred.

- * @public + * When set, a checksum will be calculated for all request payloads of operations + * modeled with the {@link httpChecksum} trait where `requestChecksumRequired` is `true` + * AND/OR a `requestAlgorithmMember` is modeled. + * {@link https://smithy.io/2.0/aws/aws-core.html#aws-protocols-httpchecksum-trait httpChecksum} */ - error_description; + WHEN_SUPPORTED: "WHEN_SUPPORTED", /** - * @internal + * When set, a checksum will only be calculated for request payloads of operations + * modeled with the {@link httpChecksum} trait where `requestChecksumRequired` is `true` + * OR where a `requestAlgorithmMember` is modeled and the user sets it. + * {@link https://smithy.io/2.0/aws/aws-core.html#aws-protocols-httpchecksum-trait httpChecksum} */ - constructor(opts) { - super({ - name: "UnsupportedGrantTypeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } + WHEN_REQUIRED: "WHEN_REQUIRED" }; - -// src/submodules/sso-oidc/protocols/Aws_restJson1.ts -var import_core2 = __nccwpck_require__(9963); -var import_core3 = __nccwpck_require__(5829); -var import_smithy_client5 = __nccwpck_require__(3570); -var se_CreateTokenCommand = /* @__PURE__ */ __name(async (input, context) => { - const b = (0, import_core3.requestBuilder)(input, context); - const headers = { - "content-type": "application/json" - }; - b.bp("/token"); - let body; - body = JSON.stringify( - (0, import_smithy_client5.take)(input, { - clientId: [], - clientSecret: [], - code: [], - codeVerifier: [], - deviceCode: [], - grantType: [], - redirectUri: [], - refreshToken: [], - scope: /* @__PURE__ */ __name((_) => (0, import_smithy_client5._json)(_), "scope") - }) - ); - b.m("POST").h(headers).b(body); - return b.build(); -}, "se_CreateTokenCommand"); -var de_CreateTokenCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode !== 200 && output.statusCode >= 300) { - return de_CommandError(output, context); - } - const contents = (0, import_smithy_client5.map)({ - $metadata: deserializeMetadata(output) - }); - const data = (0, import_smithy_client5.expectNonNull)((0, import_smithy_client5.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); - const doc = (0, import_smithy_client5.take)(data, { - accessToken: import_smithy_client5.expectString, - expiresIn: import_smithy_client5.expectInt32, - idToken: import_smithy_client5.expectString, - refreshToken: import_smithy_client5.expectString, - tokenType: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - return contents; -}, "de_CreateTokenCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core2.parseJsonErrorBody)(output.body, context) - }; - const errorCode = (0, import_core2.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 - }); - } -}, "de_CommandError"); -var throwDefaultError = (0, import_smithy_client5.withBaseException)(SSOOIDCServiceException); -var de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new AccessDeniedException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_AccessDeniedExceptionRes"); -var de_AuthorizationPendingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new AuthorizationPendingException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_AuthorizationPendingExceptionRes"); -var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new ExpiredTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_ExpiredTokenExceptionRes"); -var de_InternalServerExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InternalServerException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InternalServerExceptionRes"); -var de_InvalidClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidClientException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidClientExceptionRes"); -var de_InvalidGrantExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidGrantException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidGrantExceptionRes"); -var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidRequestException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidRequestExceptionRes"); -var de_InvalidScopeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new InvalidScopeException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_InvalidScopeExceptionRes"); -var de_SlowDownExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new SlowDownException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_SlowDownExceptionRes"); -var de_UnauthorizedClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new UnauthorizedClientException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnauthorizedClientExceptionRes"); -var de_UnsupportedGrantTypeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const contents = (0, import_smithy_client5.map)({}); - const data = parsedOutput.body; - const doc = (0, import_smithy_client5.take)(data, { - error: import_smithy_client5.expectString, - error_description: import_smithy_client5.expectString - }); - Object.assign(contents, doc); - const exception = new UnsupportedGrantTypeException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents - }); - return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); -}, "de_UnsupportedGrantTypeExceptionRes"); -var deserializeMetadata = /* @__PURE__ */ __name((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"] -}), "deserializeMetadata"); - -// src/submodules/sso-oidc/commands/CreateTokenCommand.ts -var CreateTokenCommand = class extends import_smithy_client6.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() { - static { - __name(this, "CreateTokenCommand"); - } +var DEFAULT_REQUEST_CHECKSUM_CALCULATION = RequestChecksumCalculation.WHEN_SUPPORTED; +var ResponseChecksumValidation = { + /** + * When set, checksum validation MUST be performed on all response payloads of operations + * modeled with the {@link httpChecksum} trait where `responseAlgorithms` is modeled, + * except when no modeled checksum algorithms are supported by an SDK. + * {@link https://smithy.io/2.0/aws/aws-core.html#aws-protocols-httpchecksum-trait httpChecksum} + */ + WHEN_SUPPORTED: "WHEN_SUPPORTED", + /** + * When set, checksum validation MUST NOT be performed on response payloads of operations UNLESS + * the SDK supports the modeled checksum algorithms AND the user has set the `requestValidationModeMember` to `ENABLED`. + * It is currently impossible to model an operation as requiring a response checksum, + * but this setting leaves the door open for future updates. + */ + WHEN_REQUIRED: "WHEN_REQUIRED" }; +var DEFAULT_RESPONSE_CHECKSUM_VALIDATION = RequestChecksumCalculation.WHEN_SUPPORTED; +var ChecksumAlgorithm = /* @__PURE__ */ ((ChecksumAlgorithm3) => { + ChecksumAlgorithm3["MD5"] = "MD5"; + ChecksumAlgorithm3["CRC32"] = "CRC32"; + ChecksumAlgorithm3["CRC32C"] = "CRC32C"; + ChecksumAlgorithm3["CRC64NVME"] = "CRC64NVME"; + ChecksumAlgorithm3["SHA1"] = "SHA1"; + ChecksumAlgorithm3["SHA256"] = "SHA256"; + return ChecksumAlgorithm3; +})(ChecksumAlgorithm || {}); +var ChecksumLocation = /* @__PURE__ */ ((ChecksumLocation2) => { + ChecksumLocation2["HEADER"] = "header"; + ChecksumLocation2["TRAILER"] = "trailer"; + return ChecksumLocation2; +})(ChecksumLocation || {}); +var DEFAULT_CHECKSUM_ALGORITHM = "CRC32" /* CRC32 */; -// src/submodules/sso-oidc/SSOOIDC.ts -var commands = { - CreateTokenCommand -}; -var SSOOIDC = class extends SSOOIDCClient { - static { - __name(this, "SSOOIDC"); +// src/stringUnionSelector.ts +var stringUnionSelector = /* @__PURE__ */ __name((obj, key, union, type) => { + if (!(key in obj)) return void 0; + const value = obj[key].toUpperCase(); + if (!Object.values(union).includes(value)) { + throw new TypeError(`Cannot load ${type} '${key}'. Expected one of ${Object.values(union)}, got '${obj[key]}'.`); } -}; -(0, import_smithy_client7.createAggregatedClient)(commands, SSOOIDC); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), + return value; +}, "stringUnionSelector"); -/***/ 7277: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS.ts +var ENV_REQUEST_CHECKSUM_CALCULATION = "AWS_REQUEST_CHECKSUM_CALCULATION"; +var CONFIG_REQUEST_CHECKSUM_CALCULATION = "request_checksum_calculation"; +var NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS = { + environmentVariableSelector: /* @__PURE__ */ __name((env) => stringUnionSelector(env, ENV_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, "env" /* ENV */), "environmentVariableSelector"), + configFileSelector: /* @__PURE__ */ __name((profile) => stringUnionSelector(profile, CONFIG_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, "shared config entry" /* CONFIG */), "configFileSelector"), + default: DEFAULT_REQUEST_CHECKSUM_CALCULATION +}; -"use strict"; +// src/NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS.ts +var ENV_RESPONSE_CHECKSUM_VALIDATION = "AWS_RESPONSE_CHECKSUM_VALIDATION"; +var CONFIG_RESPONSE_CHECKSUM_VALIDATION = "response_checksum_validation"; +var NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS = { + environmentVariableSelector: /* @__PURE__ */ __name((env) => stringUnionSelector(env, ENV_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, "env" /* ENV */), "environmentVariableSelector"), + configFileSelector: /* @__PURE__ */ __name((profile) => stringUnionSelector(profile, CONFIG_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, "shared config entry" /* CONFIG */), "configFileSelector"), + default: DEFAULT_RESPONSE_CHECKSUM_VALIDATION +}; -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__(8842)); -const core_1 = __nccwpck_require__(9963); -const util_user_agent_node_1 = __nccwpck_require__(8095); -const config_resolver_1 = __nccwpck_require__(3098); -const hash_node_1 = __nccwpck_require__(3081); -const middleware_retry_1 = __nccwpck_require__(6039); -const node_config_provider_1 = __nccwpck_require__(3461); -const node_http_handler_1 = __nccwpck_require__(258); -const util_body_length_node_1 = __nccwpck_require__(8075); -const util_retry_1 = __nccwpck_require__(4902); -const runtimeConfig_shared_1 = __nccwpck_require__(9513); -const smithy_client_1 = __nccwpck_require__(3570); -const util_defaults_mode_node_1 = __nccwpck_require__(2429); -const smithy_client_2 = __nccwpck_require__(3570); -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); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ 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, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, - }, config), - 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, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; +// src/crc64-nvme-crt-container.ts +var crc64NvmeCrtContainer = { + CrtCrc64Nvme: null }; -exports.getRuntimeConfig = getRuntimeConfig; +// src/flexibleChecksumsMiddleware.ts +var import_core = __nccwpck_require__(9963); +var import_protocol_http = __nccwpck_require__(4418); +var import_util_stream = __nccwpck_require__(6607); -/***/ }), +// src/types.ts +var CLIENT_SUPPORTED_ALGORITHMS = [ + "CRC32" /* CRC32 */, + "CRC32C" /* CRC32C */, + "CRC64NVME" /* CRC64NVME */, + "SHA1" /* SHA1 */, + "SHA256" /* SHA256 */ +]; +var PRIORITY_ORDER_ALGORITHMS = [ + "SHA256" /* SHA256 */, + "SHA1" /* SHA1 */, + "CRC32" /* CRC32 */, + "CRC32C" /* CRC32C */, + "CRC64NVME" /* CRC64NVME */ +]; -/***/ 9513: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/getChecksumAlgorithmForRequest.ts +var getChecksumAlgorithmForRequest = /* @__PURE__ */ __name((input, { requestChecksumRequired, requestAlgorithmMember, requestChecksumCalculation }) => { + if (!requestAlgorithmMember) { + return requestChecksumCalculation === RequestChecksumCalculation.WHEN_SUPPORTED || requestChecksumRequired ? DEFAULT_CHECKSUM_ALGORITHM : void 0; + } + if (!input[requestAlgorithmMember]) { + return void 0; + } + const checksumAlgorithm = input[requestAlgorithmMember]; + if (!CLIENT_SUPPORTED_ALGORITHMS.includes(checksumAlgorithm)) { + throw new Error( + `The checksum algorithm "${checksumAlgorithm}" is not supported by the client. Select one of ${CLIENT_SUPPORTED_ALGORITHMS}.` + ); + } + return checksumAlgorithm; +}, "getChecksumAlgorithmForRequest"); -"use strict"; +// src/getChecksumLocationName.ts +var getChecksumLocationName = /* @__PURE__ */ __name((algorithm) => algorithm === "MD5" /* MD5 */ ? "content-md5" : `x-amz-checksum-${algorithm.toLowerCase()}`, "getChecksumLocationName"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(9963); -const core_2 = __nccwpck_require__(5829); -const smithy_client_1 = __nccwpck_require__(3570); -const url_parser_1 = __nccwpck_require__(4681); -const util_base64_1 = __nccwpck_require__(5600); -const util_utf8_1 = __nccwpck_require__(1895); -const httpAuthSchemeProvider_1 = __nccwpck_require__(9414); -const endpointResolver_1 = __nccwpck_require__(5); -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 ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - serviceId: config?.serviceId ?? "SSO OIDC", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; +// src/hasHeader.ts +var hasHeader = /* @__PURE__ */ __name((header, headers) => { + const soughtHeader = header.toLowerCase(); + for (const headerName of Object.keys(headers)) { + if (soughtHeader === headerName.toLowerCase()) { + return true; + } + } + return false; +}, "hasHeader"); +// src/hasHeaderWithPrefix.ts +var hasHeaderWithPrefix = /* @__PURE__ */ __name((headerPrefix, headers) => { + const soughtHeaderPrefix = headerPrefix.toLowerCase(); + for (const headerName of Object.keys(headers)) { + if (headerName.toLowerCase().startsWith(soughtHeaderPrefix)) { + return true; + } + } + return false; +}, "hasHeaderWithPrefix"); -/***/ }), +// src/isStreaming.ts +var import_is_array_buffer = __nccwpck_require__(780); +var isStreaming = /* @__PURE__ */ __name((body) => body !== void 0 && typeof body !== "string" && !ArrayBuffer.isView(body) && !(0, import_is_array_buffer.isArrayBuffer)(body), "isStreaming"); -/***/ 8974: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/selectChecksumAlgorithmFunction.ts +var import_crc32c = __nccwpck_require__(7035); +var import_getCrc32ChecksumAlgorithmFunction = __nccwpck_require__(1436); +var selectChecksumAlgorithmFunction = /* @__PURE__ */ __name((checksumAlgorithm, config) => { + switch (checksumAlgorithm) { + case "MD5" /* MD5 */: + return config.md5; + case "CRC32" /* CRC32 */: + return (0, import_getCrc32ChecksumAlgorithmFunction.getCrc32ChecksumAlgorithmFunction)(); + case "CRC32C" /* CRC32C */: + return import_crc32c.AwsCrc32c; + case "CRC64NVME" /* CRC64NVME */: + if (typeof crc64NvmeCrtContainer.CrtCrc64Nvme !== "function") { + throw new Error( + `Please check whether you have installed the "@aws-sdk/crc64-nvme-crt" package explicitly. +You must also register the package by calling [require("@aws-sdk/crc64-nvme-crt");] or an ESM equivalent such as [import "@aws-sdk/crc64-nvme-crt";]. +For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt` + ); + } + return crc64NvmeCrtContainer.CrtCrc64Nvme; + case "SHA1" /* SHA1 */: + return config.sha1; + case "SHA256" /* SHA256 */: + return config.sha256; + default: + throw new Error(`Unsupported checksum algorithm: ${checksumAlgorithm}`); + } +}, "selectChecksumAlgorithmFunction"); -"use strict"; +// src/stringHasher.ts +var import_util_utf8 = __nccwpck_require__(1895); +var stringHasher = /* @__PURE__ */ __name((checksumAlgorithmFn, body) => { + const hash = new checksumAlgorithmFn(); + hash.update((0, import_util_utf8.toUint8Array)(body || "")); + return hash.digest(); +}, "stringHasher"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.STSClient = exports.__Client = void 0; -const middleware_host_header_1 = __nccwpck_require__(2545); -const middleware_logger_1 = __nccwpck_require__(14); -const middleware_recursion_detection_1 = __nccwpck_require__(5525); -const middleware_user_agent_1 = __nccwpck_require__(4688); -const config_resolver_1 = __nccwpck_require__(3098); -const core_1 = __nccwpck_require__(5829); -const middleware_content_length_1 = __nccwpck_require__(2800); -const middleware_endpoint_1 = __nccwpck_require__(2918); -const middleware_retry_1 = __nccwpck_require__(6039); -const smithy_client_1 = __nccwpck_require__(3570); -Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); -const httpAuthSchemeProvider_1 = __nccwpck_require__(8013); -const EndpointParameters_1 = __nccwpck_require__(1765); -const runtimeConfig_1 = __nccwpck_require__(1798); -const runtimeExtensions_1 = __nccwpck_require__(669); -class STSClient extends smithy_client_1.Client { - config; - constructor(...[configuration]) { - const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); - const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); - const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); - const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); - const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); - 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, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - }), - })); - this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); +// src/flexibleChecksumsMiddleware.ts +var flexibleChecksumsMiddlewareOptions = { + name: "flexibleChecksumsMiddleware", + step: "build", + tags: ["BODY_CHECKSUM"], + override: true +}; +var flexibleChecksumsMiddleware = /* @__PURE__ */ __name((config, middlewareConfig) => (next, context) => async (args) => { + if (!import_protocol_http.HttpRequest.isInstance(args.request)) { + return next(args); + } + if (hasHeaderWithPrefix("x-amz-checksum-", args.request.headers)) { + return next(args); + } + const { request, input } = args; + const { body: requestBody, headers } = request; + const { base64Encoder, streamHasher } = config; + const { requestChecksumRequired, requestAlgorithmMember } = middlewareConfig; + const requestChecksumCalculation = await config.requestChecksumCalculation(); + const requestAlgorithmMemberName = requestAlgorithmMember?.name; + const requestAlgorithmMemberHttpHeader = requestAlgorithmMember?.httpHeader; + if (requestAlgorithmMemberName && !input[requestAlgorithmMemberName]) { + if (requestChecksumCalculation === RequestChecksumCalculation.WHEN_SUPPORTED || requestChecksumRequired) { + input[requestAlgorithmMemberName] = DEFAULT_CHECKSUM_ALGORITHM; + if (requestAlgorithmMemberHttpHeader) { + headers[requestAlgorithmMemberHttpHeader] = DEFAULT_CHECKSUM_ALGORITHM; + } } - destroy() { - super.destroy(); + } + const checksumAlgorithm = getChecksumAlgorithmForRequest(input, { + requestChecksumRequired, + requestAlgorithmMember: requestAlgorithmMember?.name, + requestChecksumCalculation + }); + let updatedBody = requestBody; + let updatedHeaders = headers; + if (checksumAlgorithm) { + switch (checksumAlgorithm) { + case "CRC32" /* CRC32 */: + (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32", "U"); + break; + case "CRC32C" /* CRC32C */: + (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32C", "V"); + break; + case "CRC64NVME" /* CRC64NVME */: + (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_CRC64", "W"); + break; + case "SHA1" /* SHA1 */: + (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_SHA1", "X"); + break; + case "SHA256" /* SHA256 */: + (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_SHA256", "Y"); + break; } -} -exports.STSClient = STSClient; + const checksumLocationName = getChecksumLocationName(checksumAlgorithm); + const checksumAlgorithmFn = selectChecksumAlgorithmFunction(checksumAlgorithm, config); + if (isStreaming(requestBody)) { + const { getAwsChunkedEncodingStream, bodyLengthChecker } = config; + updatedBody = getAwsChunkedEncodingStream( + typeof config.requestStreamBufferSize === "number" && config.requestStreamBufferSize >= 8 * 1024 ? (0, import_util_stream.createBufferedReadable)(requestBody, config.requestStreamBufferSize, context.logger) : requestBody, + { + base64Encoder, + bodyLengthChecker, + checksumLocationName, + checksumAlgorithmFn, + streamHasher + } + ); + updatedHeaders = { + ...headers, + "content-encoding": headers["content-encoding"] ? `${headers["content-encoding"]},aws-chunked` : "aws-chunked", + "transfer-encoding": "chunked", + "x-amz-decoded-content-length": headers["content-length"], + "x-amz-content-sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER", + "x-amz-trailer": checksumLocationName + }; + delete updatedHeaders["content-length"]; + } else if (!hasHeader(checksumLocationName, headers)) { + const rawChecksum = await stringHasher(checksumAlgorithmFn, requestBody); + updatedHeaders = { + ...headers, + [checksumLocationName]: base64Encoder(rawChecksum) + }; + } + } + const result = await next({ + ...args, + request: { + ...request, + headers: updatedHeaders, + body: updatedBody + } + }); + return result; +}, "flexibleChecksumsMiddleware"); +// src/flexibleChecksumsInputMiddleware.ts -/***/ }), +var flexibleChecksumsInputMiddlewareOptions = { + name: "flexibleChecksumsInputMiddleware", + toMiddleware: "serializerMiddleware", + relation: "before", + tags: ["BODY_CHECKSUM"], + override: true +}; +var flexibleChecksumsInputMiddleware = /* @__PURE__ */ __name((config, middlewareConfig) => (next, context) => async (args) => { + const input = args.input; + const { requestValidationModeMember } = middlewareConfig; + const requestChecksumCalculation = await config.requestChecksumCalculation(); + const responseChecksumValidation = await config.responseChecksumValidation(); + switch (requestChecksumCalculation) { + case RequestChecksumCalculation.WHEN_REQUIRED: + (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED", "a"); + break; + case RequestChecksumCalculation.WHEN_SUPPORTED: + (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED", "Z"); + break; + } + switch (responseChecksumValidation) { + case ResponseChecksumValidation.WHEN_REQUIRED: + (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED", "c"); + break; + case ResponseChecksumValidation.WHEN_SUPPORTED: + (0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED", "b"); + break; + } + if (requestValidationModeMember && !input[requestValidationModeMember]) { + if (responseChecksumValidation === ResponseChecksumValidation.WHEN_SUPPORTED) { + input[requestValidationModeMember] = "ENABLED"; + } + } + return next(args); +}, "flexibleChecksumsInputMiddleware"); -/***/ 4935: -/***/ ((__unused_webpack_module, exports) => { +// src/flexibleChecksumsResponseMiddleware.ts -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - }; -}; -exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - }; -}; -exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; +// src/getChecksumAlgorithmListForResponse.ts +var getChecksumAlgorithmListForResponse = /* @__PURE__ */ __name((responseAlgorithms = []) => { + const validChecksumAlgorithms = []; + for (const algorithm of PRIORITY_ORDER_ALGORITHMS) { + if (!responseAlgorithms.includes(algorithm) || !CLIENT_SUPPORTED_ALGORITHMS.includes(algorithm)) { + continue; + } + validChecksumAlgorithms.push(algorithm); + } + return validChecksumAlgorithms; +}, "getChecksumAlgorithmListForResponse"); +// src/isChecksumWithPartNumber.ts +var isChecksumWithPartNumber = /* @__PURE__ */ __name((checksum) => { + const lastHyphenIndex = checksum.lastIndexOf("-"); + if (lastHyphenIndex !== -1) { + const numberPart = checksum.slice(lastHyphenIndex + 1); + if (!numberPart.startsWith("0")) { + const number = parseInt(numberPart, 10); + if (!isNaN(number) && number >= 1 && number <= 1e4) { + return true; + } + } + } + return false; +}, "isChecksumWithPartNumber"); -/***/ }), +// src/validateChecksumFromResponse.ts -/***/ 8013: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +// src/getChecksum.ts +var getChecksum = /* @__PURE__ */ __name(async (body, { checksumAlgorithmFn, base64Encoder }) => base64Encoder(await stringHasher(checksumAlgorithmFn, body)), "getChecksum"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; -const core_1 = __nccwpck_require__(9963); -const util_middleware_1 = __nccwpck_require__(2390); -const STSClient_1 = __nccwpck_require__(8974); -const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || - (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })(), - }; -}; -exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sts", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSTSHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "AssumeRoleWithWebIdentity": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); +// src/validateChecksumFromResponse.ts +var validateChecksumFromResponse = /* @__PURE__ */ __name(async (response, { config, responseAlgorithms, logger }) => { + const checksumAlgorithms = getChecksumAlgorithmListForResponse(responseAlgorithms); + const { body: responseBody, headers: responseHeaders } = response; + for (const algorithm of checksumAlgorithms) { + const responseHeader = getChecksumLocationName(algorithm); + const checksumFromResponse = responseHeaders[responseHeader]; + if (checksumFromResponse) { + let checksumAlgorithmFn; + try { + checksumAlgorithmFn = selectChecksumAlgorithmFunction(algorithm, config); + } catch (error) { + if (algorithm === "CRC64NVME" /* CRC64NVME */) { + logger?.warn(`Skipping ${"CRC64NVME" /* CRC64NVME */} checksum validation: ${error.message}`); + continue; } + throw error; + } + const { base64Encoder } = config; + if (isStreaming(responseBody)) { + response.body = (0, import_util_stream.createChecksumStream)({ + expectedChecksum: checksumFromResponse, + checksumSourceLocation: responseHeader, + checksum: new checksumAlgorithmFn(), + source: responseBody, + base64Encoder + }); + return; + } + const checksum = await getChecksum(responseBody, { checksumAlgorithmFn, base64Encoder }); + if (checksum === checksumFromResponse) { + break; + } + throw new Error( + `Checksum mismatch: expected "${checksum}" but received "${checksumFromResponse}" in response header "${responseHeader}".` + ); } - return options; + } +}, "validateChecksumFromResponse"); + +// src/flexibleChecksumsResponseMiddleware.ts +var flexibleChecksumsResponseMiddlewareOptions = { + name: "flexibleChecksumsResponseMiddleware", + toMiddleware: "deserializerMiddleware", + relation: "after", + tags: ["BODY_CHECKSUM"], + override: true }; -exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; -const resolveStsAuthConfig = (input) => Object.assign(input, { - stsClientCtor: STSClient_1.STSClient, -}); -exports.resolveStsAuthConfig = resolveStsAuthConfig; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, exports.resolveStsAuthConfig)(config); - const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); - return Object.assign(config_1, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), +var flexibleChecksumsResponseMiddleware = /* @__PURE__ */ __name((config, middlewareConfig) => (next, context) => async (args) => { + if (!import_protocol_http.HttpRequest.isInstance(args.request)) { + return next(args); + } + const input = args.input; + const result = await next(args); + const response = result.response; + const { requestValidationModeMember, responseAlgorithms } = middlewareConfig; + if (requestValidationModeMember && input[requestValidationModeMember] === "ENABLED") { + const { clientName, commandName } = context; + const isS3WholeObjectMultipartGetResponseChecksum = clientName === "S3Client" && commandName === "GetObjectCommand" && getChecksumAlgorithmListForResponse(responseAlgorithms).every((algorithm) => { + const responseHeader = getChecksumLocationName(algorithm); + const checksumFromResponse = response.headers[responseHeader]; + return !checksumFromResponse || isChecksumWithPartNumber(checksumFromResponse); }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; - + if (isS3WholeObjectMultipartGetResponseChecksum) { + return result; + } + await validateChecksumFromResponse(response, { + config, + responseAlgorithms, + logger: context.logger + }); + } + return result; +}, "flexibleChecksumsResponseMiddleware"); -/***/ }), +// src/getFlexibleChecksumsPlugin.ts +var getFlexibleChecksumsPlugin = /* @__PURE__ */ __name((config, middlewareConfig) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(flexibleChecksumsMiddleware(config, middlewareConfig), flexibleChecksumsMiddlewareOptions); + clientStack.addRelativeTo( + flexibleChecksumsInputMiddleware(config, middlewareConfig), + flexibleChecksumsInputMiddlewareOptions + ); + clientStack.addRelativeTo( + flexibleChecksumsResponseMiddleware(config, middlewareConfig), + flexibleChecksumsResponseMiddlewareOptions + ); + }, "applyToStack") +}), "getFlexibleChecksumsPlugin"); -/***/ 1765: -/***/ ((__unused_webpack_module, exports) => { +// src/resolveFlexibleChecksumsConfig.ts +var import_util_middleware = __nccwpck_require__(2390); +var resolveFlexibleChecksumsConfig = /* @__PURE__ */ __name((input) => { + const { requestChecksumCalculation, responseChecksumValidation, requestStreamBufferSize } = input; + return Object.assign(input, { + requestChecksumCalculation: (0, import_util_middleware.normalizeProvider)(requestChecksumCalculation ?? DEFAULT_REQUEST_CHECKSUM_CALCULATION), + responseChecksumValidation: (0, import_util_middleware.normalizeProvider)(responseChecksumValidation ?? DEFAULT_RESPONSE_CHECKSUM_VALIDATION), + requestStreamBufferSize: Number(requestStreamBufferSize ?? 0) + }); +}, "resolveFlexibleChecksumsConfig"); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.commonParams = exports.resolveClientEndpointParameters = void 0; -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - useGlobalEndpoint: options.useGlobalEndpoint ?? false, - defaultSigningName: "sts", - }); -}; -exports.resolveClientEndpointParameters = resolveClientEndpointParameters; -exports.commonParams = { - 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" }, -}; /***/ }), -/***/ 7561: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 2545: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.defaultEndpointResolver = void 0; -const util_endpoints_1 = __nccwpck_require__(3350); -const util_endpoints_2 = __nccwpck_require__(5473); -const ruleset_1 = __nccwpck_require__(9127); -const cache = new util_endpoints_2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], -}); -const defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams: endpointParams, - logger: context.logger, - })); +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -exports.defaultEndpointResolver = defaultEndpointResolver; -util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - - -/***/ }), +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -/***/ 9127: -/***/ ((__unused_webpack_module, exports) => { +// src/index.ts +var index_exports = {}; +__export(index_exports, { + getHostHeaderPlugin: () => getHostHeaderPlugin, + hostHeaderMiddleware: () => hostHeaderMiddleware, + hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions, + resolveHostHeaderConfig: () => resolveHostHeaderConfig +}); +module.exports = __toCommonJS(index_exports); +var import_protocol_http = __nccwpck_require__(4418); +function resolveHostHeaderConfig(input) { + return input; +} +__name(resolveHostHeaderConfig, "resolveHostHeaderConfig"); +var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { + if (!import_protocol_http.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); +}, "hostHeaderMiddleware"); +var hostHeaderMiddlewareOptions = { + name: "hostHeaderMiddleware", + step: "build", + priority: "low", + tags: ["HOST"], + override: true +}; +var getHostHeaderPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); + }, "applyToStack") +}), "getHostHeaderPlugin"); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -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; /***/ }), -/***/ 2273: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 2098: +/***/ ((module) => { "use strict"; @@ -54533,1068 +39279,886 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/sts/index.ts +// src/index.ts var index_exports = {}; __export(index_exports, { - AssumeRoleCommand: () => AssumeRoleCommand, - AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog, - AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand, - AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog, - AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog, - ClientInputEndpointParameters: () => import_EndpointParameters3.ClientInputEndpointParameters, - CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog, - ExpiredTokenException: () => ExpiredTokenException, - IDPCommunicationErrorException: () => IDPCommunicationErrorException, - IDPRejectedClaimException: () => IDPRejectedClaimException, - InvalidIdentityTokenException: () => InvalidIdentityTokenException, - MalformedPolicyDocumentException: () => MalformedPolicyDocumentException, - PackedPolicyTooLargeException: () => PackedPolicyTooLargeException, - RegionDisabledException: () => RegionDisabledException, - STS: () => STS, - STSServiceException: () => STSServiceException, - decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, - getDefaultRoleAssumer: () => getDefaultRoleAssumer2, - getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 + getLocationConstraintPlugin: () => getLocationConstraintPlugin, + locationConstraintMiddleware: () => locationConstraintMiddleware, + locationConstraintMiddlewareOptions: () => locationConstraintMiddlewareOptions }); module.exports = __toCommonJS(index_exports); -__reExport(index_exports, __nccwpck_require__(8974), module.exports); +function locationConstraintMiddleware(options) { + return (next) => async (args) => { + const { CreateBucketConfiguration } = args.input; + const region = await options.region(); + if (!CreateBucketConfiguration?.LocationConstraint && !CreateBucketConfiguration?.Location) { + args = { + ...args, + input: { + ...args.input, + CreateBucketConfiguration: region === "us-east-1" ? void 0 : { LocationConstraint: region } + } + }; + } + return next(args); + }; +} +__name(locationConstraintMiddleware, "locationConstraintMiddleware"); +var locationConstraintMiddlewareOptions = { + step: "initialize", + tags: ["LOCATION_CONSTRAINT", "CREATE_BUCKET_CONFIGURATION"], + name: "locationConstraintMiddleware", + override: true +}; +var getLocationConstraintPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(locationConstraintMiddleware(config), locationConstraintMiddlewareOptions); + }, "applyToStack") +}), "getLocationConstraintPlugin"); +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/sts/STS.ts -var import_smithy_client6 = __nccwpck_require__(3570); +0 && (0); -// src/submodules/sts/commands/AssumeRoleCommand.ts -var import_middleware_endpoint = __nccwpck_require__(2918); -var import_middleware_serde = __nccwpck_require__(1238); -var import_smithy_client4 = __nccwpck_require__(3570); -var import_EndpointParameters = __nccwpck_require__(1765); -// src/submodules/sts/models/models_0.ts -var import_smithy_client2 = __nccwpck_require__(3570); -// src/submodules/sts/models/STSServiceException.ts -var import_smithy_client = __nccwpck_require__(3570); -var STSServiceException = class _STSServiceException extends import_smithy_client.ServiceException { - static { - __name(this, "STSServiceException"); - } - /** - * @internal - */ - constructor(options) { - super(options); - Object.setPrototypeOf(this, _STSServiceException.prototype); - } -}; +/***/ }), -// src/submodules/sts/models/models_0.ts -var CredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client2.SENSITIVE_STRING } -}), "CredentialsFilterSensitiveLog"); -var AssumeRoleResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleResponseFilterSensitiveLog"); -var ExpiredTokenException = class _ExpiredTokenException extends STSServiceException { - static { - __name(this, "ExpiredTokenException"); - } - name = "ExpiredTokenException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - } -}; -var MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { - static { - __name(this, "MalformedPolicyDocumentException"); - } - name = "MalformedPolicyDocumentException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "MalformedPolicyDocumentException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); - } -}; -var PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { - static { - __name(this, "PackedPolicyTooLargeException"); - } - name = "PackedPolicyTooLargeException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "PackedPolicyTooLargeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); - } -}; -var RegionDisabledException = class _RegionDisabledException extends STSServiceException { - static { - __name(this, "RegionDisabledException"); - } - name = "RegionDisabledException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "RegionDisabledException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _RegionDisabledException.prototype); - } +/***/ 14: +/***/ ((module) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { - static { - __name(this, "IDPRejectedClaimException"); - } - name = "IDPRejectedClaimException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "IDPRejectedClaimException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; -var InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { - static { - __name(this, "InvalidIdentityTokenException"); - } - name = "InvalidIdentityTokenException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "InvalidIdentityTokenException", - $fault: "client", - ...opts +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + getLoggerPlugin: () => getLoggerPlugin, + loggerMiddleware: () => loggerMiddleware, + loggerMiddlewareOptions: () => loggerMiddlewareOptions +}); +module.exports = __toCommonJS(index_exports); + +// src/loggerMiddleware.ts +var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => { + try { + const response = await next(args); + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; + const { $metadata, ...outputWithoutMetadata } = response.output; + logger?.info?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + output: outputFilterSensitiveLog(outputWithoutMetadata), + metadata: $metadata }); - Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); + return response; + } catch (error) { + const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + logger?.error?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + error, + metadata: error.$metadata + }); + throw error; } +}, "loggerMiddleware"); +var loggerMiddlewareOptions = { + name: "loggerMiddleware", + tags: ["LOGGER"], + step: "initialize", + override: true }; -var AssumeRoleWithWebIdentityRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client2.SENSITIVE_STRING } -}), "AssumeRoleWithWebIdentityRequestFilterSensitiveLog"); -var AssumeRoleWithWebIdentityResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ - ...obj, - ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } -}), "AssumeRoleWithWebIdentityResponseFilterSensitiveLog"); -var IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { - static { - __name(this, "IDPCommunicationErrorException"); - } - name = "IDPCommunicationErrorException"; - $fault = "client"; - /** - * @internal - */ - constructor(opts) { - super({ - name: "IDPCommunicationErrorException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); +var getLoggerPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); + }, "applyToStack") +}), "getLoggerPlugin"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 5525: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/sts/protocols/Aws_query.ts -var import_core = __nccwpck_require__(9963); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + addRecursionDetectionMiddlewareOptions: () => addRecursionDetectionMiddlewareOptions, + getRecursionDetectionPlugin: () => getRecursionDetectionPlugin, + recursionDetectionMiddleware: () => recursionDetectionMiddleware +}); +module.exports = __toCommonJS(index_exports); var import_protocol_http = __nccwpck_require__(4418); -var import_smithy_client3 = __nccwpck_require__(3570); -var se_AssumeRoleCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleRequest(input, context), - [_A]: _AR, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleCommand"); -var se_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (input, context) => { - const headers = SHARED_HEADERS; - let body; - body = buildFormUrlencodedString({ - ...se_AssumeRoleWithWebIdentityRequest(input, context), - [_A]: _ARWWI, - [_V]: _ - }); - return buildHttpRpcRequest(context, headers, "/", void 0, body); -}, "se_AssumeRoleWithWebIdentityCommand"); -var de_AssumeRoleCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); +var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; +var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; +var ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; +var recursionDetectionMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => { + const { request } = args; + if (!import_protocol_http.HttpRequest.isInstance(request) || options.runtime !== "node") { + return next(args); } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleResponse(data.AssumeRoleResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleCommand"); -var de_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (output, context) => { - if (output.statusCode >= 300) { - return de_CommandError(output, context); + const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME; + if (request.headers.hasOwnProperty(traceIdHeader)) { + return next(args); } - const data = await (0, import_core.parseXmlBody)(output.body, context); - let contents = {}; - contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context); - const response = { - $metadata: deserializeMetadata(output), - ...contents - }; - return response; -}, "de_AssumeRoleWithWebIdentityCommand"); -var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { - const parsedOutput = { - ...output, - body: await (0, import_core.parseXmlErrorBody)(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); - 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); - default: - const parsedBody = parsedOutput.body; - return throwDefaultError({ - output, - parsedBody: parsedBody.Error, - errorCode - }); + const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; + const traceId = process.env[ENV_TRACE_ID]; + const nonEmptyString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0, "nonEmptyString"); + if (nonEmptyString(functionName) && nonEmptyString(traceId)) { + request.headers[TRACE_ID_HEADER_NAME] = traceId; } -}, "de_CommandError"); -var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_ExpiredTokenException(body.Error, context); - const exception = new ExpiredTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_ExpiredTokenExceptionRes"); -var de_IDPCommunicationErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_IDPCommunicationErrorException(body.Error, context); - const exception = new IDPCommunicationErrorException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_IDPCommunicationErrorExceptionRes"); -var de_IDPRejectedClaimExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_IDPRejectedClaimException(body.Error, context); - const exception = new IDPRejectedClaimException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_IDPRejectedClaimExceptionRes"); -var de_InvalidIdentityTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_InvalidIdentityTokenException(body.Error, context); - const exception = new InvalidIdentityTokenException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_InvalidIdentityTokenExceptionRes"); -var de_MalformedPolicyDocumentExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_MalformedPolicyDocumentException(body.Error, context); - const exception = new MalformedPolicyDocumentException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_MalformedPolicyDocumentExceptionRes"); -var de_PackedPolicyTooLargeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_PackedPolicyTooLargeException(body.Error, context); - const exception = new PackedPolicyTooLargeException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized - }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_PackedPolicyTooLargeExceptionRes"); -var de_RegionDisabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { - const body = parsedOutput.body; - const deserialized = de_RegionDisabledException(body.Error, context); - const exception = new RegionDisabledException({ - $metadata: deserializeMetadata(parsedOutput), - ...deserialized + return next({ + ...args, + request }); - return (0, import_smithy_client3.decorateServiceException)(exception, body); -}, "de_RegionDisabledExceptionRes"); -var se_AssumeRoleRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; - } - if (input[_RSN] != null) { - entries[_RSN] = input[_RSN]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - if (input[_T] != null) { - const memberEntries = se_tagListType(input[_T], context); - if (input[_T]?.length === 0) { - entries.Tags = []; - } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `Tags.${key}`; - entries[loc] = value; - }); +}, "recursionDetectionMiddleware"); +var addRecursionDetectionMiddlewareOptions = { + step: "build", + tags: ["RECURSION_DETECTION"], + name: "recursionDetectionMiddleware", + override: true, + priority: "low" +}; +var getRecursionDetectionPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions); + }, "applyToStack") +}), "getRecursionDetectionPlugin"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 1139: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - if (input[_TTK] != null) { - const memberEntries = se_tagKeyListType(input[_TTK], context); - if (input[_TTK]?.length === 0) { - entries.TransitiveTagKeys = []; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS: () => NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS, + S3ExpressIdentityCache: () => S3ExpressIdentityCache, + S3ExpressIdentityCacheEntry: () => S3ExpressIdentityCacheEntry, + S3ExpressIdentityProviderImpl: () => S3ExpressIdentityProviderImpl, + SignatureV4S3Express: () => SignatureV4S3Express, + checkContentLengthHeader: () => checkContentLengthHeader, + checkContentLengthHeaderMiddlewareOptions: () => checkContentLengthHeaderMiddlewareOptions, + getCheckContentLengthHeaderPlugin: () => getCheckContentLengthHeaderPlugin, + getRegionRedirectMiddlewarePlugin: () => getRegionRedirectMiddlewarePlugin, + getS3ExpiresMiddlewarePlugin: () => getS3ExpiresMiddlewarePlugin, + getS3ExpressHttpSigningPlugin: () => getS3ExpressHttpSigningPlugin, + getS3ExpressPlugin: () => getS3ExpressPlugin, + getThrow200ExceptionsPlugin: () => getThrow200ExceptionsPlugin, + getValidateBucketNamePlugin: () => getValidateBucketNamePlugin, + regionRedirectEndpointMiddleware: () => regionRedirectEndpointMiddleware, + regionRedirectEndpointMiddlewareOptions: () => regionRedirectEndpointMiddlewareOptions, + regionRedirectMiddleware: () => regionRedirectMiddleware, + regionRedirectMiddlewareOptions: () => regionRedirectMiddlewareOptions, + resolveS3Config: () => resolveS3Config, + s3ExpiresMiddleware: () => s3ExpiresMiddleware, + s3ExpiresMiddlewareOptions: () => s3ExpiresMiddlewareOptions, + s3ExpressHttpSigningMiddleware: () => s3ExpressHttpSigningMiddleware, + s3ExpressHttpSigningMiddlewareOptions: () => s3ExpressHttpSigningMiddlewareOptions, + s3ExpressMiddleware: () => s3ExpressMiddleware, + s3ExpressMiddlewareOptions: () => s3ExpressMiddlewareOptions, + throw200ExceptionsMiddleware: () => throw200ExceptionsMiddleware, + throw200ExceptionsMiddlewareOptions: () => throw200ExceptionsMiddlewareOptions, + validateBucketNameMiddleware: () => validateBucketNameMiddleware, + validateBucketNameMiddlewareOptions: () => validateBucketNameMiddlewareOptions +}); +module.exports = __toCommonJS(index_exports); + +// src/check-content-length-header.ts +var import_protocol_http = __nccwpck_require__(4418); +var import_smithy_client = __nccwpck_require__(3570); +var CONTENT_LENGTH_HEADER = "content-length"; +var DECODED_CONTENT_LENGTH_HEADER = "x-amz-decoded-content-length"; +function checkContentLengthHeader() { + return (next, context) => async (args) => { + const { request } = args; + if (import_protocol_http.HttpRequest.isInstance(request)) { + if (!(CONTENT_LENGTH_HEADER in request.headers) && !(DECODED_CONTENT_LENGTH_HEADER in request.headers)) { + const message = `Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.`; + if (typeof context?.logger?.warn === "function" && !(context.logger instanceof import_smithy_client.NoOpLogger)) { + context.logger.warn(message); + } else { + console.warn(message); + } + } } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `TransitiveTagKeys.${key}`; - entries[loc] = value; - }); - } - if (input[_EI] != null) { - entries[_EI] = input[_EI]; - } - if (input[_SN] != null) { - entries[_SN] = input[_SN]; - } - if (input[_TC] != null) { - entries[_TC] = input[_TC]; - } - if (input[_SI] != null) { - entries[_SI] = input[_SI]; - } - if (input[_PC] != null) { - const memberEntries = se_ProvidedContextsListType(input[_PC], context); - if (input[_PC]?.length === 0) { - entries.ProvidedContexts = []; + return next({ ...args }); + }; +} +__name(checkContentLengthHeader, "checkContentLengthHeader"); +var checkContentLengthHeaderMiddlewareOptions = { + step: "finalizeRequest", + tags: ["CHECK_CONTENT_LENGTH_HEADER"], + name: "getCheckContentLengthHeaderPlugin", + override: true +}; +var getCheckContentLengthHeaderPlugin = /* @__PURE__ */ __name((unused) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(checkContentLengthHeader(), checkContentLengthHeaderMiddlewareOptions); + }, "applyToStack") +}), "getCheckContentLengthHeaderPlugin"); + +// src/region-redirect-endpoint-middleware.ts +var regionRedirectEndpointMiddleware = /* @__PURE__ */ __name((config) => { + return (next, context) => async (args) => { + const originalRegion = await config.region(); + const regionProviderRef = config.region; + let unlock = /* @__PURE__ */ __name(() => { + }, "unlock"); + if (context.__s3RegionRedirect) { + Object.defineProperty(config, "region", { + writable: false, + value: /* @__PURE__ */ __name(async () => { + return context.__s3RegionRedirect; + }, "value") + }); + unlock = /* @__PURE__ */ __name(() => Object.defineProperty(config, "region", { + writable: true, + value: regionProviderRef + }), "unlock"); } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `ProvidedContexts.${key}`; - entries[loc] = value; - }); - } - return entries; -}, "se_AssumeRoleRequest"); -var se_AssumeRoleWithWebIdentityRequest = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_RA] != null) { - entries[_RA] = input[_RA]; - } - if (input[_RSN] != null) { - entries[_RSN] = input[_RSN]; - } - if (input[_WIT] != null) { - entries[_WIT] = input[_WIT]; - } - if (input[_PI] != null) { - entries[_PI] = input[_PI]; - } - if (input[_PA] != null) { - const memberEntries = se_policyDescriptorListType(input[_PA], context); - if (input[_PA]?.length === 0) { - entries.PolicyArns = []; + try { + const result = await next(args); + if (context.__s3RegionRedirect) { + unlock(); + const region = await config.region(); + if (originalRegion !== region) { + throw new Error("Region was not restored following S3 region redirect."); + } + } + return result; + } catch (e) { + unlock(); + throw e; } - Object.entries(memberEntries).forEach(([key, value]) => { - const loc = `PolicyArns.${key}`; - entries[loc] = value; - }); - } - if (input[_P] != null) { - entries[_P] = input[_P]; - } - if (input[_DS] != null) { - entries[_DS] = input[_DS]; - } - return entries; -}, "se_AssumeRoleWithWebIdentityRequest"); -var se_policyDescriptorListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; + }; +}, "regionRedirectEndpointMiddleware"); +var regionRedirectEndpointMiddlewareOptions = { + tags: ["REGION_REDIRECT", "S3"], + name: "regionRedirectEndpointMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware" +}; + +// src/region-redirect-middleware.ts +function regionRedirectMiddleware(clientConfig) { + return (next, context) => async (args) => { + try { + return await next(args); + } catch (err) { + if (clientConfig.followRegionRedirects) { + if (err?.$metadata?.httpStatusCode === 301 || // err.name === "PermanentRedirect" && --> removing the error name check, as that allows for HEAD operations (which have the 301 status code, but not the same error name) to be covered for region redirection as well + err?.$metadata?.httpStatusCode === 400 && err?.name === "IllegalLocationConstraintException") { + try { + const actualRegion = err.$response.headers["x-amz-bucket-region"]; + context.logger?.debug(`Redirecting from ${await clientConfig.region()} to ${actualRegion}`); + context.__s3RegionRedirect = actualRegion; + } catch (e) { + throw new Error("Region redirect failed: " + e); + } + return next(args); + } + } + throw err; } - const memberEntries = se_PolicyDescriptorType(entry, context); - Object.entries(memberEntries).forEach(([key, value]) => { - entries[`member.${counter}.${key}`] = value; - }); - counter++; - } - return entries; -}, "se_policyDescriptorListType"); -var se_PolicyDescriptorType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_a] != null) { - entries[_a] = input[_a]; - } - return entries; -}, "se_PolicyDescriptorType"); -var se_ProvidedContext = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_PAr] != null) { - entries[_PAr] = input[_PAr]; + }; +} +__name(regionRedirectMiddleware, "regionRedirectMiddleware"); +var regionRedirectMiddlewareOptions = { + step: "initialize", + tags: ["REGION_REDIRECT", "S3"], + name: "regionRedirectMiddleware", + override: true +}; +var getRegionRedirectMiddlewarePlugin = /* @__PURE__ */ __name((clientConfig) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(regionRedirectMiddleware(clientConfig), regionRedirectMiddlewareOptions); + clientStack.addRelativeTo(regionRedirectEndpointMiddleware(clientConfig), regionRedirectEndpointMiddlewareOptions); + }, "applyToStack") +}), "getRegionRedirectMiddlewarePlugin"); + +// src/s3-expires-middleware.ts + + +var s3ExpiresMiddleware = /* @__PURE__ */ __name((config) => { + return (next, context) => async (args) => { + const result = await next(args); + const { response } = result; + if (import_protocol_http.HttpResponse.isInstance(response)) { + if (response.headers.expires) { + response.headers.expiresstring = response.headers.expires; + try { + (0, import_smithy_client.parseRfc7231DateTime)(response.headers.expires); + } catch (e) { + context.logger?.warn( + `AWS SDK Warning for ${context.clientName}::${context.commandName} response parsing (${response.headers.expires}): ${e}` + ); + delete response.headers.expires; + } + } + } + return result; + }; +}, "s3ExpiresMiddleware"); +var s3ExpiresMiddlewareOptions = { + tags: ["S3"], + name: "s3ExpiresMiddleware", + override: true, + relation: "after", + toMiddleware: "deserializerMiddleware" +}; +var getS3ExpiresMiddlewarePlugin = /* @__PURE__ */ __name((clientConfig) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo(s3ExpiresMiddleware(clientConfig), s3ExpiresMiddlewareOptions); + }, "applyToStack") +}), "getS3ExpiresMiddlewarePlugin"); + +// src/s3-express/classes/S3ExpressIdentityCache.ts +var S3ExpressIdentityCache = class _S3ExpressIdentityCache { + constructor(data = {}) { + this.data = data; } - if (input[_CA] != null) { - entries[_CA] = input[_CA]; + static { + __name(this, "S3ExpressIdentityCache"); } - return entries; -}, "se_ProvidedContext"); -var se_ProvidedContextsListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; + lastPurgeTime = Date.now(); + static EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS = 3e4; + get(key) { + const entry = this.data[key]; + if (!entry) { + return; } - const memberEntries = se_ProvidedContext(entry, context); - Object.entries(memberEntries).forEach(([key, value]) => { - entries[`member.${counter}.${key}`] = value; - }); - counter++; + return entry; } - return entries; -}, "se_ProvidedContextsListType"); -var se_Tag = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - if (input[_K] != null) { - entries[_K] = input[_K]; + set(key, entry) { + this.data[key] = entry; + return entry; } - if (input[_Va] != null) { - entries[_Va] = input[_Va]; + delete(key) { + delete this.data[key]; } - return entries; -}, "se_Tag"); -var se_tagKeyListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; + async purgeExpired() { + const now = Date.now(); + if (this.lastPurgeTime + _S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS > now) { + return; } - entries[`member.${counter}`] = entry; - counter++; - } - return entries; -}, "se_tagKeyListType"); -var se_tagListType = /* @__PURE__ */ __name((input, context) => { - const entries = {}; - let counter = 1; - for (const entry of input) { - if (entry === null) { - continue; + for (const key in this.data) { + const entry = this.data[key]; + if (!entry.isRefreshing) { + const credential = await entry.identity; + if (credential.expiration) { + if (credential.expiration.getTime() < now) { + delete this.data[key]; + } + } + } } - const memberEntries = se_Tag(entry, context); - Object.entries(memberEntries).forEach(([key, value]) => { - entries[`member.${counter}.${key}`] = value; - }); - counter++; - } - return entries; -}, "se_tagListType"); -var de_AssumedRoleUser = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_ARI] != null) { - contents[_ARI] = (0, import_smithy_client3.expectString)(output[_ARI]); - } - if (output[_Ar] != null) { - contents[_Ar] = (0, import_smithy_client3.expectString)(output[_Ar]); - } - return contents; -}, "de_AssumedRoleUser"); -var de_AssumeRoleResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); - } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); - } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); - } - return contents; -}, "de_AssumeRoleResponse"); -var de_AssumeRoleWithWebIdentityResponse = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_C] != null) { - contents[_C] = de_Credentials(output[_C], context); - } - if (output[_SFWIT] != null) { - contents[_SFWIT] = (0, import_smithy_client3.expectString)(output[_SFWIT]); - } - if (output[_ARU] != null) { - contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); - } - if (output[_PPS] != null) { - contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); - } - if (output[_Pr] != null) { - contents[_Pr] = (0, import_smithy_client3.expectString)(output[_Pr]); - } - if (output[_Au] != null) { - contents[_Au] = (0, import_smithy_client3.expectString)(output[_Au]); - } - if (output[_SI] != null) { - contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); - } - return contents; -}, "de_AssumeRoleWithWebIdentityResponse"); -var de_Credentials = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_AKI] != null) { - contents[_AKI] = (0, import_smithy_client3.expectString)(output[_AKI]); - } - if (output[_SAK] != null) { - contents[_SAK] = (0, import_smithy_client3.expectString)(output[_SAK]); - } - if (output[_ST] != null) { - contents[_ST] = (0, import_smithy_client3.expectString)(output[_ST]); - } - if (output[_E] != null) { - contents[_E] = (0, import_smithy_client3.expectNonNull)((0, import_smithy_client3.parseRfc3339DateTimeWithOffset)(output[_E])); - } - return contents; -}, "de_Credentials"); -var de_ExpiredTokenException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_ExpiredTokenException"); -var de_IDPCommunicationErrorException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_IDPCommunicationErrorException"); -var de_IDPRejectedClaimException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_IDPRejectedClaimException"); -var de_InvalidIdentityTokenException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_InvalidIdentityTokenException"); -var de_MalformedPolicyDocumentException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_MalformedPolicyDocumentException"); -var de_PackedPolicyTooLargeException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_PackedPolicyTooLargeException"); -var de_RegionDisabledException = /* @__PURE__ */ __name((output, context) => { - const contents = {}; - if (output[_m] != null) { - contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); - } - return contents; -}, "de_RegionDisabledException"); -var deserializeMetadata = /* @__PURE__ */ __name((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"] -}), "deserializeMetadata"); -var throwDefaultError = (0, import_smithy_client3.withBaseException)(STSServiceException); -var buildHttpRpcRequest = /* @__PURE__ */ __name(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 !== void 0) { - contents.hostname = resolvedHostname; - } - if (body !== void 0) { - contents.body = body; } - return new import_protocol_http.HttpRequest(contents); -}, "buildHttpRpcRequest"); -var SHARED_HEADERS = { - "content-type": "application/x-www-form-urlencoded" }; -var _ = "2011-06-15"; -var _A = "Action"; -var _AKI = "AccessKeyId"; -var _AR = "AssumeRole"; -var _ARI = "AssumedRoleId"; -var _ARU = "AssumedRoleUser"; -var _ARWWI = "AssumeRoleWithWebIdentity"; -var _Ar = "Arn"; -var _Au = "Audience"; -var _C = "Credentials"; -var _CA = "ContextAssertion"; -var _DS = "DurationSeconds"; -var _E = "Expiration"; -var _EI = "ExternalId"; -var _K = "Key"; -var _P = "Policy"; -var _PA = "PolicyArns"; -var _PAr = "ProviderArn"; -var _PC = "ProvidedContexts"; -var _PI = "ProviderId"; -var _PPS = "PackedPolicySize"; -var _Pr = "Provider"; -var _RA = "RoleArn"; -var _RSN = "RoleSessionName"; -var _SAK = "SecretAccessKey"; -var _SFWIT = "SubjectFromWebIdentityToken"; -var _SI = "SourceIdentity"; -var _SN = "SerialNumber"; -var _ST = "SessionToken"; -var _T = "Tags"; -var _TC = "TokenCode"; -var _TTK = "TransitiveTagKeys"; -var _V = "Version"; -var _Va = "Value"; -var _WIT = "WebIdentityToken"; -var _a = "arn"; -var _m = "message"; -var buildFormUrlencodedString = /* @__PURE__ */ __name((formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client3.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client3.extendedEncodeURIComponent)(value)).join("&"), "buildFormUrlencodedString"); -var loadQueryErrorCode = /* @__PURE__ */ __name((output, data) => { - if (data.Error?.Code !== void 0) { - return data.Error.Code; - } - if (output.statusCode == 404) { - return "NotFound"; - } -}, "loadQueryErrorCode"); -// src/submodules/sts/commands/AssumeRoleCommand.ts -var AssumeRoleCommand = class extends import_smithy_client4.Command.classBuilder().ep(import_EndpointParameters.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() { - static { - __name(this, "AssumeRoleCommand"); +// src/s3-express/classes/S3ExpressIdentityCacheEntry.ts +var S3ExpressIdentityCacheEntry = class { + /** + * @param identity - stored identity. + * @param accessed - timestamp of last access in epoch ms. + * @param isRefreshing - this key is currently in the process of being refreshed (background). + */ + constructor(_identity, isRefreshing = false, accessed = Date.now()) { + this._identity = _identity; + this.isRefreshing = isRefreshing; + this.accessed = accessed; } -}; - -// src/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.ts -var import_middleware_endpoint2 = __nccwpck_require__(2918); -var import_middleware_serde2 = __nccwpck_require__(1238); -var import_smithy_client5 = __nccwpck_require__(3570); -var import_EndpointParameters2 = __nccwpck_require__(1765); -var AssumeRoleWithWebIdentityCommand = class extends import_smithy_client5.Command.classBuilder().ep(import_EndpointParameters2.commonParams).m(function(Command, cs, config, o) { - return [ - (0, import_middleware_serde2.getSerdePlugin)(config, this.serialize, this.deserialize), - (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) - ]; -}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() { static { - __name(this, "AssumeRoleWithWebIdentityCommand"); + __name(this, "S3ExpressIdentityCacheEntry"); } -}; - -// src/submodules/sts/STS.ts -var import_STSClient = __nccwpck_require__(8974); -var commands = { - AssumeRoleCommand, - AssumeRoleWithWebIdentityCommand -}; -var STS = class extends import_STSClient.STSClient { - static { - __name(this, "STS"); + get identity() { + this.accessed = Date.now(); + return this._identity; } }; -(0, import_smithy_client6.createAggregatedClient)(commands, STS); - -// src/submodules/sts/index.ts -var import_EndpointParameters3 = __nccwpck_require__(1765); -// src/submodules/sts/defaultStsRoleAssumers.ts -var import_client = __nccwpck_require__(2825); -var ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; -var getAccountIdFromAssumedRoleUser = /* @__PURE__ */ __name((assumedRoleUser) => { - if (typeof assumedRoleUser?.Arn === "string") { - const arnComponents = assumedRoleUser.Arn.split(":"); - if (arnComponents.length > 4 && arnComponents[4] !== "") { - return arnComponents[4]; - } +// src/s3-express/classes/S3ExpressIdentityProviderImpl.ts +var S3ExpressIdentityProviderImpl = class _S3ExpressIdentityProviderImpl { + constructor(createSessionFn, cache = new S3ExpressIdentityCache()) { + this.createSessionFn = createSessionFn; + this.cache = cache; } - return void 0; -}, "getAccountIdFromAssumedRoleUser"); -var resolveRegion = /* @__PURE__ */ __name(async (_region, _parentRegion, credentialProviderLogger) => { - const region = typeof _region === "function" ? await _region() : _region; - const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; - credentialProviderLogger?.debug?.( - "@aws-sdk/client-sts::resolveRegion", - "accepting first of:", - `${region} (provider)`, - `${parentRegion} (parent client)`, - `${ASSUME_ROLE_DEFAULT_REGION} (STS default)` - ); - return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION; -}, "resolveRegion"); -var getDefaultRoleAssumer = /* @__PURE__ */ __name((stsOptions, STSClient3) => { - let stsClient; - let closureSourceCreds; - return async (sourceCreds, params) => { - closureSourceCreds = sourceCreds; - if (!stsClient) { - const { - logger = stsOptions?.parentClientConfig?.logger, - region, - requestHandler = stsOptions?.parentClientConfig?.requestHandler, - credentialProviderLogger - } = stsOptions; - const resolvedRegion = await resolveRegion( - region, - stsOptions?.parentClientConfig?.region, - credentialProviderLogger - ); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient3({ - profile: stsOptions?.parentClientConfig?.profile, - // A hack to make sts client uses the credential in current closure. - credentialDefaultProvider: /* @__PURE__ */ __name(() => async () => closureSourceCreds, "credentialDefaultProvider"), - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger - }); - } - const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleCommand(params)); - if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); - const credentials = { - accessKeyId: Credentials2.AccessKeyId, - secretAccessKey: Credentials2.SecretAccessKey, - sessionToken: Credentials2.SessionToken, - expiration: Credentials2.Expiration, - // TODO(credentialScope): access normally when shape is updated. - ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, - ...accountId && { accountId } - }; - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); - return credentials; - }; -}, "getDefaultRoleAssumer"); -var getDefaultRoleAssumerWithWebIdentity = /* @__PURE__ */ __name((stsOptions, STSClient3) => { - let stsClient; - return async (params) => { - if (!stsClient) { - const { - logger = stsOptions?.parentClientConfig?.logger, - region, - requestHandler = stsOptions?.parentClientConfig?.requestHandler, - credentialProviderLogger - } = stsOptions; - const resolvedRegion = await resolveRegion( - region, - stsOptions?.parentClientConfig?.region, - credentialProviderLogger - ); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient3({ - profile: stsOptions?.parentClientConfig?.profile, - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger + static { + __name(this, "S3ExpressIdentityProviderImpl"); + } + static REFRESH_WINDOW_MS = 6e4; + async getS3ExpressIdentity(awsIdentity, identityProperties) { + const key = identityProperties.Bucket; + const { cache } = this; + const entry = cache.get(key); + if (entry) { + return entry.identity.then((identity) => { + const isExpired = (identity.expiration?.getTime() ?? 0) < Date.now(); + if (isExpired) { + return cache.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity; + } + const isExpiringSoon = (identity.expiration?.getTime() ?? 0) < Date.now() + _S3ExpressIdentityProviderImpl.REFRESH_WINDOW_MS; + if (isExpiringSoon && !entry.isRefreshing) { + entry.isRefreshing = true; + this.getIdentity(key).then((id) => { + cache.set(key, new S3ExpressIdentityCacheEntry(Promise.resolve(id))); + }); + } + return identity; }); } - const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); - if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); - const credentials = { - accessKeyId: Credentials2.AccessKeyId, - secretAccessKey: Credentials2.SecretAccessKey, - sessionToken: Credentials2.SessionToken, - expiration: Credentials2.Expiration, - // TODO(credentialScope): access normally when shape is updated. - ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, - ...accountId && { accountId } - }; - if (accountId) { - (0, import_client.setCredentialFeature)(credentials, "RESOLVED_ACCOUNT_ID", "T"); + return cache.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity; + } + async getIdentity(key) { + await this.cache.purgeExpired().catch((error) => { + console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n" + error); + }); + const session = await this.createSessionFn(key); + if (!session.Credentials?.AccessKeyId || !session.Credentials?.SecretAccessKey) { + throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey."); } - (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); - return credentials; - }; -}, "getDefaultRoleAssumerWithWebIdentity"); -var isH2 = /* @__PURE__ */ __name((requestHandler) => { - return requestHandler?.metadata?.handlerProtocol === "h2"; -}, "isH2"); - -// src/submodules/sts/defaultRoleAssumers.ts -var import_STSClient2 = __nccwpck_require__(8974); -var getCustomizableStsClientCtor = /* @__PURE__ */ __name((baseCtor, customizations) => { - if (!customizations) return baseCtor; - else - return class CustomizableSTSClient extends baseCtor { - static { - __name(this, "CustomizableSTSClient"); - } - constructor(config) { - super(config); - for (const customization of customizations) { - this.middlewareStack.use(customization); - } - } + const identity = { + accessKeyId: session.Credentials.AccessKeyId, + secretAccessKey: session.Credentials.SecretAccessKey, + sessionToken: session.Credentials.SessionToken, + expiration: session.Credentials.Expiration ? new Date(session.Credentials.Expiration) : void 0 }; -}, "getCustomizableStsClientCtor"); -var getDefaultRoleAssumer2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumer"); -var getDefaultRoleAssumerWithWebIdentity2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumerWithWebIdentity"); -var decorateDefaultCredentialProvider = /* @__PURE__ */ __name((provider) => (input) => provider({ - roleAssumer: getDefaultRoleAssumer2(input), - roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input), - ...input -}), "decorateDefaultCredentialProvider"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); + return identity; + } +}; +// src/s3-express/classes/SignatureV4S3Express.ts +var import_signature_v4 = __nccwpck_require__(1528); -/***/ }), +// src/s3-express/constants.ts +var import_util_config_provider = __nccwpck_require__(3375); +var S3_EXPRESS_BUCKET_TYPE = "Directory"; +var S3_EXPRESS_BACKEND = "S3Express"; +var S3_EXPRESS_AUTH_SCHEME = "sigv4-s3express"; +var SESSION_TOKEN_QUERY_PARAM = "X-Amz-S3session-Token"; +var SESSION_TOKEN_HEADER = SESSION_TOKEN_QUERY_PARAM.toLowerCase(); +var NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME = "AWS_S3_DISABLE_EXPRESS_SESSION_AUTH"; +var NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME = "s3_disable_express_session_auth"; +var NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS = { + environmentVariableSelector: /* @__PURE__ */ __name((env) => (0, import_util_config_provider.booleanSelector)(env, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME, import_util_config_provider.SelectorType.ENV), "environmentVariableSelector"), + configFileSelector: /* @__PURE__ */ __name((profile) => (0, import_util_config_provider.booleanSelector)(profile, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME, import_util_config_provider.SelectorType.CONFIG), "configFileSelector"), + default: false +}; -/***/ 1798: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/s3-express/classes/SignatureV4S3Express.ts +var SignatureV4S3Express = class extends import_signature_v4.SignatureV4 { + static { + __name(this, "SignatureV4S3Express"); + } + /** + * Signs with alternate provided credentials instead of those provided in the + * constructor. + * + * Additionally omits the credential sessionToken and assigns it to the + * alternate header field for S3 Express. + */ + async signWithCredentials(requestToSign, credentials, options) { + const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials); + requestToSign.headers[SESSION_TOKEN_HEADER] = credentials.sessionToken; + const privateAccess = this; + setSingleOverride(privateAccess, credentialsWithoutSessionToken); + return privateAccess.signRequest(requestToSign, options ?? {}); + } + /** + * Similar to {@link SignatureV4S3Express#signWithCredentials} but for presigning. + */ + async presignWithCredentials(requestToSign, credentials, options) { + const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials); + delete requestToSign.headers[SESSION_TOKEN_HEADER]; + requestToSign.headers[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken; + requestToSign.query = requestToSign.query ?? {}; + requestToSign.query[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken; + const privateAccess = this; + setSingleOverride(privateAccess, credentialsWithoutSessionToken); + return this.presign(requestToSign, options); + } +}; +function getCredentialsWithoutSessionToken(credentials) { + const credentialsWithoutSessionToken = { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + expiration: credentials.expiration + }; + return credentialsWithoutSessionToken; +} +__name(getCredentialsWithoutSessionToken, "getCredentialsWithoutSessionToken"); +function setSingleOverride(privateAccess, credentialsWithoutSessionToken) { + const id = setTimeout(() => { + throw new Error("SignatureV4S3Express credential override was created but not called."); + }, 10); + const currentCredentialProvider = privateAccess.credentialProvider; + const overrideCredentialsProviderOnce = /* @__PURE__ */ __name(() => { + clearTimeout(id); + privateAccess.credentialProvider = currentCredentialProvider; + return Promise.resolve(credentialsWithoutSessionToken); + }, "overrideCredentialsProviderOnce"); + privateAccess.credentialProvider = overrideCredentialsProviderOnce; +} +__name(setSingleOverride, "setSingleOverride"); -"use strict"; +// src/s3-express/functions/s3ExpressMiddleware.ts +var import_core = __nccwpck_require__(9963); -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__(8842)); -const core_1 = __nccwpck_require__(9963); -const util_user_agent_node_1 = __nccwpck_require__(8095); -const config_resolver_1 = __nccwpck_require__(3098); -const core_2 = __nccwpck_require__(5829); -const hash_node_1 = __nccwpck_require__(3081); -const middleware_retry_1 = __nccwpck_require__(6039); -const node_config_provider_1 = __nccwpck_require__(3461); -const node_http_handler_1 = __nccwpck_require__(258); -const util_body_length_node_1 = __nccwpck_require__(8075); -const util_retry_1 = __nccwpck_require__(4902); -const runtimeConfig_shared_1 = __nccwpck_require__(5238); -const smithy_client_1 = __nccwpck_require__(3570); -const util_defaults_mode_node_1 = __nccwpck_require__(2429); -const smithy_client_2 = __nccwpck_require__(3570); -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); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger, - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || - (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()), - signer: new core_1.AwsSdkSigV4Signer(), - }, +var s3ExpressMiddleware = /* @__PURE__ */ __name((options) => { + return (next, context) => async (args) => { + if (context.endpointV2) { + const endpoint = context.endpointV2; + const isS3ExpressAuth = endpoint.properties?.authSchemes?.[0]?.name === S3_EXPRESS_AUTH_SCHEME; + const isS3ExpressBucket = endpoint.properties?.backend === S3_EXPRESS_BACKEND || endpoint.properties?.bucketType === S3_EXPRESS_BUCKET_TYPE; + if (isS3ExpressBucket) { + (0, import_core.setFeature)(context, "S3_EXPRESS_BUCKET", "J"); + context.isS3ExpressBucket = true; + } + if (isS3ExpressAuth) { + const requestBucket = args.input.Bucket; + if (requestBucket) { + const s3ExpressIdentity = await options.s3ExpressIdentityProvider.getS3ExpressIdentity( + await options.credentials(), { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - region: config?.region ?? - (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, - }, config), - 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, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), - }; + Bucket: requestBucket + } + ); + context.s3ExpressIdentity = s3ExpressIdentity; + if (import_protocol_http.HttpRequest.isInstance(args.request) && s3ExpressIdentity.sessionToken) { + args.request.headers[SESSION_TOKEN_HEADER] = s3ExpressIdentity.sessionToken; + } + } + } + } + return next(args); + }; +}, "s3ExpressMiddleware"); +var s3ExpressMiddlewareOptions = { + name: "s3ExpressMiddleware", + step: "build", + tags: ["S3", "S3_EXPRESS"], + override: true }; -exports.getRuntimeConfig = getRuntimeConfig; +var getS3ExpressPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(s3ExpressMiddleware(options), s3ExpressMiddlewareOptions); + }, "applyToStack") +}), "getS3ExpressPlugin"); +// src/s3-express/functions/s3ExpressHttpSigningMiddleware.ts +var import_core2 = __nccwpck_require__(5829); -/***/ }), +var import_util_middleware = __nccwpck_require__(2390); -/***/ 5238: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/s3-express/functions/signS3Express.ts +var signS3Express = /* @__PURE__ */ __name(async (s3ExpressIdentity, signingOptions, request, sigV4MultiRegionSigner) => { + const signedRequest = await sigV4MultiRegionSigner.signWithCredentials(request, s3ExpressIdentity, {}); + if (signedRequest.headers["X-Amz-Security-Token"] || signedRequest.headers["x-amz-security-token"]) { + throw new Error("X-Amz-Security-Token must not be set for s3-express requests."); + } + return signedRequest; +}, "signS3Express"); -"use strict"; +// src/s3-express/functions/s3ExpressHttpSigningMiddleware.ts +var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { + throw error; +}, "defaultErrorHandler"); +var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { +}, "defaultSuccessHandler"); +var s3ExpressHttpSigningMiddlewareOptions = import_core2.httpSigningMiddlewareOptions; +var s3ExpressHttpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { + if (!import_protocol_http.HttpRequest.isInstance(args.request)) { + return next(args); + } + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { + httpAuthOption: { signingProperties = {} }, + identity, + signer + } = scheme; + let request; + if (context.s3ExpressIdentity) { + request = await signS3Express( + context.s3ExpressIdentity, + signingProperties, + args.request, + await config.signer() + ); + } else { + request = await signer.sign(args.request, identity, signingProperties); + } + const output = await next({ + ...args, + request + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; +}, "s3ExpressHttpSigningMiddleware"); +var getS3ExpressHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo( + s3ExpressHttpSigningMiddleware(config), + import_core2.httpSigningMiddlewareOptions + ); + }, "applyToStack") +}), "getS3ExpressHttpSigningPlugin"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRuntimeConfig = void 0; -const core_1 = __nccwpck_require__(9963); -const core_2 = __nccwpck_require__(5829); -const smithy_client_1 = __nccwpck_require__(3570); -const url_parser_1 = __nccwpck_require__(4681); -const util_base64_1 = __nccwpck_require__(5600); -const util_utf8_1 = __nccwpck_require__(1895); -const httpAuthSchemeProvider_1 = __nccwpck_require__(8013); -const endpointResolver_1 = __nccwpck_require__(7561); -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 ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - 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, - }; +// src/s3Configuration.ts +var resolveS3Config = /* @__PURE__ */ __name((input, { + session +}) => { + const [s3ClientProvider, CreateSessionCommandCtor] = session; + const { + forcePathStyle, + useAccelerateEndpoint, + disableMultiregionAccessPoints, + followRegionRedirects, + s3ExpressIdentityProvider, + bucketEndpoint + } = input; + return Object.assign(input, { + forcePathStyle: forcePathStyle ?? false, + useAccelerateEndpoint: useAccelerateEndpoint ?? false, + disableMultiregionAccessPoints: disableMultiregionAccessPoints ?? false, + followRegionRedirects: followRegionRedirects ?? false, + s3ExpressIdentityProvider: s3ExpressIdentityProvider ?? new S3ExpressIdentityProviderImpl( + async (key) => s3ClientProvider().send( + new CreateSessionCommandCtor({ + Bucket: key + }) + ) + ), + bucketEndpoint: bucketEndpoint ?? false + }); +}, "resolveS3Config"); + +// src/throw-200-exceptions.ts + +var import_util_stream = __nccwpck_require__(6607); +var THROW_IF_EMPTY_BODY = { + CopyObjectCommand: true, + UploadPartCopyCommand: true, + CompleteMultipartUploadCommand: true }; -exports.getRuntimeConfig = getRuntimeConfig; +var MAX_BYTES_TO_INSPECT = 3e3; +var throw200ExceptionsMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { + const result = await next(args); + const { response } = result; + if (!import_protocol_http.HttpResponse.isInstance(response)) { + return result; + } + const { statusCode, body: sourceBody } = response; + if (statusCode < 200 || statusCode >= 300) { + return result; + } + const isSplittableStream = typeof sourceBody?.stream === "function" || typeof sourceBody?.pipe === "function" || typeof sourceBody?.tee === "function"; + if (!isSplittableStream) { + return result; + } + let bodyCopy = sourceBody; + let body = sourceBody; + if (sourceBody && typeof sourceBody === "object" && !(sourceBody instanceof Uint8Array)) { + [bodyCopy, body] = await (0, import_util_stream.splitStream)(sourceBody); + } + response.body = body; + const bodyBytes = await collectBody(bodyCopy, { + streamCollector: /* @__PURE__ */ __name(async (stream) => { + return (0, import_util_stream.headStream)(stream, MAX_BYTES_TO_INSPECT); + }, "streamCollector") + }); + if (typeof bodyCopy?.destroy === "function") { + bodyCopy.destroy(); + } + const bodyStringTail = config.utf8Encoder(bodyBytes.subarray(bodyBytes.length - 16)); + if (bodyBytes.length === 0 && THROW_IF_EMPTY_BODY[context.commandName]) { + const err = new Error("S3 aborted request"); + err.name = "InternalError"; + throw err; + } + if (bodyStringTail && bodyStringTail.endsWith("")) { + response.statusCode = 400; + } + return result; +}, "throw200ExceptionsMiddleware"); +var collectBody = /* @__PURE__ */ __name((streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return Promise.resolve(streamBody); + } + return context.streamCollector(streamBody) || Promise.resolve(new Uint8Array()); +}, "collectBody"); +var throw200ExceptionsMiddlewareOptions = { + relation: "after", + toMiddleware: "deserializerMiddleware", + tags: ["THROW_200_EXCEPTIONS", "S3"], + name: "throw200ExceptionsMiddleware", + override: true +}; +var getThrow200ExceptionsPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.addRelativeTo(throw200ExceptionsMiddleware(config), throw200ExceptionsMiddlewareOptions); + }, "applyToStack") +}), "getThrow200ExceptionsPlugin"); +// src/validate-bucket-name.ts +var import_util_arn_parser = __nccwpck_require__(5487); -/***/ }), +// src/bucket-endpoint-middleware.ts +function bucketEndpointMiddleware(options) { + return (next, context) => async (args) => { + if (options.bucketEndpoint) { + const endpoint = context.endpointV2; + if (endpoint) { + const bucket = args.input.Bucket; + if (typeof bucket === "string") { + try { + const bucketEndpointUrl = new URL(bucket); + context.endpointV2 = { + ...endpoint, + url: bucketEndpointUrl + }; + } catch (e) { + const warning = `@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${bucket} could not be parsed as URL.`; + if (context.logger?.constructor?.name === "NoOpLogger") { + console.warn(warning); + } else { + context.logger?.warn?.(warning); + } + throw e; + } + } + } + } + return next(args); + }; +} +__name(bucketEndpointMiddleware, "bucketEndpointMiddleware"); +var bucketEndpointMiddlewareOptions = { + name: "bucketEndpointMiddleware", + override: true, + relation: "after", + toMiddleware: "endpointV2Middleware" +}; -/***/ 669: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/validate-bucket-name.ts +function validateBucketNameMiddleware({ bucketEndpoint }) { + return (next) => async (args) => { + const { + input: { Bucket } + } = args; + if (!bucketEndpoint && typeof Bucket === "string" && !(0, import_util_arn_parser.validate)(Bucket) && Bucket.indexOf("/") >= 0) { + const err = new Error(`Bucket name shouldn't contain '/', received '${Bucket}'`); + err.name = "InvalidBucketName"; + throw err; + } + return next({ ...args }); + }; +} +__name(validateBucketNameMiddleware, "validateBucketNameMiddleware"); +var validateBucketNameMiddlewareOptions = { + step: "initialize", + tags: ["VALIDATE_BUCKET_NAME"], + name: "validateBucketNameMiddleware", + override: true +}; +var getValidateBucketNamePlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(validateBucketNameMiddleware(options), validateBucketNameMiddlewareOptions); + clientStack.addRelativeTo(bucketEndpointMiddleware(options), bucketEndpointMiddlewareOptions); + }, "applyToStack") +}), "getValidateBucketNamePlugin"); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveRuntimeExtensions = void 0; -const region_config_resolver_1 = __nccwpck_require__(8156); -const protocol_http_1 = __nccwpck_require__(4418); -const smithy_client_1 = __nccwpck_require__(3570); -const httpAuthExtensionConfiguration_1 = __nccwpck_require__(4935); -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); -}; -exports.resolveRuntimeExtensions = resolveRuntimeExtensions; /***/ }), -/***/ 8156: +/***/ 9718: /***/ ((module) => { "use strict"; @@ -55621,76 +40185,74 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, - NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, - REGION_ENV_NAME: () => REGION_ENV_NAME, - REGION_INI_NAME: () => REGION_INI_NAME, - getAwsRegionExtensionConfiguration: () => getAwsRegionExtensionConfiguration, - resolveAwsRegionExtensionConfiguration: () => resolveAwsRegionExtensionConfiguration, - resolveRegionConfig: () => resolveRegionConfig + getSsecPlugin: () => getSsecPlugin, + isValidBase64EncodedSSECustomerKey: () => isValidBase64EncodedSSECustomerKey, + ssecMiddleware: () => ssecMiddleware, + ssecMiddlewareOptions: () => ssecMiddlewareOptions }); module.exports = __toCommonJS(index_exports); - -// src/extensions/index.ts -var getAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setRegion(region) { - runtimeConfig.region = region; - }, - region() { - return runtimeConfig.region; +function ssecMiddleware(options) { + return (next) => async (args) => { + const input = { ...args.input }; + const properties = [ + { + target: "SSECustomerKey", + hash: "SSECustomerKeyMD5" + }, + { + target: "CopySourceSSECustomerKey", + hash: "CopySourceSSECustomerKeyMD5" + } + ]; + for (const prop of properties) { + const value = input[prop.target]; + if (value) { + let valueForHash; + if (typeof value === "string") { + if (isValidBase64EncodedSSECustomerKey(value, options)) { + valueForHash = options.base64Decoder(value); + } else { + valueForHash = options.utf8Decoder(value); + input[prop.target] = options.base64Encoder(valueForHash); + } + } else { + valueForHash = ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value); + input[prop.target] = options.base64Encoder(valueForHash); + } + const hash = new options.md5(); + hash.update(valueForHash); + input[prop.hash] = options.base64Encoder(await hash.digest()); + } } + return next({ + ...args, + input + }); }; -}, "getAwsRegionExtensionConfiguration"); -var resolveAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => { - return { - region: awsRegionExtensionConfiguration.region() - }; -}, "resolveAwsRegionExtensionConfiguration"); - -// src/regionConfig/config.ts -var REGION_ENV_NAME = "AWS_REGION"; -var REGION_INI_NAME = "region"; -var NODE_REGION_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env) => env[REGION_ENV_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"), - default: /* @__PURE__ */ __name(() => { - throw new Error("Region is missing"); - }, "default") -}; -var NODE_REGION_CONFIG_FILE_OPTIONS = { - preferredFile: "credentials" +} +__name(ssecMiddleware, "ssecMiddleware"); +var ssecMiddlewareOptions = { + name: "ssecMiddleware", + step: "initialize", + tags: ["SSE"], + override: true }; - -// src/regionConfig/isFipsRegion.ts -var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); - -// src/regionConfig/getRealRegion.ts -var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); - -// src/regionConfig/resolveRegionConfig.ts -var resolveRegionConfig = /* @__PURE__ */ __name((input) => { - const { region, useFipsEndpoint } = input; - if (!region) { - throw new Error("Region is missing"); +var getSsecPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(ssecMiddleware(config), ssecMiddlewareOptions); + }, "applyToStack") +}), "getSsecPlugin"); +function isValidBase64EncodedSSECustomerKey(str, options) { + const base64Regex = /^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; + if (!base64Regex.test(str)) return false; + try { + const decodedBytes = options.base64Decoder(str); + return decodedBytes.length === 32; + } catch { + return false; } - return Object.assign(input, { - region: /* @__PURE__ */ __name(async () => { - if (typeof region === "string") { - return getRealRegion(region); - } - const providedRegion = await region(); - return getRealRegion(providedRegion); - }, "region"), - useFipsEndpoint: /* @__PURE__ */ __name(async () => { - const providedRegion = typeof region === "string" ? region : await region(); - if (isFipsRegion(providedRegion)) { - return true; - } - return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); - }, "useFipsEndpoint") - }); -}, "resolveRegionConfig"); +} +__name(isValidBase64EncodedSSECustomerKey, "isValidBase64EncodedSSECustomerKey"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -55699,7 +40261,7 @@ var resolveRegionConfig = /* @__PURE__ */ __name((input) => { /***/ }), -/***/ 1856: +/***/ 4688: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -55726,144 +40288,321 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var index_exports = {}; __export(index_exports, { - SignatureV4MultiRegion: () => SignatureV4MultiRegion, - signatureV4CrtContainer: () => signatureV4CrtContainer + DEFAULT_UA_APP_ID: () => DEFAULT_UA_APP_ID, + getUserAgentMiddlewareOptions: () => getUserAgentMiddlewareOptions, + getUserAgentPlugin: () => getUserAgentPlugin, + resolveUserAgentConfig: () => resolveUserAgentConfig, + userAgentMiddleware: () => userAgentMiddleware }); module.exports = __toCommonJS(index_exports); -// src/SignatureV4MultiRegion.ts -var import_middleware_sdk_s3 = __nccwpck_require__(1139); -var import_signature_v4 = __nccwpck_require__(1528); +// src/configurations.ts +var import_core = __nccwpck_require__(5829); +var DEFAULT_UA_APP_ID = void 0; +function isValidUserAgentAppId(appId) { + if (appId === void 0) { + return true; + } + return typeof appId === "string" && appId.length <= 50; +} +__name(isValidUserAgentAppId, "isValidUserAgentAppId"); +function resolveUserAgentConfig(input) { + const normalizedAppIdProvider = (0, import_core.normalizeProvider)(input.userAgentAppId ?? DEFAULT_UA_APP_ID); + const { customUserAgent } = input; + return Object.assign(input, { + customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, + userAgentAppId: /* @__PURE__ */ __name(async () => { + const appId = await normalizedAppIdProvider(); + if (!isValidUserAgentAppId(appId)) { + const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; + if (typeof appId !== "string") { + logger?.warn("userAgentAppId must be a string or undefined."); + } else if (appId.length > 50) { + logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); + } + } + return appId; + }, "userAgentAppId") + }); +} +__name(resolveUserAgentConfig, "resolveUserAgentConfig"); -// src/signature-v4-crt-container.ts -var signatureV4CrtContainer = { - CrtSignerV4: null -}; +// src/user-agent-middleware.ts +var import_util_endpoints = __nccwpck_require__(3350); +var import_protocol_http = __nccwpck_require__(4418); -// src/SignatureV4MultiRegion.ts -var SignatureV4MultiRegion = class { - static { - __name(this, "SignatureV4MultiRegion"); +// src/check-features.ts +var import_core2 = __nccwpck_require__(9963); +var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; +async function checkFeatures(context, config, args) { + const request = args.request; + if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { + (0, import_core2.setFeature)(context, "PROTOCOL_RPC_V2_CBOR", "M"); } - sigv4aSigner; - sigv4Signer; - signerOptions; - static sigv4aDependency() { - if (typeof signatureV4CrtContainer.CrtSignerV4 === "function") { - return "crt"; - } else if (typeof import_signature_v4.signatureV4aContainer.SignatureV4a === "function") { - return "js"; + if (typeof config.retryStrategy === "function") { + const retryStrategy = await config.retryStrategy(); + if (typeof retryStrategy.acquireInitialRetryToken === "function") { + if (retryStrategy.constructor?.name?.includes("Adaptive")) { + (0, import_core2.setFeature)(context, "RETRY_MODE_ADAPTIVE", "F"); + } else { + (0, import_core2.setFeature)(context, "RETRY_MODE_STANDARD", "E"); + } + } else { + (0, import_core2.setFeature)(context, "RETRY_MODE_LEGACY", "D"); } - return "none"; - } - constructor(options) { - this.sigv4Signer = new import_middleware_sdk_s3.SignatureV4S3Express(options); - this.signerOptions = options; } - async sign(requestToSign, options = {}) { - if (options.signingRegion === "*") { - return this.getSigv4aSigner().sign(requestToSign, options); + if (typeof config.accountIdEndpointMode === "function") { + const endpointV2 = context.endpointV2; + if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { + (0, import_core2.setFeature)(context, "ACCOUNT_ID_ENDPOINT", "O"); + } + switch (await config.accountIdEndpointMode?.()) { + case "disabled": + (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); + break; + case "preferred": + (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); + break; + case "required": + (0, import_core2.setFeature)(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); + break; } - return this.sigv4Signer.sign(requestToSign, options); } - /** - * Sign with alternate credentials to the ones provided in the constructor. - * Note: This is only supported for SigV4a when using the CRT implementation. - */ - async signWithCredentials(requestToSign, credentials, options = {}) { - if (options.signingRegion === "*") { - const signer = this.getSigv4aSigner(); - const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; - if (CrtSignerV4 && signer instanceof CrtSignerV4) { - return signer.signWithCredentials(requestToSign, credentials, options); - } else { - throw new Error( - `signWithCredentials with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt` - ); - } + const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; + if (identity?.$source) { + const credentials = identity; + if (credentials.accountId) { + (0, import_core2.setFeature)(context, "RESOLVED_ACCOUNT_ID", "T"); + } + for (const [key, value] of Object.entries(credentials.$source ?? {})) { + (0, import_core2.setFeature)(context, key, value); } - return this.sigv4Signer.signWithCredentials(requestToSign, credentials, options); } - /** - * Presign a request. - * Note: This is only supported for SigV4a when using the CRT implementation. - */ - async presign(originalRequest, options = {}) { - if (options.signingRegion === "*") { - const signer = this.getSigv4aSigner(); - const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; - if (CrtSignerV4 && signer instanceof CrtSignerV4) { - return signer.presign(originalRequest, options); +} +__name(checkFeatures, "checkFeatures"); + +// src/constants.ts +var USER_AGENT = "user-agent"; +var X_AMZ_USER_AGENT = "x-amz-user-agent"; +var SPACE = " "; +var UA_NAME_SEPARATOR = "/"; +var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g; +var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g; +var UA_ESCAPE_CHAR = "-"; + +// src/encode-features.ts +var BYTE_LIMIT = 1024; +function encodeFeatures(features) { + let buffer = ""; + for (const key in features) { + const val = features[key]; + if (buffer.length + val.length + 1 <= BYTE_LIMIT) { + if (buffer.length) { + buffer += "," + val; } else { - throw new Error( - `presign with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt` - ); + buffer += val; } + continue; } - return this.sigv4Signer.presign(originalRequest, options); + break; } - async presignWithCredentials(originalRequest, credentials, options = {}) { - if (options.signingRegion === "*") { - throw new Error("Method presignWithCredentials is not supported for [signingRegion=*]."); + return buffer; +} +__name(encodeFeatures, "encodeFeatures"); + +// src/user-agent-middleware.ts +var userAgentMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { + const { request } = args; + if (!import_protocol_http.HttpRequest.isInstance(request)) { + return next(args); + } + const { headers } = request; + const userAgent = context?.userAgent?.map(escapeUserAgent) || []; + const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); + await checkFeatures(context, options, args); + const awsContext = context; + defaultUserAgent.push( + `m/${encodeFeatures( + Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features) + )}` + ); + const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; + const appId = await options.userAgentAppId(); + if (appId) { + defaultUserAgent.push(escapeUserAgent([`app/${appId}`])); + } + const prefix = (0, import_util_endpoints.getUserAgentPrefix)(); + const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE); + const normalUAValue = [ + ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), + ...customUserAgent + ].join(SPACE); + if (options.runtime !== "browser") { + if (normalUAValue) { + headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue; } - return this.sigv4Signer.presignWithCredentials(originalRequest, credentials, options); + headers[USER_AGENT] = sdkUserAgentValue; + } else { + headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; } - getSigv4aSigner() { - if (!this.sigv4aSigner) { - const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; - const JsSigV4aSigner = import_signature_v4.signatureV4aContainer.SignatureV4a; - if (this.signerOptions.runtime === "node") { - if (!CrtSignerV4 && !JsSigV4aSigner) { - throw new Error( - "Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt" - ); - } - if (CrtSignerV4 && typeof CrtSignerV4 === "function") { - this.sigv4aSigner = new CrtSignerV4({ - ...this.signerOptions, - signingAlgorithm: 1 - }); - } else if (JsSigV4aSigner && typeof JsSigV4aSigner === "function") { - this.sigv4aSigner = new JsSigV4aSigner({ - ...this.signerOptions - }); - } else { - throw new Error( - "Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt" - ); + return next({ + ...args, + request + }); +}, "userAgentMiddleware"); +var escapeUserAgent = /* @__PURE__ */ __name((userAgentPair) => { + const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); + const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); + const prefixSeparatorIndex = name.indexOf(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}`; + } + }, ""); +}, "escapeUserAgent"); +var getUserAgentMiddlewareOptions = { + name: "getUserAgentMiddleware", + step: "build", + priority: "low", + tags: ["SET_USER_AGENT", "USER_AGENT"], + override: true +}; +var getUserAgentPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: /* @__PURE__ */ __name((clientStack) => { + clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); + }, "applyToStack") +}), "getUserAgentPlugin"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 9414: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthSchemeConfig = exports.defaultSSOOIDCHttpAuthSchemeProvider = exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0; +const core_1 = __nccwpck_require__(9963); +const util_middleware_1 = __nccwpck_require__(2390); +const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; +}; +exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sso-oauth", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "CreateToken": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; } - } else { - if (!JsSigV4aSigner || typeof JsSigV4aSigner !== "function") { - throw new Error( - "JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a" - ); + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); } - this.sigv4aSigner = new JsSigV4aSigner({ - ...this.signerOptions - }); - } } - return this.sigv4aSigner; - } + return options; +}; +exports.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); + return Object.assign(config_0, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); +}; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; + + +/***/ }), + +/***/ 5: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = __nccwpck_require__(3350); +const util_endpoints_2 = __nccwpck_require__(5473); +const ruleset_1 = __nccwpck_require__(932); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"], +}); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); }; -// Annotate the CommonJS export names for ESM import in node: +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; -0 && (0); +/***/ }), + +/***/ 932: +/***/ ((__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://oidc-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://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://oidc-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://oidc.{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://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; +exports.ruleSet = _data; /***/ }), -/***/ 2843: +/***/ 7334: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -55878,1020 +40617,1208 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts +// src/submodules/sso-oidc/index.ts var index_exports = {}; __export(index_exports, { - fromEnvSigningName: () => fromEnvSigningName, - fromSso: () => fromSso, - fromStatic: () => fromStatic, - nodeProvider: () => nodeProvider + $Command: () => import_smithy_client6.Command, + AccessDeniedException: () => AccessDeniedException, + AuthorizationPendingException: () => AuthorizationPendingException, + CreateTokenCommand: () => CreateTokenCommand, + CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog, + CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog, + ExpiredTokenException: () => ExpiredTokenException, + InternalServerException: () => InternalServerException, + InvalidClientException: () => InvalidClientException, + InvalidGrantException: () => InvalidGrantException, + InvalidRequestException: () => InvalidRequestException, + InvalidScopeException: () => InvalidScopeException, + SSOOIDC: () => SSOOIDC, + SSOOIDCClient: () => SSOOIDCClient, + SSOOIDCServiceException: () => SSOOIDCServiceException, + SlowDownException: () => SlowDownException, + UnauthorizedClientException: () => UnauthorizedClientException, + UnsupportedGrantTypeException: () => UnsupportedGrantTypeException, + __Client: () => import_smithy_client2.Client }); module.exports = __toCommonJS(index_exports); -// src/fromEnvSigningName.ts -var import_core = __nccwpck_require__(9963); -var import_property_provider = __nccwpck_require__(9721); -var fromEnvSigningName = /* @__PURE__ */ __name(({ logger, signingName } = {}) => async () => { - logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); - if (!signingName) { - throw new import_property_provider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); - } - const bearerTokenKey = (0, import_core.getBearerTokenEnvKey)(signingName); - if (!(bearerTokenKey in process.env)) { - throw new import_property_provider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); - } - return { token: process.env[bearerTokenKey] }; -}, "fromEnvSigningName"); +// src/submodules/sso-oidc/SSOOIDCClient.ts +var import_middleware_host_header = __nccwpck_require__(2545); +var import_middleware_logger = __nccwpck_require__(14); +var import_middleware_recursion_detection = __nccwpck_require__(5525); +var import_middleware_user_agent = __nccwpck_require__(4688); +var import_config_resolver = __nccwpck_require__(3098); +var import_core = __nccwpck_require__(5829); +var import_middleware_content_length = __nccwpck_require__(2800); +var import_middleware_endpoint = __nccwpck_require__(2918); +var import_middleware_retry = __nccwpck_require__(6039); +var import_smithy_client2 = __nccwpck_require__(3570); +var import_httpAuthSchemeProvider = __nccwpck_require__(9414); -// src/fromSso.ts +// src/submodules/sso-oidc/endpoint/EndpointParameters.ts +var resolveClientEndpointParameters = /* @__PURE__ */ __name((options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "sso-oauth" + }); +}, "resolveClientEndpointParameters"); +var commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } +}; +// src/submodules/sso-oidc/SSOOIDCClient.ts +var import_runtimeConfig = __nccwpck_require__(7277); +// src/submodules/sso-oidc/runtimeExtensions.ts +var import_region_config_resolver = __nccwpck_require__(8156); +var import_protocol_http = __nccwpck_require__(4418); +var import_smithy_client = __nccwpck_require__(3570); -// src/constants.ts -var EXPIRE_WINDOW_MS = 5 * 60 * 1e3; -var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; +// src/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.ts +var getHttpAuthExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + } + }; +}, "getHttpAuthExtensionConfiguration"); +var resolveHttpAuthRuntimeConfig = /* @__PURE__ */ __name((config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials() + }; +}, "resolveHttpAuthRuntimeConfig"); -// src/getSsoOidcClient.ts -var getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion, init = {}) => { - const { SSOOIDCClient } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7334))); - const ssoOidcClient = new SSOOIDCClient( - Object.assign({}, init.clientConfig ?? {}, { - region: ssoRegion ?? init.clientConfig?.region, - logger: init.clientConfig?.logger ?? init.parentClientConfig?.logger - }) +// src/submodules/sso-oidc/runtimeExtensions.ts +var resolveRuntimeExtensions = /* @__PURE__ */ __name((runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign( + (0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), + (0, import_smithy_client.getDefaultExtensionConfiguration)(runtimeConfig), + (0, import_protocol_http.getHttpHandlerExtensionConfiguration)(runtimeConfig), + getHttpAuthExtensionConfiguration(runtimeConfig) ); - return ssoOidcClient; -}, "getSsoOidcClient"); - -// src/getNewSsoOidcToken.ts -var getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion, init = {}) => { - const { CreateTokenCommand } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7334))); - const ssoOidcClient = await getSsoOidcClient(ssoRegion, init); - return ssoOidcClient.send( - new CreateTokenCommand({ - clientId: ssoToken.clientId, - clientSecret: ssoToken.clientSecret, - refreshToken: ssoToken.refreshToken, - grantType: "refresh_token" - }) + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign( + runtimeConfig, + (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), + (0, import_smithy_client.resolveDefaultRuntimeConfig)(extensionConfiguration), + (0, import_protocol_http.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), + resolveHttpAuthRuntimeConfig(extensionConfiguration) ); -}, "getNewSsoOidcToken"); +}, "resolveRuntimeExtensions"); -// src/validateTokenExpiry.ts +// src/submodules/sso-oidc/SSOOIDCClient.ts +var SSOOIDCClient = class extends import_smithy_client2.Client { + static { + __name(this, "SSOOIDCClient"); + } + /** + * The resolved configuration of SSOOIDCClient class. This is resolved and normalized from the {@link SSOOIDCClientConfig | constructor configuration interface}. + */ + config; + constructor(...[configuration]) { + const _config_0 = (0, import_runtimeConfig.getRuntimeConfig)(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, import_middleware_retry.resolveRetryConfig)(_config_2); + const _config_4 = (0, import_config_resolver.resolveRegionConfig)(_config_3); + const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); + const _config_7 = (0, import_httpAuthSchemeProvider.resolveHttpAuthSchemeConfig)(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_retry.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use( + (0, import_core.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { + httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials + }), "identityProviderConfigProvider") + }) + ); + this.middlewareStack.use((0, import_core.getHttpSigningPlugin)(this.config)); + } + /** + * Destroy underlying resources, like sockets. It's usually not necessary to do this. + * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. + * Otherwise, sockets might stay open for quite a long time before the server terminates them. + */ + destroy() { + super.destroy(); + } +}; -var validateTokenExpiry = /* @__PURE__ */ __name((token) => { - if (token.expiration && token.expiration.getTime() < Date.now()) { - throw new import_property_provider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); +// src/submodules/sso-oidc/SSOOIDC.ts +var import_smithy_client7 = __nccwpck_require__(3570); + +// src/submodules/sso-oidc/commands/CreateTokenCommand.ts +var import_middleware_endpoint2 = __nccwpck_require__(2918); +var import_middleware_serde = __nccwpck_require__(1238); +var import_smithy_client6 = __nccwpck_require__(3570); + +// src/submodules/sso-oidc/models/models_0.ts +var import_smithy_client4 = __nccwpck_require__(3570); + +// src/submodules/sso-oidc/models/SSOOIDCServiceException.ts +var import_smithy_client3 = __nccwpck_require__(3570); +var SSOOIDCServiceException = class _SSOOIDCServiceException extends import_smithy_client3.ServiceException { + static { + __name(this, "SSOOIDCServiceException"); + } + /** + * @internal + */ + constructor(options) { + super(options); + Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype); + } +}; + +// src/submodules/sso-oidc/models/models_0.ts +var AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException { + static { + __name(this, "AccessDeniedException"); + } + name = "AccessDeniedException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be access_denied.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _AccessDeniedException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +var AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException { + static { + __name(this, "AuthorizationPendingException"); + } + name = "AuthorizationPendingException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * authorization_pending.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "AuthorizationPendingException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _AuthorizationPendingException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +var CreateTokenRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.clientSecret && { clientSecret: import_smithy_client4.SENSITIVE_STRING }, + ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, + ...obj.codeVerifier && { codeVerifier: import_smithy_client4.SENSITIVE_STRING } +}), "CreateTokenRequestFilterSensitiveLog"); +var CreateTokenResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.accessToken && { accessToken: import_smithy_client4.SENSITIVE_STRING }, + ...obj.refreshToken && { refreshToken: import_smithy_client4.SENSITIVE_STRING }, + ...obj.idToken && { idToken: import_smithy_client4.SENSITIVE_STRING } +}), "CreateTokenResponseFilterSensitiveLog"); +var ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException { + static { + __name(this, "ExpiredTokenException"); + } + name = "ExpiredTokenException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be expired_token.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ExpiredTokenException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +var InternalServerException = class _InternalServerException extends SSOOIDCServiceException { + static { + __name(this, "InternalServerException"); + } + name = "InternalServerException"; + $fault = "server"; + /** + *

Single error code. For this exception the value will be server_error.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts + }); + Object.setPrototypeOf(this, _InternalServerException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +var InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException { + static { + __name(this, "InvalidClientException"); + } + name = "InvalidClientException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * invalid_client.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidClientException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +var InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException { + static { + __name(this, "InvalidGrantException"); + } + name = "InvalidGrantException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be invalid_grant.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidGrantException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidGrantException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +var InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException { + static { + __name(this, "InvalidRequestException"); + } + name = "InvalidRequestException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * invalid_request.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidRequestException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } +}; +var InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException { + static { + __name(this, "InvalidScopeException"); + } + name = "InvalidScopeException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be invalid_scope.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidScopeException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidScopeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } -}, "validateTokenExpiry"); - -// src/validateTokenKey.ts - -var validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => { - if (typeof value === "undefined") { - throw new import_property_provider.TokenProviderError( - `Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, - false - ); +}; +var SlowDownException = class _SlowDownException extends SSOOIDCServiceException { + static { + __name(this, "SlowDownException"); } -}, "validateTokenKey"); - -// src/writeSSOTokenToFile.ts -var import_shared_ini_file_loader = __nccwpck_require__(3507); -var import_fs = __nccwpck_require__(7147); -var { writeFile } = import_fs.promises; -var writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => { - const tokenFilepath = (0, import_shared_ini_file_loader.getSSOTokenFilepath)(id); - const tokenString = JSON.stringify(ssoToken, null, 2); - return writeFile(tokenFilepath, tokenString); -}, "writeSSOTokenToFile"); - -// src/fromSso.ts -var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0); -var fromSso = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { - const init = { - ..._init, - parentClientConfig: { - ...callerClientConfig, - ..._init.parentClientConfig - } - }; - init.logger?.debug("@aws-sdk/token-providers - fromSso"); - const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); - const profileName = (0, import_shared_ini_file_loader.getProfileName)({ - profile: init.profile ?? callerClientConfig?.profile - }); - const profile = profiles[profileName]; - if (!profile) { - throw new import_property_provider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); - } else if (!profile["sso_session"]) { - throw new import_property_provider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); + name = "SlowDownException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be slow_down.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "SlowDownException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _SlowDownException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - const ssoSessionName = profile["sso_session"]; - const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init); - const ssoSession = ssoSessions[ssoSessionName]; - if (!ssoSession) { - throw new import_property_provider.TokenProviderError( - `Sso session '${ssoSessionName}' could not be found in shared credentials file.`, - false - ); +}; +var UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException { + static { + __name(this, "UnauthorizedClientException"); } - for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { - if (!ssoSession[ssoSessionRequiredKey]) { - throw new import_property_provider.TokenProviderError( - `Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, - false - ); - } + name = "UnauthorizedClientException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * unauthorized_client.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "UnauthorizedClientException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _UnauthorizedClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - const ssoStartUrl = ssoSession["sso_start_url"]; - const ssoRegion = ssoSession["sso_region"]; - let ssoToken; - try { - ssoToken = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoSessionName); - } catch (e) { - throw new import_property_provider.TokenProviderError( - `The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, - false - ); +}; +var UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException { + static { + __name(this, "UnsupportedGrantTypeException"); } - validateTokenKey("accessToken", ssoToken.accessToken); - validateTokenKey("expiresAt", ssoToken.expiresAt); - const { accessToken, expiresAt } = ssoToken; - const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; - if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { - return existingToken; + name = "UnsupportedGrantTypeException"; + $fault = "client"; + /** + *

Single error code. For this exception the value will be + * unsupported_grant_type.

+ * @public + */ + error; + /** + *

Human-readable text providing additional information, used to assist the client developer + * in understanding the error that occurred.

+ * @public + */ + error_description; + /** + * @internal + */ + constructor(opts) { + super({ + name: "UnsupportedGrantTypeException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; } - if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) { - validateTokenExpiry(existingToken); - return existingToken; +}; + +// src/submodules/sso-oidc/protocols/Aws_restJson1.ts +var import_core2 = __nccwpck_require__(9963); +var import_core3 = __nccwpck_require__(5829); +var import_smithy_client5 = __nccwpck_require__(3570); +var se_CreateTokenCommand = /* @__PURE__ */ __name(async (input, context) => { + const b = (0, import_core3.requestBuilder)(input, context); + const headers = { + "content-type": "application/json" + }; + b.bp("/token"); + let body; + body = JSON.stringify( + (0, import_smithy_client5.take)(input, { + clientId: [], + clientSecret: [], + code: [], + codeVerifier: [], + deviceCode: [], + grantType: [], + redirectUri: [], + refreshToken: [], + scope: /* @__PURE__ */ __name((_) => (0, import_smithy_client5._json)(_), "scope") + }) + ); + b.m("POST").h(headers).b(body); + return b.build(); +}, "se_CreateTokenCommand"); +var de_CreateTokenCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_CommandError(output, context); } - validateTokenKey("clientId", ssoToken.clientId, true); - validateTokenKey("clientSecret", ssoToken.clientSecret, true); - validateTokenKey("refreshToken", ssoToken.refreshToken, true); - try { - lastRefreshAttemptTime.setTime(Date.now()); - const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init); - validateTokenKey("accessToken", newSsoOidcToken.accessToken); - validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); - const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3); - try { - await writeSSOTokenToFile(ssoSessionName, { - ...ssoToken, - accessToken: newSsoOidcToken.accessToken, - expiresAt: newTokenExpiration.toISOString(), - refreshToken: newSsoOidcToken.refreshToken + const contents = (0, import_smithy_client5.map)({ + $metadata: deserializeMetadata(output) + }); + const data = (0, import_smithy_client5.expectNonNull)((0, import_smithy_client5.expectObject)(await (0, import_core2.parseJsonBody)(output.body, context)), "body"); + const doc = (0, import_smithy_client5.take)(data, { + accessToken: import_smithy_client5.expectString, + expiresIn: import_smithy_client5.expectInt32, + idToken: import_smithy_client5.expectString, + refreshToken: import_smithy_client5.expectString, + tokenType: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + return contents; +}, "de_CreateTokenCommand"); +var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { + const parsedOutput = { + ...output, + body: await (0, import_core2.parseJsonErrorBody)(output.body, context) + }; + const errorCode = (0, import_core2.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 }); - } catch (error) { - } - return { - token: newSsoOidcToken.accessToken, - expiration: newTokenExpiration - }; - } catch (error) { - validateTokenExpiry(existingToken); - return existingToken; } -}, "fromSso"); - -// src/fromStatic.ts +}, "de_CommandError"); +var throwDefaultError = (0, import_smithy_client5.withBaseException)(SSOOIDCServiceException); +var de_AccessDeniedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new AccessDeniedException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_AccessDeniedExceptionRes"); +var de_AuthorizationPendingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new AuthorizationPendingException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_AuthorizationPendingExceptionRes"); +var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new ExpiredTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_ExpiredTokenExceptionRes"); +var de_InternalServerExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InternalServerException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InternalServerExceptionRes"); +var de_InvalidClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidClientException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidClientExceptionRes"); +var de_InvalidGrantExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidGrantException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidGrantExceptionRes"); +var de_InvalidRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidRequestException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidRequestExceptionRes"); +var de_InvalidScopeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new InvalidScopeException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_InvalidScopeExceptionRes"); +var de_SlowDownExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new SlowDownException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_SlowDownExceptionRes"); +var de_UnauthorizedClientExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new UnauthorizedClientException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_UnauthorizedClientExceptionRes"); +var de_UnsupportedGrantTypeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const contents = (0, import_smithy_client5.map)({}); + const data = parsedOutput.body; + const doc = (0, import_smithy_client5.take)(data, { + error: import_smithy_client5.expectString, + error_description: import_smithy_client5.expectString + }); + Object.assign(contents, doc); + const exception = new UnsupportedGrantTypeException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents + }); + return (0, import_smithy_client5.decorateServiceException)(exception, parsedOutput.body); +}, "de_UnsupportedGrantTypeExceptionRes"); +var deserializeMetadata = /* @__PURE__ */ __name((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"] +}), "deserializeMetadata"); -var fromStatic = /* @__PURE__ */ __name(({ token, logger }) => async () => { - logger?.debug("@aws-sdk/token-providers - fromStatic"); - if (!token || !token.token) { - throw new import_property_provider.TokenProviderError(`Please pass a valid token to fromStatic`, false); +// src/submodules/sso-oidc/commands/CreateTokenCommand.ts +var CreateTokenCommand = class extends import_smithy_client6.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() { + static { + __name(this, "CreateTokenCommand"); } - return token; -}, "fromStatic"); - -// src/nodeProvider.ts - -var nodeProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( - (0, import_property_provider.chain)(fromSso(init), async () => { - throw new import_property_provider.TokenProviderError("Could not load token from any providers", false); - }), - (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5, - (token) => token.expiration !== void 0 -), "nodeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 5487: -/***/ ((module) => { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; + +// src/submodules/sso-oidc/SSOOIDC.ts +var commands = { + CreateTokenCommand }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - build: () => build, - parse: () => parse, - validate: () => validate -}); -module.exports = __toCommonJS(index_exports); -var validate = /* @__PURE__ */ __name((str) => typeof str === "string" && str.indexOf("arn:") === 0 && str.split(":").length >= 6, "validate"); -var parse = /* @__PURE__ */ __name((arn) => { - const segments = arn.split(":"); - if (segments.length < 6 || segments[0] !== "arn") throw new Error("Malformed ARN"); - const [ - , - //Skip "arn" literal - partition, - service, - region, - accountId, - ...resource - ] = segments; - return { - partition, - service, - region, - accountId, - resource: resource.join(":") - }; -}, "parse"); -var build = /* @__PURE__ */ __name((arnObject) => { - const { partition = "aws", service, region, accountId, resource } = arnObject; - if ([service, region, accountId, resource].some((segment) => typeof segment !== "string")) { - throw new Error("Input ARN object is invalid"); +var SSOOIDC = class extends SSOOIDCClient { + static { + __name(this, "SSOOIDC"); } - return `arn:${partition}:${service}:${region}:${accountId}:${resource}`; -}, "build"); +}; +(0, import_smithy_client7.createAggregatedClient)(commands, SSOOIDC); // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 3350: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 7277: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - ConditionObject: () => import_util_endpoints.ConditionObject, - DeprecatedObject: () => import_util_endpoints.DeprecatedObject, - EndpointError: () => import_util_endpoints.EndpointError, - EndpointObject: () => import_util_endpoints.EndpointObject, - EndpointObjectHeaders: () => import_util_endpoints.EndpointObjectHeaders, - EndpointObjectProperties: () => import_util_endpoints.EndpointObjectProperties, - EndpointParams: () => import_util_endpoints.EndpointParams, - EndpointResolverOptions: () => import_util_endpoints.EndpointResolverOptions, - EndpointRuleObject: () => import_util_endpoints.EndpointRuleObject, - ErrorRuleObject: () => import_util_endpoints.ErrorRuleObject, - EvaluateOptions: () => import_util_endpoints.EvaluateOptions, - Expression: () => import_util_endpoints.Expression, - FunctionArgv: () => import_util_endpoints.FunctionArgv, - FunctionObject: () => import_util_endpoints.FunctionObject, - FunctionReturn: () => import_util_endpoints.FunctionReturn, - ParameterObject: () => import_util_endpoints.ParameterObject, - ReferenceObject: () => import_util_endpoints.ReferenceObject, - ReferenceRecord: () => import_util_endpoints.ReferenceRecord, - RuleSetObject: () => import_util_endpoints.RuleSetObject, - RuleSetRules: () => import_util_endpoints.RuleSetRules, - TreeRuleObject: () => import_util_endpoints.TreeRuleObject, - awsEndpointFunctions: () => awsEndpointFunctions, - getUserAgentPrefix: () => getUserAgentPrefix, - isIpAddress: () => import_util_endpoints.isIpAddress, - partition: () => partition, - resolveEndpoint: () => import_util_endpoints.resolveEndpoint, - setPartitionInfo: () => setPartitionInfo, - useDefaultPartitionInfo: () => useDefaultPartitionInfo -}); -module.exports = __toCommonJS(index_exports); - -// src/aws.ts - - -// src/lib/aws/isVirtualHostableS3Bucket.ts - - -// src/lib/isIpAddress.ts -var import_util_endpoints = __nccwpck_require__(5473); - -// src/lib/aws/isVirtualHostableS3Bucket.ts -var isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => { - if (allowSubDomains) { - for (const label of value.split(".")) { - if (!isVirtualHostableS3Bucket(label)) { - return false; - } - } - return true; - } - if (!(0, import_util_endpoints.isValidHostLabel)(value)) { - return false; - } - if (value.length < 3 || value.length > 63) { - return false; - } - if (value !== value.toLowerCase()) { - return false; - } - if ((0, import_util_endpoints.isIpAddress)(value)) { - return false; - } - return true; -}, "isVirtualHostableS3Bucket"); - -// src/lib/aws/parseArn.ts -var ARN_DELIMITER = ":"; -var RESOURCE_DELIMITER = "/"; -var parseArn = /* @__PURE__ */ __name((value) => { - const segments = value.split(ARN_DELIMITER); - if (segments.length < 6) return null; - const [arn, partition2, service, region, accountId, ...resourcePath] = segments; - if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null; - const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); - return { - partition: partition2, - service, - region, - accountId, - resourceId - }; -}, "parseArn"); - -// src/lib/aws/partitions.json -var partitions_default = { - 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|mx)\\-\\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)" - }, - "ap-southeast-5": { - description: "Asia Pacific (Malaysia)" - }, - "ap-southeast-7": { - description: "Asia Pacific (Thailand)" - }, - "aws-global": { - description: "AWS Standard global region" - }, - "ca-central-1": { - description: "Canada (Central)" - }, - "ca-west-1": { - description: "Canada West (Calgary)" - }, - "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)" - }, - "mx-central-1": { - description: "Mexico (Central)" - }, - "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: { - "aws-iso-e-global": { - description: "AWS ISOE (Europe) global region" - }, - "eu-isoe-west-1": { - description: "EU ISOE West" - } - } - }, { - 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: { - "aws-iso-f-global": { - description: "AWS ISOF global region" - }, - "us-isof-east-1": { - description: "US ISOF EAST" - }, - "us-isof-south-1": { - description: "US ISOF SOUTH" - } - } - }, { - id: "aws-eusc", - outputs: { - dnsSuffix: "amazonaws.eu", - dualStackDnsSuffix: "amazonaws.eu", - implicitGlobalRegion: "eusc-de-east-1", - name: "aws-eusc", - supportsDualStack: false, - supportsFIPS: true - }, - regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", - regions: { - "eusc-de-east-1": { - description: "EU (Germany)" - } - } - }], - version: "1.1" -}; - -// src/lib/aws/partition.ts -var selectedPartitionsInfo = partitions_default; -var selectedUserAgentPrefix = ""; -var partition = /* @__PURE__ */ __name((value) => { - const { partitions } = selectedPartitionsInfo; - for (const partition2 of partitions) { - const { regions, outputs } = partition2; - for (const [region, regionData] of Object.entries(regions)) { - if (region === value) { - return { - ...outputs, - ...regionData - }; - } - } - } - for (const partition2 of partitions) { - const { regionRegex, outputs } = partition2; - if (new RegExp(regionRegex).test(value)) { - return { - ...outputs - }; - } - } - const DEFAULT_PARTITION = partitions.find((partition2) => partition2.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 - }; -}, "partition"); -var setPartitionInfo = /* @__PURE__ */ __name((partitionsInfo, userAgentPrefix = "") => { - selectedPartitionsInfo = partitionsInfo; - selectedUserAgentPrefix = userAgentPrefix; -}, "setPartitionInfo"); -var useDefaultPartitionInfo = /* @__PURE__ */ __name(() => { - setPartitionInfo(partitions_default, ""); -}, "useDefaultPartitionInfo"); -var getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix"); - -// src/aws.ts -var awsEndpointFunctions = { - isVirtualHostableS3Bucket, - parseArn, - partition +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__(8842)); +const core_1 = __nccwpck_require__(9963); +const util_user_agent_node_1 = __nccwpck_require__(8095); +const config_resolver_1 = __nccwpck_require__(3098); +const hash_node_1 = __nccwpck_require__(3081); +const middleware_retry_1 = __nccwpck_require__(6039); +const node_config_provider_1 = __nccwpck_require__(3461); +const node_http_handler_1 = __nccwpck_require__(258); +const util_body_length_node_1 = __nccwpck_require__(8075); +const util_retry_1 = __nccwpck_require__(4902); +const runtimeConfig_shared_1 = __nccwpck_require__(9513); +const smithy_client_1 = __nccwpck_require__(3570); +const util_defaults_mode_node_1 = __nccwpck_require__(2429); +const smithy_client_2 = __nccwpck_require__(3570); +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); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ 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, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, + }, config), + 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, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; }; -import_util_endpoints.customEndpointFunctions.aws = awsEndpointFunctions; - -// src/resolveEndpoint.ts +exports.getRuntimeConfig = getRuntimeConfig; -// src/types/EndpointError.ts +/***/ }), +/***/ 9513: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/types/EndpointRuleObject.ts +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const core_1 = __nccwpck_require__(9963); +const core_2 = __nccwpck_require__(5829); +const smithy_client_1 = __nccwpck_require__(3570); +const url_parser_1 = __nccwpck_require__(4681); +const util_base64_1 = __nccwpck_require__(5600); +const util_utf8_1 = __nccwpck_require__(1895); +const httpAuthSchemeProvider_1 = __nccwpck_require__(9414); +const endpointResolver_1 = __nccwpck_require__(5); +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 ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSSOOIDCHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + logger: config?.logger ?? new smithy_client_1.NoOpLogger(), + serviceId: config?.serviceId ?? "SSO OIDC", + urlParser: config?.urlParser ?? url_parser_1.parseUrl, + utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; -// src/types/ErrorRuleObject.ts +/***/ }), -// src/types/RuleSetObject.ts +/***/ 8974: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; -// src/types/TreeRuleObject.ts +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.STSClient = exports.__Client = void 0; +const middleware_host_header_1 = __nccwpck_require__(2545); +const middleware_logger_1 = __nccwpck_require__(14); +const middleware_recursion_detection_1 = __nccwpck_require__(5525); +const middleware_user_agent_1 = __nccwpck_require__(4688); +const config_resolver_1 = __nccwpck_require__(3098); +const core_1 = __nccwpck_require__(5829); +const middleware_content_length_1 = __nccwpck_require__(2800); +const middleware_endpoint_1 = __nccwpck_require__(2918); +const middleware_retry_1 = __nccwpck_require__(6039); +const smithy_client_1 = __nccwpck_require__(3570); +Object.defineProperty(exports, "__Client", ({ enumerable: true, get: function () { return smithy_client_1.Client; } })); +const httpAuthSchemeProvider_1 = __nccwpck_require__(8013); +const EndpointParameters_1 = __nccwpck_require__(1765); +const runtimeConfig_1 = __nccwpck_require__(1798); +const runtimeExtensions_1 = __nccwpck_require__(669); +class STSClient extends smithy_client_1.Client { + config; + constructor(...[configuration]) { + const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); + const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); + const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); + const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); + const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); + const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); + 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, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + }), + })); + this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); + } + destroy() { + super.destroy(); + } +} +exports.STSClient = STSClient; -// src/types/shared.ts +/***/ }), -// Annotate the CommonJS export names for ESM import in node: +/***/ 4935: +/***/ ((__unused_webpack_module, exports) => { -0 && (0); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; +const getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } + else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + }, + }; +}; +exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; +const resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials(), + }; +}; +exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; /***/ }), -/***/ 8095: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 8013: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; +const core_1 = __nccwpck_require__(9963); +const util_middleware_1 = __nccwpck_require__(2390); +const STSClient_1 = __nccwpck_require__(8974); +const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) || + (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })(), + }; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; +exports.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sts", + region: authParameters.region, + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context, + }, + }), + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth", + }; +} +const defaultSTSHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "AssumeRoleWithWebIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - NODE_APP_ID_CONFIG_OPTIONS: () => NODE_APP_ID_CONFIG_OPTIONS, - UA_APP_ID_ENV_NAME: () => UA_APP_ID_ENV_NAME, - UA_APP_ID_INI_NAME: () => UA_APP_ID_INI_NAME, - createDefaultUserAgentProvider: () => createDefaultUserAgentProvider, - crtAvailability: () => crtAvailability, - defaultUserAgent: () => defaultUserAgent +exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; +const resolveStsAuthConfig = (input) => Object.assign(input, { + stsClientCtor: STSClient_1.STSClient, }); -module.exports = __toCommonJS(index_exports); - -// src/defaultUserAgent.ts -var import_os = __nccwpck_require__(2037); -var import_process = __nccwpck_require__(7282); - -// src/crt-availability.ts -var crtAvailability = { - isCrtAvailable: false +exports.resolveStsAuthConfig = resolveStsAuthConfig; +const resolveHttpAuthSchemeConfig = (config) => { + const config_0 = (0, exports.resolveStsAuthConfig)(config); + const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); + return Object.assign(config_1, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), + }); }; +exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; -// src/is-crt-available.ts -var isCrtAvailable = /* @__PURE__ */ __name(() => { - if (crtAvailability.isCrtAvailable) { - return ["md/crt-avail"]; - } - return null; -}, "isCrtAvailable"); -// src/defaultUserAgent.ts -var createDefaultUserAgentProvider = /* @__PURE__ */ __name(({ serviceId, clientVersion }) => { - return async (config) => { - const sections = [ - // sdk-metadata - ["aws-sdk-js", clientVersion], - // ua-metadata - ["ua", "2.1"], - // os-metadata - [`os/${(0, import_os.platform)()}`, (0, import_os.release)()], - // language-metadata - // ECMAScript edition doesn't matter in JS, so no version needed. - ["lang/js"], - ["md/nodejs", `${import_process.versions.node}`] - ]; - const crtAvailable = isCrtAvailable(); - if (crtAvailable) { - sections.push(crtAvailable); - } - if (serviceId) { - sections.push([`api/${serviceId}`, clientVersion]); - } - if (import_process.env.AWS_EXECUTION_ENV) { - sections.push([`exec-env/${import_process.env.AWS_EXECUTION_ENV}`]); - } - const appId = await config?.userAgentAppId?.(); - const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; - return resolvedUserAgent; - }; -}, "createDefaultUserAgentProvider"); -var defaultUserAgent = createDefaultUserAgentProvider; +/***/ }), -// src/nodeAppIdConfigOptions.ts -var import_middleware_user_agent = __nccwpck_require__(4688); -var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; -var UA_APP_ID_INI_NAME = "sdk_ua_app_id"; -var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; -var NODE_APP_ID_CONFIG_OPTIONS = { - environmentVariableSelector: /* @__PURE__ */ __name((env2) => env2[UA_APP_ID_ENV_NAME], "environmentVariableSelector"), - configFileSelector: /* @__PURE__ */ __name((profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], "configFileSelector"), - default: import_middleware_user_agent.DEFAULT_UA_APP_ID -}; -// Annotate the CommonJS export names for ESM import in node: +/***/ 1765: +/***/ ((__unused_webpack_module, exports) => { -0 && (0); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.commonParams = exports.resolveClientEndpointParameters = void 0; +const resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + useGlobalEndpoint: options.useGlobalEndpoint ?? false, + defaultSigningName: "sts", + }); +}; +exports.resolveClientEndpointParameters = resolveClientEndpointParameters; +exports.commonParams = { + 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" }, +}; /***/ }), -/***/ 2329: -/***/ ((module) => { +/***/ 7561: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var index_exports = {}; -__export(index_exports, { - XmlNode: () => XmlNode, - XmlText: () => XmlText +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultEndpointResolver = void 0; +const util_endpoints_1 = __nccwpck_require__(3350); +const util_endpoints_2 = __nccwpck_require__(5473); +const ruleset_1 = __nccwpck_require__(9127); +const cache = new util_endpoints_2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"], }); -module.exports = __toCommonJS(index_exports); - -// src/escape-attribute.ts -function escapeAttribute(value) { - return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); -} -__name(escapeAttribute, "escapeAttribute"); +const defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams: endpointParams, + logger: context.logger, + })); +}; +exports.defaultEndpointResolver = defaultEndpointResolver; +util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; -// src/escape-element.ts -function escapeElement(value) { - return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">").replace(/\r/g, " ").replace(/\n/g, " ").replace(/\u0085/g, "…").replace(/\u2028/, "
"); -} -__name(escapeElement, "escapeElement"); -// src/XmlText.ts -var XmlText = class { - constructor(value) { - this.value = value; - } - static { - __name(this, "XmlText"); - } - toString() { - return escapeElement("" + this.value); - } -}; +/***/ }), -// src/XmlNode.ts -var XmlNode = class _XmlNode { - constructor(name, children = []) { - this.name = name; - this.children = children; - } - static { - __name(this, "XmlNode"); - } - attributes = {}; - static of(name, childText, withName) { - const node = new _XmlNode(name); - if (childText !== void 0) { - node.addChildNode(new XmlText(childText)); - } - if (withName !== void 0) { - node.withName(withName); - } - return node; - } - withName(name) { - this.name = name; - return this; - } - addAttribute(name, value) { - this.attributes[name] = value; - return this; - } - addChildNode(child) { - this.children.push(child); - return this; - } - removeAttribute(name) { - delete this.attributes[name]; - return this; - } - /** - * @internal - * Alias of {@link XmlNode#withName(string)} for codegen brevity. - */ - n(name) { - this.name = name; - return this; - } - /** - * @internal - * Alias of {@link XmlNode#addChildNode(string)} for codegen brevity. - */ - c(child) { - this.children.push(child); - return this; - } - /** - * @internal - * Checked version of {@link XmlNode#addAttribute(string)} for codegen brevity. - */ - a(name, value) { - if (value != null) { - this.attributes[name] = value; - } - return this; - } - /** - * Create a child node. - * Used in serialization of string fields. - * @internal - */ - cc(input, field, withName = field) { - if (input[field] != null) { - const node = _XmlNode.of(field, input[field]).withName(withName); - this.c(node); - } - } - /** - * Creates list child nodes. - * @internal - */ - l(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - nodes.map((node) => { - node.withName(memberName); - this.c(node); - }); - } - } - /** - * Creates list child nodes with container. - * @internal - */ - lc(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - const containerNode = new _XmlNode(memberName); - nodes.map((node) => { - containerNode.c(node); - }); - this.c(containerNode); - } - } - toString() { - const hasChildren = Boolean(this.children.length); - let xmlText = `<${this.name}`; - const attributes = this.attributes; - for (const attributeName of Object.keys(attributes)) { - const attribute = attributes[attributeName]; - if (attribute != null) { - xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; - } - } - return xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`; - } -}; -// Annotate the CommonJS export names for ESM import in node: +/***/ 9127: +/***/ ((__unused_webpack_module, exports) => { -0 && (0); +"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; /***/ }), -/***/ 3098: +/***/ 2273: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; + var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; @@ -56909,649 +41836,1077 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - CONFIG_USE_DUALSTACK_ENDPOINT: () => CONFIG_USE_DUALSTACK_ENDPOINT, - CONFIG_USE_FIPS_ENDPOINT: () => CONFIG_USE_FIPS_ENDPOINT, - DEFAULT_USE_DUALSTACK_ENDPOINT: () => DEFAULT_USE_DUALSTACK_ENDPOINT, - DEFAULT_USE_FIPS_ENDPOINT: () => DEFAULT_USE_FIPS_ENDPOINT, - ENV_USE_DUALSTACK_ENDPOINT: () => ENV_USE_DUALSTACK_ENDPOINT, - ENV_USE_FIPS_ENDPOINT: () => ENV_USE_FIPS_ENDPOINT, - NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, - NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, - NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, - NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, - REGION_ENV_NAME: () => REGION_ENV_NAME, - REGION_INI_NAME: () => REGION_INI_NAME, - getRegionInfo: () => getRegionInfo, - resolveCustomEndpointsConfig: () => resolveCustomEndpointsConfig, - resolveEndpointsConfig: () => resolveEndpointsConfig, - resolveRegionConfig: () => resolveRegionConfig +// src/submodules/sts/index.ts +var index_exports = {}; +__export(index_exports, { + AssumeRoleCommand: () => AssumeRoleCommand, + AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog, + AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand, + AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog, + AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog, + ClientInputEndpointParameters: () => import_EndpointParameters3.ClientInputEndpointParameters, + CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog, + ExpiredTokenException: () => ExpiredTokenException, + IDPCommunicationErrorException: () => IDPCommunicationErrorException, + IDPRejectedClaimException: () => IDPRejectedClaimException, + InvalidIdentityTokenException: () => InvalidIdentityTokenException, + MalformedPolicyDocumentException: () => MalformedPolicyDocumentException, + PackedPolicyTooLargeException: () => PackedPolicyTooLargeException, + RegionDisabledException: () => RegionDisabledException, + STS: () => STS, + STSServiceException: () => STSServiceException, + decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, + getDefaultRoleAssumer: () => getDefaultRoleAssumer2, + getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 }); -module.exports = __toCommonJS(src_exports); - -// src/endpointsConfig/NodeUseDualstackEndpointConfigOptions.ts -var import_util_config_provider = __nccwpck_require__(3375); -var ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; -var CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; -var DEFAULT_USE_DUALSTACK_ENDPOINT = false; -var NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => (0, import_util_config_provider.booleanSelector)(env, ENV_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.ENV), - configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.CONFIG), - default: false -}; - -// src/endpointsConfig/NodeUseFipsEndpointConfigOptions.ts - -var ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; -var CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; -var DEFAULT_USE_FIPS_ENDPOINT = false; -var NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => (0, import_util_config_provider.booleanSelector)(env, ENV_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.ENV), - configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.CONFIG), - default: false -}; +module.exports = __toCommonJS(index_exports); +__reExport(index_exports, __nccwpck_require__(8974), module.exports); -// src/endpointsConfig/resolveCustomEndpointsConfig.ts -var import_util_middleware = __nccwpck_require__(2390); -var resolveCustomEndpointsConfig = /* @__PURE__ */ __name((input) => { - const { tls, endpoint, urlParser, useDualstackEndpoint } = input; - return Object.assign(input, { - tls: tls ?? true, - endpoint: (0, import_util_middleware.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), - isCustomEndpoint: true, - useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false) - }); -}, "resolveCustomEndpointsConfig"); +// src/submodules/sts/STS.ts +var import_smithy_client6 = __nccwpck_require__(3570); -// src/endpointsConfig/resolveEndpointsConfig.ts +// src/submodules/sts/commands/AssumeRoleCommand.ts +var import_middleware_endpoint = __nccwpck_require__(2918); +var import_middleware_serde = __nccwpck_require__(1238); +var import_smithy_client4 = __nccwpck_require__(3570); +var import_EndpointParameters = __nccwpck_require__(1765); +// src/submodules/sts/models/models_0.ts +var import_smithy_client2 = __nccwpck_require__(3570); -// src/endpointsConfig/utils/getEndpointFromRegion.ts -var getEndpointFromRegion = /* @__PURE__ */ __name(async (input) => { - 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"); +// src/submodules/sts/models/STSServiceException.ts +var import_smithy_client = __nccwpck_require__(3570); +var STSServiceException = class _STSServiceException extends import_smithy_client.ServiceException { + static { + __name(this, "STSServiceException"); } - const useDualstackEndpoint = await input.useDualstackEndpoint(); - const useFipsEndpoint = await input.useFipsEndpoint(); - const { hostname } = await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint }) ?? {}; - if (!hostname) { - throw new Error("Cannot resolve hostname from client config"); + /** + * @internal + */ + constructor(options) { + super(options); + Object.setPrototypeOf(this, _STSServiceException.prototype); } - return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`); -}, "getEndpointFromRegion"); - -// src/endpointsConfig/resolveEndpointsConfig.ts -var resolveEndpointsConfig = /* @__PURE__ */ __name((input) => { - const useDualstackEndpoint = (0, import_util_middleware.normalizeProvider)(input.useDualstackEndpoint ?? false); - const { endpoint, useFipsEndpoint, urlParser, tls } = input; - return Object.assign(input, { - tls: tls ?? true, - endpoint: endpoint ? (0, import_util_middleware.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), - isCustomEndpoint: !!endpoint, - useDualstackEndpoint - }); -}, "resolveEndpointsConfig"); +}; -// src/regionConfig/config.ts -var REGION_ENV_NAME = "AWS_REGION"; -var REGION_INI_NAME = "region"; -var NODE_REGION_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[REGION_ENV_NAME], - configFileSelector: (profile) => profile[REGION_INI_NAME], - default: () => { - throw new Error("Region is missing"); +// src/submodules/sts/models/models_0.ts +var CredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client2.SENSITIVE_STRING } +}), "CredentialsFilterSensitiveLog"); +var AssumeRoleResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } +}), "AssumeRoleResponseFilterSensitiveLog"); +var ExpiredTokenException = class _ExpiredTokenException extends STSServiceException { + static { + __name(this, "ExpiredTokenException"); + } + name = "ExpiredTokenException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ExpiredTokenException.prototype); } }; -var NODE_REGION_CONFIG_FILE_OPTIONS = { - preferredFile: "credentials" +var MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { + static { + __name(this, "MalformedPolicyDocumentException"); + } + name = "MalformedPolicyDocumentException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "MalformedPolicyDocumentException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); + } +}; +var PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { + static { + __name(this, "PackedPolicyTooLargeException"); + } + name = "PackedPolicyTooLargeException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "PackedPolicyTooLargeException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); + } +}; +var RegionDisabledException = class _RegionDisabledException extends STSServiceException { + static { + __name(this, "RegionDisabledException"); + } + name = "RegionDisabledException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "RegionDisabledException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _RegionDisabledException.prototype); + } +}; +var IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { + static { + __name(this, "IDPRejectedClaimException"); + } + name = "IDPRejectedClaimException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "IDPRejectedClaimException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); + } +}; +var InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { + static { + __name(this, "InvalidIdentityTokenException"); + } + name = "InvalidIdentityTokenException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "InvalidIdentityTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); + } +}; +var AssumeRoleWithWebIdentityRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client2.SENSITIVE_STRING } +}), "AssumeRoleWithWebIdentityRequestFilterSensitiveLog"); +var AssumeRoleWithWebIdentityResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } +}), "AssumeRoleWithWebIdentityResponseFilterSensitiveLog"); +var IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { + static { + __name(this, "IDPCommunicationErrorException"); + } + name = "IDPCommunicationErrorException"; + $fault = "client"; + /** + * @internal + */ + constructor(opts) { + super({ + name: "IDPCommunicationErrorException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); + } }; -// src/regionConfig/isFipsRegion.ts -var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); - -// src/regionConfig/getRealRegion.ts -var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); - -// src/regionConfig/resolveRegionConfig.ts -var resolveRegionConfig = /* @__PURE__ */ __name((input) => { - const { region, useFipsEndpoint } = input; - if (!region) { - throw new Error("Region is missing"); +// src/submodules/sts/protocols/Aws_query.ts +var import_core = __nccwpck_require__(9963); +var import_protocol_http = __nccwpck_require__(4418); +var import_smithy_client3 = __nccwpck_require__(3570); +var se_AssumeRoleCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_AssumeRoleRequest(input, context), + [_A]: _AR, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_AssumeRoleCommand"); +var se_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (input, context) => { + const headers = SHARED_HEADERS; + let body; + body = buildFormUrlencodedString({ + ...se_AssumeRoleWithWebIdentityRequest(input, context), + [_A]: _ARWWI, + [_V]: _ + }); + return buildHttpRpcRequest(context, headers, "/", void 0, body); +}, "se_AssumeRoleWithWebIdentityCommand"); +var de_AssumeRoleCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); } - return Object.assign(input, { - region: async () => { - if (typeof region === "string") { - return getRealRegion(region); - } - const providedRegion = await region(); - return getRealRegion(providedRegion); - }, - useFipsEndpoint: async () => { - const providedRegion = typeof region === "string" ? region : await region(); - if (isFipsRegion(providedRegion)) { - return true; - } - return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); - } + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_AssumeRoleResponse(data.AssumeRoleResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_AssumeRoleCommand"); +var de_AssumeRoleWithWebIdentityCommand = /* @__PURE__ */ __name(async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await (0, import_core.parseXmlBody)(output.body, context); + let contents = {}; + contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context); + const response = { + $metadata: deserializeMetadata(output), + ...contents + }; + return response; +}, "de_AssumeRoleWithWebIdentityCommand"); +var de_CommandError = /* @__PURE__ */ __name(async (output, context) => { + const parsedOutput = { + ...output, + body: await (0, import_core.parseXmlErrorBody)(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); + 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); + default: + const parsedBody = parsedOutput.body; + return throwDefaultError({ + output, + parsedBody: parsedBody.Error, + errorCode + }); + } +}, "de_CommandError"); +var de_ExpiredTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_ExpiredTokenException(body.Error, context); + const exception = new ExpiredTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized }); -}, "resolveRegionConfig"); - -// src/regionInfo/getHostnameFromVariants.ts -var getHostnameFromVariants = /* @__PURE__ */ __name((variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find( - ({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack") -)?.hostname, "getHostnameFromVariants"); - -// src/regionInfo/getResolvedHostname.ts -var getResolvedHostname = /* @__PURE__ */ __name((resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : void 0, "getResolvedHostname"); - -// src/regionInfo/getResolvedPartition.ts -var getResolvedPartition = /* @__PURE__ */ __name((region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws", "getResolvedPartition"); - -// src/regionInfo/getResolvedSigningRegion.ts -var getResolvedSigningRegion = /* @__PURE__ */ __name((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); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_ExpiredTokenExceptionRes"); +var de_IDPCommunicationErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_IDPCommunicationErrorException(body.Error, context); + const exception = new IDPCommunicationErrorException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_IDPCommunicationErrorExceptionRes"); +var de_IDPRejectedClaimExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_IDPRejectedClaimException(body.Error, context); + const exception = new IDPRejectedClaimException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_IDPRejectedClaimExceptionRes"); +var de_InvalidIdentityTokenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_InvalidIdentityTokenException(body.Error, context); + const exception = new InvalidIdentityTokenException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_InvalidIdentityTokenExceptionRes"); +var de_MalformedPolicyDocumentExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_MalformedPolicyDocumentException(body.Error, context); + const exception = new MalformedPolicyDocumentException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_MalformedPolicyDocumentExceptionRes"); +var de_PackedPolicyTooLargeExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_PackedPolicyTooLargeException(body.Error, context); + const exception = new PackedPolicyTooLargeException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_PackedPolicyTooLargeExceptionRes"); +var de_RegionDisabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = de_RegionDisabledException(body.Error, context); + const exception = new RegionDisabledException({ + $metadata: deserializeMetadata(parsedOutput), + ...deserialized + }); + return (0, import_smithy_client3.decorateServiceException)(exception, body); +}, "de_RegionDisabledExceptionRes"); +var se_AssumeRoleRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_RA] != null) { + entries[_RA] = input[_RA]; + } + if (input[_RSN] != null) { + entries[_RSN] = input[_RSN]; + } + if (input[_PA] != null) { + const memberEntries = se_policyDescriptorListType(input[_PA], context); + if (input[_PA]?.length === 0) { + entries.PolicyArns = []; + } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `PolicyArns.${key}`; + entries[loc] = value; + }); + } + if (input[_P] != null) { + entries[_P] = input[_P]; + } + if (input[_DS] != null) { + entries[_DS] = input[_DS]; + } + if (input[_T] != null) { + const memberEntries = se_tagListType(input[_T], context); + if (input[_T]?.length === 0) { + entries.Tags = []; + } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `Tags.${key}`; + entries[loc] = value; + }); + } + if (input[_TTK] != null) { + const memberEntries = se_tagKeyListType(input[_TTK], context); + if (input[_TTK]?.length === 0) { + entries.TransitiveTagKeys = []; } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `TransitiveTagKeys.${key}`; + entries[loc] = value; + }); } -}, "getResolvedSigningRegion"); - -// src/regionInfo/getRegionInfo.ts -var getRegionInfo = /* @__PURE__ */ __name((region, { - useFipsEndpoint = false, - useDualstackEndpoint = false, - signingService, - regionHash, - partitionHash -}) => { - const partition = getResolvedPartition(region, { partitionHash }); - const resolvedRegion = region in regionHash ? region : partitionHash[partition]?.endpoint ?? region; - const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; - const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); - const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); - const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); - if (hostname === void 0) { - throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); + if (input[_EI] != null) { + entries[_EI] = input[_EI]; } - const signingRegion = getResolvedSigningRegion(hostname, { - signingRegion: regionHash[resolvedRegion]?.signingRegion, - regionRegex: partitionHash[partition].regionRegex, - useFipsEndpoint - }); - return { - partition, - signingService, - hostname, - ...signingRegion && { signingRegion }, - ...regionHash[resolvedRegion]?.signingService && { - signingService: regionHash[resolvedRegion].signingService + if (input[_SN] != null) { + entries[_SN] = input[_SN]; + } + if (input[_TC] != null) { + entries[_TC] = input[_TC]; + } + if (input[_SI] != null) { + entries[_SI] = input[_SI]; + } + if (input[_PC] != null) { + const memberEntries = se_ProvidedContextsListType(input[_PC], context); + if (input[_PC]?.length === 0) { + entries.ProvidedContexts = []; } - }; -}, "getRegionInfo"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 5829: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `ProvidedContexts.${key}`; + entries[loc] = value; + }); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, - EXPIRATION_MS: () => EXPIRATION_MS, - HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, - HttpBearerAuthSigner: () => HttpBearerAuthSigner, - NoAuthSigner: () => NoAuthSigner, - createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, - createPaginator: () => createPaginator, - doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, - getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, - getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, - getHttpSigningPlugin: () => getHttpSigningPlugin, - getSmithyContext: () => getSmithyContext, - httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, - httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, - httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, - httpSigningMiddleware: () => httpSigningMiddleware, - httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, - isIdentityExpired: () => isIdentityExpired, - memoizeIdentityProvider: () => memoizeIdentityProvider, - normalizeProvider: () => normalizeProvider, - requestBuilder: () => import_protocols.requestBuilder, - setFeature: () => setFeature -}); -module.exports = __toCommonJS(src_exports); - -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(5756); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); - -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -var import_util_middleware = __nccwpck_require__(2390); - -// src/middleware-http-auth-scheme/resolveAuthOptions.ts -var resolveAuthOptions = /* @__PURE__ */ __name((candidateAuthOptions, authSchemePreference) => { - if (!authSchemePreference || authSchemePreference.length === 0) { - return candidateAuthOptions; + return entries; +}, "se_AssumeRoleRequest"); +var se_AssumeRoleWithWebIdentityRequest = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_RA] != null) { + entries[_RA] = input[_RA]; } - const preferredAuthOptions = []; - for (const preferredSchemeName of authSchemePreference) { - for (const candidateAuthOption of candidateAuthOptions) { - const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; - if (candidateAuthSchemeName === preferredSchemeName) { - preferredAuthOptions.push(candidateAuthOption); - } + if (input[_RSN] != null) { + entries[_RSN] = input[_RSN]; + } + if (input[_WIT] != null) { + entries[_WIT] = input[_WIT]; + } + if (input[_PI] != null) { + entries[_PI] = input[_PI]; + } + if (input[_PA] != null) { + const memberEntries = se_policyDescriptorListType(input[_PA], context); + if (input[_PA]?.length === 0) { + entries.PolicyArns = []; } + Object.entries(memberEntries).forEach(([key, value]) => { + const loc = `PolicyArns.${key}`; + entries[loc] = value; + }); } - for (const candidateAuthOption of candidateAuthOptions) { - if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { - preferredAuthOptions.push(candidateAuthOption); + if (input[_P] != null) { + entries[_P] = input[_P]; + } + if (input[_DS] != null) { + entries[_DS] = input[_DS]; + } + return entries; +}, "se_AssumeRoleWithWebIdentityRequest"); +var se_policyDescriptorListType = /* @__PURE__ */ __name((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 preferredAuthOptions; -}, "resolveAuthOptions"); - -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -function convertHttpAuthSchemesToMap(httpAuthSchemes) { - const map = /* @__PURE__ */ new Map(); - for (const scheme of httpAuthSchemes) { - map.set(scheme.schemeId, scheme); + return entries; +}, "se_policyDescriptorListType"); +var se_PolicyDescriptorType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_a] != null) { + entries[_a] = input[_a]; } - return map; -} -__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); -var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { - const options = config.httpAuthSchemeProvider( - await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) - ); - const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; - const resolvedOptions = resolveAuthOptions(options, authSchemePreference); - const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const failureReasons = []; - for (const option of resolvedOptions) { - const scheme = authSchemes.get(option.schemeId); - if (!scheme) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + return entries; +}, "se_PolicyDescriptorType"); +var se_ProvidedContext = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_PAr] != null) { + entries[_PAr] = input[_PAr]; + } + if (input[_CA] != null) { + entries[_CA] = input[_CA]; + } + return entries; +}, "se_ProvidedContext"); +var se_ProvidedContextsListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { continue; } - const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); - if (!identityProvider) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + const memberEntries = se_ProvidedContext(entry, context); + Object.entries(memberEntries).forEach(([key, value]) => { + entries[`member.${counter}.${key}`] = value; + }); + counter++; + } + return entries; +}, "se_ProvidedContextsListType"); +var se_Tag = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + if (input[_K] != null) { + entries[_K] = input[_K]; + } + if (input[_Va] != null) { + entries[_Va] = input[_Va]; + } + return entries; +}, "se_Tag"); +var se_tagKeyListType = /* @__PURE__ */ __name((input, context) => { + const entries = {}; + let counter = 1; + for (const entry of input) { + if (entry === null) { continue; } - const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; - option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); - option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); - smithyContext.selectedHttpAuthScheme = { - httpAuthOption: option, - identity: await identityProvider(option.identityProperties), - signer: scheme.signer - }; - break; + entries[`member.${counter}`] = entry; + counter++; } - if (!smithyContext.selectedHttpAuthScheme) { - throw new Error(failureReasons.join("\n")); + return entries; +}, "se_tagKeyListType"); +var se_tagListType = /* @__PURE__ */ __name((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 next(args); -}, "httpAuthSchemeMiddleware"); - -// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts -var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: "endpointV2Middleware" -}; -var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeEndpointRuleSetMiddlewareOptions - ); + return entries; +}, "se_tagListType"); +var de_AssumedRoleUser = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_ARI] != null) { + contents[_ARI] = (0, import_smithy_client3.expectString)(output[_ARI]); } -}), "getHttpAuthSchemeEndpointRuleSetPlugin"); - -// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts -var import_middleware_serde = __nccwpck_require__(1238); -var httpAuthSchemeMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: import_middleware_serde.serializerMiddlewareOption.name -}; -var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeMiddlewareOptions - ); + if (output[_Ar] != null) { + contents[_Ar] = (0, import_smithy_client3.expectString)(output[_Ar]); } -}), "getHttpAuthSchemePlugin"); - -// src/middleware-http-signing/httpSigningMiddleware.ts -var import_protocol_http = __nccwpck_require__(4418); - -var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { - throw error; -}, "defaultErrorHandler"); -var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { -}, "defaultSuccessHandler"); -var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { - if (!import_protocol_http.HttpRequest.isInstance(args.request)) { - return next(args); + return contents; +}, "de_AssumedRoleUser"); +var de_AssumeRoleResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C], context); } - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + if (output[_ARU] != null) { + contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); } - const { - httpAuthOption: { signingProperties = {} }, - identity, - signer - } = scheme; - const output = await next({ - ...args, - request: await signer.sign(args.request, identity, signingProperties) - }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); - (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); - return output; -}, "httpSigningMiddleware"); - -// src/middleware-http-signing/getHttpSigningMiddleware.ts -var httpSigningMiddlewareOptions = { - step: "finalizeRequest", - tags: ["HTTP_SIGNING"], - name: "httpSigningMiddleware", - aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], - override: true, - relation: "after", - toMiddleware: "retryMiddleware" -}; -var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); + if (output[_PPS] != null) { + contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); } -}), "getHttpSigningPlugin"); - -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") - return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); - -// src/pagination/createPaginator.ts -var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { - let command = new CommandCtor(input); - command = withCommand(command) ?? command; - return await client.send(command, ...args); -}, "makePagedClientRequest"); -function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { - return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { - const _input = input; - let token = config.startingToken ?? _input[inputTokenName]; - let hasNext = true; - let page; - while (hasNext) { - _input[inputTokenName] = token; - if (pageSizeTokenName) { - _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; - } - if (config.client instanceof ClientCtor) { - page = await makePagedClientRequest( - CommandCtor, - config.client, - input, - config.withCommand, - ...additionalArguments - ); - } else { - throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); - } - yield page; - const prevToken = token; - token = get(page, outputTokenName); - hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); - } - return void 0; - }, "paginateOperation"); -} -__name(createPaginator, "createPaginator"); -var get = /* @__PURE__ */ __name((fromObject, path) => { - let cursor = fromObject; - const pathComponents = path.split("."); - for (const step of pathComponents) { - if (!cursor || typeof cursor !== "object") { - return void 0; - } - cursor = cursor[step]; + if (output[_SI] != null) { + contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); + } + return contents; +}, "de_AssumeRoleResponse"); +var de_AssumeRoleWithWebIdentityResponse = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_C] != null) { + contents[_C] = de_Credentials(output[_C], context); + } + if (output[_SFWIT] != null) { + contents[_SFWIT] = (0, import_smithy_client3.expectString)(output[_SFWIT]); + } + if (output[_ARU] != null) { + contents[_ARU] = de_AssumedRoleUser(output[_ARU], context); + } + if (output[_PPS] != null) { + contents[_PPS] = (0, import_smithy_client3.strictParseInt32)(output[_PPS]); + } + if (output[_Pr] != null) { + contents[_Pr] = (0, import_smithy_client3.expectString)(output[_Pr]); + } + if (output[_Au] != null) { + contents[_Au] = (0, import_smithy_client3.expectString)(output[_Au]); + } + if (output[_SI] != null) { + contents[_SI] = (0, import_smithy_client3.expectString)(output[_SI]); + } + return contents; +}, "de_AssumeRoleWithWebIdentityResponse"); +var de_Credentials = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_AKI] != null) { + contents[_AKI] = (0, import_smithy_client3.expectString)(output[_AKI]); + } + if (output[_SAK] != null) { + contents[_SAK] = (0, import_smithy_client3.expectString)(output[_SAK]); + } + if (output[_ST] != null) { + contents[_ST] = (0, import_smithy_client3.expectString)(output[_ST]); + } + if (output[_E] != null) { + contents[_E] = (0, import_smithy_client3.expectNonNull)((0, import_smithy_client3.parseRfc3339DateTimeWithOffset)(output[_E])); + } + return contents; +}, "de_Credentials"); +var de_ExpiredTokenException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_ExpiredTokenException"); +var de_IDPCommunicationErrorException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_IDPCommunicationErrorException"); +var de_IDPRejectedClaimException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); + } + return contents; +}, "de_IDPRejectedClaimException"); +var de_InvalidIdentityTokenException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); } - return cursor; -}, "get"); - -// src/protocols/requestBuilder.ts -var import_protocols = __nccwpck_require__(2241); - -// src/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__smithy_context) { - context.__smithy_context = { - features: {} - }; - } else if (!context.__smithy_context.features) { - context.__smithy_context.features = {}; + return contents; +}, "de_InvalidIdentityTokenException"); +var de_MalformedPolicyDocumentException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); } - context.__smithy_context.features[feature] = value; -} -__name(setFeature, "setFeature"); - -// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts -var DefaultIdentityProviderConfig = class { - /** - * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. - * - * @param config scheme IDs and identity providers to configure - */ - constructor(config) { - this.authSchemes = /* @__PURE__ */ new Map(); - for (const [key, value] of Object.entries(config)) { - if (value !== void 0) { - this.authSchemes.set(key, value); - } - } + return contents; +}, "de_MalformedPolicyDocumentException"); +var de_PackedPolicyTooLargeException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); } - static { - __name(this, "DefaultIdentityProviderConfig"); + return contents; +}, "de_PackedPolicyTooLargeException"); +var de_RegionDisabledException = /* @__PURE__ */ __name((output, context) => { + const contents = {}; + if (output[_m] != null) { + contents[_m] = (0, import_smithy_client3.expectString)(output[_m]); } - getIdentityProvider(schemeId) { - return this.authSchemes.get(schemeId); + return contents; +}, "de_RegionDisabledException"); +var deserializeMetadata = /* @__PURE__ */ __name((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"] +}), "deserializeMetadata"); +var throwDefaultError = (0, import_smithy_client3.withBaseException)(STSServiceException); +var buildHttpRpcRequest = /* @__PURE__ */ __name(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 !== void 0) { + contents.hostname = resolvedHostname; } + if (body !== void 0) { + contents.body = body; + } + return new import_protocol_http.HttpRequest(contents); +}, "buildHttpRpcRequest"); +var SHARED_HEADERS = { + "content-type": "application/x-www-form-urlencoded" }; +var _ = "2011-06-15"; +var _A = "Action"; +var _AKI = "AccessKeyId"; +var _AR = "AssumeRole"; +var _ARI = "AssumedRoleId"; +var _ARU = "AssumedRoleUser"; +var _ARWWI = "AssumeRoleWithWebIdentity"; +var _Ar = "Arn"; +var _Au = "Audience"; +var _C = "Credentials"; +var _CA = "ContextAssertion"; +var _DS = "DurationSeconds"; +var _E = "Expiration"; +var _EI = "ExternalId"; +var _K = "Key"; +var _P = "Policy"; +var _PA = "PolicyArns"; +var _PAr = "ProviderArn"; +var _PC = "ProvidedContexts"; +var _PI = "ProviderId"; +var _PPS = "PackedPolicySize"; +var _Pr = "Provider"; +var _RA = "RoleArn"; +var _RSN = "RoleSessionName"; +var _SAK = "SecretAccessKey"; +var _SFWIT = "SubjectFromWebIdentityToken"; +var _SI = "SourceIdentity"; +var _SN = "SerialNumber"; +var _ST = "SessionToken"; +var _T = "Tags"; +var _TC = "TokenCode"; +var _TTK = "TransitiveTagKeys"; +var _V = "Version"; +var _Va = "Value"; +var _WIT = "WebIdentityToken"; +var _a = "arn"; +var _m = "message"; +var buildFormUrlencodedString = /* @__PURE__ */ __name((formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client3.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client3.extendedEncodeURIComponent)(value)).join("&"), "buildFormUrlencodedString"); +var loadQueryErrorCode = /* @__PURE__ */ __name((output, data) => { + if (data.Error?.Code !== void 0) { + return data.Error.Code; + } + if (output.statusCode == 404) { + return "NotFound"; + } +}, "loadQueryErrorCode"); -// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts - - -var HttpApiKeyAuthSigner = class { +// src/submodules/sts/commands/AssumeRoleCommand.ts +var AssumeRoleCommand = class extends import_smithy_client4.Command.classBuilder().ep(import_EndpointParameters.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() { static { - __name(this, "HttpApiKeyAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - if (!signingProperties) { - throw new Error( - "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" - ); - } - if (!signingProperties.name) { - throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); - } - if (!signingProperties.in) { - throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); - } - if (!identity.apiKey) { - throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); - } - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { - clonedRequest.query[signingProperties.name] = identity.apiKey; - } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { - clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; - } else { - throw new Error( - "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" - ); - } - return clonedRequest; + __name(this, "AssumeRoleCommand"); } }; -// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts - -var HttpBearerAuthSigner = class { +// src/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.ts +var import_middleware_endpoint2 = __nccwpck_require__(2918); +var import_middleware_serde2 = __nccwpck_require__(1238); +var import_smithy_client5 = __nccwpck_require__(3570); +var import_EndpointParameters2 = __nccwpck_require__(1765); +var AssumeRoleWithWebIdentityCommand = class extends import_smithy_client5.Command.classBuilder().ep(import_EndpointParameters2.commonParams).m(function(Command, cs, config, o) { + return [ + (0, import_middleware_serde2.getSerdePlugin)(config, this.serialize, this.deserialize), + (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions()) + ]; +}).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() { static { - __name(this, "HttpBearerAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (!identity.token) { - throw new Error("request could not be signed with `token` since the `token` is not defined"); - } - clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; - return clonedRequest; + __name(this, "AssumeRoleWithWebIdentityCommand"); } }; -// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts -var NoAuthSigner = class { +// src/submodules/sts/STS.ts +var import_STSClient = __nccwpck_require__(8974); +var commands = { + AssumeRoleCommand, + AssumeRoleWithWebIdentityCommand +}; +var STS = class extends import_STSClient.STSClient { static { - __name(this, "NoAuthSigner"); - } - async sign(httpRequest, identity, signingProperties) { - return httpRequest; + __name(this, "STS"); } }; +(0, import_smithy_client6.createAggregatedClient)(commands, STS); -// src/util-identity-and-auth/memoizeIdentityProvider.ts -var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); -var EXPIRATION_MS = 3e5; -var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); -var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); -var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - if (provider === void 0) { - return void 0; +// src/submodules/sts/index.ts +var import_EndpointParameters3 = __nccwpck_require__(1765); + +// src/submodules/sts/defaultStsRoleAssumers.ts +var import_client = __nccwpck_require__(2825); +var ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; +var getAccountIdFromAssumedRoleUser = /* @__PURE__ */ __name((assumedRoleUser) => { + if (typeof assumedRoleUser?.Arn === "string") { + const arnComponents = assumedRoleUser.Arn.split(":"); + if (arnComponents.length > 4 && arnComponents[4] !== "") { + return arnComponents[4]; + } } - const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async (options) => { - if (!pending) { - pending = normalizedProvider(options); + return void 0; +}, "getAccountIdFromAssumedRoleUser"); +var resolveRegion = /* @__PURE__ */ __name(async (_region, _parentRegion, credentialProviderLogger) => { + const region = typeof _region === "function" ? await _region() : _region; + const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; + credentialProviderLogger?.debug?.( + "@aws-sdk/client-sts::resolveRegion", + "accepting first of:", + `${region} (provider)`, + `${parentRegion} (parent client)`, + `${ASSUME_ROLE_DEFAULT_REGION} (STS default)` + ); + return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION; +}, "resolveRegion"); +var getDefaultRoleAssumer = /* @__PURE__ */ __name((stsOptions, STSClient3) => { + let stsClient; + let closureSourceCreds; + return async (sourceCreds, params) => { + closureSourceCreds = sourceCreds; + if (!stsClient) { + const { + logger = stsOptions?.parentClientConfig?.logger, + region, + requestHandler = stsOptions?.parentClientConfig?.requestHandler, + credentialProviderLogger + } = stsOptions; + const resolvedRegion = await resolveRegion( + region, + stsOptions?.parentClientConfig?.region, + credentialProviderLogger + ); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient3({ + profile: stsOptions?.parentClientConfig?.profile, + // A hack to make sts client uses the credential in current closure. + credentialDefaultProvider: /* @__PURE__ */ __name(() => async () => closureSourceCreds, "credentialDefaultProvider"), + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, + logger + }); } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; + const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleCommand(params)); + if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); - } - return resolved; + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); + const credentials = { + accessKeyId: Credentials2.AccessKeyId, + secretAccessKey: Credentials2.SecretAccessKey, + sessionToken: Credentials2.SessionToken, + expiration: Credentials2.Expiration, + // TODO(credentialScope): access normally when shape is updated. + ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, + ...accountId && { accountId } }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); - } - if (isConstant) { - return resolved; + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); + return credentials; + }; +}, "getDefaultRoleAssumer"); +var getDefaultRoleAssumerWithWebIdentity = /* @__PURE__ */ __name((stsOptions, STSClient3) => { + let stsClient; + return async (params) => { + if (!stsClient) { + const { + logger = stsOptions?.parentClientConfig?.logger, + region, + requestHandler = stsOptions?.parentClientConfig?.requestHandler, + credentialProviderLogger + } = stsOptions; + const resolvedRegion = await resolveRegion( + region, + stsOptions?.parentClientConfig?.region, + credentialProviderLogger + ); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient3({ + profile: stsOptions?.parentClientConfig?.profile, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, + logger + }); } - if (!requiresRefresh(resolved)) { - isConstant = true; - return resolved; + const { Credentials: Credentials2, AssumedRoleUser: AssumedRoleUser2 } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); + if (!Credentials2 || !Credentials2.AccessKeyId || !Credentials2.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); } - if (isExpired(resolved)) { - await coalesceProvider(options); - return resolved; + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser2); + const credentials = { + accessKeyId: Credentials2.AccessKeyId, + secretAccessKey: Credentials2.SecretAccessKey, + sessionToken: Credentials2.SessionToken, + expiration: Credentials2.Expiration, + // TODO(credentialScope): access normally when shape is updated. + ...Credentials2.CredentialScope && { credentialScope: Credentials2.CredentialScope }, + ...accountId && { accountId } + }; + if (accountId) { + (0, import_client.setCredentialFeature)(credentials, "RESOLVED_ACCOUNT_ID", "T"); } - return resolved; + (0, import_client.setCredentialFeature)(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); + return credentials; }; -}, "memoizeIdentityProvider"); +}, "getDefaultRoleAssumerWithWebIdentity"); +var isH2 = /* @__PURE__ */ __name((requestHandler) => { + return requestHandler?.metadata?.handlerProtocol === "h2"; +}, "isH2"); + +// src/submodules/sts/defaultRoleAssumers.ts +var import_STSClient2 = __nccwpck_require__(8974); +var getCustomizableStsClientCtor = /* @__PURE__ */ __name((baseCtor, customizations) => { + if (!customizations) return baseCtor; + else + return class CustomizableSTSClient extends baseCtor { + static { + __name(this, "CustomizableSTSClient"); + } + constructor(config) { + super(config); + for (const customization of customizations) { + this.middlewareStack.use(customization); + } + } + }; +}, "getCustomizableStsClientCtor"); +var getDefaultRoleAssumer2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumer"); +var getDefaultRoleAssumerWithWebIdentity2 = /* @__PURE__ */ __name((stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(import_STSClient2.STSClient, stsPlugins)), "getDefaultRoleAssumerWithWebIdentity"); +var decorateDefaultCredentialProvider = /* @__PURE__ */ __name((provider) => (input) => provider({ + roleAssumer: getDefaultRoleAssumer2(input), + roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input), + ...input +}), "decorateDefaultCredentialProvider"); // Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 1798: +/***/ ((__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__(8842)); +const core_1 = __nccwpck_require__(9963); +const util_user_agent_node_1 = __nccwpck_require__(8095); +const config_resolver_1 = __nccwpck_require__(3098); +const core_2 = __nccwpck_require__(5829); +const hash_node_1 = __nccwpck_require__(3081); +const middleware_retry_1 = __nccwpck_require__(6039); +const node_config_provider_1 = __nccwpck_require__(3461); +const node_http_handler_1 = __nccwpck_require__(258); +const util_body_length_node_1 = __nccwpck_require__(8075); +const util_retry_1 = __nccwpck_require__(4902); +const runtimeConfig_shared_1 = __nccwpck_require__(5238); +const smithy_client_1 = __nccwpck_require__(3570); +const util_defaults_mode_node_1 = __nccwpck_require__(2429); +const smithy_client_2 = __nccwpck_require__(3570); +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); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger, + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? + (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || + (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? + (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config?.requestHandler ?? 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, + }, config), + 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, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig), + }; +}; +exports.getRuntimeConfig = getRuntimeConfig; + + +/***/ }), + +/***/ 5238: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRuntimeConfig = void 0; +const core_1 = __nccwpck_require__(9963); +const core_2 = __nccwpck_require__(5829); +const smithy_client_1 = __nccwpck_require__(3570); +const url_parser_1 = __nccwpck_require__(4681); +const util_base64_1 = __nccwpck_require__(5600); +const util_utf8_1 = __nccwpck_require__(1895); +const httpAuthSchemeProvider_1 = __nccwpck_require__(8013); +const endpointResolver_1 = __nccwpck_require__(7561); +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 ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new core_1.AwsSdkSigV4Signer(), + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new core_2.NoAuthSigner(), + }, + ], + 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; -0 && (0); +/***/ }), + +/***/ 669: +/***/ ((__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__(8156); +const protocol_http_1 = __nccwpck_require__(4418); +const smithy_client_1 = __nccwpck_require__(3570); +const httpAuthExtensionConfiguration_1 = __nccwpck_require__(4935); +const resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); +}; +exports.resolveRuntimeExtensions = resolveRuntimeExtensions; /***/ }), -/***/ 2241: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 8156: +/***/ ((module) => { + +"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -57566,819 +42921,492 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/index.ts -var protocols_exports = {}; -__export(protocols_exports, { - FromStringShapeDeserializer: () => FromStringShapeDeserializer, - HttpBindingProtocol: () => HttpBindingProtocol, - HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, - HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, - RequestBuilder: () => RequestBuilder, - RpcProtocol: () => RpcProtocol, - ToStringShapeSerializer: () => ToStringShapeSerializer, - collectBody: () => collectBody, - determineTimestampFormat: () => determineTimestampFormat, - extendedEncodeURIComponent: () => extendedEncodeURIComponent, - requestBuilder: () => requestBuilder, - resolvedPath: () => resolvedPath +// src/index.ts +var index_exports = {}; +__export(index_exports, { + NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, + NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, + REGION_ENV_NAME: () => REGION_ENV_NAME, + REGION_INI_NAME: () => REGION_INI_NAME, + getAwsRegionExtensionConfiguration: () => getAwsRegionExtensionConfiguration, + resolveAwsRegionExtensionConfiguration: () => resolveAwsRegionExtensionConfiguration, + resolveRegionConfig: () => resolveRegionConfig }); -module.exports = __toCommonJS(protocols_exports); +module.exports = __toCommonJS(index_exports); -// src/submodules/protocols/collect-stream-body.ts -var import_util_stream = __nccwpck_require__(6607); -var collectBody = async (streamBody = new Uint8Array(), context) => { - if (streamBody instanceof Uint8Array) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); - } - if (!streamBody) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); - } - const fromContext = context.streamCollector(streamBody); - return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); -}; +// src/extensions/index.ts +var getAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setRegion(region) { + runtimeConfig.region = region; + }, + region() { + return runtimeConfig.region; + } + }; +}, "getAwsRegionExtensionConfiguration"); +var resolveAwsRegionExtensionConfiguration = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => { + return { + region: awsRegionExtensionConfiguration.region() + }; +}, "resolveAwsRegionExtensionConfiguration"); -// src/submodules/protocols/extended-encode-uri-component.ts -function extendedEncodeURIComponent(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} +// src/regionConfig/config.ts +var REGION_ENV_NAME = "AWS_REGION"; +var REGION_INI_NAME = "region"; +var NODE_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: /* @__PURE__ */ __name((env) => env[REGION_ENV_NAME], "environmentVariableSelector"), + configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"), + default: /* @__PURE__ */ __name(() => { + throw new Error("Region is missing"); + }, "default") +}; +var NODE_REGION_CONFIG_FILE_OPTIONS = { + preferredFile: "credentials" +}; -// src/submodules/protocols/HttpBindingProtocol.ts -var import_schema2 = __nccwpck_require__(9826); -var import_serde = __nccwpck_require__(7669); -var import_protocol_http2 = __nccwpck_require__(4418); -var import_util_stream2 = __nccwpck_require__(6607); +// src/regionConfig/isFipsRegion.ts +var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); -// src/submodules/protocols/HttpProtocol.ts -var import_schema = __nccwpck_require__(9826); -var import_protocol_http = __nccwpck_require__(4418); -var HttpProtocol = class { - constructor(options) { - this.options = options; - } - getRequestType() { - return import_protocol_http.HttpRequest; - } - getResponseType() { - return import_protocol_http.HttpResponse; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - if (this.getPayloadCodec()) { - this.getPayloadCodec().setSerdeContext(serdeContext); - } - } - updateServiceEndpoint(request, endpoint) { - if ("url" in endpoint) { - request.protocol = endpoint.url.protocol; - request.hostname = endpoint.url.hostname; - request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; - request.path = endpoint.url.pathname; - request.fragment = endpoint.url.hash || void 0; - request.username = endpoint.url.username || void 0; - request.password = endpoint.url.password || void 0; - for (const [k, v] of endpoint.url.searchParams.entries()) { - if (!request.query) { - request.query = {}; - } - request.query[k] = v; - } - return request; - } else { - request.protocol = endpoint.protocol; - request.hostname = endpoint.hostname; - request.port = endpoint.port ? Number(endpoint.port) : void 0; - request.path = endpoint.path; - request.query = { - ...endpoint.query - }; - return request; - } - } - setHostPrefix(request, operationSchema, input) { - const operationNs = import_schema.NormalizedSchema.of(operationSchema); - const inputNs = import_schema.NormalizedSchema.of(operationSchema.input); - if (operationNs.getMergedTraits().endpoint) { - let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; - if (typeof hostPrefix === "string") { - const hostLabelInputs = [...inputNs.structIterator()].filter( - ([, member]) => member.getMergedTraits().hostLabel - ); - for (const [name] of hostLabelInputs) { - const replacement = input[name]; - if (typeof replacement !== "string") { - throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); - } - hostPrefix = hostPrefix.replace(`{${name}}`, replacement); - } - request.hostname = hostPrefix + request.hostname; - } - } - } - deserializeMetadata(output) { - return { - 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"] - }; - } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - return []; - } -}; +// src/regionConfig/getRealRegion.ts +var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); -// src/submodules/protocols/HttpBindingProtocol.ts -var HttpBindingProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, _input, context) { - const input = { - ..._input ?? {} - }; - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = import_schema2.NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); - let hasNonHttpBindingMember = false; - let payload; - const request = new import_protocol_http2.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - const opTraits = import_schema2.NormalizedSchema.translateTraits(operationSchema.traits); - if (opTraits.http) { - request.method = opTraits.http[0]; - const [path, search] = opTraits.http[1].split("?"); - if (request.path == "/") { - request.path = path; - } else { - request.path += path; - } - const traitSearchParams = new URLSearchParams(search ?? ""); - Object.assign(query, Object.fromEntries(traitSearchParams)); - } - } - for (const [memberName, memberNs] of ns.structIterator()) { - const memberTraits = memberNs.getMergedTraits() ?? {}; - const inputMemberValue = input[memberName]; - if (inputMemberValue == null) { - continue; - } - if (memberTraits.httpPayload) { - const isStreaming = memberNs.isStreaming(); - if (isStreaming) { - const isEventStream = memberNs.isStructSchema(); - if (isEventStream) { - throw new Error("serialization of event streams is not yet implemented"); - } else { - payload = inputMemberValue; - } - } else { - serializer.write(memberNs, inputMemberValue); - payload = serializer.flush(); - } - delete input[memberName]; - } else if (memberTraits.httpLabel) { - serializer.write(memberNs, inputMemberValue); - const replacement = serializer.flush(); - if (request.path.includes(`{${memberName}+}`)) { - request.path = request.path.replace( - `{${memberName}+}`, - replacement.split("/").map(extendedEncodeURIComponent).join("/") - ); - } else if (request.path.includes(`{${memberName}}`)) { - request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); - } - delete input[memberName]; - } else if (memberTraits.httpHeader) { - serializer.write(memberNs, inputMemberValue); - headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); - delete input[memberName]; - } else if (typeof memberTraits.httpPrefixHeaders === "string") { - for (const [key, val] of Object.entries(inputMemberValue)) { - const amalgam = memberTraits.httpPrefixHeaders + key; - serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); - headers[amalgam.toLowerCase()] = serializer.flush(); - } - delete input[memberName]; - } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { - this.serializeQuery(memberNs, inputMemberValue, query); - delete input[memberName]; - } else { - hasNonHttpBindingMember = true; - } - } - if (hasNonHttpBindingMember && input) { - serializer.write(schema, input); - payload = serializer.flush(); - } - request.headers = headers; - request.query = query; - request.body = payload; - return request; - } - serializeQuery(ns, data, query) { - const serializer = this.serializer; - const traits = ns.getMergedTraits(); - if (traits.httpQueryParams) { - for (const [key, val] of Object.entries(data)) { - if (!(key in query)) { - this.serializeQuery( - import_schema2.NormalizedSchema.of([ - ns.getValueSchema(), - { - // We pass on the traits to the sub-schema - // because we are still in the process of serializing the map itself. - ...traits, - httpQuery: key, - httpQueryParams: void 0 - } - ]), - val, - query - ); - } - } - return; - } - if (ns.isListSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - const buffer = []; - for (const item of data) { - serializer.write([ns.getValueSchema(), traits], item); - const serializable = serializer.flush(); - if (sparse || serializable !== void 0) { - buffer.push(serializable); - } - } - query[traits.httpQuery] = buffer; - } else { - serializer.write([ns, traits], data); - query[traits.httpQuery] = serializer.flush(); - } - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema2.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema2.SCHEMA.DOCUMENT, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); - if (nonHttpBindingMembers.length) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - const dataFromBody = await deserializer.read(ns, bytes); - for (const member of nonHttpBindingMembers) { - dataObject[member] = dataFromBody[member]; - } - } - } - const output = { - $metadata: this.deserializeMetadata(response), - ...dataObject - }; - return output; +// src/regionConfig/resolveRegionConfig.ts +var resolveRegionConfig = /* @__PURE__ */ __name((input) => { + const { region, useFipsEndpoint } = input; + if (!region) { + throw new Error("Region is missing"); } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - let dataObject; - if (arg4 instanceof Set) { - dataObject = arg5; - } else { - dataObject = arg4; - } - const deserializer = this.deserializer; - const ns = import_schema2.NormalizedSchema.of(schema); - const nonHttpBindingMembers = []; - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMemberTraits(); - if (memberTraits.httpPayload) { - const isStreaming = memberSchema.isStreaming(); - if (isStreaming) { - const isEventStream = memberSchema.isStructSchema(); - if (isEventStream) { - const context2 = this.serdeContext; - if (!context2.eventStreamMarshaller) { - throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); - } - const memberSchemas = memberSchema.getMemberSchemas(); - dataObject[memberName] = context2.eventStreamMarshaller.deserialize(response.body, async (event) => { - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - if (unionMember in memberSchemas) { - const eventStreamSchema = memberSchemas[unionMember]; - return { - [unionMember]: await deserializer.read(eventStreamSchema, event[unionMember].body) - }; - } else { - return { - $unknown: event - }; - } - }); - } else { - dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); - } - } else if (response.body) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - dataObject[memberName] = await deserializer.read(memberSchema, bytes); - } - } - } else if (memberTraits.httpHeader) { - const key = String(memberTraits.httpHeader).toLowerCase(); - const value = response.headers[key]; - if (null != value) { - if (memberSchema.isListSchema()) { - const headerListValueSchema = memberSchema.getValueSchema(); - let sections; - if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT) { - sections = (0, import_serde.splitEvery)(value, ",", 2); - } else { - sections = (0, import_serde.splitHeader)(value); - } - const list = []; - for (const section of sections) { - list.push(await deserializer.read([headerListValueSchema, { httpHeader: key }], section.trim())); - } - dataObject[memberName] = list; - } else { - dataObject[memberName] = await deserializer.read(memberSchema, value); - } - } - } else if (memberTraits.httpPrefixHeaders !== void 0) { - dataObject[memberName] = {}; - for (const [header, value] of Object.entries(response.headers)) { - if (header.startsWith(memberTraits.httpPrefixHeaders)) { - dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read( - [memberSchema.getValueSchema(), { httpHeader: header }], - value - ); - } - } - } else if (memberTraits.httpResponseCode) { - dataObject[memberName] = response.statusCode; - } else { - nonHttpBindingMembers.push(memberName); + return Object.assign(input, { + region: /* @__PURE__ */ __name(async () => { + if (typeof region === "string") { + return getRealRegion(region); } - } - return nonHttpBindingMembers; - } -}; - -// src/submodules/protocols/RpcProtocol.ts -var import_schema3 = __nccwpck_require__(9826); -var import_protocol_http3 = __nccwpck_require__(4418); -var RpcProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, input, context) { - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = import_schema3.NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); - let payload; - const request = new import_protocol_http3.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "/", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - } - const _input = { - ...input - }; - if (input) { - serializer.write(schema, _input); - payload = serializer.flush(); - } - request.headers = headers; - request.query = query; - request.body = payload; - request.method = "POST"; - return request; - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = import_schema3.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes2 = await collectBody(response.body, context); - if (bytes2.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(import_schema3.SCHEMA.DOCUMENT, bytes2)); + const providedRegion = await region(); + return getRealRegion(providedRegion); + }, "region"), + useFipsEndpoint: /* @__PURE__ */ __name(async () => { + const providedRegion = typeof region === "string" ? region : await region(); + if (isFipsRegion(providedRegion)) { + return true; } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes)); - } - const output = { - $metadata: this.deserializeMetadata(response), - ...dataObject - }; - return output; + return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); + }, "useFipsEndpoint") + }); +}, "resolveRegionConfig"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 1856: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/requestBuilder.ts -var import_protocol_http4 = __nccwpck_require__(4418); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + SignatureV4MultiRegion: () => SignatureV4MultiRegion, + signatureV4CrtContainer: () => signatureV4CrtContainer +}); +module.exports = __toCommonJS(index_exports); -// src/submodules/protocols/resolve-path.ts -var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { - if (input != null && input[memberName] !== void 0) { - const labelValue = labelValueProvider(); - if (labelValue.length <= 0) { - throw new Error("Empty value provided for input HTTP label: " + memberName + "."); - } - resolvedPath2 = resolvedPath2.replace( - uriLabel, - isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) - ); - } else { - throw new Error("No value provided for input HTTP label: " + memberName + "."); - } - return resolvedPath2; +// src/SignatureV4MultiRegion.ts +var import_middleware_sdk_s3 = __nccwpck_require__(1139); +var import_signature_v4 = __nccwpck_require__(1528); + +// src/signature-v4-crt-container.ts +var signatureV4CrtContainer = { + CrtSignerV4: null }; -// src/submodules/protocols/requestBuilder.ts -function requestBuilder(input, context) { - return new RequestBuilder(input, context); -} -var RequestBuilder = class { - constructor(input, context) { - this.input = input; - this.context = context; - this.query = {}; - this.method = ""; - this.headers = {}; - this.path = ""; - this.body = null; - this.hostname = ""; - this.resolvePathStack = []; +// src/SignatureV4MultiRegion.ts +var SignatureV4MultiRegion = class { + static { + __name(this, "SignatureV4MultiRegion"); } - async build() { - const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); - this.path = basePath; - for (const resolvePath of this.resolvePathStack) { - resolvePath(this.path); + sigv4aSigner; + sigv4Signer; + signerOptions; + static sigv4aDependency() { + if (typeof signatureV4CrtContainer.CrtSignerV4 === "function") { + return "crt"; + } else if (typeof import_signature_v4.signatureV4aContainer.SignatureV4a === "function") { + return "js"; } - return new import_protocol_http4.HttpRequest({ - protocol, - hostname: this.hostname || hostname, - port, - method: this.method, - path: this.path, - query: this.query, - body: this.body, - headers: this.headers - }); - } - /** - * Brevity setter for "hostname". - */ - hn(hostname) { - this.hostname = hostname; - return this; - } - /** - * Brevity initial builder for "basepath". - */ - bp(uriLabel) { - this.resolvePathStack.push((basePath) => { - this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; - }); - return this; - } - /** - * Brevity incremental builder for "path". - */ - p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { - this.resolvePathStack.push((path) => { - this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); - }); - return this; + return "none"; } - /** - * Brevity setter for "headers". - */ - h(headers) { - this.headers = headers; - return this; + constructor(options) { + this.sigv4Signer = new import_middleware_sdk_s3.SignatureV4S3Express(options); + this.signerOptions = options; } - /** - * Brevity setter for "query". - */ - q(query) { - this.query = query; - return this; + async sign(requestToSign, options = {}) { + if (options.signingRegion === "*") { + return this.getSigv4aSigner().sign(requestToSign, options); + } + return this.sigv4Signer.sign(requestToSign, options); } /** - * Brevity setter for "body". + * Sign with alternate credentials to the ones provided in the constructor. + * Note: This is only supported for SigV4a when using the CRT implementation. */ - b(body) { - this.body = body; - return this; + async signWithCredentials(requestToSign, credentials, options = {}) { + if (options.signingRegion === "*") { + const signer = this.getSigv4aSigner(); + const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; + if (CrtSignerV4 && signer instanceof CrtSignerV4) { + return signer.signWithCredentials(requestToSign, credentials, options); + } else { + throw new Error( + `signWithCredentials with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt` + ); + } + } + return this.sigv4Signer.signWithCredentials(requestToSign, credentials, options); } /** - * Brevity setter for "method". + * Presign a request. + * Note: This is only supported for SigV4a when using the CRT implementation. */ - m(method) { - this.method = method; - return this; - } -}; - -// src/submodules/protocols/serde/FromStringShapeDeserializer.ts -var import_schema5 = __nccwpck_require__(9826); -var import_serde2 = __nccwpck_require__(7669); -var import_util_base64 = __nccwpck_require__(5600); -var import_util_utf8 = __nccwpck_require__(1895); - -// src/submodules/protocols/serde/determineTimestampFormat.ts -var import_schema4 = __nccwpck_require__(9826); -function determineTimestampFormat(ns, settings) { - if (settings.timestampFormat.useTrait) { - if (ns.isTimestampSchema() && (ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { - return ns.getSchema(); + async presign(originalRequest, options = {}) { + if (options.signingRegion === "*") { + const signer = this.getSigv4aSigner(); + const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; + if (CrtSignerV4 && signer instanceof CrtSignerV4) { + return signer.presign(originalRequest, options); + } else { + throw new Error( + `presign with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt` + ); + } } + return this.sigv4Signer.presign(originalRequest, options); } - const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); - const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? import_schema4.SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; - return bindingFormat ?? settings.timestampFormat.default; -} - -// src/submodules/protocols/serde/FromStringShapeDeserializer.ts -var FromStringShapeDeserializer = class { - constructor(settings) { - this.settings = settings; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } - read(_schema, data) { - const ns = import_schema5.NormalizedSchema.of(_schema); - if (ns.isListSchema()) { - return (0, import_serde2.splitHeader)(data).map((item) => this.read(ns.getValueSchema(), item)); - } - if (ns.isBlobSchema()) { - return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data); - } - if (ns.isTimestampSchema()) { - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case import_schema5.SCHEMA.TIMESTAMP_DATE_TIME: - return (0, import_serde2.parseRfc3339DateTimeWithOffset)(data); - case import_schema5.SCHEMA.TIMESTAMP_HTTP_DATE: - return (0, import_serde2.parseRfc7231DateTime)(data); - case import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - return (0, import_serde2.parseEpochTimestamp)(data); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", data); - return new Date(data); - } + async presignWithCredentials(originalRequest, credentials, options = {}) { + if (options.signingRegion === "*") { + throw new Error("Method presignWithCredentials is not supported for [signingRegion=*]."); } - if (ns.isStringSchema()) { - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = data; - if (mediaType) { - if (ns.getMergedTraits().httpHeader) { - intermediateValue = this.base64ToUtf8(intermediateValue); + return this.sigv4Signer.presignWithCredentials(originalRequest, credentials, options); + } + getSigv4aSigner() { + if (!this.sigv4aSigner) { + const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; + const JsSigV4aSigner = import_signature_v4.signatureV4aContainer.SignatureV4a; + if (this.signerOptions.runtime === "node") { + if (!CrtSignerV4 && !JsSigV4aSigner) { + throw new Error( + "Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt" + ); } - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = import_serde2.LazyJsonString.from(intermediateValue); + if (CrtSignerV4 && typeof CrtSignerV4 === "function") { + this.sigv4aSigner = new CrtSignerV4({ + ...this.signerOptions, + signingAlgorithm: 1 + }); + } else if (JsSigV4aSigner && typeof JsSigV4aSigner === "function") { + this.sigv4aSigner = new JsSigV4aSigner({ + ...this.signerOptions + }); + } else { + throw new Error( + "Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt" + ); } - return intermediateValue; + } else { + if (!JsSigV4aSigner || typeof JsSigV4aSigner !== "function") { + throw new Error( + "JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a" + ); + } + this.sigv4aSigner = new JsSigV4aSigner({ + ...this.signerOptions + }); } } - switch (true) { - case ns.isNumericSchema(): - return Number(data); - case ns.isBigIntegerSchema(): - return BigInt(data); - case ns.isBigDecimalSchema(): - return new import_serde2.NumericValue(data, "bigDecimal"); - case ns.isBooleanSchema(): - return String(data).toLowerCase() === "true"; - } - return data; - } - base64ToUtf8(base64String) { - return (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); + return this.sigv4aSigner; } }; +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/protocols/serde/HttpInterceptingShapeDeserializer.ts -var import_schema6 = __nccwpck_require__(9826); -var import_util_utf82 = __nccwpck_require__(1895); -var HttpInterceptingShapeDeserializer = class { - constructor(codecDeserializer, codecSettings) { - this.codecDeserializer = codecDeserializer; - this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); - } - setSerdeContext(serdeContext) { - this.stringDeserializer.setSerdeContext(serdeContext); - this.codecDeserializer.setSerdeContext(serdeContext); - this.serdeContext = serdeContext; - } - read(schema, data) { - const ns = import_schema6.NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); - const toString = this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8; - if (traits.httpHeader || traits.httpResponseCode) { - return this.stringDeserializer.read(ns, toString(data)); - } - if (traits.httpPayload) { - if (ns.isBlobSchema()) { - const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf82.fromUtf8; - if (typeof data === "string") { - return toBytes(data); - } - return data; - } else if (ns.isStringSchema()) { - if ("byteLength" in data) { - return toString(data); - } - return data; - } - } - return this.codecDeserializer.read(ns, data); +0 && (0); + + + +/***/ }), + +/***/ 2843: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts -var import_schema8 = __nccwpck_require__(9826); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + fromEnvSigningName: () => fromEnvSigningName, + fromSso: () => fromSso, + fromStatic: () => fromStatic, + nodeProvider: () => nodeProvider +}); +module.exports = __toCommonJS(index_exports); -// src/submodules/protocols/serde/ToStringShapeSerializer.ts -var import_schema7 = __nccwpck_require__(9826); -var import_serde3 = __nccwpck_require__(7669); -var import_util_base642 = __nccwpck_require__(5600); -var ToStringShapeSerializer = class { - constructor(settings) { - this.settings = settings; - this.stringBuffer = ""; - this.serdeContext = void 0; +// src/fromEnvSigningName.ts +var import_client = __nccwpck_require__(2825); +var import_httpAuthSchemes = __nccwpck_require__(7862); +var import_property_provider = __nccwpck_require__(9721); +var fromEnvSigningName = /* @__PURE__ */ __name(({ logger, signingName } = {}) => async () => { + logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); + if (!signingName) { + throw new import_property_provider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; + const bearerTokenKey = (0, import_httpAuthSchemes.getBearerTokenEnvKey)(signingName); + if (!(bearerTokenKey in process.env)) { + throw new import_property_provider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); } - write(schema, value) { - const ns = import_schema7.NormalizedSchema.of(schema); - switch (typeof value) { - case "object": - if (value === null) { - this.stringBuffer = "null"; - return; - } - if (ns.isTimestampSchema()) { - if (!(value instanceof Date)) { - throw new Error( - `@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}` - ); - } - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case import_schema7.SCHEMA.TIMESTAMP_DATE_TIME: - this.stringBuffer = value.toISOString().replace(".000Z", "Z"); - break; - case import_schema7.SCHEMA.TIMESTAMP_HTTP_DATE: - this.stringBuffer = (0, import_serde3.dateToUtcString)(value); - break; - case import_schema7.SCHEMA.TIMESTAMP_EPOCH_SECONDS: - this.stringBuffer = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - this.stringBuffer = String(value.getTime() / 1e3); - } - return; - } - if (ns.isBlobSchema() && "byteLength" in value) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); - return; - } - if (ns.isListSchema() && Array.isArray(value)) { - let buffer = ""; - for (const item of value) { - this.write([ns.getValueSchema(), ns.getMergedTraits()], item); - const headerItem = this.flush(); - const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : (0, import_serde3.quoteHeader)(headerItem); - if (buffer !== "") { - buffer += ", "; - } - buffer += serialized; - } - this.stringBuffer = buffer; - return; - } - this.stringBuffer = JSON.stringify(value, null, 2); - break; - case "string": - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = value; - if (mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = import_serde3.LazyJsonString.from(intermediateValue); - } - if (ns.getMergedTraits().httpHeader) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); - return; - } - } - this.stringBuffer = value; - break; - default: - this.stringBuffer = String(value); - } + const token = { token: process.env[bearerTokenKey] }; + (0, import_client.setTokenFeature)(token, "BEARER_SERVICE_ENV_VARS", "3"); + return token; +}, "fromEnvSigningName"); + +// src/fromSso.ts + + + +// src/constants.ts +var EXPIRE_WINDOW_MS = 5 * 60 * 1e3; +var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; + +// src/getSsoOidcClient.ts +var getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion, init = {}) => { + const { SSOOIDCClient } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7334))); + const ssoOidcClient = new SSOOIDCClient( + Object.assign({}, init.clientConfig ?? {}, { + region: ssoRegion ?? init.clientConfig?.region, + logger: init.clientConfig?.logger ?? init.parentClientConfig?.logger + }) + ); + return ssoOidcClient; +}, "getSsoOidcClient"); + +// src/getNewSsoOidcToken.ts +var getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion, init = {}) => { + const { CreateTokenCommand } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7334))); + const ssoOidcClient = await getSsoOidcClient(ssoRegion, init); + return ssoOidcClient.send( + new CreateTokenCommand({ + clientId: ssoToken.clientId, + clientSecret: ssoToken.clientSecret, + refreshToken: ssoToken.refreshToken, + grantType: "refresh_token" + }) + ); +}, "getNewSsoOidcToken"); + +// src/validateTokenExpiry.ts + +var validateTokenExpiry = /* @__PURE__ */ __name((token) => { + if (token.expiration && token.expiration.getTime() < Date.now()) { + throw new import_property_provider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); } - flush() { - const buffer = this.stringBuffer; - this.stringBuffer = ""; - return buffer; +}, "validateTokenExpiry"); + +// src/validateTokenKey.ts + +var validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => { + if (typeof value === "undefined") { + throw new import_property_provider.TokenProviderError( + `Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, + false + ); } -}; +}, "validateTokenKey"); -// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts -var HttpInterceptingShapeSerializer = class { - constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { - this.codecSerializer = codecSerializer; - this.stringSerializer = stringSerializer; +// src/writeSSOTokenToFile.ts +var import_shared_ini_file_loader = __nccwpck_require__(3507); +var import_fs = __nccwpck_require__(7147); +var { writeFile } = import_fs.promises; +var writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => { + const tokenFilepath = (0, import_shared_ini_file_loader.getSSOTokenFilepath)(id); + const tokenString = JSON.stringify(ssoToken, null, 2); + return writeFile(tokenFilepath, tokenString); +}, "writeSSOTokenToFile"); + +// src/fromSso.ts +var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0); +var fromSso = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => { + const init = { + ..._init, + parentClientConfig: { + ...callerClientConfig, + ..._init.parentClientConfig + } + }; + init.logger?.debug("@aws-sdk/token-providers - fromSso"); + const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init); + const profileName = (0, import_shared_ini_file_loader.getProfileName)({ + profile: init.profile ?? callerClientConfig?.profile + }); + const profile = profiles[profileName]; + if (!profile) { + throw new import_property_provider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); + } else if (!profile["sso_session"]) { + throw new import_property_provider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); } - setSerdeContext(serdeContext) { - this.codecSerializer.setSerdeContext(serdeContext); - this.stringSerializer.setSerdeContext(serdeContext); + const ssoSessionName = profile["sso_session"]; + const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init); + const ssoSession = ssoSessions[ssoSessionName]; + if (!ssoSession) { + throw new import_property_provider.TokenProviderError( + `Sso session '${ssoSessionName}' could not be found in shared credentials file.`, + false + ); } - write(schema, value) { - const ns = import_schema8.NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); - if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { - this.stringSerializer.write(ns, value); - this.buffer = this.stringSerializer.flush(); - return; + for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { + if (!ssoSession[ssoSessionRequiredKey]) { + throw new import_property_provider.TokenProviderError( + `Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, + false + ); } - return this.codecSerializer.write(ns, value); } - flush() { - if (this.buffer !== void 0) { - const buffer = this.buffer; - this.buffer = void 0; - return buffer; + const ssoStartUrl = ssoSession["sso_start_url"]; + const ssoRegion = ssoSession["sso_region"]; + let ssoToken; + try { + ssoToken = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoSessionName); + } catch (e) { + throw new import_property_provider.TokenProviderError( + `The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, + false + ); + } + validateTokenKey("accessToken", ssoToken.accessToken); + validateTokenKey("expiresAt", ssoToken.expiresAt); + const { accessToken, expiresAt } = ssoToken; + const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; + if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { + return existingToken; + } + if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) { + validateTokenExpiry(existingToken); + return existingToken; + } + validateTokenKey("clientId", ssoToken.clientId, true); + validateTokenKey("clientSecret", ssoToken.clientSecret, true); + validateTokenKey("refreshToken", ssoToken.refreshToken, true); + try { + lastRefreshAttemptTime.setTime(Date.now()); + const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init); + validateTokenKey("accessToken", newSsoOidcToken.accessToken); + validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); + const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3); + try { + await writeSSOTokenToFile(ssoSessionName, { + ...ssoToken, + accessToken: newSsoOidcToken.accessToken, + expiresAt: newTokenExpiration.toISOString(), + refreshToken: newSsoOidcToken.refreshToken + }); + } catch (error) { } - return this.codecSerializer.flush(); + return { + token: newSsoOidcToken.accessToken, + expiration: newTokenExpiration + }; + } catch (error) { + validateTokenExpiry(existingToken); + return existingToken; } -}; +}, "fromSso"); + +// src/fromStatic.ts + +var fromStatic = /* @__PURE__ */ __name(({ token, logger }) => async () => { + logger?.debug("@aws-sdk/token-providers - fromStatic"); + if (!token || !token.token) { + throw new import_property_provider.TokenProviderError(`Please pass a valid token to fromStatic`, false); + } + return token; +}, "fromStatic"); + +// src/nodeProvider.ts + +var nodeProvider = /* @__PURE__ */ __name((init = {}) => (0, import_property_provider.memoize)( + (0, import_property_provider.chain)(fromSso(init), async () => { + throw new import_property_provider.TokenProviderError("Could not load token from any providers", false); + }), + (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5, + (token) => token.expiration !== void 0 +), "nodeProvider"); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 9826: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5487: +/***/ ((module) => { + +"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -58393,838 +43421,643 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/schema/index.ts -var schema_exports = {}; -__export(schema_exports, { - ErrorSchema: () => ErrorSchema, - ListSchema: () => ListSchema, - MapSchema: () => MapSchema, - NormalizedSchema: () => NormalizedSchema, - OperationSchema: () => OperationSchema, - SCHEMA: () => SCHEMA, - Schema: () => Schema, - SimpleSchema: () => SimpleSchema, - StructureSchema: () => StructureSchema, - TypeRegistry: () => TypeRegistry, - deref: () => deref, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - error: () => error, - getSchemaSerdePlugin: () => getSchemaSerdePlugin, - list: () => list, - map: () => map, - op: () => op, - serializerMiddlewareOption: () => serializerMiddlewareOption, - sim: () => sim, - struct: () => struct +// src/index.ts +var index_exports = {}; +__export(index_exports, { + build: () => build, + parse: () => parse, + validate: () => validate }); -module.exports = __toCommonJS(schema_exports); - -// src/submodules/schema/deref.ts -var deref = (schemaRef) => { - if (typeof schemaRef === "function") { - return schemaRef(); - } - return schemaRef; -}; - -// src/submodules/schema/middleware/schemaDeserializationMiddleware.ts -var import_protocol_http = __nccwpck_require__(4418); -var import_util_middleware = __nccwpck_require__(2390); -var schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { - const { response } = await next(args); - const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); - try { - const parsed = await config.protocol.deserializeResponse( - operationSchema, - { - ...config, - ...context - }, - response - ); - return { - response, - output: parsed - }; - } catch (error2) { - Object.defineProperty(error2, "$response", { - value: response - }); - if (!("$metadata" in error2)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error2.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); - } - } - if (typeof error2.$responseBodyText !== "undefined") { - if (error2.$response) { - error2.$response.body = error2.$responseBodyText; - } - } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error2.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) - }; - } - } catch (e) { - } - } - throw error2; - } -}; -var findHeader = (pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}; - -// src/submodules/schema/middleware/schemaSerializationMiddleware.ts -var import_util_middleware2 = __nccwpck_require__(2390); -var schemaSerializationMiddleware = (config) => (next, context) => async (args) => { - const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); - const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint; - const request = await config.protocol.serializeRequest(operationSchema, args.input, { - ...config, - ...context, - endpoint - }); - return next({ - ...args, - request - }); -}; - -// src/submodules/schema/middleware/getSchemaSerdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true -}; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true -}; -function getSchemaSerdePlugin(config) { +module.exports = __toCommonJS(index_exports); +var validate = /* @__PURE__ */ __name((str) => typeof str === "string" && str.indexOf("arn:") === 0 && str.split(":").length >= 6, "validate"); +var parse = /* @__PURE__ */ __name((arn) => { + const segments = arn.split(":"); + if (segments.length < 6 || segments[0] !== "arn") throw new Error("Malformed ARN"); + const [ + , + //Skip "arn" literal + partition, + service, + region, + accountId, + ...resource + ] = segments; return { - applyToStack: (commandStack) => { - commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); - commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); - config.protocol.setSerdeContext(config); - } + partition, + service, + region, + accountId, + resource: resource.join(":") }; -} - -// src/submodules/schema/TypeRegistry.ts -var TypeRegistry = class _TypeRegistry { - constructor(namespace, schemas = /* @__PURE__ */ new Map()) { - this.namespace = namespace; - this.schemas = schemas; - } - static { - this.registries = /* @__PURE__ */ new Map(); - } - /** - * @param namespace - specifier. - * @returns the schema for that namespace, creating it if necessary. - */ - static for(namespace) { - if (!_TypeRegistry.registries.has(namespace)) { - _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); - } - return _TypeRegistry.registries.get(namespace); - } - /** - * Adds the given schema to a type registry with the same namespace. - * - * @param shapeId - to be registered. - * @param schema - to be registered. - */ - register(shapeId, schema) { - const qualifiedName = this.normalizeShapeId(shapeId); - const registry = _TypeRegistry.for(this.getNamespace(shapeId)); - registry.schemas.set(qualifiedName, schema); - } - /** - * @param shapeId - query. - * @returns the schema. - */ - getSchema(shapeId) { - const id = this.normalizeShapeId(shapeId); - if (!this.schemas.has(id)) { - throw new Error(`@smithy/core/schema - schema not found for ${id}`); - } - return this.schemas.get(id); - } - /** - * The smithy-typescript code generator generates a synthetic (i.e. unmodeled) base exception, - * because generated SDKs before the introduction of schemas have the notion of a ServiceBaseException, which - * is unique per service/model. - * - * This is generated under a unique prefix that is combined with the service namespace, and this - * method is used to retrieve it. - * - * The base exception synthetic schema is used when an error is returned by a service, but we cannot - * determine what existing schema to use to deserialize it. - * - * @returns the synthetic base exception of the service namespace associated with this registry instance. - */ - getBaseException() { - for (const [id, schema] of this.schemas.entries()) { - if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { - return schema; - } - } - return void 0; - } - /** - * @param predicate - criterion. - * @returns a schema in this registry matching the predicate. - */ - find(predicate) { - return [...this.schemas.values()].find(predicate); - } - /** - * Unloads the current TypeRegistry. - */ - destroy() { - _TypeRegistry.registries.delete(this.namespace); - this.schemas.clear(); - } - normalizeShapeId(shapeId) { - if (shapeId.includes("#")) { - return shapeId; - } - return this.namespace + "#" + shapeId; - } - getNamespace(shapeId) { - return this.normalizeShapeId(shapeId).split("#")[0]; - } -}; - -// src/submodules/schema/schemas/Schema.ts -var Schema = class { - constructor(name, traits) { - this.name = name; - this.traits = traits; - } -}; - -// src/submodules/schema/schemas/ListSchema.ts -var ListSchema = class _ListSchema extends Schema { - constructor(name, traits, valueSchema) { - super(name, traits); - this.name = name; - this.traits = traits; - this.valueSchema = valueSchema; - this.symbol = _ListSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/core/schema::ListSchema"); - } - static [Symbol.hasInstance](lhs) { - const isPrototype = _ListSchema.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const list2 = lhs; - return list2.symbol === _ListSchema.symbol; - } - return isPrototype; - } -}; -function list(namespace, name, traits = {}, valueSchema) { - const schema = new ListSchema( - namespace + "#" + name, - traits, - typeof valueSchema === "function" ? valueSchema() : valueSchema - ); - TypeRegistry.for(namespace).register(name, schema); - return schema; -} - -// src/submodules/schema/schemas/MapSchema.ts -var MapSchema = class _MapSchema extends Schema { - constructor(name, traits, keySchema, valueSchema) { - super(name, traits); - this.name = name; - this.traits = traits; - this.keySchema = keySchema; - this.valueSchema = valueSchema; - this.symbol = _MapSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/core/schema::MapSchema"); - } - static [Symbol.hasInstance](lhs) { - const isPrototype = _MapSchema.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const map2 = lhs; - return map2.symbol === _MapSchema.symbol; - } - return isPrototype; - } -}; -function map(namespace, name, traits = {}, keySchema, valueSchema) { - const schema = new MapSchema( - namespace + "#" + name, - traits, - keySchema, - typeof valueSchema === "function" ? valueSchema() : valueSchema - ); - TypeRegistry.for(namespace).register(name, schema); - return schema; -} - -// src/submodules/schema/schemas/OperationSchema.ts -var OperationSchema = class extends Schema { - constructor(name, traits, input, output) { - super(name, traits); - this.name = name; - this.traits = traits; - this.input = input; - this.output = output; +}, "parse"); +var build = /* @__PURE__ */ __name((arnObject) => { + const { partition = "aws", service, region, accountId, resource } = arnObject; + if ([service, region, accountId, resource].some((segment) => typeof segment !== "string")) { + throw new Error("Input ARN object is invalid"); } -}; -function op(namespace, name, traits = {}, input, output) { - const schema = new OperationSchema(namespace + "#" + name, traits, input, output); - TypeRegistry.for(namespace).register(name, schema); - return schema; -} + return `arn:${partition}:${service}:${region}:${accountId}:${resource}`; +}, "build"); +// Annotate the CommonJS export names for ESM import in node: -// src/submodules/schema/schemas/StructureSchema.ts -var StructureSchema = class _StructureSchema extends Schema { - constructor(name, traits, memberNames, memberList) { - super(name, traits); - this.name = name; - this.traits = traits; - this.memberNames = memberNames; - this.memberList = memberList; - this.symbol = _StructureSchema.symbol; - this.members = {}; - for (let i = 0; i < memberNames.length; ++i) { - this.members[memberNames[i]] = Array.isArray(memberList[i]) ? memberList[i] : [memberList[i], 0]; - } - } - static { - this.symbol = Symbol.for("@smithy/core/schema::StructureSchema"); - } - static [Symbol.hasInstance](lhs) { - const isPrototype = _StructureSchema.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const struct2 = lhs; - return struct2.symbol === _StructureSchema.symbol; - } - return isPrototype; - } -}; -function struct(namespace, name, traits, memberNames, memberList) { - const schema = new StructureSchema(namespace + "#" + name, traits, memberNames, memberList); - TypeRegistry.for(namespace).register(name, schema); - return schema; -} +0 && (0); -// src/submodules/schema/schemas/ErrorSchema.ts -var ErrorSchema = class _ErrorSchema extends StructureSchema { - constructor(name, traits, memberNames, memberList, ctor) { - super(name, traits, memberNames, memberList); - this.name = name; - this.traits = traits; - this.memberNames = memberNames; - this.memberList = memberList; - this.ctor = ctor; - this.symbol = _ErrorSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/core/schema::ErrorSchema"); - } - static [Symbol.hasInstance](lhs) { - const isPrototype = _ErrorSchema.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const err = lhs; - return err.symbol === _ErrorSchema.symbol; - } - return isPrototype; - } -}; -function error(namespace, name, traits = {}, memberNames, memberList, ctor) { - const schema = new ErrorSchema(namespace + "#" + name, traits, memberNames, memberList, ctor); - TypeRegistry.for(namespace).register(name, schema); - return schema; -} -// src/submodules/schema/schemas/sentinels.ts -var SCHEMA = { - BLOB: 21, - // 21 - STREAMING_BLOB: 42, - // 42 - BOOLEAN: 2, - // 2 - STRING: 0, - // 0 - NUMERIC: 1, - // 1 - BIG_INTEGER: 17, - // 17 - BIG_DECIMAL: 19, - // 19 - DOCUMENT: 15, - // 15 - TIMESTAMP_DEFAULT: 4, - // 4 - TIMESTAMP_DATE_TIME: 5, - // 5 - TIMESTAMP_HTTP_DATE: 6, - // 6 - TIMESTAMP_EPOCH_SECONDS: 7, - // 7 - LIST_MODIFIER: 64, - // 64 - MAP_MODIFIER: 128 - // 128 -}; -// src/submodules/schema/schemas/SimpleSchema.ts -var SimpleSchema = class _SimpleSchema extends Schema { - constructor(name, schemaRef, traits) { - super(name, traits); - this.name = name; - this.schemaRef = schemaRef; - this.traits = traits; - this.symbol = _SimpleSchema.symbol; - } - static { - this.symbol = Symbol.for("@smithy/core/schema::SimpleSchema"); - } - static [Symbol.hasInstance](lhs) { - const isPrototype = _SimpleSchema.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const sim2 = lhs; - return sim2.symbol === _SimpleSchema.symbol; - } - return isPrototype; +/***/ }), + +/***/ 3350: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; -function sim(namespace, name, schemaRef, traits) { - const schema = new SimpleSchema(namespace + "#" + name, schemaRef, traits); - TypeRegistry.for(namespace).register(name, schema); - return schema; -} +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/schema/schemas/NormalizedSchema.ts -var NormalizedSchema = class _NormalizedSchema { - /** - * @param ref - a polymorphic SchemaRef to be dereferenced/normalized. - * @param memberName - optional memberName if this NormalizedSchema should be considered a member schema. - */ - constructor(ref, memberName) { - this.ref = ref; - this.memberName = memberName; - this.symbol = _NormalizedSchema.symbol; - const traitStack = []; - let _ref = ref; - let schema = ref; - this._isMemberSchema = false; - while (Array.isArray(_ref)) { - traitStack.push(_ref[1]); - _ref = _ref[0]; - schema = deref(_ref); - this._isMemberSchema = true; - } - if (traitStack.length > 0) { - this.memberTraits = {}; - for (let i = traitStack.length - 1; i >= 0; --i) { - const traitSet = traitStack[i]; - Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); +// src/index.ts +var index_exports = {}; +__export(index_exports, { + ConditionObject: () => import_util_endpoints.ConditionObject, + DeprecatedObject: () => import_util_endpoints.DeprecatedObject, + EndpointError: () => import_util_endpoints.EndpointError, + EndpointObject: () => import_util_endpoints.EndpointObject, + EndpointObjectHeaders: () => import_util_endpoints.EndpointObjectHeaders, + EndpointObjectProperties: () => import_util_endpoints.EndpointObjectProperties, + EndpointParams: () => import_util_endpoints.EndpointParams, + EndpointResolverOptions: () => import_util_endpoints.EndpointResolverOptions, + EndpointRuleObject: () => import_util_endpoints.EndpointRuleObject, + ErrorRuleObject: () => import_util_endpoints.ErrorRuleObject, + EvaluateOptions: () => import_util_endpoints.EvaluateOptions, + Expression: () => import_util_endpoints.Expression, + FunctionArgv: () => import_util_endpoints.FunctionArgv, + FunctionObject: () => import_util_endpoints.FunctionObject, + FunctionReturn: () => import_util_endpoints.FunctionReturn, + ParameterObject: () => import_util_endpoints.ParameterObject, + ReferenceObject: () => import_util_endpoints.ReferenceObject, + ReferenceRecord: () => import_util_endpoints.ReferenceRecord, + RuleSetObject: () => import_util_endpoints.RuleSetObject, + RuleSetRules: () => import_util_endpoints.RuleSetRules, + TreeRuleObject: () => import_util_endpoints.TreeRuleObject, + awsEndpointFunctions: () => awsEndpointFunctions, + getUserAgentPrefix: () => getUserAgentPrefix, + isIpAddress: () => import_util_endpoints.isIpAddress, + partition: () => partition, + resolveDefaultAwsRegionalEndpointsConfig: () => resolveDefaultAwsRegionalEndpointsConfig, + resolveEndpoint: () => import_util_endpoints.resolveEndpoint, + setPartitionInfo: () => setPartitionInfo, + toEndpointV1: () => toEndpointV1, + useDefaultPartitionInfo: () => useDefaultPartitionInfo +}); +module.exports = __toCommonJS(index_exports); + +// src/aws.ts + + +// src/lib/aws/isVirtualHostableS3Bucket.ts + + +// src/lib/isIpAddress.ts +var import_util_endpoints = __nccwpck_require__(5473); + +// src/lib/aws/isVirtualHostableS3Bucket.ts +var isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => { + if (allowSubDomains) { + for (const label of value.split(".")) { + if (!isVirtualHostableS3Bucket(label)) { + return false; } - } else { - this.memberTraits = 0; - } - if (schema instanceof _NormalizedSchema) { - this.name = schema.name; - this.traits = schema.traits; - this._isMemberSchema = schema._isMemberSchema; - this.schema = schema.schema; - this.memberTraits = Object.assign({}, schema.getMemberTraits(), this.getMemberTraits()); - this.normalizedTraits = void 0; - this.ref = schema.ref; - this.memberName = memberName ?? schema.memberName; - return; - } - this.schema = deref(schema); - if (this.schema && typeof this.schema === "object") { - this.traits = this.schema?.traits ?? {}; - } else { - this.traits = 0; - } - this.name = (typeof this.schema === "object" ? this.schema?.name : void 0) ?? this.memberName ?? this.getSchemaName(); - if (this._isMemberSchema && !memberName) { - throw new Error( - `@smithy/core/schema - NormalizedSchema member schema ${this.getName( - true - )} must initialize with memberName argument.` - ); } + return true; } - static { - this.symbol = Symbol.for("@smithy/core/schema::NormalizedSchema"); + if (!(0, import_util_endpoints.isValidHostLabel)(value)) { + return false; } - static [Symbol.hasInstance](lhs) { - const isPrototype = _NormalizedSchema.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const ns = lhs; - return ns.symbol === _NormalizedSchema.symbol; - } - return isPrototype; + if (value.length < 3 || value.length > 63) { + return false; } - /** - * Static constructor that attempts to avoid wrapping a NormalizedSchema within another. - */ - static of(ref, memberName) { - if (ref instanceof _NormalizedSchema) { - return ref; - } - return new _NormalizedSchema(ref, memberName); + if (value !== value.toLowerCase()) { + return false; } - /** - * @param indicator - numeric indicator for preset trait combination. - * @returns equivalent trait object. - */ - static translateTraits(indicator) { - if (typeof indicator === "object") { - return indicator; - } - indicator = indicator | 0; - const traits = {}; - if ((indicator & 1) === 1) { - traits.httpLabel = 1; - } - if ((indicator >> 1 & 1) === 1) { - traits.idempotent = 1; - } - if ((indicator >> 2 & 1) === 1) { - traits.idempotencyToken = 1; - } - if ((indicator >> 3 & 1) === 1) { - traits.sensitive = 1; - } - if ((indicator >> 4 & 1) === 1) { - traits.httpPayload = 1; + if ((0, import_util_endpoints.isIpAddress)(value)) { + return false; + } + return true; +}, "isVirtualHostableS3Bucket"); + +// src/lib/aws/parseArn.ts +var ARN_DELIMITER = ":"; +var RESOURCE_DELIMITER = "/"; +var parseArn = /* @__PURE__ */ __name((value) => { + const segments = value.split(ARN_DELIMITER); + if (segments.length < 6) return null; + const [arn, partition2, service, region, accountId, ...resourcePath] = segments; + if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null; + const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); + return { + partition: partition2, + service, + region, + accountId, + resourceId + }; +}, "parseArn"); + +// src/lib/aws/partitions.json +var partitions_default = { + 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|mx)\\-\\w+\\-\\d+$", + regions: { + "af-south-1": { + description: "Africa (Cape Town)" + }, + "ap-east-1": { + description: "Asia Pacific (Hong Kong)" + }, + "ap-east-2": { + description: "Asia Pacific (Taipei)" + }, + "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)" + }, + "ap-southeast-5": { + description: "Asia Pacific (Malaysia)" + }, + "ap-southeast-7": { + description: "Asia Pacific (Thailand)" + }, + "aws-global": { + description: "AWS Standard global region" + }, + "ca-central-1": { + description: "Canada (Central)" + }, + "ca-west-1": { + description: "Canada West (Calgary)" + }, + "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)" + }, + "mx-central-1": { + description: "Mexico (Central)" + }, + "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)" + } } - if ((indicator >> 5 & 1) === 1) { - traits.httpResponseCode = 1; + }, { + 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)" + } } - if ((indicator >> 6 & 1) === 1) { - traits.httpQueryParams = 1; + }, { + 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)" + } } - return traits; - } - /** - * Creates a normalized member schema from the given schema and member name. - */ - static memberFrom(memberSchema, memberName) { - if (memberSchema instanceof _NormalizedSchema) { - memberSchema.memberName = memberName; - memberSchema._isMemberSchema = true; - return memberSchema; + }, { + 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" + } } - return new _NormalizedSchema(memberSchema, memberName); - } - /** - * @returns the underlying non-normalized schema. - */ - getSchema() { - if (this.schema instanceof _NormalizedSchema) { - return this.schema = this.schema.getSchema(); + }, { + 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)" + } } - if (this.schema instanceof SimpleSchema) { - return deref(this.schema.schemaRef); + }, { + 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: { + "aws-iso-e-global": { + description: "AWS ISOE (Europe) global region" + }, + "eu-isoe-west-1": { + description: "EU ISOE West" + } } - return deref(this.schema); - } - /** - * @param withNamespace - qualifies the name. - * @returns e.g. `MyShape` or `com.namespace#MyShape`. - */ - getName(withNamespace = false) { - if (!withNamespace) { - if (this.name && this.name.includes("#")) { - return this.name.split("#")[1]; + }, { + 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: { + "aws-iso-f-global": { + description: "AWS ISOF global region" + }, + "us-isof-east-1": { + description: "US ISOF EAST" + }, + "us-isof-south-1": { + description: "US ISOF SOUTH" } } - return this.name || void 0; - } - /** - * @returns the member name if the schema is a member schema. - * @throws Error when the schema isn't a member schema. - */ - getMemberName() { - if (!this.isMemberSchema()) { - throw new Error(`@smithy/core/schema - cannot get member name on non-member schema: ${this.getName(true)}`); + }, { + id: "aws-eusc", + outputs: { + dnsSuffix: "amazonaws.eu", + dualStackDnsSuffix: "amazonaws.eu", + implicitGlobalRegion: "eusc-de-east-1", + name: "aws-eusc", + supportsDualStack: false, + supportsFIPS: true + }, + regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", + regions: { + "eusc-de-east-1": { + description: "EU (Germany)" + } } - return this.memberName; - } - isMemberSchema() { - return this._isMemberSchema; - } - isUnitSchema() { - return this.getSchema() === "unit"; - } - /** - * boolean methods on this class help control flow in shape serialization and deserialization. - */ - isListSchema() { - const inner = this.getSchema(); - if (typeof inner === "number") { - return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; + }], + version: "1.1" +}; + +// src/lib/aws/partition.ts +var selectedPartitionsInfo = partitions_default; +var selectedUserAgentPrefix = ""; +var partition = /* @__PURE__ */ __name((value) => { + const { partitions } = selectedPartitionsInfo; + for (const partition2 of partitions) { + const { regions, outputs } = partition2; + for (const [region, regionData] of Object.entries(regions)) { + if (region === value) { + return { + ...outputs, + ...regionData + }; + } } - return inner instanceof ListSchema; } - isMapSchema() { - const inner = this.getSchema(); - if (typeof inner === "number") { - return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; + for (const partition2 of partitions) { + const { regionRegex, outputs } = partition2; + if (new RegExp(regionRegex).test(value)) { + return { + ...outputs + }; } - return inner instanceof MapSchema; - } - isDocumentSchema() { - return this.getSchema() === SCHEMA.DOCUMENT; - } - isStructSchema() { - const inner = this.getSchema(); - return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; - } - isBlobSchema() { - return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; } - isTimestampSchema() { - const schema = this.getSchema(); - return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; - } - isStringSchema() { - return this.getSchema() === SCHEMA.STRING; - } - isBooleanSchema() { - return this.getSchema() === SCHEMA.BOOLEAN; - } - isNumericSchema() { - return this.getSchema() === SCHEMA.NUMERIC; - } - isBigIntegerSchema() { - return this.getSchema() === SCHEMA.BIG_INTEGER; - } - isBigDecimalSchema() { - return this.getSchema() === SCHEMA.BIG_DECIMAL; - } - isStreaming() { - const streaming = !!this.getMergedTraits().streaming; - if (streaming) { - return true; - } - return this.getSchema() === SCHEMA.STREAMING_BLOB; + const DEFAULT_PARTITION = partitions.find((partition2) => partition2.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." + ); } - /** - * This is a shortcut to avoid calling `getMergedTraits().idempotencyToken` on every string. - * @returns whether the schema has the idempotencyToken trait. - */ - isIdempotencyToken() { - if (typeof this.traits === "number") { - return (this.traits & 4) === 4; - } else if (typeof this.traits === "object") { - return !!this.traits.idempotencyToken; - } - return false; + return { + ...DEFAULT_PARTITION.outputs + }; +}, "partition"); +var setPartitionInfo = /* @__PURE__ */ __name((partitionsInfo, userAgentPrefix = "") => { + selectedPartitionsInfo = partitionsInfo; + selectedUserAgentPrefix = userAgentPrefix; +}, "setPartitionInfo"); +var useDefaultPartitionInfo = /* @__PURE__ */ __name(() => { + setPartitionInfo(partitions_default, ""); +}, "useDefaultPartitionInfo"); +var getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix"); + +// src/aws.ts +var awsEndpointFunctions = { + isVirtualHostableS3Bucket, + parseArn, + partition +}; +import_util_endpoints.customEndpointFunctions.aws = awsEndpointFunctions; + +// src/resolveDefaultAwsRegionalEndpointsConfig.ts +var import_url_parser = __nccwpck_require__(4681); +var resolveDefaultAwsRegionalEndpointsConfig = /* @__PURE__ */ __name((input) => { + if (typeof input.endpointProvider !== "function") { + throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); } - /** - * @returns own traits merged with member traits, where member traits of the same trait key take priority. - * This method is cached. - */ - getMergedTraits() { - if (this.normalizedTraits) { - return this.normalizedTraits; - } - this.normalizedTraits = { - ...this.getOwnTraits(), - ...this.getMemberTraits() + const { endpoint } = input; + if (endpoint === void 0) { + input.endpoint = async () => { + return toEndpointV1( + input.endpointProvider( + { + Region: typeof input.region === "function" ? await input.region() : input.region, + UseDualStack: typeof input.useDualstackEndpoint === "function" ? await input.useDualstackEndpoint() : input.useDualstackEndpoint, + UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, + Endpoint: void 0 + }, + { logger: input.logger } + ) + ); }; - return this.normalizedTraits; - } - /** - * @returns only the member traits. If the schema is not a member, this returns empty. - */ - getMemberTraits() { - return _NormalizedSchema.translateTraits(this.memberTraits); - } - /** - * @returns only the traits inherent to the shape or member target shape if this schema is a member. - * If there are any member traits they are excluded. - */ - getOwnTraits() { - return _NormalizedSchema.translateTraits(this.traits); - } - /** - * @returns the map's key's schema. Returns a dummy Document schema if this schema is a Document. - * - * @throws Error if the schema is not a Map or Document. - */ - getKeySchema() { - if (this.isDocumentSchema()) { - return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], "key"); - } - if (!this.isMapSchema()) { - throw new Error(`@smithy/core/schema - cannot get key schema for non-map schema: ${this.getName(true)}`); - } - const schema = this.getSchema(); - if (typeof schema === "number") { - return _NormalizedSchema.memberFrom([63 & schema, 0], "key"); - } - return _NormalizedSchema.memberFrom([schema.keySchema, 0], "key"); - } - /** - * @returns the schema of the map's value or list's member. - * Returns a dummy Document schema if this schema is a Document. - * - * @throws Error if the schema is not a Map, List, nor Document. - */ - getValueSchema() { - const schema = this.getSchema(); - if (typeof schema === "number") { - if (this.isMapSchema()) { - return _NormalizedSchema.memberFrom([63 & schema, 0], "value"); - } else if (this.isListSchema()) { - return _NormalizedSchema.memberFrom([63 & schema, 0], "member"); - } - } - if (schema && typeof schema === "object") { - if (this.isStructSchema()) { - throw new Error(`cannot call getValueSchema() with StructureSchema ${this.getName(true)}`); - } - const collection = schema; - if ("valueSchema" in collection) { - if (this.isMapSchema()) { - return _NormalizedSchema.memberFrom([collection.valueSchema, 0], "value"); - } else if (this.isListSchema()) { - return _NormalizedSchema.memberFrom([collection.valueSchema, 0], "member"); - } - } - } - if (this.isDocumentSchema()) { - return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], "value"); - } - throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have a value member.`); } - /** - * @returns the NormalizedSchema for the given member name. The returned instance will return true for `isMemberSchema()` - * and will have the member name given. - * @param member - which member to retrieve and wrap. - * - * @throws Error if member does not exist or the schema is neither a document nor structure. - * Note that errors are assumed to be structures and unions are considered structures for these purposes. - */ - getMemberSchema(member) { - if (this.isStructSchema()) { - const struct2 = this.getSchema(); - if (!(member in struct2.members)) { - throw new Error( - `@smithy/core/schema - the schema ${this.getName(true)} does not have a member with name=${member}.` - ); - } - return _NormalizedSchema.memberFrom(struct2.members[member], member); - } - if (this.isDocumentSchema()) { - return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], member); - } - throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have members.`); + return input; +}, "resolveDefaultAwsRegionalEndpointsConfig"); +var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => (0, import_url_parser.parseUrl)(endpoint.url), "toEndpointV1"); + +// src/resolveEndpoint.ts + + +// src/types/EndpointError.ts + + +// src/types/EndpointRuleObject.ts + + +// src/types/ErrorRuleObject.ts + + +// src/types/RuleSetObject.ts + + +// src/types/TreeRuleObject.ts + + +// src/types/shared.ts + +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 8095: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - /** - * This can be used for checking the members as a hashmap. - * Prefer the structIterator method for iteration. - * - * This does NOT return list and map members, it is only for structures. - * - * @returns a map of member names to member schemas (normalized). - */ - getMemberSchemas() { - const { schema } = this; - const struct2 = schema; - if (!struct2 || typeof struct2 !== "object") { - return {}; - } - if ("members" in struct2) { - const buffer = {}; - for (const member of struct2.memberNames) { - buffer[member] = this.getMemberSchema(member); - } - return buffer; - } - return {}; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var index_exports = {}; +__export(index_exports, { + NODE_APP_ID_CONFIG_OPTIONS: () => NODE_APP_ID_CONFIG_OPTIONS, + UA_APP_ID_ENV_NAME: () => UA_APP_ID_ENV_NAME, + UA_APP_ID_INI_NAME: () => UA_APP_ID_INI_NAME, + createDefaultUserAgentProvider: () => createDefaultUserAgentProvider, + crtAvailability: () => crtAvailability, + defaultUserAgent: () => defaultUserAgent +}); +module.exports = __toCommonJS(index_exports); + +// src/defaultUserAgent.ts +var import_os = __nccwpck_require__(2037); +var import_process = __nccwpck_require__(7282); + +// src/crt-availability.ts +var crtAvailability = { + isCrtAvailable: false +}; + +// src/is-crt-available.ts +var isCrtAvailable = /* @__PURE__ */ __name(() => { + if (crtAvailability.isCrtAvailable) { + return ["md/crt-avail"]; } - /** - * Allows iteration over members of a structure schema. - * Each yield is a pair of the member name and member schema. - * - * This avoids the overhead of calling Object.entries(ns.getMemberSchemas()). - */ - *structIterator() { - if (this.isUnitSchema()) { - return; - } - if (!this.isStructSchema()) { - throw new Error("@smithy/core/schema - cannot acquire structIterator on non-struct schema."); + return null; +}, "isCrtAvailable"); + +// src/defaultUserAgent.ts +var createDefaultUserAgentProvider = /* @__PURE__ */ __name(({ serviceId, clientVersion }) => { + return async (config) => { + const sections = [ + // sdk-metadata + ["aws-sdk-js", clientVersion], + // ua-metadata + ["ua", "2.1"], + // os-metadata + [`os/${(0, import_os.platform)()}`, (0, import_os.release)()], + // language-metadata + // ECMAScript edition doesn't matter in JS, so no version needed. + ["lang/js"], + ["md/nodejs", `${import_process.versions.node}`] + ]; + const crtAvailable = isCrtAvailable(); + if (crtAvailable) { + sections.push(crtAvailable); } - const struct2 = this.getSchema(); - for (let i = 0; i < struct2.memberNames.length; ++i) { - yield [struct2.memberNames[i], _NormalizedSchema.memberFrom([struct2.memberList[i], 0], struct2.memberNames[i])]; + if (serviceId) { + sections.push([`api/${serviceId}`, clientVersion]); } - } - /** - * @returns a last-resort human-readable name for the schema if it has no other identifiers. - */ - getSchemaName() { - const schema = this.getSchema(); - if (typeof schema === "number") { - const _schema = 63 & schema; - const container = 192 & schema; - const type = Object.entries(SCHEMA).find(([, value]) => { - return value === _schema; - })?.[0] ?? "Unknown"; - switch (container) { - case SCHEMA.MAP_MODIFIER: - return `${type}Map`; - case SCHEMA.LIST_MODIFIER: - return `${type}List`; - case 0: - return type; - } + if (import_process.env.AWS_EXECUTION_ENV) { + sections.push([`exec-env/${import_process.env.AWS_EXECUTION_ENV}`]); } - return "Unknown"; - } + const appId = await config?.userAgentAppId?.(); + const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; + return resolvedUserAgent; + }; +}, "createDefaultUserAgentProvider"); +var defaultUserAgent = createDefaultUserAgentProvider; + +// src/nodeAppIdConfigOptions.ts +var import_middleware_user_agent = __nccwpck_require__(4688); +var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; +var UA_APP_ID_INI_NAME = "sdk_ua_app_id"; +var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; +var NODE_APP_ID_CONFIG_OPTIONS = { + environmentVariableSelector: /* @__PURE__ */ __name((env2) => env2[UA_APP_ID_ENV_NAME], "environmentVariableSelector"), + configFileSelector: /* @__PURE__ */ __name((profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], "configFileSelector"), + default: import_middleware_user_agent.DEFAULT_UA_APP_ID }; // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 7669: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 2329: +/***/ ((module) => { + +"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -59239,670 +44072,823 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/serde/index.ts -var serde_exports = {}; -__export(serde_exports, { - LazyJsonString: () => LazyJsonString, - NumericValue: () => NumericValue, - copyDocumentWithTransform: () => copyDocumentWithTransform, - dateToUtcString: () => dateToUtcString, - expectBoolean: () => expectBoolean, - expectByte: () => expectByte, - expectFloat32: () => expectFloat32, - expectInt: () => expectInt, - expectInt32: () => expectInt32, - expectLong: () => expectLong, - expectNonNull: () => expectNonNull, - expectNumber: () => expectNumber, - expectObject: () => expectObject, - expectShort: () => expectShort, - expectString: () => expectString, - expectUnion: () => expectUnion, - generateIdempotencyToken: () => import_uuid.v4, - handleFloat: () => handleFloat, - limitedParseDouble: () => limitedParseDouble, - limitedParseFloat: () => limitedParseFloat, - limitedParseFloat32: () => limitedParseFloat32, - logger: () => logger, - nv: () => nv, - parseBoolean: () => parseBoolean, - parseEpochTimestamp: () => parseEpochTimestamp, - parseRfc3339DateTime: () => parseRfc3339DateTime, - parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, - parseRfc7231DateTime: () => parseRfc7231DateTime, - quoteHeader: () => quoteHeader, - splitEvery: () => splitEvery, - splitHeader: () => splitHeader, - strictParseByte: () => strictParseByte, - strictParseDouble: () => strictParseDouble, - strictParseFloat: () => strictParseFloat, - strictParseFloat32: () => strictParseFloat32, - strictParseInt: () => strictParseInt, - strictParseInt32: () => strictParseInt32, - strictParseLong: () => strictParseLong, - strictParseShort: () => strictParseShort +// src/index.ts +var index_exports = {}; +__export(index_exports, { + XmlNode: () => XmlNode, + XmlText: () => XmlText }); -module.exports = __toCommonJS(serde_exports); +module.exports = __toCommonJS(index_exports); -// src/submodules/serde/copyDocumentWithTransform.ts -var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; +// src/escape-attribute.ts +function escapeAttribute(value) { + return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} +__name(escapeAttribute, "escapeAttribute"); -// src/submodules/serde/parse-utils.ts -var parseBoolean = (value) => { - switch (value) { - case "true": - return true; - case "false": - return false; - default: - throw new Error(`Unable to parse boolean value "${value}"`); - } -}; -var expectBoolean = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "number") { - if (value === 0 || value === 1) { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (value === 0) { - return false; - } - if (value === 1) { - return true; - } +// src/escape-element.ts +function escapeElement(value) { + return value.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">").replace(/\r/g, " ").replace(/\n/g, " ").replace(/\u0085/g, "…").replace(/\u2028/, "
"); +} +__name(escapeElement, "escapeElement"); + +// src/XmlText.ts +var XmlText = class { + constructor(value) { + this.value = value; } - if (typeof value === "string") { - const lower = value.toLowerCase(); - if (lower === "false" || lower === "true") { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (lower === "false") { - return false; - } - if (lower === "true") { - return true; - } + static { + __name(this, "XmlText"); } - if (typeof value === "boolean") { - return value; + toString() { + return escapeElement("" + this.value); } - throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); }; -var expectNumber = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - const parsed = parseFloat(value); - if (!Number.isNaN(parsed)) { - if (String(parsed) !== String(value)) { - logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); - } - return parsed; - } + +// src/XmlNode.ts +var XmlNode = class _XmlNode { + constructor(name, children = []) { + this.name = name; + this.children = children; } - if (typeof value === "number") { - return value; + static { + __name(this, "XmlNode"); } - throw new TypeError(`Expected number, got ${typeof value}: ${value}`); -}; -var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); -var expectFloat32 = (value) => { - const expected = expectNumber(value); - if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { - if (Math.abs(expected) > MAX_FLOAT) { - throw new TypeError(`Expected 32-bit float, got ${value}`); + attributes = {}; + static of(name, childText, withName) { + const node = new _XmlNode(name); + if (childText !== void 0) { + node.addChildNode(new XmlText(childText)); } - } - return expected; -}; -var expectLong = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (Number.isInteger(value) && !Number.isNaN(value)) { - return value; - } - throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); -}; -var expectInt = expectLong; -var expectInt32 = (value) => expectSizedInt(value, 32); -var expectShort = (value) => expectSizedInt(value, 16); -var expectByte = (value) => expectSizedInt(value, 8); -var expectSizedInt = (value, size) => { - const expected = expectLong(value); - if (expected !== void 0 && castInt(expected, size) !== expected) { - throw new TypeError(`Expected ${size}-bit integer, got ${value}`); - } - return expected; -}; -var 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]; - } -}; -var expectNonNull = (value, location) => { - if (value === null || value === void 0) { - if (location) { - throw new TypeError(`Expected a non-null value for ${location}`); + if (withName !== void 0) { + node.withName(withName); } - throw new TypeError("Expected a non-null value"); - } - return value; -}; -var expectObject = (value) => { - if (value === null || value === void 0) { - return void 0; - } - 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}`); -}; -var expectString = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - return value; - } - if (["boolean", "number", "bigint"].includes(typeof value)) { - logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); - return String(value); + return node; } - throw new TypeError(`Expected string, got ${typeof value}: ${value}`); -}; -var expectUnion = (value) => { - if (value === null || value === void 0) { - return void 0; + withName(name) { + this.name = name; + return this; } - const asObject = 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.`); + addAttribute(name, value) { + this.attributes[name] = value; + return this; } - if (setKeys.length > 1) { - throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); + addChildNode(child) { + this.children.push(child); + return this; } - return asObject; -}; -var strictParseDouble = (value) => { - if (typeof value == "string") { - return expectNumber(parseNumber(value)); + removeAttribute(name) { + delete this.attributes[name]; + return this; } - return expectNumber(value); -}; -var strictParseFloat = strictParseDouble; -var strictParseFloat32 = (value) => { - if (typeof value == "string") { - return expectFloat32(parseNumber(value)); + /** + * @internal + * Alias of {@link XmlNode#withName(string)} for codegen brevity. + */ + n(name) { + this.name = name; + return this; } - return expectFloat32(value); -}; -var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; -var 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`); + /** + * @internal + * Alias of {@link XmlNode#addChildNode(string)} for codegen brevity. + */ + c(child) { + this.children.push(child); + return this; } - return parseFloat(value); -}; -var limitedParseDouble = (value) => { - if (typeof value == "string") { - return parseFloatString(value); + /** + * @internal + * Checked version of {@link XmlNode#addAttribute(string)} for codegen brevity. + */ + a(name, value) { + if (value != null) { + this.attributes[name] = value; + } + return this; } - return expectNumber(value); -}; -var handleFloat = limitedParseDouble; -var limitedParseFloat = limitedParseDouble; -var limitedParseFloat32 = (value) => { - if (typeof value == "string") { - return parseFloatString(value); + /** + * Create a child node. + * Used in serialization of string fields. + * @internal + */ + cc(input, field, withName = field) { + if (input[field] != null) { + const node = _XmlNode.of(field, input[field]).withName(withName); + this.c(node); + } } - return expectFloat32(value); -}; -var 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}`); + /** + * Creates list child nodes. + * @internal + */ + l(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + nodes.map((node) => { + node.withName(memberName); + this.c(node); + }); + } } -}; -var strictParseLong = (value) => { - if (typeof value === "string") { - return expectLong(parseNumber(value)); + /** + * Creates list child nodes with container. + * @internal + */ + lc(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + const containerNode = new _XmlNode(memberName); + nodes.map((node) => { + containerNode.c(node); + }); + this.c(containerNode); + } } - return expectLong(value); -}; -var strictParseInt = strictParseLong; -var strictParseInt32 = (value) => { - if (typeof value === "string") { - return expectInt32(parseNumber(value)); + toString() { + const hasChildren = Boolean(this.children.length); + let xmlText = `<${this.name}`; + const attributes = this.attributes; + for (const attributeName of Object.keys(attributes)) { + const attribute = attributes[attributeName]; + if (attribute != null) { + xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; + } + } + return xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`; } - return expectInt32(value); }; -var strictParseShort = (value) => { - if (typeof value === "string") { - return expectShort(parseNumber(value)); - } - return expectShort(value); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 3098: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var strictParseByte = (value) => { - if (typeof value === "string") { - return expectByte(parseNumber(value)); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - return expectByte(value); -}; -var stackTraceWarning = (message) => { - return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); + return to; }; -var logger = { - warn: console.warn +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + CONFIG_USE_DUALSTACK_ENDPOINT: () => CONFIG_USE_DUALSTACK_ENDPOINT, + CONFIG_USE_FIPS_ENDPOINT: () => CONFIG_USE_FIPS_ENDPOINT, + DEFAULT_USE_DUALSTACK_ENDPOINT: () => DEFAULT_USE_DUALSTACK_ENDPOINT, + DEFAULT_USE_FIPS_ENDPOINT: () => DEFAULT_USE_FIPS_ENDPOINT, + ENV_USE_DUALSTACK_ENDPOINT: () => ENV_USE_DUALSTACK_ENDPOINT, + ENV_USE_FIPS_ENDPOINT: () => ENV_USE_FIPS_ENDPOINT, + NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, + NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, + NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, + NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, + REGION_ENV_NAME: () => REGION_ENV_NAME, + REGION_INI_NAME: () => REGION_INI_NAME, + getRegionInfo: () => getRegionInfo, + resolveCustomEndpointsConfig: () => resolveCustomEndpointsConfig, + resolveEndpointsConfig: () => resolveEndpointsConfig, + resolveRegionConfig: () => resolveRegionConfig +}); +module.exports = __toCommonJS(src_exports); + +// src/endpointsConfig/NodeUseDualstackEndpointConfigOptions.ts +var import_util_config_provider = __nccwpck_require__(3375); +var ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; +var CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; +var DEFAULT_USE_DUALSTACK_ENDPOINT = false; +var NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => (0, import_util_config_provider.booleanSelector)(env, ENV_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.ENV), + configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.CONFIG), + default: false }; -// src/submodules/serde/date-utils.ts -var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; -var 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`; -} -var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); -var parseRfc3339DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - 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 = 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 }); +// src/endpointsConfig/NodeUseFipsEndpointConfigOptions.ts + +var ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; +var CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; +var DEFAULT_USE_FIPS_ENDPOINT = false; +var NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => (0, import_util_config_provider.booleanSelector)(env, ENV_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.ENV), + configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.CONFIG), + default: false }; -var RFC3339_WITH_OFFSET = new RegExp( - /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ -); -var parseRfc3339DateTimeWithOffset = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); + +// src/endpointsConfig/resolveCustomEndpointsConfig.ts +var import_util_middleware = __nccwpck_require__(2390); +var resolveCustomEndpointsConfig = /* @__PURE__ */ __name((input) => { + const { tls, endpoint, urlParser, useDualstackEndpoint } = input; + return Object.assign(input, { + tls: tls ?? true, + endpoint: (0, import_util_middleware.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), + isCustomEndpoint: true, + useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false) + }); +}, "resolveCustomEndpointsConfig"); + +// src/endpointsConfig/resolveEndpointsConfig.ts + + +// src/endpointsConfig/utils/getEndpointFromRegion.ts +var getEndpointFromRegion = /* @__PURE__ */ __name(async (input) => { + 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 match = RFC3339_WITH_OFFSET.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); + const useDualstackEndpoint = await input.useDualstackEndpoint(); + const useFipsEndpoint = await input.useFipsEndpoint(); + const { hostname } = await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint }) ?? {}; + if (!hostname) { + throw new Error("Cannot resolve hostname from client config"); } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; - const year = 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 input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`); +}, "getEndpointFromRegion"); + +// src/endpointsConfig/resolveEndpointsConfig.ts +var resolveEndpointsConfig = /* @__PURE__ */ __name((input) => { + const useDualstackEndpoint = (0, import_util_middleware.normalizeProvider)(input.useDualstackEndpoint ?? false); + const { endpoint, useFipsEndpoint, urlParser, tls } = input; + return Object.assign(input, { + tls: tls ?? true, + endpoint: endpoint ? (0, import_util_middleware.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), + isCustomEndpoint: !!endpoint, + useDualstackEndpoint + }); +}, "resolveEndpointsConfig"); + +// src/regionConfig/config.ts +var REGION_ENV_NAME = "AWS_REGION"; +var REGION_INI_NAME = "region"; +var NODE_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[REGION_ENV_NAME], + configFileSelector: (profile) => profile[REGION_INI_NAME], + default: () => { + throw new Error("Region is missing"); } - return date; }; -var 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$/ -); -var 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$/ -); -var 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})$/ -); -var parseRfc7231DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-7231 date-times must be expressed as strings"); +var NODE_REGION_CONFIG_FILE_OPTIONS = { + preferredFile: "credentials" +}; + +// src/regionConfig/isFipsRegion.ts +var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); + +// src/regionConfig/getRealRegion.ts +var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); + +// src/regionConfig/resolveRegionConfig.ts +var resolveRegionConfig = /* @__PURE__ */ __name((input) => { + const { region, useFipsEndpoint } = input; + if (!region) { + throw new Error("Region is missing"); } - let match = IMF_FIXDATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr, "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); + return Object.assign(input, { + region: async () => { + if (typeof region === "string") { + return getRealRegion(region); + } + const providedRegion = await region(); + return getRealRegion(providedRegion); + }, + useFipsEndpoint: async () => { + const providedRegion = typeof region === "string" ? region : await region(); + if (isFipsRegion(providedRegion)) { + return true; + } + return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); + } + }); +}, "resolveRegionConfig"); + +// src/regionInfo/getHostnameFromVariants.ts +var getHostnameFromVariants = /* @__PURE__ */ __name((variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find( + ({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack") +)?.hostname, "getHostnameFromVariants"); + +// src/regionInfo/getResolvedHostname.ts +var getResolvedHostname = /* @__PURE__ */ __name((resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : void 0, "getResolvedHostname"); + +// src/regionInfo/getResolvedPartition.ts +var getResolvedPartition = /* @__PURE__ */ __name((region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws", "getResolvedPartition"); + +// src/regionInfo/getResolvedSigningRegion.ts +var getResolvedSigningRegion = /* @__PURE__ */ __name((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); + } } - 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 - }) - ); +}, "getResolvedSigningRegion"); + +// src/regionInfo/getRegionInfo.ts +var getRegionInfo = /* @__PURE__ */ __name((region, { + useFipsEndpoint = false, + useDualstackEndpoint = false, + signingService, + regionHash, + partitionHash +}) => { + const partition = getResolvedPartition(region, { partitionHash }); + const resolvedRegion = region in regionHash ? region : partitionHash[partition]?.endpoint ?? region; + const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; + const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); + const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); + const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); + if (hostname === void 0) { + throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); } - match = ASC_TIME.exec(value); - if (match) { - const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr.trimLeft(), "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); + const signingRegion = getResolvedSigningRegion(hostname, { + signingRegion: regionHash[resolvedRegion]?.signingRegion, + regionRegex: partitionHash[partition].regionRegex, + useFipsEndpoint + }); + return { + partition, + signingService, + hostname, + ...signingRegion && { signingRegion }, + ...regionHash[resolvedRegion]?.signingService && { + signingService: regionHash[resolvedRegion].signingService + } + }; +}, "getRegionInfo"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 5829: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - throw new TypeError("Invalid RFC-7231 date-time value"); + return to; }; -var parseEpochTimestamp = (value) => { - if (value === null || value === void 0) { - return void 0; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, + EXPIRATION_MS: () => EXPIRATION_MS, + HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, + HttpBearerAuthSigner: () => HttpBearerAuthSigner, + NoAuthSigner: () => NoAuthSigner, + createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, + createPaginator: () => createPaginator, + doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, + getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, + getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, + getHttpSigningPlugin: () => getHttpSigningPlugin, + getSmithyContext: () => getSmithyContext, + httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, + httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, + httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, + httpSigningMiddleware: () => httpSigningMiddleware, + httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, + isIdentityExpired: () => isIdentityExpired, + memoizeIdentityProvider: () => memoizeIdentityProvider, + normalizeProvider: () => normalizeProvider, + requestBuilder: () => import_protocols.requestBuilder, + setFeature: () => setFeature +}); +module.exports = __toCommonJS(src_exports); + +// src/getSmithyContext.ts +var import_types = __nccwpck_require__(5756); +var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); + +// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +var import_util_middleware = __nccwpck_require__(2390); + +// src/middleware-http-auth-scheme/resolveAuthOptions.ts +var resolveAuthOptions = /* @__PURE__ */ __name((candidateAuthOptions, authSchemePreference) => { + if (!authSchemePreference || authSchemePreference.length === 0) { + return candidateAuthOptions; } - let valueAsDouble; - if (typeof value === "number") { - valueAsDouble = value; - } else if (typeof value === "string") { - valueAsDouble = strictParseDouble(value); - } else if (typeof value === "object" && value.tag === 1) { - valueAsDouble = value.value; - } else { - throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); + const preferredAuthOptions = []; + for (const preferredSchemeName of authSchemePreference) { + for (const candidateAuthOption of candidateAuthOptions) { + const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; + if (candidateAuthSchemeName === preferredSchemeName) { + preferredAuthOptions.push(candidateAuthOption); + } + } } - if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { - throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); + for (const candidateAuthOption of candidateAuthOptions) { + if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { + preferredAuthOptions.push(candidateAuthOption); + } } - return new Date(Math.round(valueAsDouble * 1e3)); -}; -var 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), - // seconds can go up to 60 for leap seconds - parseDateValue(time.seconds, "seconds", 0, 60), - parseMilliseconds(time.fractionalMilliseconds) - ) + return preferredAuthOptions; +}, "resolveAuthOptions"); + +// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +function convertHttpAuthSchemesToMap(httpAuthSchemes) { + const map = /* @__PURE__ */ new Map(); + for (const scheme of httpAuthSchemes) { + map.set(scheme.schemeId, scheme); + } + return map; +} +__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); +var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { + const options = config.httpAuthSchemeProvider( + await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) ); -}; -var parseTwoDigitYear = (value) => { - const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); - const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); - if (valueInThisCentury < thisYear) { - return valueInThisCentury + 100; + const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; + const resolvedOptions = resolveAuthOptions(options, authSchemePreference); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const failureReasons = []; + for (const option of resolvedOptions) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer + }; + break; } - return valueInThisCentury; + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); + } + return next(args); +}, "httpAuthSchemeMiddleware"); + +// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts +var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware" }; -var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; -var adjustRfc850Year = (input) => { - if (input.getTime() - (/* @__PURE__ */ 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() - ) +var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider +}) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo( + httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), + httpAuthSchemeEndpointRuleSetMiddlewareOptions ); } - return input; +}), "getHttpAuthSchemeEndpointRuleSetPlugin"); + +// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts +var import_middleware_serde = __nccwpck_require__(1238); +var httpAuthSchemeMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: import_middleware_serde.serializerMiddlewareOption.name }; -var parseMonthByShortName = (value) => { - const monthIdx = MONTHS.indexOf(value); - if (monthIdx < 0) { - throw new TypeError(`Invalid month: ${value}`); +var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider +}) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo( + httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), + httpAuthSchemeMiddlewareOptions + ); } - return monthIdx + 1; -}; -var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -var validateDayOfMonth = (year, month, day) => { - let maxDays = DAYS_IN_MONTH[month]; - if (month === 1 && isLeapYear(year)) { - maxDays = 29; +}), "getHttpAuthSchemePlugin"); + +// src/middleware-http-signing/httpSigningMiddleware.ts +var import_protocol_http = __nccwpck_require__(4418); + +var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { + throw error; +}, "defaultErrorHandler"); +var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { +}, "defaultSuccessHandler"); +var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { + if (!import_protocol_http.HttpRequest.isInstance(args.request)) { + return next(args); } - if (day > maxDays) { - throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); } + const { + httpAuthOption: { signingProperties = {} }, + identity, + signer + } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties) + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; +}, "httpSigningMiddleware"); + +// src/middleware-http-signing/getHttpSigningMiddleware.ts +var httpSigningMiddlewareOptions = { + step: "finalizeRequest", + tags: ["HTTP_SIGNING"], + name: "httpSigningMiddleware", + aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], + override: true, + relation: "after", + toMiddleware: "retryMiddleware" }; -var isLeapYear = (year) => { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -}; -var parseDateValue = (value, type, lower, upper) => { - const dateVal = strictParseByte(stripLeadingZeroes(value)); - if (dateVal < lower || dateVal > upper) { - throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); +var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); } - return dateVal; -}; -var parseMilliseconds = (value) => { - if (value === null || value === void 0) { - return 0; +}), "getHttpSigningPlugin"); + +// src/normalizeProvider.ts +var normalizeProvider = /* @__PURE__ */ __name((input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}, "normalizeProvider"); + +// src/pagination/createPaginator.ts +var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { + let command = new CommandCtor(input); + command = withCommand(command) ?? command; + return await client.send(command, ...args); +}, "makePagedClientRequest"); +function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { + return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { + const _input = input; + let token = config.startingToken ?? _input[inputTokenName]; + let hasNext = true; + let page; + while (hasNext) { + _input[inputTokenName] = token; + if (pageSizeTokenName) { + _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; + } + if (config.client instanceof ClientCtor) { + page = await makePagedClientRequest( + CommandCtor, + config.client, + input, + config.withCommand, + ...additionalArguments + ); + } else { + throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); + } + yield page; + const prevToken = token; + token = get(page, outputTokenName); + hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); + } + return void 0; + }, "paginateOperation"); +} +__name(createPaginator, "createPaginator"); +var get = /* @__PURE__ */ __name((fromObject, path) => { + let cursor = fromObject; + const pathComponents = path.split("."); + for (const step of pathComponents) { + if (!cursor || typeof cursor !== "object") { + return void 0; + } + cursor = cursor[step]; } - return strictParseFloat32("0." + value) * 1e3; -}; -var 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 "-"`); + return cursor; +}, "get"); + +// src/protocols/requestBuilder.ts +var import_protocols = __nccwpck_require__(2241); + +// src/setFeature.ts +function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { + features: {} + }; + } else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; } - const hour = Number(value.substring(1, 3)); - const minute = Number(value.substring(4, 6)); - return direction * (hour * 60 + minute) * 60 * 1e3; -}; -var stripLeadingZeroes = (value) => { - let idx = 0; - while (idx < value.length - 1 && value.charAt(idx) === "0") { - idx++; + context.__smithy_context.features[feature] = value; +} +__name(setFeature, "setFeature"); + +// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts +var DefaultIdentityProviderConfig = class { + /** + * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. + * + * @param config scheme IDs and identity providers to configure + */ + constructor(config) { + this.authSchemes = /* @__PURE__ */ new Map(); + for (const [key, value] of Object.entries(config)) { + if (value !== void 0) { + this.authSchemes.set(key, value); + } + } } - if (idx === 0) { - return value; + static { + __name(this, "DefaultIdentityProviderConfig"); + } + getIdentityProvider(schemeId) { + return this.authSchemes.get(schemeId); } - return value.slice(idx); }; -// src/submodules/serde/generateIdempotencyToken.ts -var import_uuid = __nccwpck_require__(5840); +// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts -// src/submodules/serde/lazy-json.ts -var LazyJsonString = function LazyJsonString2(val) { - const str = Object.assign(new String(val), { - deserializeJSON() { - return JSON.parse(String(val)); - }, - toString() { - return String(val); - }, - toJSON() { - return String(val); + +var HttpApiKeyAuthSigner = class { + static { + __name(this, "HttpApiKeyAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + if (!signingProperties) { + throw new Error( + "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" + ); } - }); - return str; -}; -LazyJsonString.from = (object) => { - if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { - return object; - } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { - return LazyJsonString(String(object)); + if (!signingProperties.name) { + throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); + } + if (!signingProperties.in) { + throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); + } + if (!identity.apiKey) { + throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); + } + const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); + if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { + clonedRequest.query[signingProperties.name] = identity.apiKey; + } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { + clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; + } else { + throw new Error( + "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" + ); + } + return clonedRequest; } - return LazyJsonString(JSON.stringify(object)); }; -LazyJsonString.fromObject = LazyJsonString.from; -// src/submodules/serde/quote-header.ts -function quoteHeader(part) { - if (part.includes(",") || part.includes('"')) { - part = `"${part.replace(/"/g, '\\"')}"`; - } - return part; -} +// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts -// src/submodules/serde/split-every.ts -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; +var HttpBearerAuthSigner = class { + static { + __name(this, "HttpBearerAuthSigner"); } - 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 = ""; + async sign(httpRequest, identity, signingProperties) { + const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); + if (!identity.token) { + throw new Error("request could not be signed with `token` since the `token` is not defined"); } + clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; + return clonedRequest; } - if (currentSegment !== "") { - compoundSegments.push(currentSegment); +}; + +// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts +var NoAuthSigner = class { + static { + __name(this, "NoAuthSigner"); } - return compoundSegments; -} + async sign(httpRequest, identity, signingProperties) { + return httpRequest; + } +}; -// src/submodules/serde/split-header.ts -var splitHeader = (value) => { - const z = value.length; - const values = []; - let withinQuotes = false; - let prevChar = void 0; - let anchor = 0; - for (let i = 0; i < z; ++i) { - const char = value[i]; - switch (char) { - case `"`: - if (prevChar !== "\\") { - withinQuotes = !withinQuotes; - } - break; - case ",": - if (!withinQuotes) { - values.push(value.slice(anchor, i)); - anchor = i + 1; - } - break; - default: - } - prevChar = char; +// src/util-identity-and-auth/memoizeIdentityProvider.ts +var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); +var EXPIRATION_MS = 3e5; +var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); +var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); +var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + if (provider === void 0) { + return void 0; } - values.push(value.slice(anchor)); - return values.map((v) => { - v = v.trim(); - const z2 = v.length; - if (z2 < 2) { - return v; + const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async (options) => { + if (!pending) { + pending = normalizedProvider(options); } - if (v[0] === `"` && v[z2 - 1] === `"`) { - v = v.slice(1, z2 - 1); + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; } - return v.replace(/\\"/g, '"'); - }); -}; - -// src/submodules/serde/value/NumericValue.ts -var NumericValue = class _NumericValue { - constructor(string, type) { - this.string = string; - this.type = type; - let dot = 0; - for (let i = 0; i < string.length; ++i) { - const char = string.charCodeAt(i); - if (i === 0 && char === 45) { - continue; - } - if (char === 46) { - if (dot) { - throw new Error("@smithy/core/serde - NumericValue must contain at most one decimal point."); - } - dot = 1; - continue; - } - if (char < 48 || char > 57) { - throw new Error( - `@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".` - ); + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); } - } - } - toString() { - return this.string; + return resolved; + }; } - static [Symbol.hasInstance](object) { - if (!object || typeof object !== "object") { - return false; + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); } - const _nv = object; - const prototypeMatch = _NumericValue.prototype.isPrototypeOf(object.constructor?.prototype); - if (prototypeMatch) { - return prototypeMatch; + if (isConstant) { + return resolved; } - if (typeof _nv.string === "string" && typeof _nv.type === "string" && _nv.constructor?.name === "NumericValue") { - return true; + if (!requiresRefresh(resolved)) { + isConstant = true; + return resolved; } - return prototypeMatch; - } -}; -function nv(input) { - return new NumericValue(String(input), "bigDecimal"); -} + if (isExpired(resolved)) { + await coalesceProvider(options); + return resolved; + } + return resolved; + }; +}, "memoizeIdentityProvider"); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 7477: +/***/ 2241: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -59917,1494 +44903,1665 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES, - DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT, - ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN, - ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI, - ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI, - Endpoint: () => Endpoint, - fromContainerMetadata: () => fromContainerMetadata, - fromInstanceMetadata: () => fromInstanceMetadata, - getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint, - httpRequest: () => httpRequest, - providerConfigFromInit: () => providerConfigFromInit +// src/submodules/protocols/index.ts +var protocols_exports = {}; +__export(protocols_exports, { + FromStringShapeDeserializer: () => FromStringShapeDeserializer, + HttpBindingProtocol: () => HttpBindingProtocol, + HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, + HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, + RequestBuilder: () => RequestBuilder, + RpcProtocol: () => RpcProtocol, + ToStringShapeSerializer: () => ToStringShapeSerializer, + collectBody: () => collectBody, + determineTimestampFormat: () => determineTimestampFormat, + extendedEncodeURIComponent: () => extendedEncodeURIComponent, + requestBuilder: () => requestBuilder, + resolvedPath: () => resolvedPath }); -module.exports = __toCommonJS(src_exports); - -// src/fromContainerMetadata.ts +module.exports = __toCommonJS(protocols_exports); -var import_url = __nccwpck_require__(7310); +// src/submodules/protocols/collect-stream-body.ts +var import_util_stream = __nccwpck_require__(6607); +var collectBody = async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); + } + if (!streamBody) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + } + const fromContext = context.streamCollector(streamBody); + return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); +}; -// src/remoteProvider/httpRequest.ts -var import_property_provider = __nccwpck_require__(9721); -var import_buffer = __nccwpck_require__(4300); -var import_http = __nccwpck_require__(3685); -function httpRequest(options) { - return new Promise((resolve, reject) => { - const req = (0, import_http.request)({ - method: "GET", - ...options, - // Node.js http module doesn't accept hostname with square brackets - // Refs: https://github.com/nodejs/node/issues/39738 - hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1") - }); - req.on("error", (err) => { - reject(Object.assign(new import_property_provider.ProviderError("Unable to connect to instance metadata service"), err)); - req.destroy(); - }); - req.on("timeout", () => { - reject(new import_property_provider.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 import_property_provider.ProviderError("Error response received from instance metadata service"), { statusCode }) - ); - req.destroy(); - } - const chunks = []; - res.on("data", (chunk) => { - chunks.push(chunk); - }); - res.on("end", () => { - resolve(import_buffer.Buffer.concat(chunks)); - req.destroy(); - }); - }); - req.end(); +// src/submodules/protocols/extended-encode-uri-component.ts +function extendedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); }); } -__name(httpRequest, "httpRequest"); - -// src/remoteProvider/ImdsCredentials.ts -var isImdsCredentials = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string", "isImdsCredentials"); -var fromImdsCredentials = /* @__PURE__ */ __name((creds) => ({ - accessKeyId: creds.AccessKeyId, - secretAccessKey: creds.SecretAccessKey, - sessionToken: creds.Token, - expiration: new Date(creds.Expiration), - ...creds.AccountId && { accountId: creds.AccountId } -}), "fromImdsCredentials"); -// src/remoteProvider/RemoteProviderInit.ts -var DEFAULT_TIMEOUT = 1e3; -var DEFAULT_MAX_RETRIES = 0; -var providerConfigFromInit = /* @__PURE__ */ __name(({ - maxRetries = DEFAULT_MAX_RETRIES, - timeout = DEFAULT_TIMEOUT -}) => ({ maxRetries, timeout }), "providerConfigFromInit"); +// src/submodules/protocols/HttpBindingProtocol.ts +var import_schema2 = __nccwpck_require__(9826); +var import_serde = __nccwpck_require__(7669); +var import_protocol_http2 = __nccwpck_require__(4418); +var import_util_stream2 = __nccwpck_require__(6607); -// src/remoteProvider/retry.ts -var retry = /* @__PURE__ */ __name((toRetry, maxRetries) => { - let promise = toRetry(); - for (let i = 0; i < maxRetries; i++) { - promise = promise.catch(toRetry); +// src/submodules/protocols/HttpProtocol.ts +var import_schema = __nccwpck_require__(9826); +var import_protocol_http = __nccwpck_require__(4418); +var HttpProtocol = class { + constructor(options) { + this.options = options; } - return promise; -}, "retry"); - -// src/fromContainerMetadata.ts -var ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; -var ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; -var ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; -var fromContainerMetadata = /* @__PURE__ */ __name((init = {}) => { - const { timeout, maxRetries } = providerConfigFromInit(init); - return () => retry(async () => { - const requestOptions = await getCmdsUri({ logger: init.logger }); - const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); - if (!isImdsCredentials(credsResponse)) { - throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.", { - logger: init.logger - }); - } - return fromImdsCredentials(credsResponse); - }, maxRetries); -}, "fromContainerMetadata"); -var requestFromEcsImds = /* @__PURE__ */ __name(async (timeout, options) => { - if (process.env[ENV_CMDS_AUTH_TOKEN]) { - options.headers = { - ...options.headers, - Authorization: process.env[ENV_CMDS_AUTH_TOKEN] - }; + getRequestType() { + return import_protocol_http.HttpRequest; } - const buffer = await httpRequest({ - ...options, - timeout - }); - return buffer.toString(); -}, "requestFromEcsImds"); -var CMDS_IP = "169.254.170.2"; -var GREENGRASS_HOSTS = { - localhost: true, - "127.0.0.1": true -}; -var GREENGRASS_PROTOCOLS = { - "http:": true, - "https:": true -}; -var getCmdsUri = /* @__PURE__ */ __name(async ({ logger }) => { - if (process.env[ENV_CMDS_RELATIVE_URI]) { - return { - hostname: CMDS_IP, - path: process.env[ENV_CMDS_RELATIVE_URI] - }; + getResponseType() { + return import_protocol_http.HttpResponse; } - if (process.env[ENV_CMDS_FULL_URI]) { - const parsed = (0, import_url.parse)(process.env[ENV_CMDS_FULL_URI]); - if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { - throw new import_property_provider.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { - tryNextLink: false, - logger - }); + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + if (this.getPayloadCodec()) { + this.getPayloadCodec().setSerdeContext(serdeContext); } - if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { - throw new import_property_provider.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { - tryNextLink: false, - logger - }); + } + updateServiceEndpoint(request, endpoint) { + if ("url" in endpoint) { + request.protocol = endpoint.url.protocol; + request.hostname = endpoint.url.hostname; + request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; + request.path = endpoint.url.pathname; + request.fragment = endpoint.url.hash || void 0; + request.username = endpoint.url.username || void 0; + request.password = endpoint.url.password || void 0; + for (const [k, v] of endpoint.url.searchParams.entries()) { + if (!request.query) { + request.query = {}; + } + request.query[k] = v; + } + return request; + } else { + request.protocol = endpoint.protocol; + request.hostname = endpoint.hostname; + request.port = endpoint.port ? Number(endpoint.port) : void 0; + request.path = endpoint.path; + request.query = { + ...endpoint.query + }; + return request; + } + } + setHostPrefix(request, operationSchema, input) { + const operationNs = import_schema.NormalizedSchema.of(operationSchema); + const inputNs = import_schema.NormalizedSchema.of(operationSchema.input); + if (operationNs.getMergedTraits().endpoint) { + let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; + if (typeof hostPrefix === "string") { + const hostLabelInputs = [...inputNs.structIterator()].filter( + ([, member]) => member.getMergedTraits().hostLabel + ); + for (const [name] of hostLabelInputs) { + const replacement = input[name]; + if (typeof replacement !== "string") { + throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); + } + hostPrefix = hostPrefix.replace(`{${name}}`, replacement); + } + request.hostname = hostPrefix + request.hostname; + } } + } + deserializeMetadata(output) { return { - ...parsed, - port: parsed.port ? parseInt(parsed.port, 10) : void 0 + 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"] }; } - throw new import_property_provider.CredentialsProviderError( - `The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, - { - tryNextLink: false, - logger - } - ); -}, "getCmdsUri"); - -// src/fromInstanceMetadata.ts - - - -// src/error/InstanceMetadataV1FallbackError.ts - -var InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends import_property_provider.CredentialsProviderError { - constructor(message, tryNextLink = true) { - super(message, tryNextLink); - this.tryNextLink = tryNextLink; - this.name = "InstanceMetadataV1FallbackError"; - Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError.prototype); - } - static { - __name(this, "InstanceMetadataV1FallbackError"); + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + return []; } }; -// src/utils/getInstanceMetadataEndpoint.ts -var import_node_config_provider = __nccwpck_require__(3461); -var import_url_parser = __nccwpck_require__(4681); - -// src/config/Endpoint.ts -var Endpoint = /* @__PURE__ */ ((Endpoint2) => { - Endpoint2["IPv4"] = "http://169.254.169.254"; - Endpoint2["IPv6"] = "http://[fd00:ec2::254]"; - return Endpoint2; -})(Endpoint || {}); - -// src/config/EndpointConfigOptions.ts -var ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; -var CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; -var ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME], - configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME], - default: void 0 -}; - -// src/config/EndpointMode.ts -var EndpointMode = /* @__PURE__ */ ((EndpointMode2) => { - EndpointMode2["IPv4"] = "IPv4"; - EndpointMode2["IPv6"] = "IPv6"; - return EndpointMode2; -})(EndpointMode || {}); - -// src/config/EndpointModeConfigOptions.ts -var ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; -var CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; -var ENDPOINT_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME], - configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME], - default: "IPv4" /* IPv4 */ -}; - -// src/utils/getInstanceMetadataEndpoint.ts -var getInstanceMetadataEndpoint = /* @__PURE__ */ __name(async () => (0, import_url_parser.parseUrl)(await getFromEndpointConfig() || await getFromEndpointModeConfig()), "getInstanceMetadataEndpoint"); -var getFromEndpointConfig = /* @__PURE__ */ __name(async () => (0, import_node_config_provider.loadConfig)(ENDPOINT_CONFIG_OPTIONS)(), "getFromEndpointConfig"); -var getFromEndpointModeConfig = /* @__PURE__ */ __name(async () => { - const endpointMode = await (0, import_node_config_provider.loadConfig)(ENDPOINT_MODE_CONFIG_OPTIONS)(); - switch (endpointMode) { - case "IPv4" /* IPv4 */: - return "http://169.254.169.254" /* IPv4 */; - case "IPv6" /* IPv6 */: - return "http://[fd00:ec2::254]" /* IPv6 */; - default: - throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`); - } -}, "getFromEndpointModeConfig"); - -// src/utils/getExtendedInstanceMetadataCredentials.ts -var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; -var STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; -var STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; -var getExtendedInstanceMetadataCredentials = /* @__PURE__ */ __name((credentials, logger) => { - 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 * 1e3); - 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)}. -For more information, please visit: ` + STATIC_STABILITY_DOC_URL - ); - const originalExpiration = credentials.originalExpiration ?? credentials.expiration; - return { - ...credentials, - ...originalExpiration ? { originalExpiration } : {}, - expiration: newExpiration - }; -}, "getExtendedInstanceMetadataCredentials"); - -// src/utils/staticStabilityProvider.ts -var staticStabilityProvider = /* @__PURE__ */ __name((provider, options = {}) => { - const logger = options?.logger || console; - let pastCredentials; - return async () => { - let credentials; - try { - credentials = await provider(); - if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { - credentials = getExtendedInstanceMetadataCredentials(credentials, logger); +// src/submodules/protocols/HttpBindingProtocol.ts +var HttpBindingProtocol = class extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const input = { + ..._input ?? {} + }; + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = import_schema2.NormalizedSchema.of(operationSchema?.input); + const schema = ns.getSchema(); + let hasNonHttpBindingMember = false; + let payload; + const request = new import_protocol_http2.HttpRequest({ + protocol: "", + hostname: "", + port: void 0, + path: "", + fragment: void 0, + query, + headers, + body: void 0 + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + const opTraits = import_schema2.NormalizedSchema.translateTraits(operationSchema.traits); + if (opTraits.http) { + request.method = opTraits.http[0]; + const [path, search] = opTraits.http[1].split("?"); + if (request.path == "/") { + request.path = path; + } else { + request.path += path; + } + const traitSearchParams = new URLSearchParams(search ?? ""); + Object.assign(query, Object.fromEntries(traitSearchParams)); } - } catch (e) { - if (pastCredentials) { - logger.warn("Credential renew failed: ", e); - credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger); + } + for (const [memberName, memberNs] of ns.structIterator()) { + const memberTraits = memberNs.getMergedTraits() ?? {}; + const inputMemberValue = input[memberName]; + if (inputMemberValue == null) { + continue; + } + if (memberTraits.httpPayload) { + const isStreaming = memberNs.isStreaming(); + if (isStreaming) { + const isEventStream = memberNs.isStructSchema(); + if (isEventStream) { + throw new Error("serialization of event streams is not yet implemented"); + } else { + payload = inputMemberValue; + } + } else { + serializer.write(memberNs, inputMemberValue); + payload = serializer.flush(); + } + delete input[memberName]; + } else if (memberTraits.httpLabel) { + serializer.write(memberNs, inputMemberValue); + const replacement = serializer.flush(); + if (request.path.includes(`{${memberName}+}`)) { + request.path = request.path.replace( + `{${memberName}+}`, + replacement.split("/").map(extendedEncodeURIComponent).join("/") + ); + } else if (request.path.includes(`{${memberName}}`)) { + request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); + } + delete input[memberName]; + } else if (memberTraits.httpHeader) { + serializer.write(memberNs, inputMemberValue); + headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); + delete input[memberName]; + } else if (typeof memberTraits.httpPrefixHeaders === "string") { + for (const [key, val] of Object.entries(inputMemberValue)) { + const amalgam = memberTraits.httpPrefixHeaders + key; + serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); + headers[amalgam.toLowerCase()] = serializer.flush(); + } + delete input[memberName]; + } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { + this.serializeQuery(memberNs, inputMemberValue, query); + delete input[memberName]; } else { - throw e; + hasNonHttpBindingMember = true; } } - pastCredentials = credentials; - return credentials; - }; -}, "staticStabilityProvider"); - -// src/fromInstanceMetadata.ts -var IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; -var IMDS_TOKEN_PATH = "/latest/api/token"; -var AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; -var PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; -var X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; -var fromInstanceMetadata = /* @__PURE__ */ __name((init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger }), "fromInstanceMetadata"); -var getInstanceMetadataProvider = /* @__PURE__ */ __name((init = {}) => { - let disableFetchToken = false; - const { logger, profile } = init; - const { timeout, maxRetries } = providerConfigFromInit(init); - const getCredentials = /* @__PURE__ */ __name(async (maxRetries2, options) => { - const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null; - if (isImdsV1Fallback) { - let fallbackBlockedFromProfile = false; - let fallbackBlockedFromProcessEnv = false; - const configValue = await (0, import_node_config_provider.loadConfig)( - { - environmentVariableSelector: (env) => { - const envValue = env[AWS_EC2_METADATA_V1_DISABLED]; - fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; - if (envValue === void 0) { - throw new import_property_provider.CredentialsProviderError( - `${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, - { logger: init.logger } - ); - } - return fallbackBlockedFromProcessEnv; - }, - configFileSelector: (profile2) => { - const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED]; - fallbackBlockedFromProfile = !!profileValue && profileValue !== "false"; - return fallbackBlockedFromProfile; - }, - default: false - }, - { - profile + if (hasNonHttpBindingMember && input) { + serializer.write(schema, input); + payload = serializer.flush(); + } + request.headers = headers; + request.query = query; + request.body = payload; + return request; + } + serializeQuery(ns, data, query) { + const serializer = this.serializer; + const traits = ns.getMergedTraits(); + if (traits.httpQueryParams) { + for (const [key, val] of Object.entries(data)) { + if (!(key in query)) { + this.serializeQuery( + import_schema2.NormalizedSchema.of([ + ns.getValueSchema(), + { + // We pass on the traits to the sub-schema + // because we are still in the process of serializing the map itself. + ...traits, + httpQuery: key, + httpQueryParams: void 0 + } + ]), + val, + query + ); } - )(); - 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( - `AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join( - ", " - )}].` - ); } + return; } - const imdsProfile = (await retry(async () => { - let profile2; - try { - profile2 = await getProfile(options); - } catch (err) { - if (err.statusCode === 401) { - disableFetchToken = false; + if (ns.isListSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const buffer = []; + for (const item of data) { + serializer.write([ns.getValueSchema(), traits], item); + const serializable = serializer.flush(); + if (sparse || serializable !== void 0) { + buffer.push(serializable); } - throw err; } - return profile2; - }, maxRetries2)).trim(); - return retry(async () => { - let creds; - try { - creds = await getCredentialsFromProfile(imdsProfile, options, init); - } catch (err) { - if (err.statusCode === 401) { - disableFetchToken = false; + query[traits.httpQuery] = buffer; + } else { + serializer.write([ns, traits], data); + query[traits.httpQuery] = serializer.flush(); + } + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = import_schema2.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(import_schema2.SCHEMA.DOCUMENT, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); + if (nonHttpBindingMembers.length) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + const dataFromBody = await deserializer.read(ns, bytes); + for (const member of nonHttpBindingMembers) { + dataObject[member] = dataFromBody[member]; } - throw err; } - return creds; - }, maxRetries2); - }, "getCredentials"); - return async () => { - const endpoint = await getInstanceMetadataEndpoint(); - if (disableFetchToken) { - logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)"); - return getCredentials(maxRetries, { ...endpoint, timeout }); + } + const output = { + $metadata: this.deserializeMetadata(response), + ...dataObject + }; + return output; + } + async deserializeHttpMessage(schema, context, response, arg4, arg5) { + let dataObject; + if (arg4 instanceof Set) { + dataObject = arg5; } else { - let token; - try { - token = (await getMetadataToken({ ...endpoint, timeout })).toString(); - } catch (error) { - if (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; + dataObject = arg4; + } + const deserializer = this.deserializer; + const ns = import_schema2.NormalizedSchema.of(schema); + const nonHttpBindingMembers = []; + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMemberTraits(); + if (memberTraits.httpPayload) { + const isStreaming = memberSchema.isStreaming(); + if (isStreaming) { + const isEventStream = memberSchema.isStructSchema(); + if (isEventStream) { + const context2 = this.serdeContext; + if (!context2.eventStreamMarshaller) { + throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); + } + const memberSchemas = memberSchema.getMemberSchemas(); + dataObject[memberName] = context2.eventStreamMarshaller.deserialize(response.body, async (event) => { + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + if (unionMember in memberSchemas) { + const eventStreamSchema = memberSchemas[unionMember]; + return { + [unionMember]: await deserializer.read(eventStreamSchema, event[unionMember].body) + }; + } else { + return { + $unknown: event + }; + } + }); + } else { + dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); + } + } else if (response.body) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + dataObject[memberName] = await deserializer.read(memberSchema, bytes); + } } - logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)"); - return getCredentials(maxRetries, { ...endpoint, timeout }); + } else if (memberTraits.httpHeader) { + const key = String(memberTraits.httpHeader).toLowerCase(); + const value = response.headers[key]; + if (null != value) { + if (memberSchema.isListSchema()) { + const headerListValueSchema = memberSchema.getValueSchema(); + let sections; + if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === import_schema2.SCHEMA.TIMESTAMP_DEFAULT) { + sections = (0, import_serde.splitEvery)(value, ",", 2); + } else { + sections = (0, import_serde.splitHeader)(value); + } + const list = []; + for (const section of sections) { + list.push(await deserializer.read([headerListValueSchema, { httpHeader: key }], section.trim())); + } + dataObject[memberName] = list; + } else { + dataObject[memberName] = await deserializer.read(memberSchema, value); + } + } + } else if (memberTraits.httpPrefixHeaders !== void 0) { + dataObject[memberName] = {}; + for (const [header, value] of Object.entries(response.headers)) { + if (header.startsWith(memberTraits.httpPrefixHeaders)) { + dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read( + [memberSchema.getValueSchema(), { httpHeader: header }], + value + ); + } + } + } else if (memberTraits.httpResponseCode) { + dataObject[memberName] = response.statusCode; + } else { + nonHttpBindingMembers.push(memberName); } - return getCredentials(maxRetries, { - ...endpoint, - headers: { - [X_AWS_EC2_METADATA_TOKEN]: token - }, - timeout - }); } - }; -}, "getInstanceMetadataProvider"); -var getMetadataToken = /* @__PURE__ */ __name(async (options) => httpRequest({ - ...options, - path: IMDS_TOKEN_PATH, - method: "PUT", - headers: { - "x-aws-ec2-metadata-token-ttl-seconds": "21600" + return nonHttpBindingMembers; + } +}; + +// src/submodules/protocols/RpcProtocol.ts +var import_schema3 = __nccwpck_require__(9826); +var import_protocol_http3 = __nccwpck_require__(4418); +var RpcProtocol = class extends HttpProtocol { + async serializeRequest(operationSchema, input, context) { + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = import_schema3.NormalizedSchema.of(operationSchema?.input); + const schema = ns.getSchema(); + let payload; + const request = new import_protocol_http3.HttpRequest({ + protocol: "", + hostname: "", + port: void 0, + path: "/", + fragment: void 0, + query, + headers, + body: void 0 + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + } + const _input = { + ...input + }; + if (input) { + serializer.write(schema, _input); + payload = serializer.flush(); + } + request.headers = headers; + request.query = query; + request.body = payload; + request.method = "POST"; + return request; } -}), "getMetadataToken"); -var getProfile = /* @__PURE__ */ __name(async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(), "getProfile"); -var getCredentialsFromProfile = /* @__PURE__ */ __name(async (profile, options, init) => { - const credentialsResponse = JSON.parse( - (await httpRequest({ - ...options, - path: IMDS_PATH + profile - })).toString() - ); - if (!isImdsCredentials(credentialsResponse)) { - throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.", { - logger: init.logger - }); + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = import_schema3.NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes2 = await collectBody(response.body, context); + if (bytes2.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(import_schema3.SCHEMA.DOCUMENT, bytes2)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes)); + } + const output = { + $metadata: this.deserializeMetadata(response), + ...dataObject + }; + return output; } - return fromImdsCredentials(credentialsResponse); -}, "getCredentialsFromProfile"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), +}; -/***/ 6459: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// src/submodules/protocols/requestBuilder.ts +var import_protocol_http4 = __nccwpck_require__(4418); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/submodules/protocols/resolve-path.ts +var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { + if (input != null && input[memberName] !== void 0) { + const labelValue = labelValueProvider(); + if (labelValue.length <= 0) { + throw new Error("Empty value provided for input HTTP label: " + memberName + "."); + } + resolvedPath2 = resolvedPath2.replace( + uriLabel, + isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) + ); + } else { + throw new Error("No value provided for input HTTP label: " + memberName + "."); } - return to; + return resolvedPath2; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - EventStreamCodec: () => EventStreamCodec, - HeaderMarshaller: () => HeaderMarshaller, - Int64: () => Int64, - MessageDecoderStream: () => MessageDecoderStream, - MessageEncoderStream: () => MessageEncoderStream, - SmithyMessageDecoderStream: () => SmithyMessageDecoderStream, - SmithyMessageEncoderStream: () => SmithyMessageEncoderStream -}); -module.exports = __toCommonJS(src_exports); - -// src/EventStreamCodec.ts -var import_crc322 = __nccwpck_require__(8408); -// src/HeaderMarshaller.ts +// src/submodules/protocols/requestBuilder.ts +function requestBuilder(input, context) { + return new RequestBuilder(input, context); +} +var RequestBuilder = class { + constructor(input, context) { + this.input = input; + this.context = context; + this.query = {}; + this.method = ""; + this.headers = {}; + this.path = ""; + this.body = null; + this.hostname = ""; + this.resolvePathStack = []; + } + async build() { + const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); + this.path = basePath; + for (const resolvePath of this.resolvePathStack) { + resolvePath(this.path); + } + return new import_protocol_http4.HttpRequest({ + protocol, + hostname: this.hostname || hostname, + port, + method: this.method, + path: this.path, + query: this.query, + body: this.body, + headers: this.headers + }); + } + /** + * Brevity setter for "hostname". + */ + hn(hostname) { + this.hostname = hostname; + return this; + } + /** + * Brevity initial builder for "basepath". + */ + bp(uriLabel) { + this.resolvePathStack.push((basePath) => { + this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; + }); + return this; + } + /** + * Brevity incremental builder for "path". + */ + p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { + this.resolvePathStack.push((path) => { + this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); + }); + return this; + } + /** + * Brevity setter for "headers". + */ + h(headers) { + this.headers = headers; + return this; + } + /** + * Brevity setter for "query". + */ + q(query) { + this.query = query; + return this; + } + /** + * Brevity setter for "body". + */ + b(body) { + this.body = body; + return this; + } + /** + * Brevity setter for "method". + */ + m(method) { + this.method = method; + return this; + } +}; +// src/submodules/protocols/serde/FromStringShapeDeserializer.ts +var import_schema5 = __nccwpck_require__(9826); +var import_serde2 = __nccwpck_require__(7669); +var import_util_base64 = __nccwpck_require__(5600); +var import_util_utf8 = __nccwpck_require__(1895); -// src/Int64.ts -var import_util_hex_encoding = __nccwpck_require__(5364); -var Int64 = class _Int64 { - constructor(bytes) { - this.bytes = bytes; - if (bytes.byteLength !== 8) { - throw new Error("Int64 buffers must be exactly 8 bytes"); +// src/submodules/protocols/serde/determineTimestampFormat.ts +var import_schema4 = __nccwpck_require__(9826); +function determineTimestampFormat(ns, settings) { + if (settings.timestampFormat.useTrait) { + if (ns.isTimestampSchema() && (ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { + return ns.getSchema(); } } - static { - __name(this, "Int64"); + const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); + const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? import_schema4.SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; + return bindingFormat ?? settings.timestampFormat.default; +} + +// src/submodules/protocols/serde/FromStringShapeDeserializer.ts +var FromStringShapeDeserializer = class { + constructor(settings) { + this.settings = settings; } - static fromNumber(number) { - if (number > 9223372036854776e3 || number < -9223372036854776e3) { - throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } + read(_schema, data) { + const ns = import_schema5.NormalizedSchema.of(_schema); + if (ns.isListSchema()) { + return (0, import_serde2.splitHeader)(data).map((item) => this.read(ns.getValueSchema(), item)); } - 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 (ns.isBlobSchema()) { + return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data); } - if (number < 0) { - negate(bytes); + if (ns.isTimestampSchema()) { + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case import_schema5.SCHEMA.TIMESTAMP_DATE_TIME: + return (0, import_serde2.parseRfc3339DateTimeWithOffset)(data); + case import_schema5.SCHEMA.TIMESTAMP_HTTP_DATE: + return (0, import_serde2.parseRfc7231DateTime)(data); + case import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + return (0, import_serde2.parseEpochTimestamp)(data); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", data); + return new Date(data); + } } - return new _Int64(bytes); - } - /** - * Called implicitly by infix arithmetic operators. - */ - valueOf() { - const bytes = this.bytes.slice(0); - const negative = bytes[0] & 128; - if (negative) { - negate(bytes); + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = data; + if (mediaType) { + if (ns.getMergedTraits().httpHeader) { + intermediateValue = this.base64ToUtf8(intermediateValue); + } + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = import_serde2.LazyJsonString.from(intermediateValue); + } + return intermediateValue; + } } - return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); + switch (true) { + case ns.isNumericSchema(): + return Number(data); + case ns.isBigIntegerSchema(): + return BigInt(data); + case ns.isBigDecimalSchema(): + return new import_serde2.NumericValue(data, "bigDecimal"); + case ns.isBooleanSchema(): + return String(data).toLowerCase() === "true"; + } + return data; } - toString() { - return String(this.valueOf()); + base64ToUtf8(base64String) { + return (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); } }; -function negate(bytes) { - for (let i = 0; i < 8; i++) { - bytes[i] ^= 255; - } - for (let i = 7; i > -1; i--) { - bytes[i]++; - if (bytes[i] !== 0) - break; - } -} -__name(negate, "negate"); -// src/HeaderMarshaller.ts -var HeaderMarshaller = class { - constructor(toUtf8, fromUtf8) { - this.toUtf8 = toUtf8; - this.fromUtf8 = fromUtf8; +// src/submodules/protocols/serde/HttpInterceptingShapeDeserializer.ts +var import_schema6 = __nccwpck_require__(9826); +var import_util_utf82 = __nccwpck_require__(1895); +var HttpInterceptingShapeDeserializer = class { + constructor(codecDeserializer, codecSettings) { + this.codecDeserializer = codecDeserializer; + this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); } - static { - __name(this, "HeaderMarshaller"); + setSerdeContext(serdeContext) { + this.stringDeserializer.setSerdeContext(serdeContext); + this.codecDeserializer.setSerdeContext(serdeContext); + this.serdeContext = serdeContext; } - 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])); + read(schema, data) { + const ns = import_schema6.NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + const toString = this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8; + if (traits.httpHeader || traits.httpResponseCode) { + return this.stringDeserializer.read(ns, toString(data)); } - 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; + if (traits.httpPayload) { + if (ns.isBlobSchema()) { + const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf82.fromUtf8; + if (typeof data === "string") { + return toBytes(data); + } + return data; + } else if (ns.isStringSchema()) { + if ("byteLength" in data) { + return toString(data); + } + return data; + } } - return out; + return this.codecDeserializer.read(ns, data); } - formatHeaderValue(header) { - switch (header.type) { - case "boolean": - return Uint8Array.from([header.value ? 0 /* boolTrue */ : 1 /* boolFalse */]); - case "byte": - return Uint8Array.from([2 /* byte */, header.value]); - case "short": - const shortView = new DataView(new ArrayBuffer(3)); - shortView.setUint8(0, 3 /* short */); - shortView.setInt16(1, header.value, false); - return new Uint8Array(shortView.buffer); - case "integer": - const intView = new DataView(new ArrayBuffer(5)); - intView.setUint8(0, 4 /* integer */); - intView.setInt32(1, header.value, false); - return new Uint8Array(intView.buffer); - case "long": - const longBytes = new Uint8Array(9); - longBytes[0] = 5 /* long */; - longBytes.set(header.value.bytes, 1); - return longBytes; - case "binary": - const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); - binView.setUint8(0, 6 /* byteArray */); - binView.setUint16(1, header.value.byteLength, false); - const binBytes = new Uint8Array(binView.buffer); - binBytes.set(header.value, 3); - return binBytes; +}; + +// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts +var import_schema8 = __nccwpck_require__(9826); + +// src/submodules/protocols/serde/ToStringShapeSerializer.ts +var import_schema7 = __nccwpck_require__(9826); +var import_serde3 = __nccwpck_require__(7669); +var import_util_base642 = __nccwpck_require__(5600); +var ToStringShapeSerializer = class { + constructor(settings) { + this.settings = settings; + this.stringBuffer = ""; + this.serdeContext = void 0; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } + write(schema, value) { + const ns = import_schema7.NormalizedSchema.of(schema); + switch (typeof value) { + case "object": + if (value === null) { + this.stringBuffer = "null"; + return; + } + if (ns.isTimestampSchema()) { + if (!(value instanceof Date)) { + throw new Error( + `@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}` + ); + } + const format = determineTimestampFormat(ns, this.settings); + switch (format) { + case import_schema7.SCHEMA.TIMESTAMP_DATE_TIME: + this.stringBuffer = value.toISOString().replace(".000Z", "Z"); + break; + case import_schema7.SCHEMA.TIMESTAMP_HTTP_DATE: + this.stringBuffer = (0, import_serde3.dateToUtcString)(value); + break; + case import_schema7.SCHEMA.TIMESTAMP_EPOCH_SECONDS: + this.stringBuffer = String(value.getTime() / 1e3); + break; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + this.stringBuffer = String(value.getTime() / 1e3); + } + return; + } + if (ns.isBlobSchema() && "byteLength" in value) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); + return; + } + if (ns.isListSchema() && Array.isArray(value)) { + let buffer = ""; + for (const item of value) { + this.write([ns.getValueSchema(), ns.getMergedTraits()], item); + const headerItem = this.flush(); + const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : (0, import_serde3.quoteHeader)(headerItem); + if (buffer !== "") { + buffer += ", "; + } + buffer += serialized; + } + this.stringBuffer = buffer; + return; + } + this.stringBuffer = JSON.stringify(value, null, 2); + break; case "string": - const utf8Bytes = this.fromUtf8(header.value); - const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); - strView.setUint8(0, 7 /* string */); - 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 /* timestamp */; - tsBytes.set(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 mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = value; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = import_serde3.LazyJsonString.from(intermediateValue); + } + if (ns.getMergedTraits().httpHeader) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); + return; + } } - const uuidBytes = new Uint8Array(17); - uuidBytes[0] = 9 /* uuid */; - uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1); - return uuidBytes; + this.stringBuffer = value; + break; + default: + this.stringBuffer = String(value); + } + } + flush() { + const buffer = this.stringBuffer; + this.stringBuffer = ""; + return buffer; + } +}; + +// src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts +var HttpInterceptingShapeSerializer = class { + constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { + this.codecSerializer = codecSerializer; + this.stringSerializer = stringSerializer; + } + setSerdeContext(serdeContext) { + this.codecSerializer.setSerdeContext(serdeContext); + this.stringSerializer.setSerdeContext(serdeContext); + } + write(schema, value) { + const ns = import_schema8.NormalizedSchema.of(schema); + const traits = ns.getMergedTraits(); + if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { + this.stringSerializer.write(ns, value); + this.buffer = this.stringSerializer.flush(); + return; } + return this.codecSerializer.write(ns, value); } - 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 /* boolTrue */: - out[name] = { - type: BOOLEAN_TAG, - value: true - }; - break; - case 1 /* boolFalse */: - out[name] = { - type: BOOLEAN_TAG, - value: false - }; - break; - case 2 /* byte */: - out[name] = { - type: BYTE_TAG, - value: headers.getInt8(position++) - }; - break; - case 3 /* short */: - out[name] = { - type: SHORT_TAG, - value: headers.getInt16(position, false) - }; - position += 2; - break; - case 4 /* integer */: - out[name] = { - type: INT_TAG, - value: headers.getInt32(position, false) - }; - position += 4; - break; - case 5 /* long */: - out[name] = { - type: LONG_TAG, - value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)) - }; - position += 8; - break; - case 6 /* byteArray */: - 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 /* string */: - 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 /* timestamp */: - out[name] = { - type: TIMESTAMP_TAG, - value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()) - }; - position += 8; - break; - case 9 /* uuid */: - const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); - position += 16; - out[name] = { - type: UUID_TAG, - value: `${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(0, 4))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(4, 6))}-${(0, import_util_hex_encoding.toHex)( - uuidBytes.subarray(6, 8) - )}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(8, 10))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(10))}` - }; - break; - default: - throw new Error(`Unrecognized header type tag`); - } + flush() { + if (this.buffer !== void 0) { + const buffer = this.buffer; + this.buffer = void 0; + return buffer; } - return out; + return this.codecSerializer.flush(); } }; -var BOOLEAN_TAG = "boolean"; -var BYTE_TAG = "byte"; -var SHORT_TAG = "short"; -var INT_TAG = "integer"; -var LONG_TAG = "long"; -var BINARY_TAG = "binary"; -var STRING_TAG = "string"; -var TIMESTAMP_TAG = "timestamp"; -var UUID_TAG = "uuid"; -var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); -// src/splitMessage.ts -var import_crc32 = __nccwpck_require__(8408); -var PRELUDE_MEMBER_LENGTH = 4; -var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; -var CHECKSUM_LENGTH = 4; -var 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"); + +/***/ }), + +/***/ 9826: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - 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 import_crc32.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()})` - ); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/submodules/schema/index.ts +var schema_exports = {}; +__export(schema_exports, { + ErrorSchema: () => ErrorSchema, + ListSchema: () => ListSchema, + MapSchema: () => MapSchema, + NormalizedSchema: () => NormalizedSchema, + OperationSchema: () => OperationSchema, + SCHEMA: () => SCHEMA, + Schema: () => Schema, + SimpleSchema: () => SimpleSchema, + StructureSchema: () => StructureSchema, + TypeRegistry: () => TypeRegistry, + deref: () => deref, + deserializerMiddlewareOption: () => deserializerMiddlewareOption, + error: () => error, + getSchemaSerdePlugin: () => getSchemaSerdePlugin, + list: () => list, + map: () => map, + op: () => op, + serializerMiddlewareOption: () => serializerMiddlewareOption, + sim: () => sim, + struct: () => struct +}); +module.exports = __toCommonJS(schema_exports); + +// src/submodules/schema/deref.ts +var deref = (schemaRef) => { + if (typeof schemaRef === "function") { + return schemaRef(); } - 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 schemaRef; +}; + +// src/submodules/schema/middleware/schemaDeserializationMiddleware.ts +var import_protocol_http = __nccwpck_require__(4418); +var import_util_middleware = __nccwpck_require__(2390); +var schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { + const { response } = await next(args); + const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); + try { + const parsed = await config.protocol.deserializeResponse( + operationSchema, + { + ...config, + ...context + }, + response ); + return { + response, + output: parsed + }; + } catch (error2) { + Object.defineProperty(error2, "$response", { + value: response + }); + if (!("$metadata" in error2)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error2.message += "\n " + hint; + } catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); + } + } + if (typeof error2.$responseBodyText !== "undefined") { + if (error2.$response) { + error2.$response.body = error2.$responseBodyText; + } + } + try { + if (import_protocol_http.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error2.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + }; + } + } catch (e) { + } + } + throw error2; } +}; +var findHeader = (pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}; + +// src/submodules/schema/middleware/schemaSerializationMiddleware.ts +var import_util_middleware2 = __nccwpck_require__(2390); +var schemaSerializationMiddleware = (config) => (next, context) => async (args) => { + const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); + const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint; + const request = await config.protocol.serializeRequest(operationSchema, args.input, { + ...config, + ...context, + endpoint + }); + return next({ + ...args, + request + }); +}; + +// src/submodules/schema/middleware/getSchemaSerdePlugin.ts +var deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true +}; +var serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true +}; +function getSchemaSerdePlugin(config) { 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) - ) + applyToStack: (commandStack) => { + commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); + commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); + config.protocol.setSerdeContext(config); + } }; } -__name(splitMessage, "splitMessage"); -// src/EventStreamCodec.ts -var EventStreamCodec = class { - static { - __name(this, "EventStreamCodec"); - } - constructor(toUtf8, fromUtf8) { - this.headerMarshaller = new HeaderMarshaller(toUtf8, fromUtf8); - this.messageBuffer = []; - this.isEndOfStream = false; +// src/submodules/schema/TypeRegistry.ts +var TypeRegistry = class _TypeRegistry { + constructor(namespace, schemas = /* @__PURE__ */ new Map()) { + this.namespace = namespace; + this.schemas = schemas; } - feed(message) { - this.messageBuffer.push(this.decode(message)); + static { + this.registries = /* @__PURE__ */ new Map(); } - endOfStream() { - this.isEndOfStream = true; + /** + * @param namespace - specifier. + * @returns the schema for that namespace, creating it if necessary. + */ + static for(namespace) { + if (!_TypeRegistry.registries.has(namespace)) { + _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); + } + return _TypeRegistry.registries.get(namespace); } - getMessage() { - const message = this.messageBuffer.pop(); - const isEndOfStream = this.isEndOfStream; - return { - getMessage() { - return message; - }, - isEndOfStream() { - return isEndOfStream; - } - }; + /** + * Adds the given schema to a type registry with the same namespace. + * + * @param shapeId - to be registered. + * @param schema - to be registered. + */ + register(shapeId, schema) { + const qualifiedName = this.normalizeShapeId(shapeId); + const registry = _TypeRegistry.for(this.getNamespace(shapeId)); + registry.schemas.set(qualifiedName, schema); } - getAvailableMessages() { - const messages = this.messageBuffer; - this.messageBuffer = []; - const isEndOfStream = this.isEndOfStream; - return { - getMessages() { - return messages; - }, - isEndOfStream() { - return isEndOfStream; - } - }; + /** + * @param shapeId - query. + * @returns the schema. + */ + getSchema(shapeId) { + const id = this.normalizeShapeId(shapeId); + if (!this.schemas.has(id)) { + throw new Error(`@smithy/core/schema - schema not found for ${id}`); + } + return this.schemas.get(id); } /** - * Convert a structured JavaScript object with tagged headers into a binary - * event stream message. + * The smithy-typescript code generator generates a synthetic (i.e. unmodeled) base exception, + * because generated SDKs before the introduction of schemas have the notion of a ServiceBaseException, which + * is unique per service/model. + * + * This is generated under a unique prefix that is combined with the service namespace, and this + * method is used to retrieve it. + * + * The base exception synthetic schema is used when an error is returned by a service, but we cannot + * determine what existing schema to use to deserialize it. + * + * @returns the synthetic base exception of the service namespace associated with this registry instance. */ - 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 import_crc322.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; + getBaseException() { + for (const [id, schema] of this.schemas.entries()) { + if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { + return schema; + } + } + return void 0; } /** - * Convert a binary event stream message into a JavaScript object with an - * opaque, binary body and tagged, parsed headers. + * @param predicate - criterion. + * @returns a schema in this registry matching the predicate. */ - decode(message) { - const { headers, body } = splitMessage(message); - return { headers: this.headerMarshaller.parse(headers), body }; + find(predicate) { + return [...this.schemas.values()].find(predicate); } /** - * Convert a structured JavaScript object with tagged headers into a binary - * event stream message header. + * Unloads the current TypeRegistry. */ - formatHeaders(rawHeaders) { - return this.headerMarshaller.format(rawHeaders); + destroy() { + _TypeRegistry.registries.delete(this.namespace); + this.schemas.clear(); + } + normalizeShapeId(shapeId) { + if (shapeId.includes("#")) { + return shapeId; + } + return this.namespace + "#" + shapeId; + } + getNamespace(shapeId) { + return this.normalizeShapeId(shapeId).split("#")[0]; } }; -// src/MessageDecoderStream.ts -var MessageDecoderStream = class { - constructor(options) { - this.options = options; +// src/submodules/schema/schemas/Schema.ts +var Schema = class { + constructor(name, traits) { + this.name = name; + this.traits = traits; + } +}; + +// src/submodules/schema/schemas/ListSchema.ts +var ListSchema = class _ListSchema extends Schema { + constructor(name, traits, valueSchema) { + super(name, traits); + this.name = name; + this.traits = traits; + this.valueSchema = valueSchema; + this.symbol = _ListSchema.symbol; } static { - __name(this, "MessageDecoderStream"); + this.symbol = Symbol.for("@smithy/core/schema::ListSchema"); } - [Symbol.asyncIterator]() { - return this.asyncIterator(); + static [Symbol.hasInstance](lhs) { + const isPrototype = _ListSchema.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const list2 = lhs; + return list2.symbol === _ListSchema.symbol; + } + return isPrototype; } - async *asyncIterator() { - for await (const bytes of this.options.inputStream) { - const decoded = this.options.decoder.decode(bytes); - yield decoded; +}; +function list(namespace, name, traits = {}, valueSchema) { + const schema = new ListSchema( + namespace + "#" + name, + traits, + typeof valueSchema === "function" ? valueSchema() : valueSchema + ); + TypeRegistry.for(namespace).register(name, schema); + return schema; +} + +// src/submodules/schema/schemas/MapSchema.ts +var MapSchema = class _MapSchema extends Schema { + constructor(name, traits, keySchema, valueSchema) { + super(name, traits); + this.name = name; + this.traits = traits; + this.keySchema = keySchema; + this.valueSchema = valueSchema; + this.symbol = _MapSchema.symbol; + } + static { + this.symbol = Symbol.for("@smithy/core/schema::MapSchema"); + } + static [Symbol.hasInstance](lhs) { + const isPrototype = _MapSchema.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const map2 = lhs; + return map2.symbol === _MapSchema.symbol; } + return isPrototype; + } +}; +function map(namespace, name, traits = {}, keySchema, valueSchema) { + const schema = new MapSchema( + namespace + "#" + name, + traits, + keySchema, + typeof valueSchema === "function" ? valueSchema() : valueSchema + ); + TypeRegistry.for(namespace).register(name, schema); + return schema; +} + +// src/submodules/schema/schemas/OperationSchema.ts +var OperationSchema = class extends Schema { + constructor(name, traits, input, output) { + super(name, traits); + this.name = name; + this.traits = traits; + this.input = input; + this.output = output; } }; +function op(namespace, name, traits = {}, input, output) { + const schema = new OperationSchema(namespace + "#" + name, traits, input, output); + TypeRegistry.for(namespace).register(name, schema); + return schema; +} -// src/MessageEncoderStream.ts -var MessageEncoderStream = class { - constructor(options) { - this.options = options; +// src/submodules/schema/schemas/StructureSchema.ts +var StructureSchema = class _StructureSchema extends Schema { + constructor(name, traits, memberNames, memberList) { + super(name, traits); + this.name = name; + this.traits = traits; + this.memberNames = memberNames; + this.memberList = memberList; + this.symbol = _StructureSchema.symbol; + this.members = {}; + for (let i = 0; i < memberNames.length; ++i) { + this.members[memberNames[i]] = Array.isArray(memberList[i]) ? memberList[i] : [memberList[i], 0]; + } } static { - __name(this, "MessageEncoderStream"); - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); + this.symbol = Symbol.for("@smithy/core/schema::StructureSchema"); } - 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); + static [Symbol.hasInstance](lhs) { + const isPrototype = _StructureSchema.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const struct2 = lhs; + return struct2.symbol === _StructureSchema.symbol; } + return isPrototype; } }; +function struct(namespace, name, traits, memberNames, memberList) { + const schema = new StructureSchema(namespace + "#" + name, traits, memberNames, memberList); + TypeRegistry.for(namespace).register(name, schema); + return schema; +} -// src/SmithyMessageDecoderStream.ts -var SmithyMessageDecoderStream = class { - constructor(options) { - this.options = options; +// src/submodules/schema/schemas/ErrorSchema.ts +var ErrorSchema = class _ErrorSchema extends StructureSchema { + constructor(name, traits, memberNames, memberList, ctor) { + super(name, traits, memberNames, memberList); + this.name = name; + this.traits = traits; + this.memberNames = memberNames; + this.memberList = memberList; + this.ctor = ctor; + this.symbol = _ErrorSchema.symbol; } static { - __name(this, "SmithyMessageDecoderStream"); - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); + this.symbol = Symbol.for("@smithy/core/schema::ErrorSchema"); } - async *asyncIterator() { - for await (const message of this.options.messageStream) { - const deserialized = await this.options.deserializer(message); - if (deserialized === void 0) - continue; - yield deserialized; + static [Symbol.hasInstance](lhs) { + const isPrototype = _ErrorSchema.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const err = lhs; + return err.symbol === _ErrorSchema.symbol; } + return isPrototype; } }; +function error(namespace, name, traits = {}, memberNames, memberList, ctor) { + const schema = new ErrorSchema(namespace + "#" + name, traits, memberNames, memberList, ctor); + TypeRegistry.for(namespace).register(name, schema); + return schema; +} -// src/SmithyMessageEncoderStream.ts -var SmithyMessageEncoderStream = class { - constructor(options) { - this.options = options; +// src/submodules/schema/schemas/sentinels.ts +var SCHEMA = { + BLOB: 21, + // 21 + STREAMING_BLOB: 42, + // 42 + BOOLEAN: 2, + // 2 + STRING: 0, + // 0 + NUMERIC: 1, + // 1 + BIG_INTEGER: 17, + // 17 + BIG_DECIMAL: 19, + // 19 + DOCUMENT: 15, + // 15 + TIMESTAMP_DEFAULT: 4, + // 4 + TIMESTAMP_DATE_TIME: 5, + // 5 + TIMESTAMP_HTTP_DATE: 6, + // 6 + TIMESTAMP_EPOCH_SECONDS: 7, + // 7 + LIST_MODIFIER: 64, + // 64 + MAP_MODIFIER: 128 + // 128 +}; + +// src/submodules/schema/schemas/SimpleSchema.ts +var SimpleSchema = class _SimpleSchema extends Schema { + constructor(name, schemaRef, traits) { + super(name, traits); + this.name = name; + this.schemaRef = schemaRef; + this.traits = traits; + this.symbol = _SimpleSchema.symbol; } static { - __name(this, "SmithyMessageEncoderStream"); - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); + this.symbol = Symbol.for("@smithy/core/schema::SimpleSchema"); } - async *asyncIterator() { - for await (const chunk of this.options.inputStream) { - const payloadBuf = this.options.serializer(chunk); - yield payloadBuf; + static [Symbol.hasInstance](lhs) { + const isPrototype = _SimpleSchema.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const sim2 = lhs; + return sim2.symbol === _SimpleSchema.symbol; } + return isPrototype; } }; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 6181: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - resolveEventStreamSerdeConfig: () => resolveEventStreamSerdeConfig -}); -module.exports = __toCommonJS(src_exports); - -// src/EventStreamSerdeConfig.ts -var resolveEventStreamSerdeConfig = /* @__PURE__ */ __name((input) => Object.assign(input, { - eventStreamMarshaller: input.eventStreamSerdeProvider(input) -}), "resolveEventStreamSerdeConfig"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 7682: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - EventStreamMarshaller: () => EventStreamMarshaller, - eventStreamSerdeProvider: () => eventStreamSerdeProvider -}); -module.exports = __toCommonJS(src_exports); - -// src/EventStreamMarshaller.ts -var import_eventstream_serde_universal = __nccwpck_require__(6673); -var import_stream = __nccwpck_require__(2781); +function sim(namespace, name, schemaRef, traits) { + const schema = new SimpleSchema(namespace + "#" + name, schemaRef, traits); + TypeRegistry.for(namespace).register(name, schema); + return schema; +} -// src/utils.ts -async function* readabletoIterable(readStream) { - let streamEnded = false; - let generationEnded = false; - const records = new Array(); - readStream.on("error", (err) => { - if (!streamEnded) { - streamEnded = true; +// src/submodules/schema/schemas/NormalizedSchema.ts +var NormalizedSchema = class _NormalizedSchema { + /** + * @param ref - a polymorphic SchemaRef to be dereferenced/normalized. + * @param memberName - optional memberName if this NormalizedSchema should be considered a member schema. + */ + constructor(ref, memberName) { + this.ref = ref; + this.memberName = memberName; + this.symbol = _NormalizedSchema.symbol; + const traitStack = []; + let _ref = ref; + let schema = ref; + this._isMemberSchema = false; + while (Array.isArray(_ref)) { + traitStack.push(_ref[1]); + _ref = _ref[0]; + schema = deref(_ref); + this._isMemberSchema = true; } - if (err) { - throw err; + if (traitStack.length > 0) { + this.memberTraits = {}; + for (let i = traitStack.length - 1; i >= 0; --i) { + const traitSet = traitStack[i]; + Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); + } + } else { + this.memberTraits = 0; } - }); - readStream.on("data", (data) => { - records.push(data); - }); - readStream.on("end", () => { - streamEnded = true; - }); - while (!generationEnded) { - const value = await new Promise((resolve) => setTimeout(() => resolve(records.shift()), 0)); - if (value) { - yield value; + if (schema instanceof _NormalizedSchema) { + this.name = schema.name; + this.traits = schema.traits; + this._isMemberSchema = schema._isMemberSchema; + this.schema = schema.schema; + this.memberTraits = Object.assign({}, schema.getMemberTraits(), this.getMemberTraits()); + this.normalizedTraits = void 0; + this.ref = schema.ref; + this.memberName = memberName ?? schema.memberName; + return; + } + this.schema = deref(schema); + if (this.schema && typeof this.schema === "object") { + this.traits = this.schema?.traits ?? {}; + } else { + this.traits = 0; + } + this.name = (typeof this.schema === "object" ? this.schema?.name : void 0) ?? this.memberName ?? this.getSchemaName(); + if (this._isMemberSchema && !memberName) { + throw new Error( + `@smithy/core/schema - NormalizedSchema member schema ${this.getName( + true + )} must initialize with memberName argument.` + ); } - generationEnded = streamEnded && records.length === 0; } -} -__name(readabletoIterable, "readabletoIterable"); - -// src/EventStreamMarshaller.ts -var EventStreamMarshaller = class { static { - __name(this, "EventStreamMarshaller"); + this.symbol = Symbol.for("@smithy/core/schema::NormalizedSchema"); } - constructor({ utf8Encoder, utf8Decoder }) { - this.universalMarshaller = new import_eventstream_serde_universal.EventStreamMarshaller({ - utf8Decoder, - utf8Encoder - }); + static [Symbol.hasInstance](lhs) { + const isPrototype = _NormalizedSchema.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const ns = lhs; + return ns.symbol === _NormalizedSchema.symbol; + } + return isPrototype; } - deserialize(body, deserializer) { - const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body); - return this.universalMarshaller.deserialize(bodyIterable, deserializer); + /** + * Static constructor that attempts to avoid wrapping a NormalizedSchema within another. + */ + static of(ref, memberName) { + if (ref instanceof _NormalizedSchema) { + return ref; + } + return new _NormalizedSchema(ref, memberName); } - serialize(input, serializer) { - return import_stream.Readable.from(this.universalMarshaller.serialize(input, serializer)); + /** + * @param indicator - numeric indicator for preset trait combination. + * @returns equivalent trait object. + */ + static translateTraits(indicator) { + if (typeof indicator === "object") { + return indicator; + } + indicator = indicator | 0; + const traits = {}; + if ((indicator & 1) === 1) { + traits.httpLabel = 1; + } + if ((indicator >> 1 & 1) === 1) { + traits.idempotent = 1; + } + if ((indicator >> 2 & 1) === 1) { + traits.idempotencyToken = 1; + } + if ((indicator >> 3 & 1) === 1) { + traits.sensitive = 1; + } + if ((indicator >> 4 & 1) === 1) { + traits.httpPayload = 1; + } + if ((indicator >> 5 & 1) === 1) { + traits.httpResponseCode = 1; + } + if ((indicator >> 6 & 1) === 1) { + traits.httpQueryParams = 1; + } + return traits; } -}; - -// src/provider.ts -var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 6673: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + /** + * Creates a normalized member schema from the given schema and member name. + */ + static memberFrom(memberSchema, memberName) { + if (memberSchema instanceof _NormalizedSchema) { + memberSchema.memberName = memberName; + memberSchema._isMemberSchema = true; + return memberSchema; + } + return new _NormalizedSchema(memberSchema, memberName); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - EventStreamMarshaller: () => EventStreamMarshaller, - eventStreamSerdeProvider: () => eventStreamSerdeProvider -}); -module.exports = __toCommonJS(src_exports); - -// src/EventStreamMarshaller.ts -var import_eventstream_codec = __nccwpck_require__(6459); - -// src/getChunkedStream.ts -function getChunkedStream(source) { - let currentMessageTotalLength = 0; - let currentMessagePendingLength = 0; - let currentMessage = null; - let messageLengthBuffer = null; - const allocateMessage = /* @__PURE__ */ __name((size) => { - if (typeof size !== "number") { - throw new Error("Attempted to allocate an event message where size was not a number: " + size); + /** + * @returns the underlying non-normalized schema. + */ + getSchema() { + if (this.schema instanceof _NormalizedSchema) { + return this.schema = this.schema.getSchema(); } - currentMessageTotalLength = size; - currentMessagePendingLength = 4; - currentMessage = new Uint8Array(size); - const currentMessageView = new DataView(currentMessage.buffer); - currentMessageView.setUint32(0, size, false); - }, "allocateMessage"); - const iterator = /* @__PURE__ */ __name(async function* () { - const sourceIterator = source[Symbol.asyncIterator](); - while (true) { - const { value, done } = await sourceIterator.next(); - if (done) { - if (!currentMessageTotalLength) { - return; - } else if (currentMessageTotalLength === currentMessagePendingLength) { - yield currentMessage; - } else { - throw new Error("Truncated event message received."); - } - return; - } - const chunkLength = value.length; - let currentOffset = 0; - while (currentOffset < chunkLength) { - if (!currentMessage) { - const bytesRemaining = chunkLength - currentOffset; - if (!messageLengthBuffer) { - messageLengthBuffer = new Uint8Array(4); - } - const numBytesForTotal = Math.min( - 4 - currentMessagePendingLength, - // remaining bytes to fill the messageLengthBuffer - bytesRemaining - // bytes left in chunk - ); - messageLengthBuffer.set( - // @ts-ignore error TS2532: Object is possibly 'undefined' for value - value.slice(currentOffset, currentOffset + numBytesForTotal), - currentMessagePendingLength - ); - currentMessagePendingLength += numBytesForTotal; - currentOffset += numBytesForTotal; - if (currentMessagePendingLength < 4) { - break; - } - allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); - messageLengthBuffer = null; - } - const numBytesToWrite = Math.min( - currentMessageTotalLength - currentMessagePendingLength, - // number of bytes left to complete message - chunkLength - currentOffset - // number of bytes left in the original chunk - ); - currentMessage.set( - // @ts-ignore error TS2532: Object is possibly 'undefined' for value - value.slice(currentOffset, currentOffset + numBytesToWrite), - currentMessagePendingLength - ); - currentMessagePendingLength += numBytesToWrite; - currentOffset += numBytesToWrite; - if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { - yield currentMessage; - currentMessage = null; - currentMessageTotalLength = 0; - currentMessagePendingLength = 0; - } + if (this.schema instanceof SimpleSchema) { + return deref(this.schema.schemaRef); + } + return deref(this.schema); + } + /** + * @param withNamespace - qualifies the name. + * @returns e.g. `MyShape` or `com.namespace#MyShape`. + */ + getName(withNamespace = false) { + if (!withNamespace) { + if (this.name && this.name.includes("#")) { + return this.name.split("#")[1]; } } - }, "iterator"); - return { - [Symbol.asyncIterator]: iterator - }; -} -__name(getChunkedStream, "getChunkedStream"); - -// src/getUnmarshalledStream.ts -function getMessageUnmarshaller(deserializer, toUtf8) { - return async function(message) { - const { value: messageType } = message.headers[":message-type"]; - if (messageType === "error") { - const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError"); - unmodeledError.name = message.headers[":error-code"].value; - throw unmodeledError; - } else if (messageType === "exception") { - const code = message.headers[":exception-type"].value; - const exception = { [code]: message }; - const deserializedException = await deserializer(exception); - if (deserializedException.$unknown) { - const error = new Error(toUtf8(message.body)); - error.name = code; - throw error; - } - throw deserializedException[code]; - } else if (messageType === "event") { - const event = { - [message.headers[":event-type"].value]: message - }; - const deserialized = await deserializer(event); - if (deserialized.$unknown) - return; - return deserialized; - } else { - throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`); + return this.name || void 0; + } + /** + * @returns the member name if the schema is a member schema. + * @throws Error when the schema isn't a member schema. + */ + getMemberName() { + if (!this.isMemberSchema()) { + throw new Error(`@smithy/core/schema - cannot get member name on non-member schema: ${this.getName(true)}`); } - }; -} -__name(getMessageUnmarshaller, "getMessageUnmarshaller"); - -// src/EventStreamMarshaller.ts -var EventStreamMarshaller = class { - static { - __name(this, "EventStreamMarshaller"); + return this.memberName; } - constructor({ utf8Encoder, utf8Decoder }) { - this.eventStreamCodec = new import_eventstream_codec.EventStreamCodec(utf8Encoder, utf8Decoder); - this.utfEncoder = utf8Encoder; + isMemberSchema() { + return this._isMemberSchema; } - deserialize(body, deserializer) { - const inputStream = getChunkedStream(body); - return new import_eventstream_codec.SmithyMessageDecoderStream({ - messageStream: new import_eventstream_codec.MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), - // @ts-expect-error Type 'T' is not assignable to type 'Record' - deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder) - }); + isUnitSchema() { + return this.getSchema() === "unit"; } - serialize(inputStream, serializer) { - return new import_eventstream_codec.MessageEncoderStream({ - messageStream: new import_eventstream_codec.SmithyMessageEncoderStream({ inputStream, serializer }), - encoder: this.eventStreamCodec, - includeEndFrame: true - }); + /** + * boolean methods on this class help control flow in shape serialization and deserialization. + */ + isListSchema() { + const inner = this.getSchema(); + if (typeof inner === "number") { + return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; + } + return inner instanceof ListSchema; } -}; - -// src/provider.ts -var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 2687: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + isMapSchema() { + const inner = this.getSchema(); + if (typeof inner === "number") { + return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; + } + return inner instanceof MapSchema; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - FetchHttpHandler: () => FetchHttpHandler, - keepAliveSupport: () => keepAliveSupport, - streamCollector: () => streamCollector -}); -module.exports = __toCommonJS(src_exports); - -// src/fetch-http-handler.ts -var import_protocol_http = __nccwpck_require__(4418); -var import_querystring_builder = __nccwpck_require__(8031); - -// src/create-request.ts -function createRequest(url, requestOptions) { - return new Request(url, requestOptions); -} -__name(createRequest, "createRequest"); - -// src/request-timeout.ts -function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); + isDocumentSchema() { + return this.getSchema() === SCHEMA.DOCUMENT; + } + isStructSchema() { + const inner = this.getSchema(); + return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; + } + isBlobSchema() { + return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; + } + isTimestampSchema() { + const schema = this.getSchema(); + return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; + } + isStringSchema() { + return this.getSchema() === SCHEMA.STRING; + } + isBooleanSchema() { + return this.getSchema() === SCHEMA.BOOLEAN; + } + isNumericSchema() { + return this.getSchema() === SCHEMA.NUMERIC; + } + isBigIntegerSchema() { + return this.getSchema() === SCHEMA.BIG_INTEGER; + } + isBigDecimalSchema() { + return this.getSchema() === SCHEMA.BIG_DECIMAL; + } + isStreaming() { + const streaming = !!this.getMergedTraits().streaming; + if (streaming) { + return true; } - }); -} -__name(requestTimeout, "requestTimeout"); - -// src/fetch-http-handler.ts -var keepAliveSupport = { - supported: void 0 -}; -var FetchHttpHandler = class _FetchHttpHandler { - static { - __name(this, "FetchHttpHandler"); + return this.getSchema() === SCHEMA.STREAMING_BLOB; } /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. + * This is a shortcut to avoid calling `getMergedTraits().idempotencyToken` on every string. + * @returns whether the schema has the idempotencyToken trait. */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; + isIdempotencyToken() { + if (typeof this.traits === "number") { + return (this.traits & 4) === 4; + } else if (typeof this.traits === "object") { + return !!this.traits.idempotencyToken; } - return new _FetchHttpHandler(instanceOrOptions); + return false; } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === void 0) { - keepAliveSupport.supported = Boolean( - typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") - ); + /** + * @returns own traits merged with member traits, where member traits of the same trait key take priority. + * This method is cached. + */ + getMergedTraits() { + if (this.normalizedTraits) { + return this.normalizedTraits; } + this.normalizedTraits = { + ...this.getOwnTraits(), + ...this.getMemberTraits() + }; + return this.normalizedTraits; } - destroy() { + /** + * @returns only the member traits. If the schema is not a member, this returns empty. + */ + getMemberTraits() { + return _NormalizedSchema.translateTraits(this.memberTraits); } - async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return Promise.reject(abortError); + /** + * @returns only the traits inherent to the shape or member target shape if this schema is a member. + * If there are any member traits they are excluded. + */ + getOwnTraits() { + return _NormalizedSchema.translateTraits(this.traits); + } + /** + * @returns the map's key's schema. Returns a dummy Document schema if this schema is a Document. + * + * @throws Error if the schema is not a Map or Document. + */ + getKeySchema() { + if (this.isDocumentSchema()) { + return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], "key"); } - let path = request.path; - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - if (queryString) { - path += `?${queryString}`; + if (!this.isMapSchema()) { + throw new Error(`@smithy/core/schema - cannot get key schema for non-map schema: ${this.getName(true)}`); } - if (request.fragment) { - path += `#${request.fragment}`; + const schema = this.getSchema(); + if (typeof schema === "number") { + return _NormalizedSchema.memberFrom([63 & schema, 0], "key"); } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; + return _NormalizedSchema.memberFrom([schema.keySchema, 0], "key"); + } + /** + * @returns the schema of the map's value or list's member. + * Returns a dummy Document schema if this schema is a Document. + * + * @throws Error if the schema is not a Map, List, nor Document. + */ + getValueSchema() { + const schema = this.getSchema(); + if (typeof schema === "number") { + if (this.isMapSchema()) { + return _NormalizedSchema.memberFrom([63 & schema, 0], "value"); + } else if (this.isListSchema()) { + return _NormalizedSchema.memberFrom([63 & schema, 0], "member"); + } } - const { port, method } = request; - const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; - const body = method === "GET" || method === "HEAD" ? void 0 : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method, - credentials - }; - if (this.config?.cache) { - requestOptions.cache = this.config.cache; + if (schema && typeof schema === "object") { + if (this.isStructSchema()) { + throw new Error(`cannot call getValueSchema() with StructureSchema ${this.getName(true)}`); + } + const collection = schema; + if ("valueSchema" in collection) { + if (this.isMapSchema()) { + return _NormalizedSchema.memberFrom([collection.valueSchema, 0], "value"); + } else if (this.isListSchema()) { + return _NormalizedSchema.memberFrom([collection.valueSchema, 0], "member"); + } + } } - if (body) { - requestOptions.duplex = "half"; + if (this.isDocumentSchema()) { + return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], "value"); } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; + throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have a value member.`); + } + /** + * @returns the NormalizedSchema for the given member name. The returned instance will return true for `isMemberSchema()` + * and will have the member name given. + * @param member - which member to retrieve and wrap. + * + * @throws Error if member does not exist or the schema is neither a document nor structure. + * Note that errors are assumed to be structures and unions are considered structures for these purposes. + */ + getMemberSchema(member) { + if (this.isStructSchema()) { + const struct2 = this.getSchema(); + if (!(member in struct2.members)) { + throw new Error( + `@smithy/core/schema - the schema ${this.getName(true)} does not have a member with name=${member}.` + ); + } + return _NormalizedSchema.memberFrom(struct2.members[member], member); } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; + if (this.isDocumentSchema()) { + return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], member); } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); + throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have members.`); + } + /** + * This can be used for checking the members as a hashmap. + * Prefer the structIterator method for iteration. + * + * This does NOT return list and map members, it is only for structures. + * + * @returns a map of member names to member schemas (normalized). + */ + getMemberSchemas() { + const { schema } = this; + const struct2 = schema; + if (!struct2 || typeof struct2 !== "object") { + return {}; } - let removeSignalEventListener = /* @__PURE__ */ __name(() => { - }, "removeSignalEventListener"); - const fetchRequest = createRequest(url, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; - } - const hasReadableStream = response.body != void 0; - if (!hasReadableStream) { - return response.blob().then((body2) => ({ - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: body2 - }) - })); - } - return { - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body - }) - }; - }), - requestTimeout(requestTimeoutInMs) - ]; - if (abortSignal) { - raceOfPromises.push( - new Promise((resolve, reject) => { - const onAbort = /* @__PURE__ */ __name(() => { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); - } else { - abortSignal.onabort = onAbort; - } - }) - ); + if ("members" in struct2) { + const buffer = {}; + for (const member of struct2.memberNames) { + buffer[member] = this.getMemberSchema(member); + } + return buffer; } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - config[key] = value; - return config; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; + return {}; } -}; - -// src/stream-collector.ts -var import_util_base64 = __nccwpck_require__(5600); -var streamCollector = /* @__PURE__ */ __name(async (stream) => { - if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { - if (Blob.prototype.arrayBuffer !== void 0) { - return new Uint8Array(await stream.arrayBuffer()); + /** + * Allows iteration over members of a structure schema. + * Each yield is a pair of the member name and member schema. + * + * This avoids the overhead of calling Object.entries(ns.getMemberSchemas()). + */ + *structIterator() { + if (this.isUnitSchema()) { + return; } - return collectBlob(stream); - } - return collectStream(stream); -}, "streamCollector"); -async function collectBlob(blob) { - const base64 = await readToBase64(blob); - const arrayBuffer = (0, import_util_base64.fromBase64)(base64); - return new Uint8Array(arrayBuffer); -} -__name(collectBlob, "collectBlob"); -async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; + if (!this.isStructSchema()) { + throw new Error("@smithy/core/schema - cannot acquire structIterator on non-struct schema."); + } + const struct2 = this.getSchema(); + for (let i = 0; i < struct2.memberNames.length; ++i) { + yield [struct2.memberNames[i], _NormalizedSchema.memberFrom([struct2.memberList[i], 0], struct2.memberNames[i])]; } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; } - return collected; -} -__name(collectStream, "collectStream"); -function readToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - if (reader.readyState !== 2) { - return reject(new Error("Reader aborted too early")); + /** + * @returns a last-resort human-readable name for the schema if it has no other identifiers. + */ + getSchemaName() { + const schema = this.getSchema(); + if (typeof schema === "number") { + const _schema = 63 & schema; + const container = 192 & schema; + const type = Object.entries(SCHEMA).find(([, value]) => { + return value === _schema; + })?.[0] ?? "Unknown"; + switch (container) { + case SCHEMA.MAP_MODIFIER: + return `${type}Map`; + case SCHEMA.LIST_MODIFIER: + return `${type}List`; + case 0: + return type; } - const result = reader.result ?? ""; - const commaIndex = result.indexOf(","); - const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; - resolve(result.substring(dataOffset)); - }; - reader.onabort = () => reject(new Error("Read aborted")); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); - }); -} -__name(readToBase64, "readToBase64"); + } + return "Unknown"; + } +}; // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 3081: +/***/ 7669: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -61419,627 +46576,663 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - Hash: () => Hash +// src/submodules/serde/index.ts +var serde_exports = {}; +__export(serde_exports, { + LazyJsonString: () => LazyJsonString, + NumericValue: () => NumericValue, + copyDocumentWithTransform: () => copyDocumentWithTransform, + dateToUtcString: () => dateToUtcString, + expectBoolean: () => expectBoolean, + expectByte: () => expectByte, + expectFloat32: () => expectFloat32, + expectInt: () => expectInt, + expectInt32: () => expectInt32, + expectLong: () => expectLong, + expectNonNull: () => expectNonNull, + expectNumber: () => expectNumber, + expectObject: () => expectObject, + expectShort: () => expectShort, + expectString: () => expectString, + expectUnion: () => expectUnion, + generateIdempotencyToken: () => import_uuid.v4, + handleFloat: () => handleFloat, + limitedParseDouble: () => limitedParseDouble, + limitedParseFloat: () => limitedParseFloat, + limitedParseFloat32: () => limitedParseFloat32, + logger: () => logger, + nv: () => nv, + parseBoolean: () => parseBoolean, + parseEpochTimestamp: () => parseEpochTimestamp, + parseRfc3339DateTime: () => parseRfc3339DateTime, + parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, + parseRfc7231DateTime: () => parseRfc7231DateTime, + quoteHeader: () => quoteHeader, + splitEvery: () => splitEvery, + splitHeader: () => splitHeader, + strictParseByte: () => strictParseByte, + strictParseDouble: () => strictParseDouble, + strictParseFloat: () => strictParseFloat, + strictParseFloat32: () => strictParseFloat32, + strictParseInt: () => strictParseInt, + strictParseInt32: () => strictParseInt32, + strictParseLong: () => strictParseLong, + strictParseShort: () => strictParseShort }); -module.exports = __toCommonJS(src_exports); -var import_util_buffer_from = __nccwpck_require__(1381); -var import_util_utf8 = __nccwpck_require__(1895); -var import_buffer = __nccwpck_require__(4300); -var import_crypto = __nccwpck_require__(6113); -var Hash = class { - static { - __name(this, "Hash"); +module.exports = __toCommonJS(serde_exports); + +// src/submodules/serde/copyDocumentWithTransform.ts +var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; + +// src/submodules/serde/parse-utils.ts +var parseBoolean = (value) => { + switch (value) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(`Unable to parse boolean value "${value}"`); } - constructor(algorithmIdentifier, secret) { - this.algorithmIdentifier = algorithmIdentifier; - this.secret = secret; - this.reset(); +}; +var expectBoolean = (value) => { + if (value === null || value === void 0) { + return void 0; } - update(toHash, encoding) { - this.hash.update((0, import_util_utf8.toUint8Array)(castSourceData(toHash, encoding))); + if (typeof value === "number") { + if (value === 0 || value === 1) { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (value === 0) { + return false; + } + if (value === 1) { + return true; + } } - digest() { - return Promise.resolve(this.hash.digest()); + if (typeof value === "string") { + const lower = value.toLowerCase(); + if (lower === "false" || lower === "true") { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (lower === "false") { + return false; + } + if (lower === "true") { + return true; + } } - reset() { - this.hash = this.secret ? (0, import_crypto.createHmac)(this.algorithmIdentifier, castSourceData(this.secret)) : (0, import_crypto.createHash)(this.algorithmIdentifier); + if (typeof value === "boolean") { + return value; } + throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); }; -function castSourceData(toCast, encoding) { - if (import_buffer.Buffer.isBuffer(toCast)) { - return toCast; +var expectNumber = (value) => { + if (value === null || value === void 0) { + return void 0; } - if (typeof toCast === "string") { - return (0, import_util_buffer_from.fromString)(toCast, encoding); + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + } + return parsed; + } } - if (ArrayBuffer.isView(toCast)) { - return (0, import_util_buffer_from.fromArrayBuffer)(toCast.buffer, toCast.byteOffset, toCast.byteLength); + if (typeof value === "number") { + return value; } - return (0, import_util_buffer_from.fromArrayBuffer)(toCast); -} -__name(castSourceData, "castSourceData"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 8866: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); +var expectFloat32 = (value) => { + const expected = expectNumber(value); + if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { + if (Math.abs(expected) > MAX_FLOAT) { + throw new TypeError(`Expected 32-bit float, got ${value}`); + } } - return to; + return expected; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fileStreamHasher: () => fileStreamHasher, - readableStreamHasher: () => readableStreamHasher -}); -module.exports = __toCommonJS(src_exports); - -// src/fileStreamHasher.ts -var import_fs = __nccwpck_require__(7147); - -// src/HashCalculator.ts -var import_util_utf8 = __nccwpck_require__(1895); -var import_stream = __nccwpck_require__(2781); -var HashCalculator = class extends import_stream.Writable { - constructor(hash, options) { - super(options); - this.hash = hash; +var expectLong = (value) => { + if (value === null || value === void 0) { + return void 0; } - static { - __name(this, "HashCalculator"); + if (Number.isInteger(value) && !Number.isNaN(value)) { + return value; } - _write(chunk, encoding, callback) { - try { - this.hash.update((0, import_util_utf8.toUint8Array)(chunk)); - } catch (err) { - return callback(err); + throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); +}; +var expectInt = expectLong; +var expectInt32 = (value) => expectSizedInt(value, 32); +var expectShort = (value) => expectSizedInt(value, 16); +var expectByte = (value) => expectSizedInt(value, 8); +var expectSizedInt = (value, size) => { + const expected = expectLong(value); + if (expected !== void 0 && castInt(expected, size) !== expected) { + throw new TypeError(`Expected ${size}-bit integer, got ${value}`); + } + return expected; +}; +var 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]; + } +}; +var expectNonNull = (value, location) => { + if (value === null || value === void 0) { + if (location) { + throw new TypeError(`Expected a non-null value for ${location}`); } - callback(); + throw new TypeError("Expected a non-null value"); + } + return value; +}; +var expectObject = (value) => { + if (value === null || value === void 0) { + return void 0; + } + 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}`); +}; +var expectString = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + return value; + } + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); + } + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); +}; +var expectUnion = (value) => { + if (value === null || value === void 0) { + return void 0; + } + const asObject = 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; +}; +var strictParseDouble = (value) => { + if (typeof value == "string") { + return expectNumber(parseNumber(value)); + } + return expectNumber(value); +}; +var strictParseFloat = strictParseDouble; +var strictParseFloat32 = (value) => { + if (typeof value == "string") { + return expectFloat32(parseNumber(value)); + } + return expectFloat32(value); +}; +var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; +var 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); +}; +var limitedParseDouble = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectNumber(value); +}; +var handleFloat = limitedParseDouble; +var limitedParseFloat = limitedParseDouble; +var limitedParseFloat32 = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectFloat32(value); +}; +var 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}`); + } +}; +var strictParseLong = (value) => { + if (typeof value === "string") { + return expectLong(parseNumber(value)); + } + return expectLong(value); +}; +var strictParseInt = strictParseLong; +var strictParseInt32 = (value) => { + if (typeof value === "string") { + return expectInt32(parseNumber(value)); + } + return expectInt32(value); +}; +var strictParseShort = (value) => { + if (typeof value === "string") { + return expectShort(parseNumber(value)); + } + return expectShort(value); +}; +var strictParseByte = (value) => { + if (typeof value === "string") { + return expectByte(parseNumber(value)); + } + return expectByte(value); +}; +var stackTraceWarning = (message) => { + return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); +}; +var logger = { + warn: console.warn +}; + +// src/submodules/serde/date-utils.ts +var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +var 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`; +} +var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); +var parseRfc3339DateTime = (value) => { + if (value === null || value === void 0) { + return void 0; + } + 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 = 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 }); +}; +var RFC3339_WITH_OFFSET = new RegExp( + /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ +); +var parseRfc3339DateTimeWithOffset = (value) => { + if (value === null || value === void 0) { + return void 0; + } + 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 = 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; +}; +var 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$/ +); +var 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$/ +); +var 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})$/ +); +var parseRfc7231DateTime = (value) => { + if (value === null || value === void 0) { + return void 0; + } + 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( + 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( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr.trimLeft(), "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } + ); + } + throw new TypeError("Invalid RFC-7231 date-time value"); +}; +var parseEpochTimestamp = (value) => { + if (value === null || value === void 0) { + return void 0; + } + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } else if (typeof value === "object" && value.tag === 1) { + valueAsDouble = value.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 * 1e3)); +}; +var 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), + // seconds can go up to 60 for leap seconds + parseDateValue(time.seconds, "seconds", 0, 60), + parseMilliseconds(time.fractionalMilliseconds) + ) + ); +}; +var parseTwoDigitYear = (value) => { + const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); + const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); + if (valueInThisCentury < thisYear) { + return valueInThisCentury + 100; } + return valueInThisCentury; }; - -// src/fileStreamHasher.ts -var fileStreamHasher = /* @__PURE__ */ __name((hashCtor, fileStream) => new Promise((resolve, reject) => { - if (!isReadStream(fileStream)) { - reject(new Error("Unable to calculate hash for non-file streams.")); - return; +var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; +var adjustRfc850Year = (input) => { + if (input.getTime() - (/* @__PURE__ */ 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() + ) + ); } - const fileStreamTee = (0, import_fs.createReadStream)(fileStream.path, { - start: fileStream.start, - end: fileStream.end - }); - const hash = new hashCtor(); - const hashCalculator = new HashCalculator(hash); - fileStreamTee.pipe(hashCalculator); - fileStreamTee.on("error", (err) => { - hashCalculator.end(); - reject(err); - }); - hashCalculator.on("error", reject); - hashCalculator.on("finish", function() { - hash.digest().then(resolve).catch(reject); - }); -}), "fileStreamHasher"); -var isReadStream = /* @__PURE__ */ __name((stream) => typeof stream.path === "string", "isReadStream"); - -// src/readableStreamHasher.ts -var readableStreamHasher = /* @__PURE__ */ __name((hashCtor, readableStream) => { - if (readableStream.readableFlowing !== null) { - throw new Error("Unable to calculate hash for flowing readable stream"); + return input; +}; +var parseMonthByShortName = (value) => { + const monthIdx = MONTHS.indexOf(value); + if (monthIdx < 0) { + throw new TypeError(`Invalid month: ${value}`); } - const hash = new hashCtor(); - const hashCalculator = new HashCalculator(hash); - readableStream.pipe(hashCalculator); - return new Promise((resolve, reject) => { - readableStream.on("error", (err) => { - hashCalculator.end(); - reject(err); - }); - hashCalculator.on("error", reject); - hashCalculator.on("finish", () => { - hash.digest().then(resolve).catch(reject); - }); - }); -}, "readableStreamHasher"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 780: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); + return monthIdx + 1; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var 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}`); } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - isArrayBuffer: () => isArrayBuffer -}); -module.exports = __toCommonJS(src_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 2800: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +var isLeapYear = (year) => { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var parseDateValue = (value, type, lower, upper) => { + const dateVal = strictParseByte(stripLeadingZeroes(value)); + if (dateVal < lower || dateVal > upper) { + throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); } - return to; + return dateVal; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - contentLengthMiddleware: () => contentLengthMiddleware, - contentLengthMiddlewareOptions: () => contentLengthMiddlewareOptions, - getContentLengthPlugin: () => getContentLengthPlugin -}); -module.exports = __toCommonJS(src_exports); -var import_protocol_http = __nccwpck_require__(4418); -var CONTENT_LENGTH_HEADER = "content-length"; -function contentLengthMiddleware(bodyLengthChecker) { - return (next) => async (args) => { - const request = args.request; - if (import_protocol_http.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 - }); - }; -} -__name(contentLengthMiddleware, "contentLengthMiddleware"); -var contentLengthMiddlewareOptions = { - step: "build", - tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], - name: "contentLengthMiddleware", - override: true +var parseMilliseconds = (value) => { + if (value === null || value === void 0) { + return 0; + } + return strictParseFloat32("0." + value) * 1e3; }; -var getContentLengthPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: (clientStack) => { - clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); +var 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 "-"`); } -}), "getContentLengthPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 1518: -/***/ ((__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__(3461); -const getEndpointUrlConfig_1 = __nccwpck_require__(7574); -const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId !== null && serviceId !== void 0 ? serviceId : ""))(); -exports.getEndpointFromConfig = getEndpointFromConfig; - - -/***/ }), - -/***/ 7574: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const hour = Number(value.substring(1, 3)); + const minute = Number(value.substring(4, 6)); + return direction * (hour * 60 + minute) * 60 * 1e3; +}; +var stripLeadingZeroes = (value) => { + let idx = 0; + while (idx < value.length - 1 && value.charAt(idx) === "0") { + idx++; + } + if (idx === 0) { + return value; + } + return value.slice(idx); +}; -"use strict"; +// src/submodules/serde/generateIdempotencyToken.ts +var import_uuid = __nccwpck_require__(5840); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getEndpointUrlConfig = void 0; -const shared_ini_file_loader_1 = __nccwpck_require__(3507); -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; +// src/submodules/serde/lazy-json.ts +var LazyJsonString = function LazyJsonString2(val) { + const str = Object.assign(new String(val), { + deserializeJSON() { + return JSON.parse(String(val)); }, - 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; + toString() { + return String(val); }, - default: undefined, -}); -exports.getEndpointUrlConfig = getEndpointUrlConfig; - - -/***/ }), - -/***/ 2918: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); + toJSON() { + return String(val); + } + }); + return str; }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +LazyJsonString.from = (object) => { + if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { + return object; + } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { + return LazyJsonString(String(object)); } - return to; + return LazyJsonString(JSON.stringify(object)); }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - endpointMiddleware: () => endpointMiddleware, - endpointMiddlewareOptions: () => endpointMiddlewareOptions, - getEndpointFromInstructions: () => getEndpointFromInstructions, - getEndpointPlugin: () => getEndpointPlugin, - resolveEndpointConfig: () => resolveEndpointConfig, - resolveEndpointRequiredConfig: () => resolveEndpointRequiredConfig, - resolveParams: () => resolveParams, - toEndpointV1: () => toEndpointV1 -}); -module.exports = __toCommonJS(src_exports); +LazyJsonString.fromObject = LazyJsonString.from; -// src/service-customizations/s3.ts -var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => { - const bucket = endpointParams?.Bucket || ""; - if (typeof endpointParams.Bucket === "string") { - endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); - } - if (isArnBucketName(bucket)) { - if (endpointParams.ForcePathStyle === true) { - throw new Error("Path-style addressing cannot be used with ARN buckets"); - } - } else if (!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; -}, "resolveParamsForS3"); -var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; -var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; -var DOTS_PATTERN = /\.\./; -var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName"); -var isArnBucketName = /* @__PURE__ */ __name((bucketName) => { - const [arn, partition, service, , , bucket] = bucketName.split(":"); - const isArn = arn === "arn" && bucketName.split(":").length >= 6; - const isValidArn = Boolean(isArn && partition && service && bucket); - if (isArn && !isValidArn) { - throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); +// src/submodules/serde/quote-header.ts +function quoteHeader(part) { + if (part.includes(",") || part.includes('"')) { + part = `"${part.replace(/"/g, '\\"')}"`; } - return isValidArn; -}, "isArnBucketName"); + return part; +} -// src/adaptors/createConfigValueProvider.ts -var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => { - const configProvider = /* @__PURE__ */ __name(async () => { - const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; - if (typeof configValue === "function") { - return configValue(); - } - return configValue; - }, "configProvider"); - if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { - return async () => { - const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; - const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; - return configValue; - }; - } - if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { - return async () => { - const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; - const configValue = credentials?.accountId ?? credentials?.AccountId; - return configValue; - }; - } - if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { - return async () => { - if (config.isCustomEndpoint === false) { - return void 0; - } - 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; - }; +// src/submodules/serde/split-every.ts +function splitEvery(value, delimiter, numDelimiters) { + if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { + throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); } - return configProvider; -}, "createConfigValueProvider"); - -// src/adaptors/getEndpointFromInstructions.ts -var import_getEndpointFromConfig = __nccwpck_require__(1518); - -// src/adaptors/toEndpointV1.ts -var import_url_parser = __nccwpck_require__(4681); -var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => { - if (typeof endpoint === "object") { - if ("url" in endpoint) { - return (0, import_url_parser.parseUrl)(endpoint.url); - } - return endpoint; + const segments = value.split(delimiter); + if (numDelimiters === 1) { + return segments; } - return (0, import_url_parser.parseUrl)(endpoint); -}, "toEndpointV1"); - -// src/adaptors/getEndpointFromInstructions.ts -var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => { - if (!clientConfig.isCustomEndpoint) { - let endpointFromConfig; - if (clientConfig.serviceConfiguredEndpoint) { - endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); + const compoundSegments = []; + let currentSegment = ""; + for (let i = 0; i < segments.length; i++) { + if (currentSegment === "") { + currentSegment = segments[i]; } else { - endpointFromConfig = await (0, import_getEndpointFromConfig.getEndpointFromConfig)(clientConfig.serviceId); + currentSegment += delimiter + segments[i]; } - if (endpointFromConfig) { - clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); - clientConfig.isCustomEndpoint = true; + if ((i + 1) % numDelimiters === 0) { + compoundSegments.push(currentSegment); + currentSegment = ""; } } - const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); - if (typeof clientConfig.endpointProvider !== "function") { - throw new Error("config.endpointProvider is not set."); + if (currentSegment !== "") { + compoundSegments.push(currentSegment); } - const endpoint = clientConfig.endpointProvider(endpointParams, context); - return endpoint; -}, "getEndpointFromInstructions"); -var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => { - const endpointParams = {}; - const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; - 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 createConfigValueProvider(instruction.name, name, clientConfig)(); + return compoundSegments; +} + +// src/submodules/serde/split-header.ts +var splitHeader = (value) => { + const z = value.length; + const values = []; + let withinQuotes = false; + let prevChar = void 0; + let anchor = 0; + for (let i = 0; i < z; ++i) { + const char = value[i]; + switch (char) { + case `"`: + if (prevChar !== "\\") { + withinQuotes = !withinQuotes; + } break; - case "operationContextParams": - endpointParams[name] = instruction.get(commandInput); + case ",": + if (!withinQuotes) { + values.push(value.slice(anchor, i)); + anchor = i + 1; + } 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 resolveParamsForS3(endpointParams); - } - return endpointParams; -}, "resolveParams"); - -// src/endpointMiddleware.ts -var import_core = __nccwpck_require__(5829); -var import_util_middleware = __nccwpck_require__(2390); -var endpointMiddleware = /* @__PURE__ */ __name(({ - config, - instructions -}) => { - return (next, context) => async (args) => { - if (config.isCustomEndpoint) { - (0, import_core.setFeature)(context, "ENDPOINT_OVERRIDE", "N"); + prevChar = char; + } + values.push(value.slice(anchor)); + return values.map((v) => { + v = v.trim(); + const z2 = v.length; + if (z2 < 2) { + return v; } - const endpoint = await getEndpointFromInstructions( - args.input, - { - getEndpointParameterInstructions() { - return instructions; + if (v[0] === `"` && v[z2 - 1] === `"`) { + v = v.slice(1, z2 - 1); + } + return v.replace(/\\"/g, '"'); + }); +}; + +// src/submodules/serde/value/NumericValue.ts +var NumericValue = class _NumericValue { + constructor(string, type) { + this.string = string; + this.type = type; + let dot = 0; + for (let i = 0; i < string.length; ++i) { + const char = string.charCodeAt(i); + if (i === 0 && char === 45) { + continue; + } + if (char === 46) { + if (dot) { + throw new Error("@smithy/core/serde - NumericValue must contain at most one decimal point."); } - }, - { ...config }, - context - ); - context.endpointV2 = endpoint; - context.authSchemes = endpoint.properties?.authSchemes; - const authScheme = context.authSchemes?.[0]; - if (authScheme) { - context["signing_region"] = authScheme.signingRegion; - context["signing_service"] = authScheme.signingName; - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.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 + dot = 1; + continue; + } + if (char < 48 || char > 57) { + throw new Error( + `@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".` ); } } - return next({ - ...args - }); - }; -}, "endpointMiddleware"); - -// src/getEndpointPlugin.ts -var import_middleware_serde = __nccwpck_require__(1238); -var endpointMiddlewareOptions = { - step: "serialize", - tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], - name: "endpointV2Middleware", - override: true, - relation: "before", - toMiddleware: import_middleware_serde.serializerMiddlewareOption.name -}; -var getEndpointPlugin = /* @__PURE__ */ __name((config, instructions) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo( - endpointMiddleware({ - config, - instructions - }), - endpointMiddlewareOptions - ); } -}), "getEndpointPlugin"); - -// src/resolveEndpointConfig.ts - -var import_getEndpointFromConfig2 = __nccwpck_require__(1518); -var resolveEndpointConfig = /* @__PURE__ */ __name((input) => { - const tls = input.tls ?? true; - const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; - const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware.normalizeProvider)(endpoint)()) : void 0; - const isCustomEndpoint = !!endpoint; - const resolvedConfig = Object.assign(input, { - endpoint: customEndpointProvider, - tls, - isCustomEndpoint, - useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false), - useFipsEndpoint: (0, import_util_middleware.normalizeProvider)(useFipsEndpoint ?? false) - }); - let configuredEndpointPromise = void 0; - resolvedConfig.serviceConfiguredEndpoint = async () => { - if (input.serviceId && !configuredEndpointPromise) { - configuredEndpointPromise = (0, import_getEndpointFromConfig2.getEndpointFromConfig)(input.serviceId); + toString() { + return this.string; + } + static [Symbol.hasInstance](object) { + if (!object || typeof object !== "object") { + return false; } - return configuredEndpointPromise; - }; - return resolvedConfig; -}, "resolveEndpointConfig"); - -// src/resolveEndpointRequiredConfig.ts -var resolveEndpointRequiredConfig = /* @__PURE__ */ __name((input) => { - const { endpoint } = input; - if (endpoint === void 0) { - input.endpoint = async () => { - throw new Error( - "@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint." - ); - }; + const _nv = object; + const prototypeMatch = _NumericValue.prototype.isPrototypeOf(object.constructor?.prototype); + if (prototypeMatch) { + return prototypeMatch; + } + if (typeof _nv.string === "string" && typeof _nv.type === "string" && _nv.constructor?.name === "NumericValue") { + return true; + } + return prototypeMatch; } - return input; -}, "resolveEndpointRequiredConfig"); +}; +function nv(input) { + return new NumericValue(String(input), "bigDecimal"); +} // Annotate the CommonJS export names for ESM import in node: - 0 && (0); - /***/ }), -/***/ 6039: +/***/ 7477: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -62064,386 +47257,413 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - AdaptiveRetryStrategy: () => AdaptiveRetryStrategy, - CONFIG_MAX_ATTEMPTS: () => CONFIG_MAX_ATTEMPTS, - CONFIG_RETRY_MODE: () => CONFIG_RETRY_MODE, - ENV_MAX_ATTEMPTS: () => ENV_MAX_ATTEMPTS, - ENV_RETRY_MODE: () => ENV_RETRY_MODE, - NODE_MAX_ATTEMPT_CONFIG_OPTIONS: () => NODE_MAX_ATTEMPT_CONFIG_OPTIONS, - NODE_RETRY_MODE_CONFIG_OPTIONS: () => NODE_RETRY_MODE_CONFIG_OPTIONS, - StandardRetryStrategy: () => StandardRetryStrategy, - defaultDelayDecider: () => defaultDelayDecider, - defaultRetryDecider: () => defaultRetryDecider, - getOmitRetryHeadersPlugin: () => getOmitRetryHeadersPlugin, - getRetryAfterHint: () => getRetryAfterHint, - getRetryPlugin: () => getRetryPlugin, - omitRetryHeadersMiddleware: () => omitRetryHeadersMiddleware, - omitRetryHeadersMiddlewareOptions: () => omitRetryHeadersMiddlewareOptions, - resolveRetryConfig: () => resolveRetryConfig, - retryMiddleware: () => retryMiddleware, - retryMiddlewareOptions: () => retryMiddlewareOptions + DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES, + DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT, + ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN, + ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI, + ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI, + Endpoint: () => Endpoint, + fromContainerMetadata: () => fromContainerMetadata, + fromInstanceMetadata: () => fromInstanceMetadata, + getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint, + httpRequest: () => httpRequest, + providerConfigFromInit: () => providerConfigFromInit }); module.exports = __toCommonJS(src_exports); -// src/AdaptiveRetryStrategy.ts - - -// src/StandardRetryStrategy.ts -var import_protocol_http = __nccwpck_require__(4418); - +// src/fromContainerMetadata.ts -var import_uuid = __nccwpck_require__(5840); +var import_url = __nccwpck_require__(7310); -// src/defaultRetryQuota.ts -var import_util_retry = __nccwpck_require__(4902); -var getDefaultRetryQuota = /* @__PURE__ */ __name((initialRetryTokens, options) => { - const MAX_CAPACITY = initialRetryTokens; - const noRetryIncrement = options?.noRetryIncrement ?? import_util_retry.NO_RETRY_INCREMENT; - const retryCost = options?.retryCost ?? import_util_retry.RETRY_COST; - const timeoutRetryCost = options?.timeoutRetryCost ?? import_util_retry.TIMEOUT_RETRY_COST; - let availableCapacity = initialRetryTokens; - const getCapacityAmount = /* @__PURE__ */ __name((error) => error.name === "TimeoutError" ? timeoutRetryCost : retryCost, "getCapacityAmount"); - const hasRetryTokens = /* @__PURE__ */ __name((error) => getCapacityAmount(error) <= availableCapacity, "hasRetryTokens"); - const retrieveRetryTokens = /* @__PURE__ */ __name((error) => { - if (!hasRetryTokens(error)) { - throw new Error("No retry token available"); - } - const capacityAmount = getCapacityAmount(error); - availableCapacity -= capacityAmount; - return capacityAmount; - }, "retrieveRetryTokens"); - const releaseRetryTokens = /* @__PURE__ */ __name((capacityReleaseAmount) => { - availableCapacity += capacityReleaseAmount ?? noRetryIncrement; - availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); - }, "releaseRetryTokens"); - return Object.freeze({ - hasRetryTokens, - retrieveRetryTokens, - releaseRetryTokens +// src/remoteProvider/httpRequest.ts +var import_property_provider = __nccwpck_require__(9721); +var import_buffer = __nccwpck_require__(4300); +var import_http = __nccwpck_require__(3685); +function httpRequest(options) { + return new Promise((resolve, reject) => { + const req = (0, import_http.request)({ + method: "GET", + ...options, + // Node.js http module doesn't accept hostname with square brackets + // Refs: https://github.com/nodejs/node/issues/39738 + hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1") + }); + req.on("error", (err) => { + reject(Object.assign(new import_property_provider.ProviderError("Unable to connect to instance metadata service"), err)); + req.destroy(); + }); + req.on("timeout", () => { + reject(new import_property_provider.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 import_property_provider.ProviderError("Error response received from instance metadata service"), { statusCode }) + ); + req.destroy(); + } + const chunks = []; + res.on("data", (chunk) => { + chunks.push(chunk); + }); + res.on("end", () => { + resolve(import_buffer.Buffer.concat(chunks)); + req.destroy(); + }); + }); + req.end(); }); -}, "getDefaultRetryQuota"); +} +__name(httpRequest, "httpRequest"); -// src/delayDecider.ts +// src/remoteProvider/ImdsCredentials.ts +var isImdsCredentials = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string", "isImdsCredentials"); +var fromImdsCredentials = /* @__PURE__ */ __name((creds) => ({ + accessKeyId: creds.AccessKeyId, + secretAccessKey: creds.SecretAccessKey, + sessionToken: creds.Token, + expiration: new Date(creds.Expiration), + ...creds.AccountId && { accountId: creds.AccountId } +}), "fromImdsCredentials"); -var defaultDelayDecider = /* @__PURE__ */ __name((delayBase, attempts) => Math.floor(Math.min(import_util_retry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)), "defaultDelayDecider"); +// src/remoteProvider/RemoteProviderInit.ts +var DEFAULT_TIMEOUT = 1e3; +var DEFAULT_MAX_RETRIES = 0; +var providerConfigFromInit = /* @__PURE__ */ __name(({ + maxRetries = DEFAULT_MAX_RETRIES, + timeout = DEFAULT_TIMEOUT +}) => ({ maxRetries, timeout }), "providerConfigFromInit"); -// src/retryDecider.ts -var import_service_error_classification = __nccwpck_require__(6375); -var defaultRetryDecider = /* @__PURE__ */ __name((error) => { - if (!error) { - return false; +// src/remoteProvider/retry.ts +var retry = /* @__PURE__ */ __name((toRetry, maxRetries) => { + let promise = toRetry(); + for (let i = 0; i < maxRetries; i++) { + promise = promise.catch(toRetry); } - return (0, import_service_error_classification.isRetryableByTrait)(error) || (0, import_service_error_classification.isClockSkewError)(error) || (0, import_service_error_classification.isThrottlingError)(error) || (0, import_service_error_classification.isTransientError)(error); -}, "defaultRetryDecider"); - -// src/util.ts -var asSdkError = /* @__PURE__ */ __name((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}`); -}, "asSdkError"); + return promise; +}, "retry"); -// src/StandardRetryStrategy.ts -var StandardRetryStrategy = class { - constructor(maxAttemptsProvider, options) { - this.maxAttemptsProvider = maxAttemptsProvider; - this.mode = import_util_retry.RETRY_MODES.STANDARD; - this.retryDecider = options?.retryDecider ?? defaultRetryDecider; - this.delayDecider = options?.delayDecider ?? defaultDelayDecider; - this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(import_util_retry.INITIAL_RETRY_TOKENS); - } - static { - __name(this, "StandardRetryStrategy"); - } - 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 = import_util_retry.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 (import_protocol_http.HttpRequest.isInstance(request)) { - request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)(); - } - while (true) { - try { - if (import_protocol_http.HttpRequest.isInstance(request)) { - request.headers[import_util_retry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; - } - if (options?.beforeRequest) { - await options.beforeRequest(); - } - const { response, output } = await next(args); - if (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 = asSdkError(e); - attempts++; - if (this.shouldRetry(err, attempts, maxAttempts)) { - retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); - const delayFromDecider = this.delayDecider( - (0, import_service_error_classification.isThrottlingError)(err) ? import_util_retry.THROTTLING_RETRY_DELAY_BASE : import_util_retry.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; - } +// src/fromContainerMetadata.ts +var ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; +var ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; +var ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; +var fromContainerMetadata = /* @__PURE__ */ __name((init = {}) => { + const { timeout, maxRetries } = providerConfigFromInit(init); + return () => retry(async () => { + const requestOptions = await getCmdsUri({ logger: init.logger }); + const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); + if (!isImdsCredentials(credsResponse)) { + throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.", { + logger: init.logger + }); } + return fromImdsCredentials(credsResponse); + }, maxRetries); +}, "fromContainerMetadata"); +var requestFromEcsImds = /* @__PURE__ */ __name(async (timeout, options) => { + if (process.env[ENV_CMDS_AUTH_TOKEN]) { + options.headers = { + ...options.headers, + Authorization: process.env[ENV_CMDS_AUTH_TOKEN] + }; } + const buffer = await httpRequest({ + ...options, + timeout + }); + return buffer.toString(); +}, "requestFromEcsImds"); +var CMDS_IP = "169.254.170.2"; +var GREENGRASS_HOSTS = { + localhost: true, + "127.0.0.1": true }; -var getDelayFromRetryAfterHeader = /* @__PURE__ */ __name((response) => { - if (!import_protocol_http.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 * 1e3; - const retryAfterDate = new Date(retryAfter); - return retryAfterDate.getTime() - Date.now(); -}, "getDelayFromRetryAfterHeader"); - -// src/AdaptiveRetryStrategy.ts -var AdaptiveRetryStrategy = class extends StandardRetryStrategy { - static { - __name(this, "AdaptiveRetryStrategy"); - } - constructor(maxAttemptsProvider, options) { - const { rateLimiter, ...superOptions } = options ?? {}; - super(maxAttemptsProvider, superOptions); - this.rateLimiter = rateLimiter ?? new import_util_retry.DefaultRateLimiter(); - this.mode = import_util_retry.RETRY_MODES.ADAPTIVE; - } - async retry(next, args) { - return super.retry(next, args, { - beforeRequest: async () => { - return this.rateLimiter.getSendToken(); - }, - afterRequest: (response) => { - this.rateLimiter.updateClientSendingRate(response); - } - }); - } +var GREENGRASS_PROTOCOLS = { + "http:": true, + "https:": true }; - -// src/configurations.ts -var import_util_middleware = __nccwpck_require__(2390); - -var ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; -var CONFIG_MAX_ATTEMPTS = "max_attempts"; -var NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => { - const value = env[ENV_MAX_ATTEMPTS]; - if (!value) - return void 0; - const maxAttempt = parseInt(value); - if (Number.isNaN(maxAttempt)) { - throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); - } - return maxAttempt; - }, - configFileSelector: (profile) => { - const value = profile[CONFIG_MAX_ATTEMPTS]; - if (!value) - return void 0; - const maxAttempt = parseInt(value); - if (Number.isNaN(maxAttempt)) { - throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); +var getCmdsUri = /* @__PURE__ */ __name(async ({ logger }) => { + if (process.env[ENV_CMDS_RELATIVE_URI]) { + return { + hostname: CMDS_IP, + path: process.env[ENV_CMDS_RELATIVE_URI] + }; + } + if (process.env[ENV_CMDS_FULL_URI]) { + const parsed = (0, import_url.parse)(process.env[ENV_CMDS_FULL_URI]); + if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { + throw new import_property_provider.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { + tryNextLink: false, + logger + }); } - return maxAttempt; - }, - default: import_util_retry.DEFAULT_MAX_ATTEMPTS -}; -var resolveRetryConfig = /* @__PURE__ */ __name((input) => { - const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input; - const maxAttempts = (0, import_util_middleware.normalizeProvider)(_maxAttempts ?? import_util_retry.DEFAULT_MAX_ATTEMPTS); - return Object.assign(input, { - maxAttempts, - retryStrategy: async () => { - if (retryStrategy) { - return retryStrategy; - } - const retryMode = await (0, import_util_middleware.normalizeProvider)(_retryMode)(); - if (retryMode === import_util_retry.RETRY_MODES.ADAPTIVE) { - return new import_util_retry.AdaptiveRetryStrategy(maxAttempts); - } - return new import_util_retry.StandardRetryStrategy(maxAttempts); + if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { + throw new import_property_provider.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { + tryNextLink: false, + logger + }); } - }); -}, "resolveRetryConfig"); -var ENV_RETRY_MODE = "AWS_RETRY_MODE"; -var CONFIG_RETRY_MODE = "retry_mode"; -var NODE_RETRY_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[ENV_RETRY_MODE], - configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], - default: import_util_retry.DEFAULT_RETRY_MODE -}; + return { + ...parsed, + port: parsed.port ? parseInt(parsed.port, 10) : void 0 + }; + } + throw new import_property_provider.CredentialsProviderError( + `The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, + { + tryNextLink: false, + logger + } + ); +}, "getCmdsUri"); -// src/omitRetryHeadersMiddleware.ts +// src/fromInstanceMetadata.ts -var omitRetryHeadersMiddleware = /* @__PURE__ */ __name(() => (next) => async (args) => { - const { request } = args; - if (import_protocol_http.HttpRequest.isInstance(request)) { - delete request.headers[import_util_retry.INVOCATION_ID_HEADER]; - delete request.headers[import_util_retry.REQUEST_HEADER]; + +// src/error/InstanceMetadataV1FallbackError.ts + +var InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends import_property_provider.CredentialsProviderError { + constructor(message, tryNextLink = true) { + super(message, tryNextLink); + this.tryNextLink = tryNextLink; + this.name = "InstanceMetadataV1FallbackError"; + Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError.prototype); } - return next(args); -}, "omitRetryHeadersMiddleware"); -var omitRetryHeadersMiddlewareOptions = { - name: "omitRetryHeadersMiddleware", - tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], - relation: "before", - toMiddleware: "awsAuthMiddleware", - override: true -}; -var getOmitRetryHeadersPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); + static { + __name(this, "InstanceMetadataV1FallbackError"); } -}), "getOmitRetryHeadersPlugin"); +}; -// src/retryMiddleware.ts +// src/utils/getInstanceMetadataEndpoint.ts +var import_node_config_provider = __nccwpck_require__(3461); +var import_url_parser = __nccwpck_require__(4681); + +// src/config/Endpoint.ts +var Endpoint = /* @__PURE__ */ ((Endpoint2) => { + Endpoint2["IPv4"] = "http://169.254.169.254"; + Endpoint2["IPv6"] = "http://[fd00:ec2::254]"; + return Endpoint2; +})(Endpoint || {}); +// src/config/EndpointConfigOptions.ts +var ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; +var CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; +var ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME], + configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME], + default: void 0 +}; -var import_smithy_client = __nccwpck_require__(3570); +// src/config/EndpointMode.ts +var EndpointMode = /* @__PURE__ */ ((EndpointMode2) => { + EndpointMode2["IPv4"] = "IPv4"; + EndpointMode2["IPv6"] = "IPv6"; + return EndpointMode2; +})(EndpointMode || {}); +// src/config/EndpointModeConfigOptions.ts +var ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; +var CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; +var ENDPOINT_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME], + configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME], + default: "IPv4" /* IPv4 */ +}; -var import_isStreamingPayload = __nccwpck_require__(8977); -var retryMiddleware = /* @__PURE__ */ __name((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; - const isRequest = import_protocol_http.HttpRequest.isInstance(request); - if (isRequest) { - request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)(); +// src/utils/getInstanceMetadataEndpoint.ts +var getInstanceMetadataEndpoint = /* @__PURE__ */ __name(async () => (0, import_url_parser.parseUrl)(await getFromEndpointConfig() || await getFromEndpointModeConfig()), "getInstanceMetadataEndpoint"); +var getFromEndpointConfig = /* @__PURE__ */ __name(async () => (0, import_node_config_provider.loadConfig)(ENDPOINT_CONFIG_OPTIONS)(), "getFromEndpointConfig"); +var getFromEndpointModeConfig = /* @__PURE__ */ __name(async () => { + const endpointMode = await (0, import_node_config_provider.loadConfig)(ENDPOINT_MODE_CONFIG_OPTIONS)(); + switch (endpointMode) { + case "IPv4" /* IPv4 */: + return "http://169.254.169.254" /* IPv4 */; + case "IPv6" /* IPv6 */: + return "http://[fd00:ec2::254]" /* IPv6 */; + default: + throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`); + } +}, "getFromEndpointModeConfig"); + +// src/utils/getExtendedInstanceMetadataCredentials.ts +var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; +var STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; +var STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; +var getExtendedInstanceMetadataCredentials = /* @__PURE__ */ __name((credentials, logger) => { + 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 * 1e3); + 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)}. +For more information, please visit: ` + STATIC_STABILITY_DOC_URL + ); + const originalExpiration = credentials.originalExpiration ?? credentials.expiration; + return { + ...credentials, + ...originalExpiration ? { originalExpiration } : {}, + expiration: newExpiration + }; +}, "getExtendedInstanceMetadataCredentials"); + +// src/utils/staticStabilityProvider.ts +var staticStabilityProvider = /* @__PURE__ */ __name((provider, options = {}) => { + const logger = options?.logger || console; + let pastCredentials; + return async () => { + let credentials; + try { + credentials = await provider(); + if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { + credentials = getExtendedInstanceMetadataCredentials(credentials, logger); + } + } catch (e) { + if (pastCredentials) { + logger.warn("Credential renew failed: ", e); + credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger); + } else { + throw e; + } } - while (true) { + pastCredentials = credentials; + return credentials; + }; +}, "staticStabilityProvider"); + +// src/fromInstanceMetadata.ts +var IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; +var IMDS_TOKEN_PATH = "/latest/api/token"; +var AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; +var PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; +var X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; +var fromInstanceMetadata = /* @__PURE__ */ __name((init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger }), "fromInstanceMetadata"); +var getInstanceMetadataProvider = /* @__PURE__ */ __name((init = {}) => { + let disableFetchToken = false; + const { logger, profile } = init; + const { timeout, maxRetries } = providerConfigFromInit(init); + const getCredentials = /* @__PURE__ */ __name(async (maxRetries2, options) => { + const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null; + if (isImdsV1Fallback) { + let fallbackBlockedFromProfile = false; + let fallbackBlockedFromProcessEnv = false; + const configValue = await (0, import_node_config_provider.loadConfig)( + { + environmentVariableSelector: (env) => { + const envValue = env[AWS_EC2_METADATA_V1_DISABLED]; + fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; + if (envValue === void 0) { + throw new import_property_provider.CredentialsProviderError( + `${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, + { logger: init.logger } + ); + } + return fallbackBlockedFromProcessEnv; + }, + configFileSelector: (profile2) => { + const profileValue = profile2[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( + `AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join( + ", " + )}].` + ); + } + } + const imdsProfile = (await retry(async () => { + let profile2; try { - if (isRequest) { - request.headers[import_util_retry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + profile2 = await getProfile(options); + } catch (err) { + if (err.statusCode === 401) { + disableFetchToken = false; } - 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 = asSdkError(e); - if (isRequest && (0, import_isStreamingPayload.isStreamingPayload)(request)) { - (context.logger instanceof import_smithy_client.NoOpLogger ? console : context.logger)?.warn( - "An error was encountered in a non-retryable streaming request." - ); - throw lastError; + throw err; + } + return profile2; + }, maxRetries2)).trim(); + return retry(async () => { + let creds; + try { + creds = await getCredentialsFromProfile(imdsProfile, options, init); + } catch (err) { + if (err.statusCode === 401) { + disableFetchToken = false; } - 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; + throw err; + } + return creds; + }, maxRetries2); + }, "getCredentials"); + return async () => { + const endpoint = await getInstanceMetadataEndpoint(); + if (disableFetchToken) { + 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?.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; } - attempts = retryToken.getRetryCount(); - const delay = retryToken.getRetryDelay(); - totalRetryDelay += delay; - await new Promise((resolve) => setTimeout(resolve, delay)); + 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 + }); } - } else { - retryStrategy = retryStrategy; - if (retryStrategy?.mode) - context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]]; - return retryStrategy.retry(next, args); - } -}, "retryMiddleware"); -var isRetryStrategyV2 = /* @__PURE__ */ __name((retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined", "isRetryStrategyV2"); -var getRetryErrorInfo = /* @__PURE__ */ __name((error) => { - const errorInfo = { - error, - errorType: getRetryErrorType(error) }; - const retryAfterHint = getRetryAfterHint(error.$response); - if (retryAfterHint) { - errorInfo.retryAfterHint = retryAfterHint; +}, "getInstanceMetadataProvider"); +var getMetadataToken = /* @__PURE__ */ __name(async (options) => httpRequest({ + ...options, + path: IMDS_TOKEN_PATH, + method: "PUT", + headers: { + "x-aws-ec2-metadata-token-ttl-seconds": "21600" } - return errorInfo; -}, "getRetryErrorInfo"); -var getRetryErrorType = /* @__PURE__ */ __name((error) => { - if ((0, import_service_error_classification.isThrottlingError)(error)) - return "THROTTLING"; - if ((0, import_service_error_classification.isTransientError)(error)) - return "TRANSIENT"; - if ((0, import_service_error_classification.isServerError)(error)) - return "SERVER_ERROR"; - return "CLIENT_ERROR"; -}, "getRetryErrorType"); -var retryMiddlewareOptions = { - name: "retryMiddleware", - tags: ["RETRY"], - step: "finalizeRequest", - priority: "high", - override: true -}; -var getRetryPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: (clientStack) => { - clientStack.add(retryMiddleware(options), retryMiddlewareOptions); +}), "getMetadataToken"); +var getProfile = /* @__PURE__ */ __name(async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(), "getProfile"); +var getCredentialsFromProfile = /* @__PURE__ */ __name(async (profile, options, init) => { + const credentialsResponse = JSON.parse( + (await httpRequest({ + ...options, + path: IMDS_PATH + profile + })).toString() + ); + if (!isImdsCredentials(credentialsResponse)) { + throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.", { + logger: init.logger + }); } -}), "getRetryPlugin"); -var getRetryAfterHint = /* @__PURE__ */ __name((response) => { - if (!import_protocol_http.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 * 1e3); - const retryAfterDate = new Date(retryAfter); - return retryAfterDate; -}, "getRetryAfterHint"); + return fromImdsCredentials(credentialsResponse); +}, "getCredentialsFromProfile"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -62452,22 +47672,7 @@ var getRetryAfterHint = /* @__PURE__ */ __name((response) => { /***/ }), -/***/ 8977: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isStreamingPayload = void 0; -const stream_1 = __nccwpck_require__(2781); -const isStreamingPayload = (request) => (request === null || request === void 0 ? void 0 : request.body) instanceof stream_1.Readable || - (typeof ReadableStream !== "undefined" && (request === null || request === void 0 ? void 0 : request.body) instanceof ReadableStream); -exports.isStreamingPayload = isStreamingPayload; - - -/***/ }), - -/***/ 1238: +/***/ 6459: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -62492,420 +47697,446 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - deserializerMiddleware: () => deserializerMiddleware, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - getSerdePlugin: () => getSerdePlugin, - serializerMiddleware: () => serializerMiddleware, - serializerMiddlewareOption: () => serializerMiddlewareOption + EventStreamCodec: () => EventStreamCodec, + HeaderMarshaller: () => HeaderMarshaller, + Int64: () => Int64, + MessageDecoderStream: () => MessageDecoderStream, + MessageEncoderStream: () => MessageEncoderStream, + SmithyMessageDecoderStream: () => SmithyMessageDecoderStream, + SmithyMessageEncoderStream: () => SmithyMessageEncoderStream }); module.exports = __toCommonJS(src_exports); -// src/deserializerMiddleware.ts -var import_protocol_http = __nccwpck_require__(4418); -var deserializerMiddleware = /* @__PURE__ */ __name((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.`; - try { - error.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); - } - } - if (typeof error.$responseBodyText !== "undefined") { - if (error.$response) { - error.$response.body = error.$responseBodyText; +// src/EventStreamCodec.ts +var import_crc322 = __nccwpck_require__(8408); + +// src/HeaderMarshaller.ts + + +// src/Int64.ts +var import_util_hex_encoding = __nccwpck_require__(5364); +var Int64 = class _Int64 { + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static { + __name(this, "Int64"); + } + static fromNumber(number) { + if (number > 9223372036854776e3 || number < -9223372036854776e3) { + 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); + } + /** + * Called implicitly by infix arithmetic operators. + */ + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 128; + if (negative) { + negate(bytes); + } + return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } +}; +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 255; + } + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; + } +} +__name(negate, "negate"); + +// src/HeaderMarshaller.ts +var HeaderMarshaller = class { + constructor(toUtf8, fromUtf8) { + this.toUtf8 = toUtf8; + this.fromUtf8 = fromUtf8; + } + static { + __name(this, "HeaderMarshaller"); + } + 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 /* boolTrue */ : 1 /* boolFalse */]); + case "byte": + return Uint8Array.from([2 /* byte */, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3 /* short */); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4 /* integer */); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5 /* long */; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6 /* byteArray */); + 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 /* string */); + 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 /* timestamp */; + tsBytes.set(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}`); } - } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9 /* uuid */; + uuidBytes.set((0, import_util_hex_encoding.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 /* boolTrue */: + out[name] = { + type: BOOLEAN_TAG, + value: true }; - } - } catch (e) { + break; + case 1 /* boolFalse */: + out[name] = { + type: BOOLEAN_TAG, + value: false + }; + break; + case 2 /* byte */: + out[name] = { + type: BYTE_TAG, + value: headers.getInt8(position++) + }; + break; + case 3 /* short */: + out[name] = { + type: SHORT_TAG, + value: headers.getInt16(position, false) + }; + position += 2; + break; + case 4 /* integer */: + out[name] = { + type: INT_TAG, + value: headers.getInt32(position, false) + }; + position += 4; + break; + case 5 /* long */: + out[name] = { + type: LONG_TAG, + value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)) + }; + position += 8; + break; + case 6 /* byteArray */: + 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 /* string */: + 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 /* timestamp */: + out[name] = { + type: TIMESTAMP_TAG, + value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()) + }; + position += 8; + break; + case 9 /* uuid */: + const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); + position += 16; + out[name] = { + type: UUID_TAG, + value: `${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(0, 4))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(4, 6))}-${(0, import_util_hex_encoding.toHex)( + uuidBytes.subarray(6, 8) + )}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(8, 10))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(10))}` + }; + break; + default: + throw new Error(`Unrecognized header type tag`); } } - throw error; + return out; } -}, "deserializerMiddleware"); -var findHeader = /* @__PURE__ */ __name((pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}, "findHeader"); +}; +var BOOLEAN_TAG = "boolean"; +var BYTE_TAG = "byte"; +var SHORT_TAG = "short"; +var INT_TAG = "integer"; +var LONG_TAG = "long"; +var BINARY_TAG = "binary"; +var STRING_TAG = "string"; +var TIMESTAMP_TAG = "timestamp"; +var UUID_TAG = "uuid"; +var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; -// src/serializerMiddleware.ts -var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { - const endpointConfig = options; - const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; - if (!endpoint) { - throw new Error("No valid endpoint provider available."); +// src/splitMessage.ts +var import_crc32 = __nccwpck_require__(8408); +var PRELUDE_MEMBER_LENGTH = 4; +var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; +var CHECKSUM_LENGTH = 4; +var 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 import_crc32.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}` + ); } - const request = await serializer(args.input, { ...options, endpoint }); - return next({ - ...args, - request - }); -}, "serializerMiddleware"); - -// src/serdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true -}; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true -}; -function getSerdePlugin(config, serializer, deserializer) { return { - applyToStack: (commandStack) => { - commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); - commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); - } + 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) + ) }; } -__name(getSerdePlugin, "getSerdePlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 7911: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - constructStack: () => constructStack -}); -module.exports = __toCommonJS(src_exports); +__name(splitMessage, "splitMessage"); -// src/MiddlewareStack.ts -var getAllAliases = /* @__PURE__ */ __name((name, aliases) => { - const _aliases = []; - if (name) { - _aliases.push(name); - } - if (aliases) { - for (const alias of aliases) { - _aliases.push(alias); - } +// src/EventStreamCodec.ts +var EventStreamCodec = class { + static { + __name(this, "EventStreamCodec"); } - return _aliases; -}, "getAllAliases"); -var getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name, aliases) => { - return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; -}, "getMiddlewareNameWithAliases"); -var constructStack = /* @__PURE__ */ __name(() => { - let absoluteEntries = []; - let relativeEntries = []; - let identifyOnResolve = false; - const entriesNameSet = /* @__PURE__ */ new Set(); - const sort = /* @__PURE__ */ __name((entries) => entries.sort( - (a, b) => stepWeights[b.step] - stepWeights[a.step] || priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"] - ), "sort"); - const removeByName = /* @__PURE__ */ __name((toRemove) => { - let isRemoved = false; - const filterCb = /* @__PURE__ */ __name((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; - }, "filterCb"); - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, "removeByName"); - const removeByReference = /* @__PURE__ */ __name((toRemove) => { - let isRemoved = false; - const filterCb = /* @__PURE__ */ __name((entry) => { - if (entry.middleware === toRemove) { - isRemoved = true; - for (const alias of getAllAliases(entry.name, entry.aliases)) { - entriesNameSet.delete(alias); - } - return false; - } - return true; - }, "filterCb"); - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, "removeByReference"); - const cloneTo = /* @__PURE__ */ __name((toStack) => { - absoluteEntries.forEach((entry) => { - toStack.add(entry.middleware, { ...entry }); - }); - relativeEntries.forEach((entry) => { - toStack.addRelativeTo(entry.middleware, { ...entry }); - }); - toStack.identifyOnResolve?.(stack.identifyOnResolve()); - return toStack; - }, "cloneTo"); - const expandRelativeMiddlewareList = /* @__PURE__ */ __name((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; - }, "expandRelativeMiddlewareList"); - const getMiddlewareList = /* @__PURE__ */ __name((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 === void 0) { - 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; - }, "getMiddlewareList"); - 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( - (entry2) => entry2.name === alias || entry2.aliases?.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( - (entry2) => entry2.name === alias || entry2.aliases?.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(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 = /* @__PURE__ */ __name((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; - }, "filterCb"); - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, - concat: (from) => { - const cloned = cloneTo(constructStack()); - cloned.use(from); - cloned.identifyOnResolve( - identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false) - ); - return cloned; - }, - applyToStack: cloneTo, - identify: () => { - return getMiddlewareList(true).map((mw) => { - const step = mw.step ?? 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); + constructor(toUtf8, fromUtf8) { + this.headerMarshaller = new 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; } - if (identifyOnResolve) { - console.log(stack.identify()); + }; + } + getAvailableMessages() { + const messages = this.messageBuffer; + this.messageBuffer = []; + const isEndOfStream = this.isEndOfStream; + return { + getMessages() { + return messages; + }, + isEndOfStream() { + return isEndOfStream; } - return handler; + }; + } + /** + * Convert a structured JavaScript object with tagged headers into a binary + * event stream message. + */ + 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 import_crc322.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; + } + /** + * Convert a binary event stream message into a JavaScript object with an + * opaque, binary body and tagged, parsed headers. + */ + decode(message) { + const { headers, body } = splitMessage(message); + return { headers: this.headerMarshaller.parse(headers), body }; + } + /** + * Convert a structured JavaScript object with tagged headers into a binary + * event stream message header. + */ + formatHeaders(rawHeaders) { + return this.headerMarshaller.format(rawHeaders); + } +}; + +// src/MessageDecoderStream.ts +var MessageDecoderStream = class { + constructor(options) { + this.options = options; + } + static { + __name(this, "MessageDecoderStream"); + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const bytes of this.options.inputStream) { + const decoded = this.options.decoder.decode(bytes); + yield decoded; } - }; - return stack; -}, "constructStack"); -var stepWeights = { - initialize: 5, - serialize: 4, - build: 3, - finalizeRequest: 2, - deserialize: 1 + } }; -var priorityWeights = { - high: 3, - normal: 2, - low: 1 + +// src/MessageEncoderStream.ts +var MessageEncoderStream = class { + constructor(options) { + this.options = options; + } + static { + __name(this, "MessageEncoderStream"); + } + [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); + } + } +}; + +// src/SmithyMessageDecoderStream.ts +var SmithyMessageDecoderStream = class { + constructor(options) { + this.options = options; + } + static { + __name(this, "SmithyMessageDecoderStream"); + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const message of this.options.messageStream) { + const deserialized = await this.options.deserializer(message); + if (deserialized === void 0) + continue; + yield deserialized; + } + } +}; + +// src/SmithyMessageEncoderStream.ts +var SmithyMessageEncoderStream = class { + constructor(options) { + this.options = options; + } + static { + __name(this, "SmithyMessageEncoderStream"); + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const chunk of this.options.inputStream) { + const payloadBuf = this.options.serializer(chunk); + yield payloadBuf; + } + } }; // Annotate the CommonJS export names for ESM import in node: @@ -62915,8 +48146,8 @@ var priorityWeights = { /***/ }), -/***/ 3461: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 6181: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -62940,87 +48171,294 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - loadConfig: () => loadConfig + resolveEventStreamSerdeConfig: () => resolveEventStreamSerdeConfig }); module.exports = __toCommonJS(src_exports); -// src/configLoader.ts +// src/EventStreamSerdeConfig.ts +var resolveEventStreamSerdeConfig = /* @__PURE__ */ __name((input) => Object.assign(input, { + eventStreamMarshaller: input.eventStreamSerdeProvider(input) +}), "resolveEventStreamSerdeConfig"); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); -// src/fromEnv.ts -var import_property_provider = __nccwpck_require__(9721); -// src/getSelectorName.ts -function getSelectorName(functionString) { - try { - const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); - constants.delete("CONFIG"); - constants.delete("CONFIG_PREFIX_SEPARATOR"); - constants.delete("ENV"); - return [...constants].join(", "); - } catch (e) { - return functionString; + +/***/ }), + +/***/ 7682: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } -} -__name(getSelectorName, "getSelectorName"); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/fromEnv.ts -var fromEnv = /* @__PURE__ */ __name((envVarSelector, options) => async () => { - try { - const config = envVarSelector(process.env, options); - if (config === void 0) { - throw new Error(); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + EventStreamMarshaller: () => EventStreamMarshaller, + eventStreamSerdeProvider: () => eventStreamSerdeProvider +}); +module.exports = __toCommonJS(src_exports); + +// src/EventStreamMarshaller.ts +var import_eventstream_serde_universal = __nccwpck_require__(6673); +var import_stream = __nccwpck_require__(2781); + +// src/utils.ts +async function* readabletoIterable(readStream) { + let streamEnded = false; + let generationEnded = false; + const records = new Array(); + readStream.on("error", (err) => { + if (!streamEnded) { + streamEnded = true; } - return config; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, - { logger: options?.logger } - ); + if (err) { + throw err; + } + }); + readStream.on("data", (data) => { + records.push(data); + }); + readStream.on("end", () => { + streamEnded = true; + }); + while (!generationEnded) { + const value = await new Promise((resolve) => setTimeout(() => resolve(records.shift()), 0)); + if (value) { + yield value; + } + generationEnded = streamEnded && records.length === 0; } -}, "fromEnv"); +} +__name(readabletoIterable, "readabletoIterable"); -// src/fromSharedConfigFiles.ts +// src/EventStreamMarshaller.ts +var EventStreamMarshaller = class { + static { + __name(this, "EventStreamMarshaller"); + } + constructor({ utf8Encoder, utf8Decoder }) { + this.universalMarshaller = new import_eventstream_serde_universal.EventStreamMarshaller({ + utf8Decoder, + utf8Encoder + }); + } + deserialize(body, deserializer) { + const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body); + return this.universalMarshaller.deserialize(bodyIterable, deserializer); + } + serialize(input, serializer) { + return import_stream.Readable.from(this.universalMarshaller.serialize(input, serializer)); + } +}; -var import_shared_ini_file_loader = __nccwpck_require__(3507); -var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init } = {}) => async () => { - const profile = (0, import_shared_ini_file_loader.getProfileName)(init); - const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.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 === void 0) { - throw new Error(); - } - return configValue; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, - { logger: init.logger } - ); +// src/provider.ts +var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 6673: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } -}, "fromSharedConfigFiles"); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/fromStatic.ts +// src/index.ts +var src_exports = {}; +__export(src_exports, { + EventStreamMarshaller: () => EventStreamMarshaller, + eventStreamSerdeProvider: () => eventStreamSerdeProvider +}); +module.exports = __toCommonJS(src_exports); -var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction"); -var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic"); +// src/EventStreamMarshaller.ts +var import_eventstream_codec = __nccwpck_require__(6459); -// src/configLoader.ts -var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { - const { signingName, logger } = configuration; - const envOptions = { signingName, logger }; - return (0, import_property_provider.memoize)( - (0, import_property_provider.chain)( - fromEnv(environmentVariableSelector, envOptions), - fromSharedConfigFiles(configFileSelector, configuration), - fromStatic(defaultValue) - ) - ); -}, "loadConfig"); +// src/getChunkedStream.ts +function getChunkedStream(source) { + let currentMessageTotalLength = 0; + let currentMessagePendingLength = 0; + let currentMessage = null; + let messageLengthBuffer = null; + const allocateMessage = /* @__PURE__ */ __name((size) => { + if (typeof size !== "number") { + throw new Error("Attempted to allocate an event message where size was not a number: " + size); + } + currentMessageTotalLength = size; + currentMessagePendingLength = 4; + currentMessage = new Uint8Array(size); + const currentMessageView = new DataView(currentMessage.buffer); + currentMessageView.setUint32(0, size, false); + }, "allocateMessage"); + const iterator = /* @__PURE__ */ __name(async function* () { + const sourceIterator = source[Symbol.asyncIterator](); + while (true) { + const { value, done } = await sourceIterator.next(); + if (done) { + if (!currentMessageTotalLength) { + return; + } else if (currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + } else { + throw new Error("Truncated event message received."); + } + return; + } + const chunkLength = value.length; + let currentOffset = 0; + while (currentOffset < chunkLength) { + if (!currentMessage) { + const bytesRemaining = chunkLength - currentOffset; + if (!messageLengthBuffer) { + messageLengthBuffer = new Uint8Array(4); + } + const numBytesForTotal = Math.min( + 4 - currentMessagePendingLength, + // remaining bytes to fill the messageLengthBuffer + bytesRemaining + // bytes left in chunk + ); + messageLengthBuffer.set( + // @ts-ignore error TS2532: Object is possibly 'undefined' for value + value.slice(currentOffset, currentOffset + numBytesForTotal), + currentMessagePendingLength + ); + currentMessagePendingLength += numBytesForTotal; + currentOffset += numBytesForTotal; + if (currentMessagePendingLength < 4) { + break; + } + allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); + messageLengthBuffer = null; + } + const numBytesToWrite = Math.min( + currentMessageTotalLength - currentMessagePendingLength, + // number of bytes left to complete message + chunkLength - currentOffset + // number of bytes left in the original chunk + ); + currentMessage.set( + // @ts-ignore error TS2532: Object is possibly 'undefined' for value + value.slice(currentOffset, currentOffset + numBytesToWrite), + currentMessagePendingLength + ); + currentMessagePendingLength += numBytesToWrite; + currentOffset += numBytesToWrite; + if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + currentMessage = null; + currentMessageTotalLength = 0; + currentMessagePendingLength = 0; + } + } + } + }, "iterator"); + return { + [Symbol.asyncIterator]: iterator + }; +} +__name(getChunkedStream, "getChunkedStream"); + +// src/getUnmarshalledStream.ts +function getMessageUnmarshaller(deserializer, toUtf8) { + return async function(message) { + const { value: messageType } = message.headers[":message-type"]; + if (messageType === "error") { + const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError"); + unmodeledError.name = message.headers[":error-code"].value; + throw unmodeledError; + } else if (messageType === "exception") { + const code = message.headers[":exception-type"].value; + const exception = { [code]: message }; + const deserializedException = await deserializer(exception); + if (deserializedException.$unknown) { + const error = new Error(toUtf8(message.body)); + error.name = code; + throw error; + } + throw deserializedException[code]; + } else if (messageType === "event") { + const event = { + [message.headers[":event-type"].value]: message + }; + const deserialized = await deserializer(event); + if (deserialized.$unknown) + return; + return deserialized; + } else { + throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`); + } + }; +} +__name(getMessageUnmarshaller, "getMessageUnmarshaller"); + +// src/EventStreamMarshaller.ts +var EventStreamMarshaller = class { + static { + __name(this, "EventStreamMarshaller"); + } + constructor({ utf8Encoder, utf8Decoder }) { + this.eventStreamCodec = new import_eventstream_codec.EventStreamCodec(utf8Encoder, utf8Decoder); + this.utfEncoder = utf8Encoder; + } + deserialize(body, deserializer) { + const inputStream = getChunkedStream(body); + return new import_eventstream_codec.SmithyMessageDecoderStream({ + messageStream: new import_eventstream_codec.MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), + // @ts-expect-error Type 'T' is not assignable to type 'Record' + deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder) + }); + } + serialize(inputStream, serializer) { + return new import_eventstream_codec.MessageEncoderStream({ + messageStream: new import_eventstream_codec.SmithyMessageEncoderStream({ inputStream, serializer }), + encoder: this.eventStreamCodec, + includeEndFrame: true + }); + } +}; + +// src/provider.ts +var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -63029,14 +48467,12 @@ var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFi /***/ }), -/***/ 258: +/***/ 2687: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -63050,212 +48486,49 @@ var __copyProps = (to, from, except, desc) => { __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); +}; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { - DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, - NodeHttp2Handler: () => NodeHttp2Handler, - NodeHttpHandler: () => NodeHttpHandler, + FetchHttpHandler: () => FetchHttpHandler, + keepAliveSupport: () => keepAliveSupport, streamCollector: () => streamCollector }); module.exports = __toCommonJS(src_exports); -// src/node-http-handler.ts +// src/fetch-http-handler.ts var import_protocol_http = __nccwpck_require__(4418); var import_querystring_builder = __nccwpck_require__(8031); -var import_http = __nccwpck_require__(3685); -var import_https = __nccwpck_require__(5687); - -// src/constants.ts -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; - -// src/get-transformed-headers.ts -var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { - const transformedHeaders = {}; - for (const name of Object.keys(headers)) { - const headerValues = headers[name]; - transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; - } - return transformedHeaders; -}, "getTransformedHeaders"); - -// src/timing.ts -var timing = { - setTimeout: (cb, ms) => setTimeout(cb, ms), - clearTimeout: (timeoutId) => clearTimeout(timeoutId) -}; - -// src/set-connection-timeout.ts -var DEFER_EVENT_LISTENER_TIME = 1e3; -var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { - if (!timeoutInMs) { - return -1; - } - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeoutId = timing.setTimeout(() => { - request.destroy(); - reject( - Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { - name: "TimeoutError" - }) - ); - }, timeoutInMs - offset); - const doWithSocket = /* @__PURE__ */ __name((socket) => { - if (socket?.connecting) { - socket.on("connect", () => { - timing.clearTimeout(timeoutId); - }); - } else { - timing.clearTimeout(timeoutId); - } - }, "doWithSocket"); - if (request.socket) { - doWithSocket(request.socket); - } else { - request.on("socket", doWithSocket); - } - }, "registerTimeout"); - if (timeoutInMs < 2e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); -}, "setConnectionTimeout"); - -// src/set-socket-keep-alive.ts -var DEFER_EVENT_LISTENER_TIME2 = 3e3; -var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { - if (keepAlive !== true) { - return -1; - } - const registerListener = /* @__PURE__ */ __name(() => { - if (request.socket) { - request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - } else { - request.on("socket", (socket) => { - socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - }); - } - }, "registerListener"); - if (deferTimeMs === 0) { - registerListener(); - return 0; - } - return timing.setTimeout(registerListener, deferTimeMs); -}, "setSocketKeepAlive"); - -// src/set-socket-timeout.ts -var DEFER_EVENT_LISTENER_TIME3 = 3e3; -var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeout = timeoutInMs - offset; - const onTimeout = /* @__PURE__ */ __name(() => { - request.destroy(); - reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); - }, "onTimeout"); - if (request.socket) { - request.socket.setTimeout(timeout, onTimeout); - request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); - } else { - request.setTimeout(timeout, onTimeout); - } - }, "registerTimeout"); - if (0 < timeoutInMs && timeoutInMs < 6e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout( - registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), - DEFER_EVENT_LISTENER_TIME3 - ); -}, "setSocketTimeout"); -// src/write-request-body.ts -var import_stream = __nccwpck_require__(2781); -var MIN_WAIT_TIME = 6e3; -async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { - const headers = request.headers ?? {}; - const expect = headers["Expect"] || headers["expect"]; - let timeoutId = -1; - let sendBody = true; - if (expect === "100-continue") { - sendBody = await Promise.race([ - new Promise((resolve) => { - timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); - }), - new Promise((resolve) => { - httpRequest.on("continue", () => { - timing.clearTimeout(timeoutId); - resolve(true); - }); - httpRequest.on("response", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - httpRequest.on("error", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - }) - ]); - } - if (sendBody) { - writeBody(httpRequest, request.body); - } +// src/create-request.ts +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); } -__name(writeRequestBody, "writeRequestBody"); -function writeBody(httpRequest, body) { - if (body instanceof import_stream.Readable) { - body.pipe(httpRequest); - return; - } - if (body) { - if (Buffer.isBuffer(body) || typeof body === "string") { - httpRequest.end(body); - return; - } - const uint8 = body; - if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { - httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); - return; +__name(createRequest, "createRequest"); + +// src/request-timeout.ts +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); } - httpRequest.end(Buffer.from(body)); - return; - } - httpRequest.end(); + }); } -__name(writeBody, "writeBody"); +__name(requestTimeout, "requestTimeout"); -// src/node-http-handler.ts -var DEFAULT_REQUEST_TIMEOUT = 0; -var NodeHttpHandler = class _NodeHttpHandler { - constructor(options) { - this.socketWarningTimestamp = 0; - // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 - 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)); - } - }); - } +// src/fetch-http-handler.ts +var keepAliveSupport = { + supported: void 0 +}; +var FetchHttpHandler = class _FetchHttpHandler { static { - __name(this, "NodeHttpHandler"); + __name(this, "FetchHttpHandler"); } /** * @returns the input if it is an HttpHandler of any class, @@ -63265,572 +48538,482 @@ var NodeHttpHandler = class _NodeHttpHandler { if (typeof instanceOrOptions?.handle === "function") { return instanceOrOptions; } - return new _NodeHttpHandler(instanceOrOptions); + return new _FetchHttpHandler(instanceOrOptions); } - /** - * @internal - * - * @param agent - http(s) agent in use by the NodeHttpHandler instance. - * @param socketWarningTimestamp - last socket usage check timestamp. - * @param logger - channel for the warning. - * @returns timestamp of last emitted warning. - */ - static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { - const { sockets, requests, maxSockets } = agent; - if (typeof maxSockets !== "number" || maxSockets === Infinity) { - return socketWarningTimestamp; - } - const interval = 15e3; - if (Date.now() - interval < socketWarningTimestamp) { - return socketWarningTimestamp; + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); } - if (sockets && requests) { - for (const origin in sockets) { - const socketsInUse = sockets[origin]?.length ?? 0; - const requestsEnqueued = requests[origin]?.length ?? 0; - if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { - logger?.warn?.( - `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. -See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html -or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` - ); - return Date.now(); - } - } + if (keepAliveSupport.supported === void 0) { + keepAliveSupport.supported = Boolean( + typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") + ); } - return socketWarningTimestamp; - } - resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; - const keepAlive = true; - const maxSockets = 50; - return { - connectionTimeout, - requestTimeout: requestTimeout ?? socketTimeout, - socketAcquisitionWarningTimeout, - httpAgent: (() => { - if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { - return httpAgent; - } - return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); - })(), - httpsAgent: (() => { - if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { - return httpsAgent; - } - return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); - })(), - logger: console - }; } destroy() { - this.config?.httpAgent?.destroy(); - this.config?.httpsAgent?.destroy(); } - async handle(request, { abortSignal, requestTimeout } = {}) { + async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { if (!this.config) { this.config = await this.configProvider; } - return new Promise((_resolve, _reject) => { - let writeRequestBodyPromise = void 0; - const timeouts = []; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _reject(arg); - }, "reject"); - if (!this.config) { - throw new Error("Node HTTP request handler config is not resolved"); - } - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const isSSL = request.protocol === "https:"; - const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; - timeouts.push( - timing.setTimeout( - () => { - this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( - agent, - this.socketWarningTimestamp, - this.config.logger - ); - }, - this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) - ) - ); - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - let auth = void 0; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}`; - } - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let hostname = request.hostname ?? ""; - if (hostname[0] === "[" && hostname.endsWith("]")) { - hostname = request.hostname.slice(1, -1); - } else { - hostname = request.hostname; - } - const nodeHttpsOptions = { - headers: request.headers, - host: hostname, - method: request.method, - path, - port: request.port, - agent, - auth - }; - const requestFunc = isSSL ? import_https.request : import_http.request; - const req = requestFunc(nodeHttpsOptions, (res) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: res.statusCode || -1, - reason: res.statusMessage, - headers: getTransformedHeaders(res.headers), - body: res - }); - resolve({ response: httpResponse }); - }); - req.on("error", (err) => { - if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { - reject(Object.assign(err, { name: "TimeoutError" })); - } else { - reject(err); + const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); + } + let path = request.path; + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? void 0 : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method, + credentials + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = /* @__PURE__ */ __name(() => { + }, "removeSignalEventListener"); + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; } - }); - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.destroy(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; + const hasReadableStream = response.body != void 0; + if (!hasReadableStream) { + return response.blob().then((body2) => ({ + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: body2 + }) + })); } - } - const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; - timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); - timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); - const httpAgent = nodeHttpsOptions.agent; - if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { - timeouts.push( - setSocketKeepAlive(req, { - // @ts-expect-error keepAlive is not public on httpAgent. - keepAlive: httpAgent.keepAlive, - // @ts-expect-error keepAliveMsecs is not public on httpAgent. - keepAliveMsecs: httpAgent.keepAliveMsecs + return { + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body }) - ); - } - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { - timeouts.forEach(timing.clearTimeout); - return _reject(e); - }); - }); + }; + }), + requestTimeout(requestTimeoutInMs) + ]; + if (abortSignal) { + raceOfPromises.push( + new Promise((resolve, reject) => { + const onAbort = /* @__PURE__ */ __name(() => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); + } else { + abortSignal.onabort = onAbort; + } + }) + ); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); } updateHttpClientConfig(key, value) { this.config = void 0; this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; + config[key] = value; + return config; }); } - httpHandlerConfigs() { - return this.config ?? {}; + httpHandlerConfigs() { + return this.config ?? {}; + } +}; + +// src/stream-collector.ts +var import_util_base64 = __nccwpck_require__(5600); +var streamCollector = /* @__PURE__ */ __name(async (stream) => { + if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== void 0) { + return new Uint8Array(await stream.arrayBuffer()); + } + return collectBlob(stream); + } + return collectStream(stream); +}, "streamCollector"); +async function collectBlob(blob) { + const base64 = await readToBase64(blob); + const arrayBuffer = (0, import_util_base64.fromBase64)(base64); + return new Uint8Array(arrayBuffer); +} +__name(collectBlob, "collectBlob"); +async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; } -}; + return collected; +} +__name(collectStream, "collectStream"); +function readToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); + } + const result = reader.result ?? ""; + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve(result.substring(dataOffset)); + }; + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); +} +__name(readToBase64, "readToBase64"); +// Annotate the CommonJS export names for ESM import in node: -// src/node-http2-handler.ts +0 && (0); -var import_http22 = __nccwpck_require__(5158); -// src/node-http2-connection-manager.ts -var import_http2 = __toESM(__nccwpck_require__(5158)); +/***/ }), -// src/node-http2-connection-pool.ts -var NodeHttp2ConnectionPool = class { - constructor(sessions) { - this.sessions = []; - this.sessions = sessions ?? []; - } - static { - __name(this, "NodeHttp2ConnectionPool"); - } - 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(); - } - } - } +/***/ 3081: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/node-http2-connection-manager.ts -var NodeHttp2ConnectionManager = class { - constructor(config) { - this.sessionCache = /* @__PURE__ */ new Map(); - this.config = config; - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrency must be greater than zero."); - } - } +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Hash: () => Hash +}); +module.exports = __toCommonJS(src_exports); +var import_util_buffer_from = __nccwpck_require__(1381); +var import_util_utf8 = __nccwpck_require__(1895); +var import_buffer = __nccwpck_require__(4300); +var import_crypto = __nccwpck_require__(6113); +var Hash = class { static { - __name(this, "NodeHttp2ConnectionManager"); + __name(this, "Hash"); } - 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 = import_http2.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 = /* @__PURE__ */ __name(() => { - session.destroy(); - this.deleteSession(url, session); - }, "destroySessionCb"); - 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 NodeHttp2ConnectionPool(); - connectionPool.offerLast(session); - this.sessionCache.set(url, connectionPool); - return session; + constructor(algorithmIdentifier, secret) { + this.algorithmIdentifier = algorithmIdentifier; + this.secret = secret; + this.reset(); } - /** - * Delete a session from the connection pool. - * @param authority The authority of the session to delete. - * @param session The session to delete. - */ - 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); + update(toHash, encoding) { + this.hash.update((0, import_util_utf8.toUint8Array)(castSourceData(toHash, encoding))); } - release(requestContext, session) { - const cacheKey = this.getUrlString(requestContext); - this.sessionCache.get(cacheKey)?.offerLast(session); + digest() { + return Promise.resolve(this.hash.digest()); } - 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); - } + reset() { + this.hash = this.secret ? (0, import_crypto.createHmac)(this.algorithmIdentifier, castSourceData(this.secret)) : (0, import_crypto.createHash)(this.algorithmIdentifier); } - setMaxConcurrentStreams(maxConcurrentStreams) { - if (maxConcurrentStreams && maxConcurrentStreams <= 0) { - throw new RangeError("maxConcurrentStreams must be greater than zero."); - } - this.config.maxConcurrency = maxConcurrentStreams; +}; +function castSourceData(toCast, encoding) { + if (import_buffer.Buffer.isBuffer(toCast)) { + return toCast; } - setDisableConcurrentStreams(disableConcurrentStreams) { - this.config.disableConcurrency = disableConcurrentStreams; + if (typeof toCast === "string") { + return (0, import_util_buffer_from.fromString)(toCast, encoding); } - getUrlString(request) { - return request.destination.toString(); + if (ArrayBuffer.isView(toCast)) { + return (0, import_util_buffer_from.fromArrayBuffer)(toCast.buffer, toCast.byteOffset, toCast.byteLength); + } + return (0, import_util_buffer_from.fromArrayBuffer)(toCast); +} +__name(castSourceData, "castSourceData"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 8866: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/node-http2-handler.ts -var NodeHttp2Handler = class _NodeHttp2Handler { - constructor(options) { - this.metadata = { handlerProtocol: "h2" }; - this.connectionManager = new NodeHttp2ConnectionManager({}); - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((opts) => { - resolve(opts || {}); - }).catch(reject); - } else { - resolve(options || {}); - } - }); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fileStreamHasher: () => fileStreamHasher, + readableStreamHasher: () => readableStreamHasher +}); +module.exports = __toCommonJS(src_exports); + +// src/fileStreamHasher.ts +var import_fs = __nccwpck_require__(7147); + +// src/HashCalculator.ts +var import_util_utf8 = __nccwpck_require__(1895); +var import_stream = __nccwpck_require__(2781); +var HashCalculator = class extends import_stream.Writable { + constructor(hash, options) { + super(options); + this.hash = hash; } static { - __name(this, "NodeHttp2Handler"); + __name(this, "HashCalculator"); } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; + _write(chunk, encoding, callback) { + try { + this.hash.update((0, import_util_utf8.toUint8Array)(chunk)); + } catch (err) { + return callback(err); } - return new _NodeHttp2Handler(instanceOrOptions); + callback(); } - destroy() { - this.connectionManager.destroy(); +}; + +// src/fileStreamHasher.ts +var fileStreamHasher = /* @__PURE__ */ __name((hashCtor, fileStream) => new Promise((resolve, reject) => { + if (!isReadStream(fileStream)) { + reject(new Error("Unable to calculate hash for non-file streams.")); + return; } - async handle(request, { abortSignal, requestTimeout } = {}) { - 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: configRequestTimeout, disableConcurrentStreams } = this.config; - const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; - return new Promise((_resolve, _reject) => { - let fulfilled = false; - let writeRequestBodyPromise = void 0; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }, "reject"); - if (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 = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; - const requestContext = { destination: new URL(authority) }; - const session = this.connectionManager.lease(requestContext, { - requestTimeout: this.config?.sessionTimeout, - disableConcurrentStreams: disableConcurrentStreams || false - }); - const rejectWithDestroy = /* @__PURE__ */ __name((err) => { - if (disableConcurrentStreams) { - this.destroySession(session); - } - fulfilled = true; - reject(err); - }, "rejectWithDestroy"); - const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - const req = session.request({ - ...request.headers, - [import_http22.constants.HTTP2_HEADER_PATH]: path, - [import_http22.constants.HTTP2_HEADER_METHOD]: method - }); - session.ref(); - req.on("response", (headers) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: headers[":status"] || -1, - headers: getTransformedHeaders(headers), - body: req - }); - fulfilled = true; - resolve({ response: httpResponse }); - if (disableConcurrentStreams) { - session.close(); - this.connectionManager.deleteSession(authority, session); - } - }); - if (effectiveRequestTimeout) { - req.setTimeout(effectiveRequestTimeout, () => { - req.close(); - const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); - timeoutError.name = "TimeoutError"; - rejectWithDestroy(timeoutError); - }); - } - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.close(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - rejectWithDestroy(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; - } - } - 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 = writeRequestBody(req, request, effectiveRequestTimeout); - }); + const fileStreamTee = (0, import_fs.createReadStream)(fileStream.path, { + start: fileStream.start, + end: fileStream.end + }); + const hash = new hashCtor(); + const hashCalculator = new HashCalculator(hash); + fileStreamTee.pipe(hashCalculator); + fileStreamTee.on("error", (err) => { + hashCalculator.end(); + reject(err); + }); + hashCalculator.on("error", reject); + hashCalculator.on("finish", function() { + hash.digest().then(resolve).catch(reject); + }); +}), "fileStreamHasher"); +var isReadStream = /* @__PURE__ */ __name((stream) => typeof stream.path === "string", "isReadStream"); + +// src/readableStreamHasher.ts +var readableStreamHasher = /* @__PURE__ */ __name((hashCtor, readableStream) => { + if (readableStream.readableFlowing !== null) { + throw new Error("Unable to calculate hash for flowing readable stream"); } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; + const hash = new hashCtor(); + const hashCalculator = new HashCalculator(hash); + readableStream.pipe(hashCalculator); + return new Promise((resolve, reject) => { + readableStream.on("error", (err) => { + hashCalculator.end(); + reject(err); }); + hashCalculator.on("error", reject); + hashCalculator.on("finish", () => { + hash.digest().then(resolve).catch(reject); + }); + }); +}, "readableStreamHasher"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 780: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - httpHandlerConfigs() { - return this.config ?? {}; - } - /** - * Destroys a session. - * @param session - the session to destroy. - */ - destroySession(session) { - if (!session.destroyed) { - session.destroy(); - } - } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + isArrayBuffer: () => isArrayBuffer +}); +module.exports = __toCommonJS(src_exports); +var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + -// src/stream-collector/collector.ts +/***/ }), -var Collector = class extends import_stream.Writable { - constructor() { - super(...arguments); - this.bufferedBytes = []; - } - static { - __name(this, "Collector"); - } - _write(chunk, encoding, callback) { - this.bufferedBytes.push(chunk); - callback(); +/***/ 2800: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/stream-collector/index.ts -var streamCollector = /* @__PURE__ */ __name((stream) => { - if (isReadableStreamInstance(stream)) { - return collectReadableStream(stream); - } - return new Promise((resolve, reject) => { - const collector = new 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); - }); - }); -}, "streamCollector"); -var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); -async function collectReadableStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; +// src/index.ts +var src_exports = {}; +__export(src_exports, { + contentLengthMiddleware: () => contentLengthMiddleware, + contentLengthMiddlewareOptions: () => contentLengthMiddlewareOptions, + getContentLengthPlugin: () => getContentLengthPlugin +}); +module.exports = __toCommonJS(src_exports); +var import_protocol_http = __nccwpck_require__(4418); +var CONTENT_LENGTH_HEADER = "content-length"; +function contentLengthMiddleware(bodyLengthChecker) { + return (next) => async (args) => { + const request = args.request; + if (import_protocol_http.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) { + } + } } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; - } - return collected; + return next({ + ...args, + request + }); + }; } -__name(collectReadableStream, "collectReadableStream"); +__name(contentLengthMiddleware, "contentLengthMiddleware"); +var contentLengthMiddlewareOptions = { + step: "build", + tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], + name: "contentLengthMiddleware", + override: true +}; +var getContentLengthPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: (clientStack) => { + clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); + } +}), "getContentLengthPlugin"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -63839,8 +49022,66 @@ __name(collectReadableStream, "collectReadableStream"); /***/ }), -/***/ 9721: -/***/ ((module) => { +/***/ 1518: +/***/ ((__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__(3461); +const getEndpointUrlConfig_1 = __nccwpck_require__(7574); +const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId !== null && serviceId !== void 0 ? serviceId : ""))(); +exports.getEndpointFromConfig = getEndpointFromConfig; + + +/***/ }), + +/***/ 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__(3507); +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; + + +/***/ }), + +/***/ 2918: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -63864,143 +49105,269 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize + endpointMiddleware: () => endpointMiddleware, + endpointMiddlewareOptions: () => endpointMiddlewareOptions, + getEndpointFromInstructions: () => getEndpointFromInstructions, + getEndpointPlugin: () => getEndpointPlugin, + resolveEndpointConfig: () => resolveEndpointConfig, + resolveEndpointRequiredConfig: () => resolveEndpointRequiredConfig, + resolveParams: () => resolveParams, + toEndpointV1: () => toEndpointV1 }); module.exports = __toCommonJS(src_exports); -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; +// src/service-customizations/s3.ts +var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => { + const bucket = endpointParams?.Bucket || ""; + if (typeof endpointParams.Bucket === "string") { + endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); + } + if (isArnBucketName(bucket)) { + if (endpointParams.ForcePathStyle === true) { + throw new Error("Path-style addressing cannot be used with ARN buckets"); } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); + } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { + endpointParams.ForcePathStyle = true; } - static { - __name(this, "ProviderError"); + if (endpointParams.DisableMultiRegionAccessPoints) { + endpointParams.disableMultiRegionAccessPoints = true; + endpointParams.DisableMRAP = true; } - /** - * @deprecated use new operator. - */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); + return endpointParams; +}, "resolveParamsForS3"); +var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; +var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; +var DOTS_PATTERN = /\.\./; +var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName"); +var isArnBucketName = /* @__PURE__ */ __name((bucketName) => { + const [arn, partition, service, , , bucket] = bucketName.split(":"); + const isArn = arn === "arn" && bucketName.split(":").length >= 6; + const isValidArn = Boolean(isArn && partition && service && bucket); + if (isArn && !isValidArn) { + throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); } -}; + return isValidArn; +}, "isArnBucketName"); -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); - } - static { - __name(this, "CredentialsProviderError"); +// src/adaptors/createConfigValueProvider.ts +var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => { + const configProvider = /* @__PURE__ */ __name(async () => { + const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; + if (typeof configValue === "function") { + return configValue(); + } + return configValue; + }, "configProvider"); + if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; + return configValue; + }; } -}; - -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); + if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.accountId ?? credentials?.AccountId; + return configValue; + }; } - static { - __name(this, "TokenProviderError"); + if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { + return async () => { + if (config.isCustomEndpoint === false) { + return void 0; + } + 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; +}, "createConfigValueProvider"); -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new 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?.tryNextLink) { - continue; - } - throw err; +// src/adaptors/getEndpointFromInstructions.ts +var import_getEndpointFromConfig = __nccwpck_require__(1518); + +// src/adaptors/toEndpointV1.ts +var import_url_parser = __nccwpck_require__(4681); +var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => { + if (typeof endpoint === "object") { + if ("url" in endpoint) { + return (0, import_url_parser.parseUrl)(endpoint.url); } + return endpoint; } - throw lastProviderError; -}, "chain"); - -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); + return (0, import_url_parser.parseUrl)(endpoint); +}, "toEndpointV1"); -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); +// src/adaptors/getEndpointFromInstructions.ts +var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => { + if (!clientConfig.isCustomEndpoint) { + let endpointFromConfig; + if (clientConfig.serviceConfiguredEndpoint) { + endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); + } else { + endpointFromConfig = await (0, import_getEndpointFromConfig.getEndpointFromConfig)(clientConfig.serviceId); } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; + if (endpointFromConfig) { + clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); + clientConfig.isCustomEndpoint = true; } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; - }; } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); + const endpointParams = await 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; +}, "getEndpointFromInstructions"); +var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => { + const endpointParams = {}; + const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; + 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 createConfigValueProvider(instruction.name, name, clientConfig)(); + break; + case "operationContextParams": + endpointParams[name] = instruction.get(commandInput); + break; + default: + throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); } - if (isConstant) { - return resolved; + } + if (Object.keys(instructions).length === 0) { + Object.assign(endpointParams, clientConfig); + } + if (String(clientConfig.serviceId).toLowerCase() === "s3") { + await resolveParamsForS3(endpointParams); + } + return endpointParams; +}, "resolveParams"); + +// src/endpointMiddleware.ts +var import_core = __nccwpck_require__(5829); +var import_util_middleware = __nccwpck_require__(2390); +var endpointMiddleware = /* @__PURE__ */ __name(({ + config, + instructions +}) => { + return (next, context) => async (args) => { + if (config.isCustomEndpoint) { + (0, import_core.setFeature)(context, "ENDPOINT_OVERRIDE", "N"); } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; + const endpoint = await getEndpointFromInstructions( + args.input, + { + getEndpointParameterInstructions() { + return instructions; + } + }, + { ...config }, + context + ); + context.endpointV2 = endpoint; + context.authSchemes = endpoint.properties?.authSchemes; + const authScheme = context.authSchemes?.[0]; + if (authScheme) { + context["signing_region"] = authScheme.signingRegion; + context["signing_service"] = authScheme.signingName; + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.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 + ); + } } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; + return next({ + ...args + }); + }; +}, "endpointMiddleware"); + +// src/getEndpointPlugin.ts +var import_middleware_serde = __nccwpck_require__(1238); +var endpointMiddlewareOptions = { + step: "serialize", + tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], + name: "endpointV2Middleware", + override: true, + relation: "before", + toMiddleware: import_middleware_serde.serializerMiddlewareOption.name +}; +var getEndpointPlugin = /* @__PURE__ */ __name((config, instructions) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo( + endpointMiddleware({ + config, + instructions + }), + endpointMiddlewareOptions + ); + } +}), "getEndpointPlugin"); + +// src/resolveEndpointConfig.ts + +var import_getEndpointFromConfig2 = __nccwpck_require__(1518); +var resolveEndpointConfig = /* @__PURE__ */ __name((input) => { + const tls = input.tls ?? true; + const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; + const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware.normalizeProvider)(endpoint)()) : void 0; + const isCustomEndpoint = !!endpoint; + const resolvedConfig = Object.assign(input, { + endpoint: customEndpointProvider, + tls, + isCustomEndpoint, + useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false), + useFipsEndpoint: (0, import_util_middleware.normalizeProvider)(useFipsEndpoint ?? false) + }); + let configuredEndpointPromise = void 0; + resolvedConfig.serviceConfiguredEndpoint = async () => { + if (input.serviceId && !configuredEndpointPromise) { + configuredEndpointPromise = (0, import_getEndpointFromConfig2.getEndpointFromConfig)(input.serviceId); } - return resolved; + return configuredEndpointPromise; }; -}, "memoize"); + return resolvedConfig; +}, "resolveEndpointConfig"); + +// src/resolveEndpointRequiredConfig.ts +var resolveEndpointRequiredConfig = /* @__PURE__ */ __name((input) => { + const { endpoint } = input; + if (endpoint === void 0) { + input.endpoint = async () => { + throw new Error( + "@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint." + ); + }; + } + return input; +}, "resolveEndpointRequiredConfig"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -64009,7 +49376,7 @@ var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { /***/ }), -/***/ 4418: +/***/ 6039: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -64034,234 +49401,386 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig + AdaptiveRetryStrategy: () => AdaptiveRetryStrategy, + CONFIG_MAX_ATTEMPTS: () => CONFIG_MAX_ATTEMPTS, + CONFIG_RETRY_MODE: () => CONFIG_RETRY_MODE, + ENV_MAX_ATTEMPTS: () => ENV_MAX_ATTEMPTS, + ENV_RETRY_MODE: () => ENV_RETRY_MODE, + NODE_MAX_ATTEMPT_CONFIG_OPTIONS: () => NODE_MAX_ATTEMPT_CONFIG_OPTIONS, + NODE_RETRY_MODE_CONFIG_OPTIONS: () => NODE_RETRY_MODE_CONFIG_OPTIONS, + StandardRetryStrategy: () => StandardRetryStrategy, + defaultDelayDecider: () => defaultDelayDecider, + defaultRetryDecider: () => defaultRetryDecider, + getOmitRetryHeadersPlugin: () => getOmitRetryHeadersPlugin, + getRetryAfterHint: () => getRetryAfterHint, + getRetryPlugin: () => getRetryPlugin, + omitRetryHeadersMiddleware: () => omitRetryHeadersMiddleware, + omitRetryHeadersMiddlewareOptions: () => omitRetryHeadersMiddlewareOptions, + resolveRetryConfig: () => resolveRetryConfig, + retryMiddleware: () => retryMiddleware, + retryMiddlewareOptions: () => retryMiddlewareOptions }); module.exports = __toCommonJS(src_exports); -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); +// src/AdaptiveRetryStrategy.ts + + +// src/StandardRetryStrategy.ts +var import_protocol_http = __nccwpck_require__(4418); + + +var import_uuid = __nccwpck_require__(5840); + +// src/defaultRetryQuota.ts +var import_util_retry = __nccwpck_require__(4902); +var getDefaultRetryQuota = /* @__PURE__ */ __name((initialRetryTokens, options) => { + const MAX_CAPACITY = initialRetryTokens; + const noRetryIncrement = options?.noRetryIncrement ?? import_util_retry.NO_RETRY_INCREMENT; + const retryCost = options?.retryCost ?? import_util_retry.RETRY_COST; + const timeoutRetryCost = options?.timeoutRetryCost ?? import_util_retry.TIMEOUT_RETRY_COST; + let availableCapacity = initialRetryTokens; + const getCapacityAmount = /* @__PURE__ */ __name((error) => error.name === "TimeoutError" ? timeoutRetryCost : retryCost, "getCapacityAmount"); + const hasRetryTokens = /* @__PURE__ */ __name((error) => getCapacityAmount(error) <= availableCapacity, "hasRetryTokens"); + const retrieveRetryTokens = /* @__PURE__ */ __name((error) => { + if (!hasRetryTokens(error)) { + throw new Error("No retry token available"); } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); + const capacityAmount = getCapacityAmount(error); + availableCapacity -= capacityAmount; + return capacityAmount; + }, "retrieveRetryTokens"); + const releaseRetryTokens = /* @__PURE__ */ __name((capacityReleaseAmount) => { + availableCapacity += capacityReleaseAmount ?? noRetryIncrement; + availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); + }, "releaseRetryTokens"); + return Object.freeze({ + hasRetryTokens, + retrieveRetryTokens, + releaseRetryTokens + }); +}, "getDefaultRetryQuota"); -// src/Field.ts -var import_types = __nccwpck_require__(5756); -var Field = class { - static { - __name(this, "Field"); - } - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; +// src/delayDecider.ts + +var defaultDelayDecider = /* @__PURE__ */ __name((delayBase, attempts) => Math.floor(Math.min(import_util_retry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)), "defaultDelayDecider"); + +// src/retryDecider.ts +var import_service_error_classification = __nccwpck_require__(6375); +var defaultRetryDecider = /* @__PURE__ */ __name((error) => { + if (!error) { + return false; } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); + return (0, import_service_error_classification.isRetryableByTrait)(error) || (0, import_service_error_classification.isClockSkewError)(error) || (0, import_service_error_classification.isThrottlingError)(error) || (0, import_service_error_classification.isTransientError)(error); +}, "defaultRetryDecider"); + +// src/util.ts +var asSdkError = /* @__PURE__ */ __name((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}`); +}, "asSdkError"); + +// src/StandardRetryStrategy.ts +var StandardRetryStrategy = class { + constructor(maxAttemptsProvider, options) { + this.maxAttemptsProvider = maxAttemptsProvider; + this.mode = import_util_retry.RETRY_MODES.STANDARD; + this.retryDecider = options?.retryDecider ?? defaultRetryDecider; + this.delayDecider = options?.delayDecider ?? defaultDelayDecider; + this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(import_util_retry.INITIAL_RETRY_TOKENS); } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; + static { + __name(this, "StandardRetryStrategy"); } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); + shouldRetry(error, attempts, maxAttempts) { + return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error); } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + async getMaxAttempts() { + let maxAttempts; + try { + maxAttempts = await this.maxAttemptsProvider(); + } catch (error) { + maxAttempts = import_util_retry.DEFAULT_MAX_ATTEMPTS; + } + return maxAttempts; } - /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. - */ - get() { - return this.values; + async retry(next, args, options) { + let retryTokenAmount; + let attempts = 0; + let totalDelay = 0; + const maxAttempts = await this.getMaxAttempts(); + const { request } = args; + if (import_protocol_http.HttpRequest.isInstance(request)) { + request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)(); + } + while (true) { + try { + if (import_protocol_http.HttpRequest.isInstance(request)) { + request.headers[import_util_retry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + if (options?.beforeRequest) { + await options.beforeRequest(); + } + const { response, output } = await next(args); + if (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 = asSdkError(e); + attempts++; + if (this.shouldRetry(err, attempts, maxAttempts)) { + retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); + const delayFromDecider = this.delayDecider( + (0, import_service_error_classification.isThrottlingError)(err) ? import_util_retry.THROTTLING_RETRY_DELAY_BASE : import_util_retry.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; + } + } } }; +var getDelayFromRetryAfterHeader = /* @__PURE__ */ __name((response) => { + if (!import_protocol_http.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 * 1e3; + const retryAfterDate = new Date(retryAfter); + return retryAfterDate.getTime() - Date.now(); +}, "getDelayFromRetryAfterHeader"); -// src/Fields.ts -var Fields = class { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } +// src/AdaptiveRetryStrategy.ts +var AdaptiveRetryStrategy = class extends StandardRetryStrategy { static { - __name(this, "Fields"); - } - /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. - */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; - } - /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. - */ - getField(name) { - return this.entries[name.toLowerCase()]; + __name(this, "AdaptiveRetryStrategy"); } - /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. - */ - removeField(name) { - delete this.entries[name.toLowerCase()]; + constructor(maxAttemptsProvider, options) { + const { rateLimiter, ...superOptions } = options ?? {}; + super(maxAttemptsProvider, superOptions); + this.rateLimiter = rateLimiter ?? new import_util_retry.DefaultRateLimiter(); + this.mode = import_util_retry.RETRY_MODES.ADAPTIVE; } - /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. - */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); + async retry(next, args) { + return super.retry(next, args, { + beforeRequest: async () => { + return this.rateLimiter.getSendToken(); + }, + afterRequest: (response) => { + this.rateLimiter.updateClientSendingRate(response); + } + }); } }; -// src/httpRequest.ts +// src/configurations.ts +var import_util_middleware = __nccwpck_require__(2390); -var HttpRequest = class _HttpRequest { - static { - __name(this, "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; - } - /** - * Note: this does not deep-clone the body. - */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); +var ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; +var CONFIG_MAX_ATTEMPTS = "max_attempts"; +var NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => { + const value = env[ENV_MAX_ATTEMPTS]; + if (!value) + return void 0; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); } - return cloned; - } - /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. - * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. - */ - static isInstance(request) { - if (!request) { - return false; + return maxAttempt; + }, + configFileSelector: (profile) => { + const value = profile[CONFIG_MAX_ATTEMPTS]; + if (!value) + return void 0; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; - } - /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). - */ - clone() { - return _HttpRequest.clone(this); - } + return maxAttempt; + }, + default: import_util_retry.DEFAULT_MAX_ATTEMPTS +}; +var resolveRetryConfig = /* @__PURE__ */ __name((input) => { + const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input; + const maxAttempts = (0, import_util_middleware.normalizeProvider)(_maxAttempts ?? import_util_retry.DEFAULT_MAX_ATTEMPTS); + return Object.assign(input, { + maxAttempts, + retryStrategy: async () => { + if (retryStrategy) { + return retryStrategy; + } + const retryMode = await (0, import_util_middleware.normalizeProvider)(_retryMode)(); + if (retryMode === import_util_retry.RETRY_MODES.ADAPTIVE) { + return new import_util_retry.AdaptiveRetryStrategy(maxAttempts); + } + return new import_util_retry.StandardRetryStrategy(maxAttempts); + } + }); +}, "resolveRetryConfig"); +var ENV_RETRY_MODE = "AWS_RETRY_MODE"; +var CONFIG_RETRY_MODE = "retry_mode"; +var NODE_RETRY_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_RETRY_MODE], + configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], + default: import_util_retry.DEFAULT_RETRY_MODE }; -function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param - }; - }, {}); -} -__name(cloneQuery, "cloneQuery"); -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); +// src/omitRetryHeadersMiddleware.ts + + +var omitRetryHeadersMiddleware = /* @__PURE__ */ __name(() => (next) => async (args) => { + const { request } = args; + if (import_protocol_http.HttpRequest.isInstance(request)) { + delete request.headers[import_util_retry.INVOCATION_ID_HEADER]; + delete request.headers[import_util_retry.REQUEST_HEADER]; } - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; + return next(args); +}, "omitRetryHeadersMiddleware"); +var omitRetryHeadersMiddlewareOptions = { + name: "omitRetryHeadersMiddleware", + tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], + relation: "before", + toMiddleware: "awsAuthMiddleware", + override: true +}; +var getOmitRetryHeadersPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); + } +}), "getOmitRetryHeadersPlugin"); + +// src/retryMiddleware.ts + + +var import_smithy_client = __nccwpck_require__(3570); + + +var import_isStreamingPayload = __nccwpck_require__(8977); +var retryMiddleware = /* @__PURE__ */ __name((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; + const isRequest = import_protocol_http.HttpRequest.isInstance(request); + if (isRequest) { + request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)(); + } + while (true) { + try { + if (isRequest) { + request.headers[import_util_retry.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 = asSdkError(e); + if (isRequest && (0, import_isStreamingPayload.isStreamingPayload)(request)) { + (context.logger instanceof import_smithy_client.NoOpLogger ? console : context.logger)?.warn( + "An error was encountered in a non-retryable streaming request." + ); + throw lastError; + } + 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?.mode) + context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]]; + return retryStrategy.retry(next, args); } - static isInstance(response) { - if (!response) - return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; +}, "retryMiddleware"); +var isRetryStrategyV2 = /* @__PURE__ */ __name((retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined", "isRetryStrategyV2"); +var getRetryErrorInfo = /* @__PURE__ */ __name((error) => { + const errorInfo = { + error, + errorType: getRetryErrorType(error) + }; + const retryAfterHint = getRetryAfterHint(error.$response); + if (retryAfterHint) { + errorInfo.retryAfterHint = retryAfterHint; } + return errorInfo; +}, "getRetryErrorInfo"); +var getRetryErrorType = /* @__PURE__ */ __name((error) => { + if ((0, import_service_error_classification.isThrottlingError)(error)) + return "THROTTLING"; + if ((0, import_service_error_classification.isTransientError)(error)) + return "TRANSIENT"; + if ((0, import_service_error_classification.isServerError)(error)) + return "SERVER_ERROR"; + return "CLIENT_ERROR"; +}, "getRetryErrorType"); +var retryMiddlewareOptions = { + name: "retryMiddleware", + tags: ["RETRY"], + step: "finalizeRequest", + priority: "high", + override: true }; - -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); +var getRetryPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: (clientStack) => { + clientStack.add(retryMiddleware(options), retryMiddlewareOptions); + } +}), "getRetryPlugin"); +var getRetryAfterHint = /* @__PURE__ */ __name((response) => { + if (!import_protocol_http.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 * 1e3); + const retryAfterDate = new Date(retryAfter); + return retryAfterDate; +}, "getRetryAfterHint"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -64270,65 +49789,23 @@ __name(isValidHostname, "isValidHostname"); /***/ }), -/***/ 8031: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - buildQueryString: () => buildQueryString -}); -module.exports = __toCommonJS(src_exports); -var import_util_uri_escape = __nccwpck_require__(4197); -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = (0, import_util_uri_escape.escapeUri)(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); - } - } else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; - } - parts.push(qsEntry); - } - } - return parts.join("&"); -} -__name(buildQueryString, "buildQueryString"); -// Annotate the CommonJS export names for ESM import in node: +/***/ 8977: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -0 && (0); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isStreamingPayload = void 0; +const stream_1 = __nccwpck_require__(2781); +const isStreamingPayload = (request) => (request === null || request === void 0 ? void 0 : request.body) instanceof stream_1.Readable || + (typeof ReadableStream !== "undefined" && (request === null || request === void 0 ? void 0 : request.body) instanceof ReadableStream); +exports.isStreamingPayload = isStreamingPayload; /***/ }), -/***/ 4769: -/***/ ((module) => { +/***/ 1238: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -64352,31 +49829,103 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - parseQueryString: () => parseQueryString + deserializerMiddleware: () => deserializerMiddleware, + deserializerMiddlewareOption: () => deserializerMiddlewareOption, + getSerdePlugin: () => getSerdePlugin, + serializerMiddleware: () => serializerMiddleware, + serializerMiddlewareOption: () => serializerMiddlewareOption }); module.exports = __toCommonJS(src_exports); -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); + +// src/deserializerMiddleware.ts +var import_protocol_http = __nccwpck_require__(4418); +var deserializerMiddleware = /* @__PURE__ */ __name((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.`; + try { + error.message += "\n " + hint; + } catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); + } } - if (!(key in query)) { - query[key] = value; - } else if (Array.isArray(query[key])) { - query[key].push(value); - } else { - query[key] = [query[key], value]; + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } + } + try { + if (import_protocol_http.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + }; + } + } catch (e) { } } + throw error; } - return query; +}, "deserializerMiddleware"); +var findHeader = /* @__PURE__ */ __name((pattern, headers) => { + return (headers.find(([k]) => { + return k.match(pattern); + }) || [void 0, void 0])[1]; +}, "findHeader"); + +// src/serializerMiddleware.ts +var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { + const endpointConfig = options; + const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; + if (!endpoint) { + throw new Error("No valid endpoint provider available."); + } + const request = await serializer(args.input, { ...options, endpoint }); + return next({ + ...args, + request + }); +}, "serializerMiddleware"); + +// src/serdePlugin.ts +var deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true +}; +var serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true +}; +function getSerdePlugin(config, serializer, deserializer) { + return { + applyToStack: (commandStack) => { + commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); + commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); + } + }; } -__name(parseQueryString, "parseQueryString"); +__name(getSerdePlugin, "getSerdePlugin"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -64385,7 +49934,7 @@ __name(parseQueryString, "parseQueryString"); /***/ }), -/***/ 6375: +/***/ 7911: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -64410,165 +49959,300 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - isBrowserNetworkError: () => isBrowserNetworkError, - isClockSkewCorrectedError: () => isClockSkewCorrectedError, - isClockSkewError: () => isClockSkewError, - isRetryableByTrait: () => isRetryableByTrait, - isServerError: () => isServerError, - isThrottlingError: () => isThrottlingError, - isTransientError: () => isTransientError + constructStack: () => constructStack }); module.exports = __toCommonJS(src_exports); -// src/constants.ts -var CLOCK_SKEW_ERROR_CODES = [ - "AuthFailure", - "InvalidSignatureException", - "RequestExpired", - "RequestInTheFuture", - "RequestTimeTooSkewed", - "SignatureDoesNotMatch" -]; -var THROTTLING_ERROR_CODES = [ - "BandwidthLimitExceeded", - "EC2ThrottledException", - "LimitExceededException", - "PriorRequestNotComplete", - "ProvisionedThroughputExceededException", - "RequestLimitExceeded", - "RequestThrottled", - "RequestThrottledException", - "SlowDown", - "ThrottledException", - "Throttling", - "ThrottlingException", - "TooManyRequestsException", - "TransactionInProgressException" - // DynamoDB -]; -var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; -var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; -var NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND"]; - -// src/index.ts -var isRetryableByTrait = /* @__PURE__ */ __name((error) => error.$retryable !== void 0, "isRetryableByTrait"); -var isClockSkewError = /* @__PURE__ */ __name((error) => CLOCK_SKEW_ERROR_CODES.includes(error.name), "isClockSkewError"); -var isClockSkewCorrectedError = /* @__PURE__ */ __name((error) => error.$metadata?.clockSkewCorrected, "isClockSkewCorrectedError"); -var isBrowserNetworkError = /* @__PURE__ */ __name((error) => { - const errorMessages = /* @__PURE__ */ new Set([ - "Failed to fetch", - // Chrome - "NetworkError when attempting to fetch resource", - // Firefox - "The Internet connection appears to be offline", - // Safari 16 - "Load failed", - // Safari 17+ - "Network request failed" - // `cross-fetch` - ]); - const isValid = error && error instanceof TypeError; - if (!isValid) { - return false; +// src/MiddlewareStack.ts +var getAllAliases = /* @__PURE__ */ __name((name, aliases) => { + const _aliases = []; + if (name) { + _aliases.push(name); } - return errorMessages.has(error.message); -}, "isBrowserNetworkError"); -var isThrottlingError = /* @__PURE__ */ __name((error) => error.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error.name) || error.$retryable?.throttling == true, "isThrottlingError"); -var isTransientError = /* @__PURE__ */ __name((error, depth = 0) => isClockSkewCorrectedError(error) || TRANSIENT_ERROR_CODES.includes(error.name) || NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || NODEJS_NETWORK_ERROR_CODES.includes(error?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) || isBrowserNetworkError(error) || error.cause !== void 0 && depth <= 10 && isTransientError(error.cause, depth + 1), "isTransientError"); -var isServerError = /* @__PURE__ */ __name((error) => { - if (error.$metadata?.httpStatusCode !== void 0) { - const statusCode = error.$metadata.httpStatusCode; - if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) { - return true; + if (aliases) { + for (const alias of aliases) { + _aliases.push(alias); } - return false; } - return false; -}, "isServerError"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 8340: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getHomeDir = void 0; -const os_1 = __nccwpck_require__(2037); -const path_1 = __nccwpck_require__(1017); -const homeDirCache = {}; -const getHomeDirCacheKey = () => { - if (process && process.geteuid) { - return `${process.geteuid()}`; + return _aliases; +}, "getAllAliases"); +var getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name, aliases) => { + return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; +}, "getMiddlewareNameWithAliases"); +var constructStack = /* @__PURE__ */ __name(() => { + let absoluteEntries = []; + let relativeEntries = []; + let identifyOnResolve = false; + const entriesNameSet = /* @__PURE__ */ new Set(); + const sort = /* @__PURE__ */ __name((entries) => entries.sort( + (a, b) => stepWeights[b.step] - stepWeights[a.step] || priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"] + ), "sort"); + const removeByName = /* @__PURE__ */ __name((toRemove) => { + let isRemoved = false; + const filterCb = /* @__PURE__ */ __name((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; + }, "filterCb"); + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, "removeByName"); + const removeByReference = /* @__PURE__ */ __name((toRemove) => { + let isRemoved = false; + const filterCb = /* @__PURE__ */ __name((entry) => { + if (entry.middleware === toRemove) { + isRemoved = true; + for (const alias of getAllAliases(entry.name, entry.aliases)) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }, "filterCb"); + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, "removeByReference"); + const cloneTo = /* @__PURE__ */ __name((toStack) => { + absoluteEntries.forEach((entry) => { + toStack.add(entry.middleware, { ...entry }); + }); + relativeEntries.forEach((entry) => { + toStack.addRelativeTo(entry.middleware, { ...entry }); + }); + toStack.identifyOnResolve?.(stack.identifyOnResolve()); + return toStack; + }, "cloneTo"); + const expandRelativeMiddlewareList = /* @__PURE__ */ __name((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; + }, "expandRelativeMiddlewareList"); + const getMiddlewareList = /* @__PURE__ */ __name((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 === void 0) { + 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; + }, "getMiddlewareList"); + 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( + (entry2) => entry2.name === alias || entry2.aliases?.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( + (entry2) => entry2.name === alias || entry2.aliases?.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(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 = /* @__PURE__ */ __name((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; + }, "filterCb"); + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, + concat: (from) => { + const cloned = cloneTo(constructStack()); + cloned.use(from); + cloned.identifyOnResolve( + identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false) + ); + return cloned; + }, + applyToStack: cloneTo, + identify: () => { + return getMiddlewareList(true).map((mw) => { + const step = mw.step ?? 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 "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]; + }; + return stack; +}, "constructStack"); +var stepWeights = { + initialize: 5, + serialize: 4, + build: 3, + finalizeRequest: 2, + deserialize: 1 }; -exports.getHomeDir = getHomeDir; - - -/***/ }), - -/***/ 4740: -/***/ ((__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__(1017); -const getHomeDir_1 = __nccwpck_require__(8340); -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`); +var priorityWeights = { + high: 3, + normal: 2, + low: 1 }; -exports.getSSOTokenFilepath = getSSOTokenFilepath; - - -/***/ }), - -/***/ 9678: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFromFile = void 0; -const fs_1 = __nccwpck_require__(7147); -const getSSOTokenFilepath_1 = __nccwpck_require__(4740); -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; /***/ }), -/***/ 3507: +/***/ 3461: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -64588,215 +50272,108 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { - CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, - DEFAULT_PROFILE: () => DEFAULT_PROFILE, - ENV_PROFILE: () => ENV_PROFILE, - getProfileName: () => getProfileName, - loadSharedConfigFiles: () => loadSharedConfigFiles, - loadSsoSessionData: () => loadSsoSessionData, - parseKnownFiles: () => parseKnownFiles + loadConfig: () => loadConfig }); module.exports = __toCommonJS(src_exports); -__reExport(src_exports, __nccwpck_require__(8340), module.exports); - -// src/getProfileName.ts -var ENV_PROFILE = "AWS_PROFILE"; -var DEFAULT_PROFILE = "default"; -var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); -// src/index.ts -__reExport(src_exports, __nccwpck_require__(4740), module.exports); -__reExport(src_exports, __nccwpck_require__(9678), module.exports); +// src/configLoader.ts -// src/loadSharedConfigFiles.ts +// src/fromEnv.ts +var import_property_provider = __nccwpck_require__(9721); -// src/getConfigData.ts -var import_types = __nccwpck_require__(5756); -var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; - } - return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}).reduce( - (acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; - }, - { - // Populate default profile, if present. - ...data.default && { default: data.default } +// src/getSelectorName.ts +function getSelectorName(functionString) { + try { + const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); + constants.delete("CONFIG"); + constants.delete("CONFIG_PREFIX_SEPARATOR"); + constants.delete("ENV"); + return [...constants].join(", "); + } catch (e) { + return functionString; } -), "getConfigData"); - -// src/getConfigFilepath.ts -var import_path = __nccwpck_require__(1017); -var import_getHomeDir = __nccwpck_require__(8340); -var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); - -// src/getCredentialsFilepath.ts - -var import_getHomeDir2 = __nccwpck_require__(8340); -var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); - -// src/loadSharedConfigFiles.ts -var import_getHomeDir3 = __nccwpck_require__(8340); - -// src/parseIni.ts +} +__name(getSelectorName, "getSelectorName"); -var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; -var profileNameBlockList = ["__proto__", "profile __proto__"]; -var parseIni = /* @__PURE__ */ __name((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 = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(import_types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(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 = void 0; - } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; - } - } +// src/fromEnv.ts +var fromEnv = /* @__PURE__ */ __name((envVarSelector, options) => async () => { + try { + const config = envVarSelector(process.env, options); + if (config === void 0) { + throw new Error(); } + return config; + } catch (e) { + throw new import_property_provider.CredentialsProviderError( + e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, + { logger: options?.logger } + ); } - return map; -}, "parseIni"); - -// src/loadSharedConfigFiles.ts -var import_slurpFile = __nccwpck_require__(9155); -var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var CONFIG_PREFIX_SEPARATOR = "."; -var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = (0, import_getHomeDir3.getHomeDir)(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError), - (0, import_slurpFile.slurpFile)(resolvedFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).catch(swallowError) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; -}, "loadSharedConfigFiles"); - -// src/getSsoSessionData.ts - -var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); +}, "fromEnv"); -// src/loadSsoSessionData.ts -var import_slurpFile2 = __nccwpck_require__(9155); -var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); +// src/fromSharedConfigFiles.ts -// src/mergeConfigFiles.ts -var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values); - } else { - merged[key] = values; - } +var import_shared_ini_file_loader = __nccwpck_require__(3507); +var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init } = {}) => async () => { + const profile = (0, import_shared_ini_file_loader.getProfileName)(init); + const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.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 === void 0) { + throw new Error(); } + return configValue; + } catch (e) { + throw new import_property_provider.CredentialsProviderError( + e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, + { logger: init.logger } + ); } - return merged; -}, "mergeConfigFiles"); - -// src/parseKnownFiles.ts -var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}, "parseKnownFiles"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +}, "fromSharedConfigFiles"); +// src/fromStatic.ts -/***/ }), +var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction"); +var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic"); -/***/ 9155: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/configLoader.ts +var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { + const { signingName, logger } = configuration; + const envOptions = { signingName, logger }; + return (0, import_property_provider.memoize)( + (0, import_property_provider.chain)( + fromEnv(environmentVariableSelector, envOptions), + fromSharedConfigFiles(configFileSelector, configuration), + fromStatic(defaultValue) + ) + ); +}, "loadConfig"); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.slurpFile = void 0; -const fs_1 = __nccwpck_require__(7147); -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; /***/ }), -/***/ 1528: +/***/ 258: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -64811,627 +50388,786 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { - ALGORITHM_IDENTIFIER: () => ALGORITHM_IDENTIFIER, - ALGORITHM_IDENTIFIER_V4A: () => ALGORITHM_IDENTIFIER_V4A, - ALGORITHM_QUERY_PARAM: () => ALGORITHM_QUERY_PARAM, - ALWAYS_UNSIGNABLE_HEADERS: () => ALWAYS_UNSIGNABLE_HEADERS, - AMZ_DATE_HEADER: () => AMZ_DATE_HEADER, - AMZ_DATE_QUERY_PARAM: () => AMZ_DATE_QUERY_PARAM, - AUTH_HEADER: () => AUTH_HEADER, - CREDENTIAL_QUERY_PARAM: () => CREDENTIAL_QUERY_PARAM, - DATE_HEADER: () => DATE_HEADER, - EVENT_ALGORITHM_IDENTIFIER: () => EVENT_ALGORITHM_IDENTIFIER, - EXPIRES_QUERY_PARAM: () => EXPIRES_QUERY_PARAM, - GENERATED_HEADERS: () => GENERATED_HEADERS, - HOST_HEADER: () => HOST_HEADER, - KEY_TYPE_IDENTIFIER: () => KEY_TYPE_IDENTIFIER, - MAX_CACHE_SIZE: () => MAX_CACHE_SIZE, - MAX_PRESIGNED_TTL: () => MAX_PRESIGNED_TTL, - PROXY_HEADER_PATTERN: () => PROXY_HEADER_PATTERN, - REGION_SET_PARAM: () => REGION_SET_PARAM, - SEC_HEADER_PATTERN: () => SEC_HEADER_PATTERN, - SHA256_HEADER: () => SHA256_HEADER, - SIGNATURE_HEADER: () => SIGNATURE_HEADER, - SIGNATURE_QUERY_PARAM: () => SIGNATURE_QUERY_PARAM, - SIGNED_HEADERS_QUERY_PARAM: () => SIGNED_HEADERS_QUERY_PARAM, - SignatureV4: () => SignatureV4, - SignatureV4Base: () => SignatureV4Base, - TOKEN_HEADER: () => TOKEN_HEADER, - TOKEN_QUERY_PARAM: () => TOKEN_QUERY_PARAM, - UNSIGNABLE_PATTERNS: () => UNSIGNABLE_PATTERNS, - UNSIGNED_PAYLOAD: () => UNSIGNED_PAYLOAD, - clearCredentialCache: () => clearCredentialCache, - createScope: () => createScope, - getCanonicalHeaders: () => getCanonicalHeaders, - getCanonicalQuery: () => getCanonicalQuery, - getPayloadHash: () => getPayloadHash, - getSigningKey: () => getSigningKey, - hasHeader: () => hasHeader, - moveHeadersToQuery: () => moveHeadersToQuery, - prepareRequest: () => prepareRequest, - signatureV4aContainer: () => signatureV4aContainer + DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, + NodeHttp2Handler: () => NodeHttp2Handler, + NodeHttpHandler: () => NodeHttpHandler, + streamCollector: () => streamCollector }); module.exports = __toCommonJS(src_exports); -// src/SignatureV4.ts - -var import_util_utf85 = __nccwpck_require__(1895); - -// src/constants.ts -var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; -var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; -var AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; -var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; -var EXPIRES_QUERY_PARAM = "X-Amz-Expires"; -var SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; -var TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; -var REGION_SET_PARAM = "X-Amz-Region-Set"; -var AUTH_HEADER = "authorization"; -var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); -var DATE_HEADER = "date"; -var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; -var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); -var SHA256_HEADER = "x-amz-content-sha256"; -var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); -var HOST_HEADER = "host"; -var 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 -}; -var PROXY_HEADER_PATTERN = /^proxy-/; -var SEC_HEADER_PATTERN = /^sec-/; -var UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i]; -var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; -var ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256"; -var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; -var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; -var MAX_CACHE_SIZE = 50; -var KEY_TYPE_IDENTIFIER = "aws4_request"; -var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; - -// src/credentialDerivation.ts -var import_util_hex_encoding = __nccwpck_require__(5364); -var import_util_utf8 = __nccwpck_require__(1895); -var signingKeyCache = {}; -var cacheQueue = []; -var createScope = /* @__PURE__ */ __name((shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, "createScope"); -var getSigningKey = /* @__PURE__ */ __name(async (sha256Constructor, credentials, shortDate, region, service) => { - const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); - const cacheKey = `${shortDate}:${region}:${service}:${(0, import_util_hex_encoding.toHex)(credsHash)}:${credentials.sessionToken}`; - if (cacheKey in signingKeyCache) { - return signingKeyCache[cacheKey]; - } - cacheQueue.push(cacheKey); - while (cacheQueue.length > MAX_CACHE_SIZE) { - delete signingKeyCache[cacheQueue.shift()]; - } - let key = `AWS4${credentials.secretAccessKey}`; - for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { - key = await hmac(sha256Constructor, key, signable); +// src/node-http-handler.ts +var import_protocol_http = __nccwpck_require__(4418); +var import_querystring_builder = __nccwpck_require__(8031); +var import_http = __nccwpck_require__(3685); +var import_https = __nccwpck_require__(5687); + +// src/constants.ts +var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; + +// src/get-transformed-headers.ts +var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { + const transformedHeaders = {}; + for (const name of Object.keys(headers)) { + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; } - return signingKeyCache[cacheKey] = key; -}, "getSigningKey"); -var clearCredentialCache = /* @__PURE__ */ __name(() => { - cacheQueue.length = 0; - Object.keys(signingKeyCache).forEach((cacheKey) => { - delete signingKeyCache[cacheKey]; - }); -}, "clearCredentialCache"); -var hmac = /* @__PURE__ */ __name((ctor, secret, data) => { - const hash = new ctor(secret); - hash.update((0, import_util_utf8.toUint8Array)(data)); - return hash.digest(); -}, "hmac"); + return transformedHeaders; +}, "getTransformedHeaders"); -// src/getCanonicalHeaders.ts -var getCanonicalHeaders = /* @__PURE__ */ __name(({ headers }, unsignableHeaders, signableHeaders) => { - const canonical = {}; - for (const headerName of Object.keys(headers).sort()) { - if (headers[headerName] == void 0) { - continue; - } - const canonicalHeaderName = headerName.toLowerCase(); - if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) { - if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { - continue; +// src/timing.ts +var timing = { + setTimeout: (cb, ms) => setTimeout(cb, ms), + clearTimeout: (timeoutId) => clearTimeout(timeoutId) +}; + +// src/set-connection-timeout.ts +var DEFER_EVENT_LISTENER_TIME = 1e3; +var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return -1; + } + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeoutId = timing.setTimeout(() => { + request.destroy(); + reject( + Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { + name: "TimeoutError" + }) + ); + }, timeoutInMs - offset); + const doWithSocket = /* @__PURE__ */ __name((socket) => { + if (socket?.connecting) { + socket.on("connect", () => { + timing.clearTimeout(timeoutId); + }); + } else { + timing.clearTimeout(timeoutId); } + }, "doWithSocket"); + if (request.socket) { + doWithSocket(request.socket); + } else { + request.on("socket", doWithSocket); } - canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); + }, "registerTimeout"); + if (timeoutInMs < 2e3) { + registerTimeout(0); + return 0; } - return canonical; -}, "getCanonicalHeaders"); - -// src/getPayloadHash.ts -var import_is_array_buffer = __nccwpck_require__(780); + return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); +}, "setConnectionTimeout"); -var import_util_utf82 = __nccwpck_require__(1895); -var getPayloadHash = /* @__PURE__ */ __name(async ({ headers, body }, hashConstructor) => { - for (const headerName of Object.keys(headers)) { - if (headerName.toLowerCase() === SHA256_HEADER) { - return headers[headerName]; - } +// src/set-socket-keep-alive.ts +var DEFER_EVENT_LISTENER_TIME2 = 3e3; +var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { + if (keepAlive !== true) { + return -1; } - if (body == void 0) { - return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; - } else if (typeof body === "string" || ArrayBuffer.isView(body) || (0, import_is_array_buffer.isArrayBuffer)(body)) { - const hashCtor = new hashConstructor(); - hashCtor.update((0, import_util_utf82.toUint8Array)(body)); - return (0, import_util_hex_encoding.toHex)(await hashCtor.digest()); + const registerListener = /* @__PURE__ */ __name(() => { + if (request.socket) { + request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + } else { + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); + } + }, "registerListener"); + if (deferTimeMs === 0) { + registerListener(); + return 0; } - return UNSIGNED_PAYLOAD; -}, "getPayloadHash"); + return timing.setTimeout(registerListener, deferTimeMs); +}, "setSocketKeepAlive"); -// src/HeaderFormatter.ts +// src/set-socket-timeout.ts +var DEFER_EVENT_LISTENER_TIME3 = 3e3; +var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeout = timeoutInMs - offset; + const onTimeout = /* @__PURE__ */ __name(() => { + request.destroy(); + reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); + }, "onTimeout"); + if (request.socket) { + request.socket.setTimeout(timeout, onTimeout); + request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); + } else { + request.setTimeout(timeout, onTimeout); + } + }, "registerTimeout"); + if (0 < timeoutInMs && timeoutInMs < 6e3) { + registerTimeout(0); + return 0; + } + return timing.setTimeout( + registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), + DEFER_EVENT_LISTENER_TIME3 + ); +}, "setSocketTimeout"); -var import_util_utf83 = __nccwpck_require__(1895); -var HeaderFormatter = class { - static { - __name(this, "HeaderFormatter"); +// src/write-request-body.ts +var import_stream = __nccwpck_require__(2781); +var MIN_WAIT_TIME = 6e3; +async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { + const headers = request.headers ?? {}; + const expect = headers["Expect"] || headers["expect"]; + let timeoutId = -1; + let sendBody = true; + if (expect === "100-continue") { + sendBody = await Promise.race([ + new Promise((resolve) => { + timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve) => { + httpRequest.on("continue", () => { + timing.clearTimeout(timeoutId); + resolve(true); + }); + httpRequest.on("response", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + httpRequest.on("error", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + }) + ]); } - format(headers) { - const chunks = []; - for (const headerName of Object.keys(headers)) { - const bytes = (0, import_util_utf83.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; + if (sendBody) { + writeBody(httpRequest, request.body); } - formatHeaderValue(header) { - switch (header.type) { - case "boolean": - return Uint8Array.from([header.value ? 0 /* boolTrue */ : 1 /* boolFalse */]); - case "byte": - return Uint8Array.from([2 /* byte */, header.value]); - case "short": - const shortView = new DataView(new ArrayBuffer(3)); - shortView.setUint8(0, 3 /* short */); - shortView.setInt16(1, header.value, false); - return new Uint8Array(shortView.buffer); - case "integer": - const intView = new DataView(new ArrayBuffer(5)); - intView.setUint8(0, 4 /* integer */); - intView.setInt32(1, header.value, false); - return new Uint8Array(intView.buffer); - case "long": - const longBytes = new Uint8Array(9); - longBytes[0] = 5 /* long */; - longBytes.set(header.value.bytes, 1); - return longBytes; - case "binary": - const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); - binView.setUint8(0, 6 /* byteArray */); - binView.setUint16(1, header.value.byteLength, false); - const binBytes = new Uint8Array(binView.buffer); - binBytes.set(header.value, 3); - return binBytes; - case "string": - const utf8Bytes = (0, import_util_utf83.fromUtf8)(header.value); - const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); - strView.setUint8(0, 7 /* string */); - 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 /* timestamp */; - tsBytes.set(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 /* uuid */; - uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1); - return uuidBytes; - } +} +__name(writeRequestBody, "writeRequestBody"); +function writeBody(httpRequest, body) { + if (body instanceof import_stream.Readable) { + body.pipe(httpRequest); + return; } -}; -var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; -var Int64 = class _Int64 { - constructor(bytes) { - this.bytes = bytes; - if (bytes.byteLength !== 8) { - throw new Error("Int64 buffers must be exactly 8 bytes"); + if (body) { + if (Buffer.isBuffer(body) || typeof body === "string") { + httpRequest.end(body); + return; } + const uint8 = body; + if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { + httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; + } + httpRequest.end(Buffer.from(body)); + return; + } + httpRequest.end(); +} +__name(writeBody, "writeBody"); + +// src/node-http-handler.ts +var DEFAULT_REQUEST_TIMEOUT = 0; +var NodeHttpHandler = class _NodeHttpHandler { + constructor(options) { + this.socketWarningTimestamp = 0; + // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 + 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)); + } + }); } static { - __name(this, "Int64"); + __name(this, "NodeHttpHandler"); } - static fromNumber(number) { - if (number > 9223372036854776e3 || number < -9223372036854776e3) { - 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); + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; } - return new _Int64(bytes); + return new _NodeHttpHandler(instanceOrOptions); } /** - * Called implicitly by infix arithmetic operators. + * @internal + * + * @param agent - http(s) agent in use by the NodeHttpHandler instance. + * @param socketWarningTimestamp - last socket usage check timestamp. + * @param logger - channel for the warning. + * @returns timestamp of last emitted warning. */ - valueOf() { - const bytes = this.bytes.slice(0); - const negative = bytes[0] & 128; - if (negative) { - negate(bytes); + static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; } - return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); - } - toString() { - return String(this.valueOf()); + const interval = 15e3; + if (Date.now() - interval < socketWarningTimestamp) { + return socketWarningTimestamp; + } + if (sockets && requests) { + for (const origin in sockets) { + const socketsInUse = sockets[origin]?.length ?? 0; + const requestsEnqueued = requests[origin]?.length ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + logger?.warn?.( + `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. +See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html +or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` + ); + return Date.now(); + } + } + } + return socketWarningTimestamp; } -}; -function negate(bytes) { - for (let i = 0; i < 8; i++) { - bytes[i] ^= 255; + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout: requestTimeout ?? socketTimeout, + socketAcquisitionWarningTimeout, + httpAgent: (() => { + if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { + return httpAgent; + } + return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); + })(), + httpsAgent: (() => { + if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { + return httpsAgent; + } + return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })(), + logger: console + }; } - for (let i = 7; i > -1; i--) { - bytes[i]++; - if (bytes[i] !== 0) - break; + destroy() { + this.config?.httpAgent?.destroy(); + this.config?.httpsAgent?.destroy(); } -} -__name(negate, "negate"); - -// src/headerUtil.ts -var hasHeader = /* @__PURE__ */ __name((soughtHeader, headers) => { - soughtHeader = soughtHeader.toLowerCase(); - for (const headerName of Object.keys(headers)) { - if (soughtHeader === headerName.toLowerCase()) { - return true; + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; } + return new Promise((_resolve, _reject) => { + let writeRequestBodyPromise = void 0; + const timeouts = []; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _reject(arg); + }, "reject"); + if (!this.config) { + throw new Error("Node HTTP request handler config is not resolved"); + } + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const isSSL = request.protocol === "https:"; + const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; + timeouts.push( + timing.setTimeout( + () => { + this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( + agent, + this.socketWarningTimestamp, + this.config.logger + ); + }, + this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) + ) + ); + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + let auth = void 0; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; + } + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let hostname = request.hostname ?? ""; + if (hostname[0] === "[" && hostname.endsWith("]")) { + hostname = request.hostname.slice(1, -1); + } else { + hostname = request.hostname; + } + const nodeHttpsOptions = { + headers: request.headers, + host: hostname, + method: request.method, + path, + port: request.port, + agent, + auth + }; + const requestFunc = isSSL ? import_https.request : import_http.request; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res + }); + resolve({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); + } else { + reject(err); + } + }); + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.destroy(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout; + timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); + timeouts.push(setSocketTimeout(req, reject, effectiveRequestTimeout)); + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + timeouts.push( + setSocketKeepAlive(req, { + // @ts-expect-error keepAlive is not public on httpAgent. + keepAlive: httpAgent.keepAlive, + // @ts-expect-error keepAliveMsecs is not public on httpAgent. + keepAliveMsecs: httpAgent.keepAliveMsecs + }) + ); + } + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e) => { + timeouts.forEach(timing.clearTimeout); + return _reject(e); + }); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); } - return false; -}, "hasHeader"); - -// src/moveHeadersToQuery.ts -var import_protocol_http = __nccwpck_require__(4418); -var moveHeadersToQuery = /* @__PURE__ */ __name((request, options = {}) => { - const { headers, query = {} } = import_protocol_http.HttpRequest.clone(request); - for (const name of Object.keys(headers)) { - const lname = name.toLowerCase(); - if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) { - query[name] = headers[name]; - delete headers[name]; - } + httpHandlerConfigs() { + return this.config ?? {}; } - return { - ...request, - headers, - query - }; -}, "moveHeadersToQuery"); - -// src/prepareRequest.ts +}; -var prepareRequest = /* @__PURE__ */ __name((request) => { - request = import_protocol_http.HttpRequest.clone(request); - for (const headerName of Object.keys(request.headers)) { - if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { - delete request.headers[headerName]; - } - } - return request; -}, "prepareRequest"); +// src/node-http2-handler.ts -// src/SignatureV4Base.ts -var import_util_middleware = __nccwpck_require__(2390); +var import_http22 = __nccwpck_require__(5158); -var import_util_utf84 = __nccwpck_require__(1895); +// src/node-http2-connection-manager.ts +var import_http2 = __toESM(__nccwpck_require__(5158)); -// src/getCanonicalQuery.ts -var import_util_uri_escape = __nccwpck_require__(4197); -var getCanonicalQuery = /* @__PURE__ */ __name(({ query = {} }) => { - const keys = []; - const serialized = {}; - for (const key of Object.keys(query)) { - if (key.toLowerCase() === SIGNATURE_HEADER) { - continue; - } - const encodedKey = (0, import_util_uri_escape.escapeUri)(key); - keys.push(encodedKey); - const value = query[key]; - if (typeof value === "string") { - serialized[encodedKey] = `${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value)}`; - } else if (Array.isArray(value)) { - serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value2)}`]), []).sort().join("&"); +// src/node-http2-connection-pool.ts +var NodeHttp2ConnectionPool = class { + constructor(sessions) { + this.sessions = []; + this.sessions = sessions ?? []; + } + static { + __name(this, "NodeHttp2ConnectionPool"); + } + poll() { + if (this.sessions.length > 0) { + return this.sessions.shift(); } } - return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); -}, "getCanonicalQuery"); - -// src/utilDate.ts -var iso8601 = /* @__PURE__ */ __name((time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z"), "iso8601"); -var toDate = /* @__PURE__ */ __name((time) => { - if (typeof time === "number") { - return new Date(time * 1e3); + offerLast(session) { + this.sessions.push(session); } - if (typeof time === "string") { - if (Number(time)) { - return new Date(Number(time) * 1e3); + 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(); + } + } } - return new Date(time); } - return time; -}, "toDate"); +}; -// src/SignatureV4Base.ts -var SignatureV4Base = class { +// src/node-http2-connection-manager.ts +var NodeHttp2ConnectionManager = class { + constructor(config) { + this.sessionCache = /* @__PURE__ */ new Map(); + this.config = config; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); + } + } static { - __name(this, "SignatureV4Base"); + __name(this, "NodeHttp2ConnectionManager"); } - constructor({ - applyChecksum, - credentials, - region, - service, - sha256, - uriEscapePath = true - }) { - this.service = service; - this.sha256 = sha256; - this.uriEscapePath = uriEscapePath; - this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; - this.regionProvider = (0, import_util_middleware.normalizeProvider)(region); - this.credentialProvider = (0, import_util_middleware.normalizeProvider)(credentials); + 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 = import_http2.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 = /* @__PURE__ */ __name(() => { + session.destroy(); + this.deleteSession(url, session); + }, "destroySessionCb"); + 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 NodeHttp2ConnectionPool(); + connectionPool.offerLast(session); + this.sessionCache.set(url, connectionPool); + return session; } - createCanonicalRequest(request, canonicalHeaders, payloadHash) { - const sortedHeaders = Object.keys(canonicalHeaders).sort(); - return `${request.method} -${this.getCanonicalPath(request)} -${getCanonicalQuery(request)} -${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} - -${sortedHeaders.join(";")} -${payloadHash}`; + /** + * Delete a session from the connection pool. + * @param authority The authority of the session to delete. + * @param session The session to delete. + */ + 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); } - async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { - const hash = new this.sha256(); - hash.update((0, import_util_utf84.toUint8Array)(canonicalRequest)); - const hashedRequest = await hash.digest(); - return `${algorithmIdentifier} -${longDate} -${credentialScope} -${(0, import_util_hex_encoding.toHex)(hashedRequest)}`; + release(requestContext, session) { + const cacheKey = this.getUrlString(requestContext); + this.sessionCache.get(cacheKey)?.offerLast(session); } - getCanonicalPath({ path }) { - if (this.uriEscapePath) { - const normalizedPathSegments = []; - for (const pathSegment of path.split("/")) { - if (pathSegment?.length === 0) - continue; - if (pathSegment === ".") - continue; - if (pathSegment === "..") { - normalizedPathSegments.pop(); - } else { - normalizedPathSegments.push(pathSegment); + destroy() { + for (const [key, connectionPool] of this.sessionCache) { + for (const session of connectionPool) { + if (!session.destroyed) { + session.destroy(); } + connectionPool.remove(session); } - const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; - const doubleEncoded = (0, import_util_uri_escape.escapeUri)(normalizedPath); - return doubleEncoded.replace(/%2F/g, "/"); + this.sessionCache.delete(key); } - return path; } - validateResolvedCredentials(credentials) { - if (typeof credentials !== "object" || // @ts-expect-error: Property 'accessKeyId' does not exist on type 'object'.ts(2339) - typeof credentials.accessKeyId !== "string" || // @ts-expect-error: Property 'secretAccessKey' does not exist on type 'object'.ts(2339) - typeof credentials.secretAccessKey !== "string") { - throw new Error("Resolved credential object is not valid"); + setMaxConcurrentStreams(maxConcurrentStreams) { + if (maxConcurrentStreams && maxConcurrentStreams <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); } + this.config.maxConcurrency = maxConcurrentStreams; } - formatDate(now) { - const longDate = iso8601(now).replace(/[\-:]/g, ""); - return { - longDate, - shortDate: longDate.slice(0, 8) - }; + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; } - getCanonicalHeaderList(headers) { - return Object.keys(headers).sort().join(";"); + getUrlString(request) { + return request.destination.toString(); } }; -// src/SignatureV4.ts -var SignatureV4 = class extends SignatureV4Base { - constructor({ - applyChecksum, - credentials, - region, - service, - sha256, - uriEscapePath = true - }) { - super({ - applyChecksum, - credentials, - region, - service, - sha256, - uriEscapePath +// src/node-http2-handler.ts +var NodeHttp2Handler = class _NodeHttp2Handler { + constructor(options) { + this.metadata = { handlerProtocol: "h2" }; + this.connectionManager = new NodeHttp2ConnectionManager({}); + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((opts) => { + resolve(opts || {}); + }).catch(reject); + } else { + resolve(options || {}); + } }); - this.headerFormatter = new HeaderFormatter(); } static { - __name(this, "SignatureV4"); - } - async presign(originalRequest, options = {}) { - const { - signingDate = /* @__PURE__ */ new Date(), - expiresIn = 3600, - unsignableHeaders, - unhoistableHeaders, - signableHeaders, - hoistableHeaders, - signingRegion, - signingService - } = options; - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const { longDate, shortDate } = this.formatDate(signingDate); - if (expiresIn > 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 = createScope(shortDate, region, signingService ?? this.service); - const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); - if (credentials.sessionToken) { - request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; - } - request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; - request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; - request.query[AMZ_DATE_QUERY_PARAM] = longDate; - request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); - const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); - request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); - request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature( - longDate, - scope, - this.getSigningKey(credentials, region, shortDate, signingService), - this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)) - ); - return request; + __name(this, "NodeHttp2Handler"); } - 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); + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; } + return new _NodeHttp2Handler(instanceOrOptions); } - async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { - const region = signingRegion ?? await this.regionProvider(); - const { shortDate, longDate } = this.formatDate(signingDate); - const scope = createScope(shortDate, region, signingService ?? this.service); - const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); - const hash = new this.sha256(); - hash.update(headers); - const hashedHeaders = (0, import_util_hex_encoding.toHex)(await hash.digest()); - const stringToSign = [ - EVENT_ALGORITHM_IDENTIFIER, - longDate, - scope, - priorSignature, - hashedHeaders, - hashedPayload - ].join("\n"); - return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); + destroy() { + this.connectionManager.destroy(); } - async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { - const promise = this.signEvent( - { - headers: this.headerFormatter.format(signableMessage.message.headers), - payload: signableMessage.message.body - }, - { - signingDate, - signingRegion, - signingService, - priorSignature: signableMessage.priorSignature + async handle(request, { abortSignal, requestTimeout } = {}) { + 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); } - ); - return promise.then((signature) => { - return { message: signableMessage.message, signature }; - }); - } - async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const { shortDate } = this.formatDate(signingDate); - const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); - hash.update((0, import_util_utf85.toUint8Array)(stringToSign)); - return (0, import_util_hex_encoding.toHex)(await hash.digest()); - } - async signRequest(requestToSign, { - signingDate = /* @__PURE__ */ new Date(), - signableHeaders, - unsignableHeaders, - signingRegion, - signingService - } = {}) { - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const request = prepareRequest(requestToSign); - const { longDate, shortDate } = this.formatDate(signingDate); - const scope = createScope(shortDate, region, signingService ?? this.service); - request.headers[AMZ_DATE_HEADER] = longDate; - if (credentials.sessionToken) { - request.headers[TOKEN_HEADER] = credentials.sessionToken; - } - const payloadHash = await getPayloadHash(request, this.sha256); - if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { - request.headers[SHA256_HEADER] = payloadHash; } - const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); - const signature = await this.getSignature( - longDate, - scope, - this.getSigningKey(credentials, region, shortDate, signingService), - this.createCanonicalRequest(request, canonicalHeaders, payloadHash) - ); - request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; - return request; + const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; + const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; + return new Promise((_resolve, _reject) => { + let fulfilled = false; + let writeRequestBodyPromise = void 0; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }, "reject"); + if (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 = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const session = this.connectionManager.lease(requestContext, { + requestTimeout: this.config?.sessionTimeout, + disableConcurrentStreams: disableConcurrentStreams || false + }); + const rejectWithDestroy = /* @__PURE__ */ __name((err) => { + if (disableConcurrentStreams) { + this.destroySession(session); + } + fulfilled = true; + reject(err); + }, "rejectWithDestroy"); + const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + const req = session.request({ + ...request.headers, + [import_http22.constants.HTTP2_HEADER_PATH]: path, + [import_http22.constants.HTTP2_HEADER_METHOD]: method + }); + session.ref(); + req.on("response", (headers) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: headers[":status"] || -1, + headers: getTransformedHeaders(headers), + body: req + }); + fulfilled = true; + resolve({ response: httpResponse }); + if (disableConcurrentStreams) { + session.close(); + this.connectionManager.deleteSession(authority, session); + } + }); + if (effectiveRequestTimeout) { + req.setTimeout(effectiveRequestTimeout, () => { + req.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); + } + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.close(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + rejectWithDestroy(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + 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 = writeRequestBody(req, request, effectiveRequestTimeout); + }); } - async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { - const stringToSign = await this.createStringToSign( - longDate, - credentialScope, - canonicalRequest, - ALGORITHM_IDENTIFIER - ); - const hash = new this.sha256(await keyPromise); - hash.update((0, import_util_utf85.toUint8Array)(stringToSign)); - return (0, import_util_hex_encoding.toHex)(await hash.digest()); + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); } - getSigningKey(credentials, region, shortDate, service) { - return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); + httpHandlerConfigs() { + return this.config ?? {}; + } + /** + * Destroys a session. + * @param session - the session to destroy. + */ + destroySession(session) { + if (!session.destroyed) { + session.destroy(); + } } }; -// src/signature-v4a-container.ts -var signatureV4aContainer = { - SignatureV4a: null +// src/stream-collector/collector.ts + +var Collector = class extends import_stream.Writable { + constructor() { + super(...arguments); + this.bufferedBytes = []; + } + static { + __name(this, "Collector"); + } + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); + } }; + +// src/stream-collector/index.ts +var streamCollector = /* @__PURE__ */ __name((stream) => { + if (isReadableStreamInstance(stream)) { + return collectReadableStream(stream); + } + return new Promise((resolve, reject) => { + const collector = new 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); + }); + }); +}, "streamCollector"); +var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); +async function collectReadableStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +__name(collectReadableStream, "collectReadableStream"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -65440,8 +51176,8 @@ var signatureV4aContainer = { /***/ }), -/***/ 3570: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9721: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -65460,666 +51196,633 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { - Client: () => Client, - Command: () => Command, - NoOpLogger: () => NoOpLogger, - SENSITIVE_STRING: () => SENSITIVE_STRING, - ServiceException: () => ServiceException, - _json: () => _json, - collectBody: () => import_protocols.collectBody, - convertMap: () => convertMap, - createAggregatedClient: () => createAggregatedClient, - decorateServiceException: () => decorateServiceException, - emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, - extendedEncodeURIComponent: () => import_protocols.extendedEncodeURIComponent, - getArrayIfSingleItem: () => getArrayIfSingleItem, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration, - getValueFromTextNode: () => getValueFromTextNode, - isSerializableHeaderValue: () => isSerializableHeaderValue, - loadConfigsForDefaultMode: () => loadConfigsForDefaultMode, - map: () => map, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig, - resolvedPath: () => import_protocols.resolvedPath, - serializeDateTime: () => serializeDateTime, - serializeFloat: () => serializeFloat, - take: () => take, - throwDefaultError: () => throwDefaultError, - withBaseException: () => withBaseException + CredentialsProviderError: () => CredentialsProviderError, + ProviderError: () => ProviderError, + TokenProviderError: () => TokenProviderError, + chain: () => chain, + fromStatic: () => fromStatic, + memoize: () => memoize }); module.exports = __toCommonJS(src_exports); -// src/client.ts -var import_middleware_stack = __nccwpck_require__(7911); -var Client = class { - constructor(config) { - this.config = config; - this.middlewareStack = (0, import_middleware_stack.constructStack)(); +// src/ProviderError.ts +var ProviderError = class _ProviderError extends Error { + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.name = "ProviderError"; + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } static { - __name(this, "Client"); - } - send(command, optionsOrCb, cb) { - const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0; - const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; - const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true; - let handler; - if (useHandlerCache) { - if (!this.handlers) { - this.handlers = /* @__PURE__ */ new WeakMap(); - } - const handlers = this.handlers; - if (handlers.has(command.constructor)) { - handler = handlers.get(command.constructor); - } else { - handler = command.resolveMiddleware(this.middlewareStack, this.config, options); - handlers.set(command.constructor, handler); - } - } else { - delete this.handlers; - handler = command.resolveMiddleware(this.middlewareStack, this.config, options); - } - if (callback) { - handler(command).then( - (result) => callback(null, result.output), - (err) => callback(err) - ).catch( - // prevent any errors thrown in the callback from triggering an - // unhandled promise rejection - () => { - } - ); - } else { - return handler(command).then((result) => result.output); - } + __name(this, "ProviderError"); } - destroy() { - this.config?.requestHandler?.destroy?.(); - delete this.handlers; + /** + * @deprecated use new operator. + */ + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); } }; -// src/collect-stream-body.ts -var import_protocols = __nccwpck_require__(2241); - -// src/command.ts - -var import_types = __nccwpck_require__(5756); -var Command = class { - constructor() { - this.middlewareStack = (0, import_middleware_stack.constructStack)(); +// src/CredentialsProviderError.ts +var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "CredentialsProviderError"; + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); } static { - __name(this, "Command"); + __name(this, "CredentialsProviderError"); } +}; + +// src/TokenProviderError.ts +var TokenProviderError = class _TokenProviderError extends ProviderError { /** - * Factory for Command ClassBuilder. - * @internal + * @override */ - static classBuilder() { - return new ClassBuilder(); + constructor(message, options = true) { + super(message, options); + this.name = "TokenProviderError"; + Object.setPrototypeOf(this, _TokenProviderError.prototype); } - /** - * @internal - */ - resolveMiddlewareWithContext(clientStack, configuration, options, { - middlewareFn, - clientName, - commandName, - inputFilterSensitiveLog, - outputFilterSensitiveLog, - smithyContext, - additionalContext, - CommandCtor - }) { - for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { - this.middlewareStack.use(mw); + static { + __name(this, "TokenProviderError"); + } +}; + +// src/chain.ts +var chain = /* @__PURE__ */ __name((...providers) => async () => { + if (providers.length === 0) { + throw new 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?.tryNextLink) { + continue; + } + throw err; } - const stack = clientStack.concat(this.middlewareStack); - const { logger } = configuration; - const handlerExecutionContext = { - logger, - clientName, - commandName, - inputFilterSensitiveLog, - outputFilterSensitiveLog, - [import_types.SMITHY_CONTEXT_KEY]: { - commandInstance: this, - ...smithyContext - }, - ...additionalContext + } + throw lastProviderError; +}, "chain"); + +// src/fromStatic.ts +var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); + +// src/memoize.ts +var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; }; - const { requestHandler } = configuration; - return stack.resolve( - (request) => requestHandler.handle(request.request, options || {}), - handlerExecutionContext - ); } + return async (options) => { + if (!hasResult || 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; + }; +}, "memoize"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 4418: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var ClassBuilder = class { - constructor() { - this._init = () => { - }; - this._ep = {}; - this._middlewareFn = () => []; - this._commandName = ""; - this._clientName = ""; - this._additionalContext = {}; - this._smithyContext = {}; - this._inputFilterSensitiveLog = (_) => _; - this._outputFilterSensitiveLog = (_) => _; - this._serializer = null; - this._deserializer = null; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Field: () => Field, + Fields: () => Fields, + HttpRequest: () => HttpRequest, + HttpResponse: () => HttpResponse, + IHttpRequest: () => import_types.HttpRequest, + getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, + isValidHostname: () => isValidHostname, + resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig +}); +module.exports = __toCommonJS(src_exports); + +// src/extensions/httpExtensionConfiguration.ts +var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + } + }; +}, "getHttpHandlerExtensionConfiguration"); +var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler() + }; +}, "resolveHttpHandlerRuntimeConfig"); + +// src/Field.ts +var import_types = __nccwpck_require__(5756); +var Field = class { static { - __name(this, "ClassBuilder"); + __name(this, "Field"); } - /** - * Optional init callback. - */ - init(cb) { - this._init = cb; + constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; } /** - * Set the endpoint parameter instructions. + * Appends a value to the field. + * + * @param value The value to append. */ - ep(endpointParameterInstructions) { - this._ep = endpointParameterInstructions; - return this; + add(value) { + this.values.push(value); } /** - * Add any number of middleware. + * Overwrite existing field values. + * + * @param values The new field values. */ - m(middlewareSupplier) { - this._middlewareFn = middlewareSupplier; - return this; + set(values) { + this.values = values; } /** - * Set the initial handler execution context Smithy field. + * Remove all matching entries from list. + * + * @param value Value to remove. */ - s(service, operation, smithyContext = {}) { - this._smithyContext = { - service, - operation, - ...smithyContext - }; - return this; + remove(value) { + this.values = this.values.filter((v) => v !== value); } /** - * Set the initial handler execution context. + * Get comma-delimited string. + * + * @returns String representation of {@link Field}. */ - c(additionalContext = {}) { - this._additionalContext = additionalContext; - return this; + toString() { + return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); } /** - * Set constant string identifiers for the operation. + * Get string values as a list + * + * @returns Values in {@link Field} as a list. */ - n(clientName, commandName) { - this._clientName = clientName; - this._commandName = commandName; - return this; + get() { + return this.values; } - /** - * Set the input and output sensistive log filters. - */ - f(inputFilter = (_) => _, outputFilter = (_) => _) { - this._inputFilterSensitiveLog = inputFilter; - this._outputFilterSensitiveLog = outputFilter; - return this; +}; + +// src/Fields.ts +var Fields = class { + constructor({ fields = [], encoding = "utf-8" }) { + this.entries = {}; + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + static { + __name(this, "Fields"); } /** - * Sets the serializer. + * Set entry for a {@link Field} name. The `name` + * attribute will be used to key the collection. + * + * @param field The {@link Field} to set. */ - ser(serializer) { - this._serializer = serializer; - return this; + setField(field) { + this.entries[field.name.toLowerCase()] = field; } /** - * Sets the deserializer. + * Retrieve {@link Field} entry by name. + * + * @param name The name of the {@link Field} entry + * to retrieve + * @returns The {@link Field} if it exists. */ - de(deserializer) { - this._deserializer = deserializer; - return this; + getField(name) { + return this.entries[name.toLowerCase()]; } /** - * Sets input/output schema for the operation. + * Delete entry from collection. + * + * @param name Name of the entry to delete. */ - sc(operation) { - this._operationSchema = operation; - this._smithyContext.operationSchema = operation; - return this; + removeField(name) { + delete this.entries[name.toLowerCase()]; } /** - * @returns a Command class with the classBuilder properties. + * Helper function for retrieving specific types of fields. + * Used to grab all headers or all trailers. + * + * @param kind {@link FieldPosition} of entries to retrieve. + * @returns The {@link Field} entries with the specified + * {@link FieldPosition}. */ - build() { - const closure = this; - let CommandRef; - return CommandRef = class extends Command { - /** - * @public - */ - constructor(...[input]) { - super(); - /** - * @internal - */ - // @ts-ignore used in middlewareFn closure. - this.serialize = closure._serializer; - /** - * @internal - */ - // @ts-ignore used in middlewareFn closure. - this.deserialize = closure._deserializer; - this.input = input ?? {}; - closure._init(this); - this.schema = closure._operationSchema; - } - static { - __name(this, "CommandRef"); - } - /** - * @public - */ - static getEndpointParameterInstructions() { - return closure._ep; - } - /** - * @internal - */ - resolveMiddleware(stack, configuration, options) { - return this.resolveMiddlewareWithContext(stack, configuration, options, { - CommandCtor: CommandRef, - middlewareFn: closure._middlewareFn, - clientName: closure._clientName, - commandName: closure._commandName, - inputFilterSensitiveLog: closure._inputFilterSensitiveLog, - outputFilterSensitiveLog: closure._outputFilterSensitiveLog, - smithyContext: closure._smithyContext, - additionalContext: closure._additionalContext - }); - } - }; + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); } }; -// src/constants.ts -var SENSITIVE_STRING = "***SensitiveInformation***"; - -// src/create-aggregated-client.ts -var createAggregatedClient = /* @__PURE__ */ __name((commands, Client2) => { - for (const command of Object.keys(commands)) { - const CommandCtor = commands[command]; - const methodImpl = /* @__PURE__ */ __name(async function(args, optionsOrCb, cb) { - const command2 = new CommandCtor(args); - if (typeof optionsOrCb === "function") { - this.send(command2, optionsOrCb); - } else if (typeof cb === "function") { - if (typeof optionsOrCb !== "object") - throw new Error(`Expected http options but got ${typeof optionsOrCb}`); - this.send(command2, optionsOrCb || {}, cb); - } else { - return this.send(command2, optionsOrCb); - } - }, "methodImpl"); - const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); - Client2.prototype[methodName] = methodImpl; - } -}, "createAggregatedClient"); +// src/httpRequest.ts -// src/exceptions.ts -var ServiceException = class _ServiceException extends Error { +var HttpRequest = class _HttpRequest { static { - __name(this, "ServiceException"); + __name(this, "HttpRequest"); } constructor(options) { - super(options.message); - Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); - this.name = options.name; - this.$fault = options.$fault; - this.$metadata = options.$metadata; + 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; } /** - * Checks if a value is an instance of ServiceException (duck typed) + * Note: this does not deep-clone the body. */ - static isInstance(value) { - if (!value) - return false; - const candidate = value; - return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server"); + static clone(request) { + const cloned = new _HttpRequest({ + ...request, + headers: { ...request.headers } + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; } /** - * Custom instanceof check to support the operator for ServiceException base class + * This method only actually asserts that request is the interface {@link IHttpRequest}, + * and not necessarily this concrete class. Left in place for API stability. + * + * Do not call instance methods on the input of this function, and + * do not assume it has the HttpRequest prototype. */ - static [Symbol.hasInstance](instance) { - if (!instance) + static isInstance(request) { + if (!request) { return false; - const candidate = instance; - if (this === _ServiceException) { - return _ServiceException.isInstance(instance); - } - if (_ServiceException.isInstance(instance)) { - if (candidate.name && this.name) { - return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; - } - return this.prototype.isPrototypeOf(instance); } - 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"; + } + /** + * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call + * this method because {@link HttpRequest.isInstance} incorrectly + * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). + */ + clone() { + return _HttpRequest.clone(this); } }; -var decorateServiceException = /* @__PURE__ */ __name((exception, additions = {}) => { - Object.entries(additions).filter(([, v]) => v !== void 0).forEach(([k, v]) => { - if (exception[k] == void 0 || exception[k] === "") { - exception[k] = v; - } - }); - const message = exception.message || exception.Message || "UnknownError"; - exception.message = message; - delete exception.Message; - return exception; -}, "decorateServiceException"); - -// src/default-error-handler.ts -var throwDefaultError = /* @__PURE__ */ __name(({ output, parsedBody, exceptionCtor, errorCode }) => { - const $metadata = deserializeMetadata(output); - const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0; - const response = new exceptionCtor({ - name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", - $fault: "client", - $metadata - }); - throw decorateServiceException(response, parsedBody); -}, "throwDefaultError"); -var withBaseException = /* @__PURE__ */ __name((ExceptionCtor) => { - return ({ output, parsedBody, errorCode }) => { - throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); - }; -}, "withBaseException"); -var deserializeMetadata = /* @__PURE__ */ __name((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"] -}), "deserializeMetadata"); +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); +} +__name(cloneQuery, "cloneQuery"); -// src/defaults-mode.ts -var loadConfigsForDefaultMode = /* @__PURE__ */ __name((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: 3e4 - }; - default: - return {}; +// src/httpResponse.ts +var HttpResponse = class { + static { + __name(this, "HttpResponse"); } -}, "loadConfigsForDefaultMode"); - -// src/emitWarningIfUnsupportedVersion.ts -var warningEmitted = false; -var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { - if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { - warningEmitted = true; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; } -}, "emitWarningIfUnsupportedVersion"); - -// src/extended-encode-uri-component.ts - - -// src/extensions/checksum.ts - -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - for (const id in import_types.AlgorithmId) { - const algorithmId = import_types.AlgorithmId[id]; - if (runtimeConfig[algorithmId] === void 0) { - continue; - } - checksumAlgorithms.push({ - algorithmId: () => algorithmId, - checksumConstructor: () => runtimeConfig[algorithmId] - }); + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); +}; -// src/extensions/retry.ts -var getRetryConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setRetryStrategy(retryStrategy) { - runtimeConfig.retryStrategy = retryStrategy; - }, - retryStrategy() { - return runtimeConfig.retryStrategy; - } - }; -}, "getRetryConfiguration"); -var resolveRetryRuntimeConfig = /* @__PURE__ */ __name((retryStrategyConfiguration) => { - const runtimeConfig = {}; - runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); - return runtimeConfig; -}, "resolveRetryRuntimeConfig"); +// src/isValidHostname.ts +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +__name(isValidHostname, "isValidHostname"); +// Annotate the CommonJS export names for ESM import in node: -// src/extensions/defaultExtensionConfiguration.ts -var getDefaultExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); -}, "getDefaultExtensionConfiguration"); -var getDefaultClientConfiguration = getDefaultExtensionConfiguration; -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); -}, "resolveDefaultRuntimeConfig"); +0 && (0); -// src/get-array-if-single-item.ts -var getArrayIfSingleItem = /* @__PURE__ */ __name((mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray], "getArrayIfSingleItem"); -// src/get-value-from-text-node.ts -var getValueFromTextNode = /* @__PURE__ */ __name((obj) => { - const textNodeName = "#text"; - for (const key in obj) { - if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) { - obj[key] = obj[key][textNodeName]; - } else if (typeof obj[key] === "object" && obj[key] !== null) { - obj[key] = getValueFromTextNode(obj[key]); - } - } - return obj; -}, "getValueFromTextNode"); -// src/is-serializable-header-value.ts -var isSerializableHeaderValue = /* @__PURE__ */ __name((value) => { - return value != null; -}, "isSerializableHeaderValue"); +/***/ }), -// src/NoOpLogger.ts -var NoOpLogger = class { - static { - __name(this, "NoOpLogger"); - } - trace() { - } - debug() { - } - info() { - } - warn() { - } - error() { +/***/ 8031: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/object-mapping.ts -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); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + buildQueryString: () => buildQueryString +}); +module.exports = __toCommonJS(src_exports); +var import_util_uri_escape = __nccwpck_require__(4197); +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = (0, import_util_uri_escape.escapeUri)(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); + } } else { - instructions = arg1; - } - } - for (const key of Object.keys(instructions)) { - if (!Array.isArray(instructions[key])) { - target[key] = instructions[key]; - continue; + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; + } + parts.push(qsEntry); } - applyInstruction(target, null, instructions, key); } - return target; + return parts.join("&"); } -__name(map, "map"); -var convertMap = /* @__PURE__ */ __name((target) => { - const output = {}; - for (const [k, v] of Object.entries(target || {})) { - output[k] = [, v]; - } - return output; -}, "convertMap"); -var take = /* @__PURE__ */ __name((source, instructions) => { - const out = {}; - for (const key in instructions) { - applyInstruction(out, source, instructions, key); - } - return out; -}, "take"); -var mapWithFilter = /* @__PURE__ */ __name((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; - }, - {} - ) - ); -}, "mapWithFilter"); -var applyInstruction = /* @__PURE__ */ __name((target, source, instructions, targetKey) => { - if (source !== null) { - let instruction = instructions[targetKey]; - if (typeof instruction === "function") { - instruction = [, instruction]; - } - const [filter2 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; - if (typeof filter2 === "function" && filter2(source[sourceKey]) || typeof filter2 !== "function" && !!filter2) { - target[targetKey] = valueFn(source[sourceKey]); - } - return; +__name(buildQueryString, "buildQueryString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 4769: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - let [filter, value] = instructions[targetKey]; - if (typeof value === "function") { - let _value; - const defaultFilterPassed = filter === void 0 && (_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 === void 0 && value != null; - const customFilterPassed = typeof filter === "function" && !!filter(value) || typeof filter !== "function" && !!filter; - if (defaultFilterPassed || customFilterPassed) { - target[targetKey] = value; + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + parseQueryString: () => parseQueryString +}); +module.exports = __toCommonJS(src_exports); +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]; + } } } -}, "applyInstruction"); -var nonNullish = /* @__PURE__ */ __name((_) => _ != null, "nonNullish"); -var pass = /* @__PURE__ */ __name((_) => _, "pass"); + return query; +} +__name(parseQueryString, "parseQueryString"); +// Annotate the CommonJS export names for ESM import in node: -// src/resolve-path.ts +0 && (0); -// src/ser-utils.ts -var serializeFloat = /* @__PURE__ */ __name((value) => { - if (value !== value) { - return "NaN"; - } - switch (value) { - case Infinity: - return "Infinity"; - case -Infinity: - return "-Infinity"; - default: - return value; - } -}, "serializeFloat"); -var serializeDateTime = /* @__PURE__ */ __name((date) => date.toISOString().replace(".000Z", "Z"), "serializeDateTime"); -// src/serde-json.ts -var _json = /* @__PURE__ */ __name((obj) => { - if (obj == null) { - return {}; +/***/ }), + +/***/ 6375: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - if (Array.isArray(obj)) { - return obj.filter((_) => _ != null).map(_json); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + isBrowserNetworkError: () => isBrowserNetworkError, + isClockSkewCorrectedError: () => isClockSkewCorrectedError, + isClockSkewError: () => isClockSkewError, + isRetryableByTrait: () => isRetryableByTrait, + isServerError: () => isServerError, + isThrottlingError: () => isThrottlingError, + isTransientError: () => isTransientError +}); +module.exports = __toCommonJS(src_exports); + +// src/constants.ts +var CLOCK_SKEW_ERROR_CODES = [ + "AuthFailure", + "InvalidSignatureException", + "RequestExpired", + "RequestInTheFuture", + "RequestTimeTooSkewed", + "SignatureDoesNotMatch" +]; +var THROTTLING_ERROR_CODES = [ + "BandwidthLimitExceeded", + "EC2ThrottledException", + "LimitExceededException", + "PriorRequestNotComplete", + "ProvisionedThroughputExceededException", + "RequestLimitExceeded", + "RequestThrottled", + "RequestThrottledException", + "SlowDown", + "ThrottledException", + "Throttling", + "ThrottlingException", + "TooManyRequestsException", + "TransactionInProgressException" + // DynamoDB +]; +var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; +var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; +var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; +var NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND"]; + +// src/index.ts +var isRetryableByTrait = /* @__PURE__ */ __name((error) => error.$retryable !== void 0, "isRetryableByTrait"); +var isClockSkewError = /* @__PURE__ */ __name((error) => CLOCK_SKEW_ERROR_CODES.includes(error.name), "isClockSkewError"); +var isClockSkewCorrectedError = /* @__PURE__ */ __name((error) => error.$metadata?.clockSkewCorrected, "isClockSkewCorrectedError"); +var isBrowserNetworkError = /* @__PURE__ */ __name((error) => { + const errorMessages = /* @__PURE__ */ new Set([ + "Failed to fetch", + // Chrome + "NetworkError when attempting to fetch resource", + // Firefox + "The Internet connection appears to be offline", + // Safari 16 + "Load failed", + // Safari 17+ + "Network request failed" + // `cross-fetch` + ]); + const isValid = error && error instanceof TypeError; + if (!isValid) { + return false; } - if (typeof obj === "object") { - const target = {}; - for (const key of Object.keys(obj)) { - if (obj[key] == null) { - continue; - } - target[key] = _json(obj[key]); + return errorMessages.has(error.message); +}, "isBrowserNetworkError"); +var isThrottlingError = /* @__PURE__ */ __name((error) => error.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error.name) || error.$retryable?.throttling == true, "isThrottlingError"); +var isTransientError = /* @__PURE__ */ __name((error, depth = 0) => isClockSkewCorrectedError(error) || TRANSIENT_ERROR_CODES.includes(error.name) || NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || NODEJS_NETWORK_ERROR_CODES.includes(error?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) || isBrowserNetworkError(error) || error.cause !== void 0 && depth <= 10 && isTransientError(error.cause, depth + 1), "isTransientError"); +var isServerError = /* @__PURE__ */ __name((error) => { + if (error.$metadata?.httpStatusCode !== void 0) { + const statusCode = error.$metadata.httpStatusCode; + if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) { + return true; } - return target; + return false; } - return obj; -}, "_json"); - -// src/index.ts -__reExport(src_exports, __nccwpck_require__(7669), module.exports); + return false; +}, "isServerError"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -66128,8 +51831,82 @@ __reExport(src_exports, __nccwpck_require__(7669), module.exports); /***/ }), -/***/ 5756: -/***/ ((module) => { +/***/ 8340: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getHomeDir = void 0; +const os_1 = __nccwpck_require__(2037); +const path_1 = __nccwpck_require__(1017); +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; + + +/***/ }), + +/***/ 4740: +/***/ ((__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__(1017); +const getHomeDir_1 = __nccwpck_require__(8340); +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; + + +/***/ }), + +/***/ 9678: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFromFile = void 0; +const fs_1 = __nccwpck_require__(7147); +const getSSOTokenFilepath_1 = __nccwpck_require__(4740); +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; + + +/***/ }), + +/***/ 3507: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -66148,118 +51925,180 @@ var __copyProps = (to, from, except, desc) => { } return to; }; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig + CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, + DEFAULT_PROFILE: () => DEFAULT_PROFILE, + ENV_PROFILE: () => ENV_PROFILE, + getProfileName: () => getProfileName, + loadSharedConfigFiles: () => loadSharedConfigFiles, + loadSsoSessionData: () => loadSsoSessionData, + parseKnownFiles: () => parseKnownFiles }); module.exports = __toCommonJS(src_exports); +__reExport(src_exports, __nccwpck_require__(8340), module.exports); -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); +// src/getProfileName.ts +var ENV_PROFILE = "AWS_PROFILE"; +var DEFAULT_PROFILE = "default"; +var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); +// src/index.ts +__reExport(src_exports, __nccwpck_require__(4740), module.exports); +__reExport(src_exports, __nccwpck_require__(9678), module.exports); -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); +// src/loadSharedConfigFiles.ts -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: () => "sha256" /* SHA256 */, - checksumConstructor: () => runtimeConfig.sha256 - }); + +// src/getConfigData.ts +var import_types = __nccwpck_require__(5756); +var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: () => "md5" /* MD5 */, - checksumConstructor: () => runtimeConfig.md5 - }); + return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}).reduce( + (acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; + }, + { + // Populate default profile, if present. + ...data.default && { default: data.default } } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; +), "getConfigData"); + +// src/getConfigFilepath.ts +var import_path = __nccwpck_require__(1017); +var import_getHomeDir = __nccwpck_require__(8340); +var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); + +// src/getCredentialsFilepath.ts + +var import_getHomeDir2 = __nccwpck_require__(8340); +var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); + +// src/loadSharedConfigFiles.ts +var import_getHomeDir3 = __nccwpck_require__(8340); + +// src/parseIni.ts + +var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +var profileNameBlockList = ["__proto__", "profile __proto__"]; +var parseIni = /* @__PURE__ */ __name((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 = void 0; + currentSubSection = void 0; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(import_types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(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 = void 0; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; + } + } } + } + return map; +}, "parseIni"); + +// src/loadSharedConfigFiles.ts +var import_slurpFile = __nccwpck_require__(9155); +var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var CONFIG_PREFIX_SEPARATOR = "."; +var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = (0, import_getHomeDir3.getHomeDir)(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); + } + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).then(getConfigData).catch(swallowError), + (0, import_slurpFile.slurpFile)(resolvedFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).catch(swallowError) + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1] }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); +}, "loadSharedConfigFiles"); -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); +// src/getSsoSessionData.ts -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); +var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; +// src/loadSsoSessionData.ts +var import_slurpFile2 = __nccwpck_require__(9155); +var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); +// src/mergeConfigFiles.ts +var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== void 0) { + Object.assign(merged[key], values); + } else { + merged[key] = values; + } + } + } + return merged; +}, "mergeConfigFiles"); -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); +// src/parseKnownFiles.ts +var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}, "parseKnownFiles"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -66268,7 +52107,28 @@ var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { /***/ }), -/***/ 4681: +/***/ 9155: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slurpFile = void 0; +const fs_1 = __nccwpck_require__(7147); +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; + + +/***/ }), + +/***/ 1528: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -66293,347 +52153,622 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - parseUrl: () => parseUrl + ALGORITHM_IDENTIFIER: () => ALGORITHM_IDENTIFIER, + ALGORITHM_IDENTIFIER_V4A: () => ALGORITHM_IDENTIFIER_V4A, + ALGORITHM_QUERY_PARAM: () => ALGORITHM_QUERY_PARAM, + ALWAYS_UNSIGNABLE_HEADERS: () => ALWAYS_UNSIGNABLE_HEADERS, + AMZ_DATE_HEADER: () => AMZ_DATE_HEADER, + AMZ_DATE_QUERY_PARAM: () => AMZ_DATE_QUERY_PARAM, + AUTH_HEADER: () => AUTH_HEADER, + CREDENTIAL_QUERY_PARAM: () => CREDENTIAL_QUERY_PARAM, + DATE_HEADER: () => DATE_HEADER, + EVENT_ALGORITHM_IDENTIFIER: () => EVENT_ALGORITHM_IDENTIFIER, + EXPIRES_QUERY_PARAM: () => EXPIRES_QUERY_PARAM, + GENERATED_HEADERS: () => GENERATED_HEADERS, + HOST_HEADER: () => HOST_HEADER, + KEY_TYPE_IDENTIFIER: () => KEY_TYPE_IDENTIFIER, + MAX_CACHE_SIZE: () => MAX_CACHE_SIZE, + MAX_PRESIGNED_TTL: () => MAX_PRESIGNED_TTL, + PROXY_HEADER_PATTERN: () => PROXY_HEADER_PATTERN, + REGION_SET_PARAM: () => REGION_SET_PARAM, + SEC_HEADER_PATTERN: () => SEC_HEADER_PATTERN, + SHA256_HEADER: () => SHA256_HEADER, + SIGNATURE_HEADER: () => SIGNATURE_HEADER, + SIGNATURE_QUERY_PARAM: () => SIGNATURE_QUERY_PARAM, + SIGNED_HEADERS_QUERY_PARAM: () => SIGNED_HEADERS_QUERY_PARAM, + SignatureV4: () => SignatureV4, + SignatureV4Base: () => SignatureV4Base, + TOKEN_HEADER: () => TOKEN_HEADER, + TOKEN_QUERY_PARAM: () => TOKEN_QUERY_PARAM, + UNSIGNABLE_PATTERNS: () => UNSIGNABLE_PATTERNS, + UNSIGNED_PAYLOAD: () => UNSIGNED_PAYLOAD, + clearCredentialCache: () => clearCredentialCache, + createScope: () => createScope, + getCanonicalHeaders: () => getCanonicalHeaders, + getCanonicalQuery: () => getCanonicalQuery, + getPayloadHash: () => getPayloadHash, + getSigningKey: () => getSigningKey, + hasHeader: () => hasHeader, + moveHeadersToQuery: () => moveHeadersToQuery, + prepareRequest: () => prepareRequest, + signatureV4aContainer: () => signatureV4aContainer }); module.exports = __toCommonJS(src_exports); -var import_querystring_parser = __nccwpck_require__(4769); -var parseUrl = /* @__PURE__ */ __name((url) => { - if (typeof url === "string") { - return parseUrl(new URL(url)); - } - const { hostname, pathname, port, protocol, search } = url; - let query; - if (search) { - query = (0, import_querystring_parser.parseQueryString)(search); - } - return { - hostname, - port: port ? parseInt(port) : void 0, - protocol, - path: pathname, - query - }; -}, "parseUrl"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +// src/SignatureV4.ts -/***/ }), +var import_util_utf85 = __nccwpck_require__(1895); -/***/ 305: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/constants.ts +var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; +var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; +var AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; +var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; +var EXPIRES_QUERY_PARAM = "X-Amz-Expires"; +var SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; +var TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; +var REGION_SET_PARAM = "X-Amz-Region-Set"; +var AUTH_HEADER = "authorization"; +var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); +var DATE_HEADER = "date"; +var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; +var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); +var SHA256_HEADER = "x-amz-content-sha256"; +var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); +var HOST_HEADER = "host"; +var 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 +}; +var PROXY_HEADER_PATTERN = /^proxy-/; +var SEC_HEADER_PATTERN = /^sec-/; +var UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i]; +var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; +var ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256"; +var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; +var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; +var MAX_CACHE_SIZE = 50; +var KEY_TYPE_IDENTIFIER = "aws4_request"; +var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; -"use strict"; +// src/credentialDerivation.ts +var import_util_hex_encoding = __nccwpck_require__(5364); +var import_util_utf8 = __nccwpck_require__(1895); +var signingKeyCache = {}; +var cacheQueue = []; +var createScope = /* @__PURE__ */ __name((shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, "createScope"); +var getSigningKey = /* @__PURE__ */ __name(async (sha256Constructor, credentials, shortDate, region, service) => { + const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); + const cacheKey = `${shortDate}:${region}:${service}:${(0, import_util_hex_encoding.toHex)(credsHash)}:${credentials.sessionToken}`; + if (cacheKey in signingKeyCache) { + return signingKeyCache[cacheKey]; + } + cacheQueue.push(cacheKey); + while (cacheQueue.length > MAX_CACHE_SIZE) { + delete signingKeyCache[cacheQueue.shift()]; + } + let key = `AWS4${credentials.secretAccessKey}`; + for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { + key = await hmac(sha256Constructor, key, signable); + } + return signingKeyCache[cacheKey] = key; +}, "getSigningKey"); +var clearCredentialCache = /* @__PURE__ */ __name(() => { + cacheQueue.length = 0; + Object.keys(signingKeyCache).forEach((cacheKey) => { + delete signingKeyCache[cacheKey]; + }); +}, "clearCredentialCache"); +var hmac = /* @__PURE__ */ __name((ctor, secret, data) => { + const hash = new ctor(secret); + hash.update((0, import_util_utf8.toUint8Array)(data)); + return hash.digest(); +}, "hmac"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(1381); -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.`); +// src/getCanonicalHeaders.ts +var getCanonicalHeaders = /* @__PURE__ */ __name(({ headers }, unsignableHeaders, signableHeaders) => { + const canonical = {}; + for (const headerName of Object.keys(headers).sort()) { + if (headers[headerName] == void 0) { + continue; } - if (!BASE64_REGEX.exec(input)) { - throw new TypeError(`Invalid base64 string.`); + const canonicalHeaderName = headerName.toLowerCase(); + if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) { + if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { + continue; + } } - const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); - return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); -}; -exports.fromBase64 = fromBase64; + canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); + } + return canonical; +}, "getCanonicalHeaders"); +// src/getPayloadHash.ts +var import_is_array_buffer = __nccwpck_require__(780); -/***/ }), +var import_util_utf82 = __nccwpck_require__(1895); +var getPayloadHash = /* @__PURE__ */ __name(async ({ headers, body }, hashConstructor) => { + for (const headerName of Object.keys(headers)) { + if (headerName.toLowerCase() === SHA256_HEADER) { + return headers[headerName]; + } + } + if (body == void 0) { + return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + } else if (typeof body === "string" || ArrayBuffer.isView(body) || (0, import_is_array_buffer.isArrayBuffer)(body)) { + const hashCtor = new hashConstructor(); + hashCtor.update((0, import_util_utf82.toUint8Array)(body)); + return (0, import_util_hex_encoding.toHex)(await hashCtor.digest()); + } + return UNSIGNED_PAYLOAD; +}, "getPayloadHash"); -/***/ 5600: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// src/HeaderFormatter.ts -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +var import_util_utf83 = __nccwpck_require__(1895); +var HeaderFormatter = class { + static { + __name(this, "HeaderFormatter"); + } + format(headers) { + const chunks = []; + for (const headerName of Object.keys(headers)) { + const bytes = (0, import_util_utf83.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 /* boolTrue */ : 1 /* boolFalse */]); + case "byte": + return Uint8Array.from([2 /* byte */, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3 /* short */); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4 /* integer */); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5 /* long */; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6 /* byteArray */); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = (0, import_util_utf83.fromUtf8)(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7 /* string */); + 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 /* timestamp */; + tsBytes.set(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 /* uuid */; + uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1); + return uuidBytes; + } } - return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; +var Int64 = class _Int64 { + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static { + __name(this, "Int64"); + } + static fromNumber(number) { + if (number > 9223372036854776e3 || number < -9223372036854776e3) { + 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); + } + /** + * Called implicitly by infix arithmetic operators. + */ + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 128; + if (negative) { + negate(bytes); + } + return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } +}; +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 255; + } + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; + } +} +__name(negate, "negate"); -// src/index.ts -var src_exports = {}; -module.exports = __toCommonJS(src_exports); -__reExport(src_exports, __nccwpck_require__(305), module.exports); -__reExport(src_exports, __nccwpck_require__(4730), module.exports); -// Annotate the CommonJS export names for ESM import in node: +// src/headerUtil.ts +var hasHeader = /* @__PURE__ */ __name((soughtHeader, headers) => { + soughtHeader = soughtHeader.toLowerCase(); + for (const headerName of Object.keys(headers)) { + if (soughtHeader === headerName.toLowerCase()) { + return true; + } + } + return false; +}, "hasHeader"); -0 && (0); +// src/moveHeadersToQuery.ts +var import_protocol_http = __nccwpck_require__(4418); +var moveHeadersToQuery = /* @__PURE__ */ __name((request, options = {}) => { + const { headers, query = {} } = import_protocol_http.HttpRequest.clone(request); + for (const name of Object.keys(headers)) { + const lname = name.toLowerCase(); + if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) { + query[name] = headers[name]; + delete headers[name]; + } + } + return { + ...request, + headers, + query + }; +}, "moveHeadersToQuery"); +// src/prepareRequest.ts +var prepareRequest = /* @__PURE__ */ __name((request) => { + request = import_protocol_http.HttpRequest.clone(request); + for (const headerName of Object.keys(request.headers)) { + if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { + delete request.headers[headerName]; + } + } + return request; +}, "prepareRequest"); -/***/ }), +// src/SignatureV4Base.ts -/***/ 4730: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var import_util_middleware = __nccwpck_require__(2390); -"use strict"; +var import_util_utf84 = __nccwpck_require__(1895); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(1381); -const util_utf8_1 = __nccwpck_require__(1895); -const toBase64 = (_input) => { - let input; - if (typeof _input === "string") { - input = (0, util_utf8_1.fromUtf8)(_input); - } - else { - input = _input; +// src/getCanonicalQuery.ts +var import_util_uri_escape = __nccwpck_require__(4197); +var getCanonicalQuery = /* @__PURE__ */ __name(({ query = {} }) => { + const keys = []; + const serialized = {}; + for (const key of Object.keys(query)) { + if (key.toLowerCase() === SIGNATURE_HEADER) { + continue; } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + const encodedKey = (0, import_util_uri_escape.escapeUri)(key); + keys.push(encodedKey); + const value = query[key]; + if (typeof value === "string") { + serialized[encodedKey] = `${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value)}`; + } else if (Array.isArray(value)) { + serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value2)}`]), []).sort().join("&"); } - return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); -}; -exports.toBase64 = toBase64; - + } + return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); +}, "getCanonicalQuery"); -/***/ }), +// src/utilDate.ts +var iso8601 = /* @__PURE__ */ __name((time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z"), "iso8601"); +var toDate = /* @__PURE__ */ __name((time) => { + if (typeof time === "number") { + return new Date(time * 1e3); + } + if (typeof time === "string") { + if (Number(time)) { + return new Date(Number(time) * 1e3); + } + return new Date(time); + } + return time; +}, "toDate"); -/***/ 713: -/***/ ((module) => { +// src/SignatureV4Base.ts +var SignatureV4Base = class { + static { + __name(this, "SignatureV4Base"); + } + constructor({ + applyChecksum, + credentials, + region, + service, + sha256, + uriEscapePath = true + }) { + this.service = service; + this.sha256 = sha256; + this.uriEscapePath = uriEscapePath; + this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; + this.regionProvider = (0, import_util_middleware.normalizeProvider)(region); + this.credentialProvider = (0, import_util_middleware.normalizeProvider)(credentials); + } + createCanonicalRequest(request, canonicalHeaders, payloadHash) { + const sortedHeaders = Object.keys(canonicalHeaders).sort(); + return `${request.method} +${this.getCanonicalPath(request)} +${getCanonicalQuery(request)} +${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +${sortedHeaders.join(";")} +${payloadHash}`; + } + async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { + const hash = new this.sha256(); + hash.update((0, import_util_utf84.toUint8Array)(canonicalRequest)); + const hashedRequest = await hash.digest(); + return `${algorithmIdentifier} +${longDate} +${credentialScope} +${(0, import_util_hex_encoding.toHex)(hashedRequest)}`; + } + getCanonicalPath({ path }) { + if (this.uriEscapePath) { + const normalizedPathSegments = []; + for (const pathSegment of path.split("/")) { + if (pathSegment?.length === 0) + continue; + if (pathSegment === ".") + continue; + if (pathSegment === "..") { + normalizedPathSegments.pop(); + } else { + normalizedPathSegments.push(pathSegment); + } + } + const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; + const doubleEncoded = (0, import_util_uri_escape.escapeUri)(normalizedPath); + return doubleEncoded.replace(/%2F/g, "/"); + } + return path; + } + validateResolvedCredentials(credentials) { + if (typeof credentials !== "object" || // @ts-expect-error: Property 'accessKeyId' does not exist on type 'object'.ts(2339) + typeof credentials.accessKeyId !== "string" || // @ts-expect-error: Property 'secretAccessKey' does not exist on type 'object'.ts(2339) + typeof credentials.secretAccessKey !== "string") { + throw new Error("Resolved credential object is not valid"); + } + } + formatDate(now) { + const longDate = iso8601(now).replace(/[\-:]/g, ""); + return { + longDate, + shortDate: longDate.slice(0, 8) + }; + } + getCanonicalHeaderList(headers) { + return Object.keys(headers).sort().join(";"); } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - calculateBodyLength: () => calculateBodyLength -}); -module.exports = __toCommonJS(src_exports); -// src/calculateBodyLength.ts -var TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder() : null; -var calculateBodyLength = /* @__PURE__ */ __name((body) => { - if (typeof body === "string") { - if (TEXT_ENCODER) { - return TEXT_ENCODER.encode(body).byteLength; +// src/SignatureV4.ts +var SignatureV4 = class extends SignatureV4Base { + constructor({ + applyChecksum, + credentials, + region, + service, + sha256, + uriEscapePath = true + }) { + super({ + applyChecksum, + credentials, + region, + service, + sha256, + uriEscapePath + }); + this.headerFormatter = new HeaderFormatter(); + } + static { + __name(this, "SignatureV4"); + } + async presign(originalRequest, options = {}) { + const { + signingDate = /* @__PURE__ */ new Date(), + expiresIn = 3600, + unsignableHeaders, + unhoistableHeaders, + signableHeaders, + hoistableHeaders, + signingRegion, + signingService + } = options; + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? await this.regionProvider(); + const { longDate, shortDate } = this.formatDate(signingDate); + if (expiresIn > MAX_PRESIGNED_TTL) { + return Promise.reject( + "Signature version 4 presigned URLs must have an expiration date less than one week in the future" + ); } - let len = body.length; - for (let i = len - 1; i >= 0; i--) { - const code = body.charCodeAt(i); - if (code > 127 && code <= 2047) - len++; - else if (code > 2047 && code <= 65535) - len += 2; - if (code >= 56320 && code <= 57343) - i--; + const scope = createScope(shortDate, region, signingService ?? this.service); + const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); + if (credentials.sessionToken) { + request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; } - return len; - } else if (typeof body.byteLength === "number") { - return body.byteLength; - } else if (typeof body.size === "number") { - return body.size; + request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; + request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; + request.query[AMZ_DATE_QUERY_PARAM] = longDate; + request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); + request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature( + longDate, + scope, + this.getSigningKey(credentials, region, shortDate, signingService), + this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)) + ); + return request; } - throw new Error(`Body Length computation failed for ${body}`); -}, "calculateBodyLength"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 8075: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + 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); + } } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - calculateBodyLength: () => calculateBodyLength -}); -module.exports = __toCommonJS(src_exports); - -// src/calculateBodyLength.ts -var import_fs = __nccwpck_require__(7147); -var calculateBodyLength = /* @__PURE__ */ __name((body) => { - if (!body) { - return 0; + async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { + const region = signingRegion ?? await this.regionProvider(); + const { shortDate, longDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); + const hash = new this.sha256(); + hash.update(headers); + const hashedHeaders = (0, import_util_hex_encoding.toHex)(await hash.digest()); + const stringToSign = [ + EVENT_ALGORITHM_IDENTIFIER, + longDate, + scope, + priorSignature, + hashedHeaders, + hashedPayload + ].join("\n"); + return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); } - if (typeof body === "string") { - return Buffer.byteLength(body); - } 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, import_fs.lstatSync)(body.path).size; - } else if (typeof body.fd === "number") { - return (0, import_fs.fstatSync)(body.fd).size; + async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { + const promise = this.signEvent( + { + headers: this.headerFormatter.format(signableMessage.message.headers), + payload: signableMessage.message.body + }, + { + signingDate, + signingRegion, + signingService, + priorSignature: signableMessage.priorSignature + } + ); + return promise.then((signature) => { + return { message: signableMessage.message, signature }; + }); } - throw new Error(`Body Length computation failed for ${body}`); -}, "calculateBodyLength"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 1381: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? await this.regionProvider(); + const { shortDate } = this.formatDate(signingDate); + const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); + hash.update((0, import_util_utf85.toUint8Array)(stringToSign)); + return (0, import_util_hex_encoding.toHex)(await hash.digest()); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString -}); -module.exports = __toCommonJS(src_exports); -var import_is_array_buffer = __nccwpck_require__(780); -var import_buffer = __nccwpck_require__(4300); -var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + async signRequest(requestToSign, { + signingDate = /* @__PURE__ */ new Date(), + signableHeaders, + unsignableHeaders, + signingRegion, + signingService + } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? await this.regionProvider(); + const request = prepareRequest(requestToSign); + const { longDate, shortDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + request.headers[AMZ_DATE_HEADER] = longDate; + if (credentials.sessionToken) { + request.headers[TOKEN_HEADER] = credentials.sessionToken; + } + const payloadHash = await getPayloadHash(request, this.sha256); + if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { + request.headers[SHA256_HEADER] = payloadHash; + } + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + const signature = await this.getSignature( + longDate, + scope, + this.getSigningKey(credentials, region, shortDate, signingService), + this.createCanonicalRequest(request, canonicalHeaders, payloadHash) + ); + request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; + return request; } - return import_buffer.Buffer.from(input, offset, length); -}, "fromArrayBuffer"); -var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { + const stringToSign = await this.createStringToSign( + longDate, + credentialScope, + canonicalRequest, + ALGORITHM_IDENTIFIER + ); + const hash = new this.sha256(await keyPromise); + hash.update((0, import_util_utf85.toUint8Array)(stringToSign)); + return (0, import_util_hex_encoding.toHex)(await hash.digest()); } - return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); -}, "fromString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 3375: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + getSigningKey(credentials, region, shortDate, service) { + return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - SelectorType: () => SelectorType, - booleanSelector: () => booleanSelector, - numberSelector: () => numberSelector -}); -module.exports = __toCommonJS(src_exports); - -// src/booleanSelector.ts -var booleanSelector = /* @__PURE__ */ __name((obj, key, type) => { - if (!(key in obj)) - return void 0; - 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]}.`); -}, "booleanSelector"); - -// src/numberSelector.ts -var numberSelector = /* @__PURE__ */ __name((obj, key, type) => { - if (!(key in obj)) - return void 0; - const numberValue = parseInt(obj[key], 10); - if (Number.isNaN(numberValue)) { - throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); - } - return numberValue; -}, "numberSelector"); -// src/types.ts -var SelectorType = /* @__PURE__ */ ((SelectorType2) => { - SelectorType2["ENV"] = "env"; - SelectorType2["CONFIG"] = "shared config entry"; - return SelectorType2; -})(SelectorType || {}); +// src/signature-v4a-container.ts +var signatureV4aContainer = { + SignatureV4a: null +}; // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -66642,14 +52777,12 @@ var SelectorType = /* @__PURE__ */ ((SelectorType2) => { /***/ }), -/***/ 2429: +/***/ 3570: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -66664,715 +52797,666 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { - resolveDefaultsModeConfig: () => resolveDefaultsModeConfig + Client: () => Client, + Command: () => Command, + NoOpLogger: () => NoOpLogger, + SENSITIVE_STRING: () => SENSITIVE_STRING, + ServiceException: () => ServiceException, + _json: () => _json, + collectBody: () => import_protocols.collectBody, + convertMap: () => convertMap, + createAggregatedClient: () => createAggregatedClient, + decorateServiceException: () => decorateServiceException, + emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, + extendedEncodeURIComponent: () => import_protocols.extendedEncodeURIComponent, + getArrayIfSingleItem: () => getArrayIfSingleItem, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration, + getValueFromTextNode: () => getValueFromTextNode, + isSerializableHeaderValue: () => isSerializableHeaderValue, + loadConfigsForDefaultMode: () => loadConfigsForDefaultMode, + map: () => map, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig, + resolvedPath: () => import_protocols.resolvedPath, + serializeDateTime: () => serializeDateTime, + serializeFloat: () => serializeFloat, + take: () => take, + throwDefaultError: () => throwDefaultError, + withBaseException: () => withBaseException }); module.exports = __toCommonJS(src_exports); -// src/resolveDefaultsModeConfig.ts -var import_config_resolver = __nccwpck_require__(3098); -var import_node_config_provider = __nccwpck_require__(3461); -var import_property_provider = __nccwpck_require__(9721); - -// src/constants.ts -var AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; -var AWS_REGION_ENV = "AWS_REGION"; -var AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; -var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; -var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; -var IMDS_REGION_PATH = "/latest/meta-data/placement/region"; - -// src/defaultsModeConfig.ts -var AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; -var AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; -var NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => { - return env[AWS_DEFAULTS_MODE_ENV]; - }, - configFileSelector: (profile) => { - return profile[AWS_DEFAULTS_MODE_CONFIG]; - }, - default: "legacy" -}; - -// src/resolveDefaultsModeConfig.ts -var resolveDefaultsModeConfig = /* @__PURE__ */ __name(({ - region = (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_REGION_CONFIG_OPTIONS), - defaultsMode = (0, import_node_config_provider.loadConfig)(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) -} = {}) => (0, import_property_provider.memoize)(async () => { - const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; - switch (mode?.toLowerCase()) { - case "auto": - return resolveNodeDefaultsModeAuto(region); - case "in-region": - case "cross-region": - case "mobile": - case "standard": - case "legacy": - return Promise.resolve(mode?.toLocaleLowerCase()); - case void 0: - return Promise.resolve("legacy"); - default: - throw new Error( - `Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}` - ); +// src/client.ts +var import_middleware_stack = __nccwpck_require__(7911); +var Client = class { + constructor(config) { + this.config = config; + this.middlewareStack = (0, import_middleware_stack.constructStack)(); } -}), "resolveDefaultsModeConfig"); -var resolveNodeDefaultsModeAuto = /* @__PURE__ */ __name(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"; + static { + __name(this, "Client"); + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = /* @__PURE__ */ new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } } else { - return "cross-region"; + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); } - } - return "standard"; -}, "resolveNodeDefaultsModeAuto"); -var inferPhysicalRegion = /* @__PURE__ */ __name(async () => { - if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { - return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; - } - if (!process.env[ENV_IMDS_DISABLED]) { - try { - const { getInstanceMetadataEndpoint, httpRequest } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); - const endpoint = await getInstanceMetadataEndpoint(); - return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString(); - } catch (e) { + if (callback) { + handler(command).then( + (result) => callback(null, result.output), + (err) => callback(err) + ).catch( + // prevent any errors thrown in the callback from triggering an + // unhandled promise rejection + () => { + } + ); + } else { + return handler(command).then((result) => result.output); } } -}, "inferPhysicalRegion"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 5473: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - EndpointCache: () => EndpointCache, - EndpointError: () => EndpointError, - customEndpointFunctions: () => customEndpointFunctions, - isIpAddress: () => isIpAddress, - isValidHostLabel: () => isValidHostLabel, - resolveEndpoint: () => resolveEndpoint -}); -module.exports = __toCommonJS(src_exports); +// src/collect-stream-body.ts +var import_protocols = __nccwpck_require__(2241); -// src/cache/EndpointCache.ts -var EndpointCache = class { +// src/command.ts + +var import_types = __nccwpck_require__(5756); +var Command = class { + constructor() { + this.middlewareStack = (0, import_middleware_stack.constructStack)(); + } + static { + __name(this, "Command"); + } /** - * @param [size] - desired average maximum capacity. A buffer of 10 additional keys will be allowed - * before keys are dropped. - * @param [params] - list of params to consider as part of the cache key. - * - * If the params list is not populated, no caching will happen. - * This may be out of order depending on how the object is created and arrives to this class. + * Factory for Command ClassBuilder. + * @internal */ - constructor({ size, params }) { - this.data = /* @__PURE__ */ new Map(); - this.parameters = []; - this.capacity = size ?? 50; - if (params) { - this.parameters = params; + static classBuilder() { + return new ClassBuilder(); + } + /** + * @internal + */ + resolveMiddlewareWithContext(clientStack, configuration, options, { + middlewareFn, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + smithyContext, + additionalContext, + CommandCtor + }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); } + const stack = clientStack.concat(this.middlewareStack); + const { logger } = configuration; + const handlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [import_types.SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext + }, + ...additionalContext + }; + const { requestHandler } = configuration; + return stack.resolve( + (request) => requestHandler.handle(request.request, options || {}), + handlerExecutionContext + ); + } +}; +var ClassBuilder = class { + constructor() { + this._init = () => { + }; + this._ep = {}; + this._middlewareFn = () => []; + this._commandName = ""; + this._clientName = ""; + this._additionalContext = {}; + this._smithyContext = {}; + this._inputFilterSensitiveLog = (_) => _; + this._outputFilterSensitiveLog = (_) => _; + this._serializer = null; + this._deserializer = null; } static { - __name(this, "EndpointCache"); + __name(this, "ClassBuilder"); } /** - * @param endpointParams - query for endpoint. - * @param resolver - provider of the value if not present. - * @returns endpoint corresponding to the query. + * Optional init callback. */ - get(endpointParams, resolver) { - const key = this.hash(endpointParams); - if (key === false) { - return resolver(); - } - if (!this.data.has(key)) { - if (this.data.size > this.capacity + 10) { - const keys = this.data.keys(); - let i = 0; - while (true) { - const { value, done } = keys.next(); - this.data.delete(value); - if (done || ++i > 10) { - break; - } - } - } - this.data.set(key, resolver()); - } - return this.data.get(key); + init(cb) { + this._init = cb; } - size() { - return this.data.size; + /** + * Set the endpoint parameter instructions. + */ + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; } /** - * @returns cache key or false if not cachable. + * Add any number of middleware. */ - hash(endpointParams) { - let buffer = ""; - const { parameters } = this; - if (parameters.length === 0) { - return false; - } - for (const param of parameters) { - const val = String(endpointParams[param] ?? ""); - if (val.includes("|;")) { - return false; - } - buffer += val + "|;"; - } - return buffer; + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; } -}; - -// src/lib/isIpAddress.ts -var 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}$` -); -var isIpAddress = /* @__PURE__ */ __name((value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"), "isIpAddress"); - -// src/lib/isValidHostLabel.ts -var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); -var isValidHostLabel = /* @__PURE__ */ __name((value, allowSubDomains = false) => { - if (!allowSubDomains) { - return VALID_HOST_LABEL_REGEX.test(value); + /** + * Set the initial handler execution context Smithy field. + */ + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext + }; + return this; } - const labels = value.split("."); - for (const label of labels) { - if (!isValidHostLabel(label)) { - return false; - } + /** + * Set the initial handler execution context. + */ + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; } - return true; -}, "isValidHostLabel"); - -// src/utils/customEndpointFunctions.ts -var customEndpointFunctions = {}; - -// src/debug/debugId.ts -var debugId = "endpoints"; - -// src/debug/toDebugString.ts -function toDebugString(input) { - if (typeof input !== "object" || input == null) { - return input; + /** + * Set constant string identifiers for the operation. + */ + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; } - if ("ref" in input) { - return `$${toDebugString(input.ref)}`; + /** + * Set the input and output sensistive log filters. + */ + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; } - if ("fn" in input) { - return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; + /** + * Sets the serializer. + */ + ser(serializer) { + this._serializer = serializer; + return this; } - return JSON.stringify(input, null, 2); -} -__name(toDebugString, "toDebugString"); - -// src/types/EndpointError.ts -var EndpointError = class extends Error { - static { - __name(this, "EndpointError"); + /** + * Sets the deserializer. + */ + de(deserializer) { + this._deserializer = deserializer; + return this; } - constructor(message) { - super(message); - this.name = "EndpointError"; + /** + * Sets input/output schema for the operation. + */ + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; } -}; - -// src/lib/booleanEquals.ts -var booleanEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "booleanEquals"); - -// src/lib/getAttrPathList.ts -var getAttrPathList = /* @__PURE__ */ __name((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 EndpointError(`Path: '${path}' does not end with ']'`); + /** + * @returns a Command class with the classBuilder properties. + */ + build() { + const closure = this; + let CommandRef; + return CommandRef = class extends Command { + /** + * @public + */ + constructor(...[input]) { + super(); + /** + * @internal + */ + // @ts-ignore used in middlewareFn closure. + this.serialize = closure._serializer; + /** + * @internal + */ + // @ts-ignore used in middlewareFn closure. + this.deserialize = closure._deserializer; + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; } - const arrayIndex = part.slice(squareBracketIndex + 1, -1); - if (Number.isNaN(parseInt(arrayIndex))) { - throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); + static { + __name(this, "CommandRef"); } - if (squareBracketIndex !== 0) { - pathList.push(part.slice(0, squareBracketIndex)); + /** + * @public + */ + static getEndpointParameterInstructions() { + return closure._ep; } - pathList.push(arrayIndex); - } else { - pathList.push(part); - } - } - return pathList; -}, "getAttrPathList"); - -// src/lib/getAttr.ts -var getAttr = /* @__PURE__ */ __name((value, path) => getAttrPathList(path).reduce((acc, index) => { - if (typeof acc !== "object") { - throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); - } else if (Array.isArray(acc)) { - return acc[parseInt(index)]; + /** + * @internal + */ + resolveMiddleware(stack, configuration, options) { + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog, + outputFilterSensitiveLog: closure._outputFilterSensitiveLog, + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext + }); + } + }; } - return acc[index]; -}, value), "getAttr"); - -// src/lib/isSet.ts -var isSet = /* @__PURE__ */ __name((value) => value != null, "isSet"); +}; -// src/lib/not.ts -var not = /* @__PURE__ */ __name((value) => !value, "not"); +// src/constants.ts +var SENSITIVE_STRING = "***SensitiveInformation***"; -// src/lib/parseURL.ts -var import_types3 = __nccwpck_require__(5756); -var DEFAULT_PORTS = { - [import_types3.EndpointURLScheme.HTTP]: 80, - [import_types3.EndpointURLScheme.HTTPS]: 443 -}; -var parseURL = /* @__PURE__ */ __name((value) => { - const whatwgURL = (() => { - try { - if (value instanceof URL) { - return value; - } - if (typeof value === "object" && "hostname" in value) { - const { hostname: hostname2, port, protocol: protocol2 = "", path = "", query = {} } = value; - const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path}`); - url.search = Object.entries(query).map(([k, v]) => `${k}=${v}`).join("&"); - return url; +// src/create-aggregated-client.ts +var createAggregatedClient = /* @__PURE__ */ __name((commands, Client2) => { + for (const command of Object.keys(commands)) { + const CommandCtor = commands[command]; + const methodImpl = /* @__PURE__ */ __name(async function(args, optionsOrCb, cb) { + const command2 = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command2, optionsOrCb); + } else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command2, optionsOrCb || {}, cb); + } else { + return this.send(command2, optionsOrCb); } - 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(import_types3.EndpointURLScheme).includes(scheme)) { - return null; + }, "methodImpl"); + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client2.prototype[methodName] = methodImpl; } - const isIp = 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 - }; -}, "parseURL"); - -// src/lib/stringEquals.ts -var stringEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "stringEquals"); +}, "createAggregatedClient"); -// src/lib/substring.ts -var substring = /* @__PURE__ */ __name((input, start, stop, reverse) => { - if (start >= stop || input.length < stop) { - return null; +// src/exceptions.ts +var ServiceException = class _ServiceException extends Error { + static { + __name(this, "ServiceException"); } - if (!reverse) { - return input.substring(start, stop); + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; } - return input.substring(input.length - stop, input.length - start); -}, "substring"); - -// src/lib/uriEncode.ts -var uriEncode = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`), "uriEncode"); - -// src/utils/endpointFunctions.ts -var endpointFunctions = { - booleanEquals, - getAttr, - isSet, - isValidHostLabel, - not, - parseURL, - stringEquals, - substring, - uriEncode -}; - -// src/utils/evaluateTemplate.ts -var evaluateTemplate = /* @__PURE__ */ __name((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(getAttr(templateContext[refName], attrName)); - } else { - evaluatedTemplateArr.push(templateContext[parameterName]); + /** + * Checks if a value is an instance of ServiceException (duck typed) + */ + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server"); + } + /** + * Custom instanceof check to support the operator for ServiceException base class + */ + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === _ServiceException) { + return _ServiceException.isInstance(instance); } - currentIndex = closingBraceIndex + 1; + if (_ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; } - return evaluatedTemplateArr.join(""); -}, "evaluateTemplate"); +}; +var decorateServiceException = /* @__PURE__ */ __name((exception, additions = {}) => { + Object.entries(additions).filter(([, v]) => v !== void 0).forEach(([k, v]) => { + if (exception[k] == void 0 || exception[k] === "") { + exception[k] = v; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}, "decorateServiceException"); -// src/utils/getReferenceValue.ts -var getReferenceValue = /* @__PURE__ */ __name(({ ref }, options) => { - const referenceRecord = { - ...options.endpointParams, - ...options.referenceRecord +// src/default-error-handler.ts +var throwDefaultError = /* @__PURE__ */ __name(({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata + }); + throw decorateServiceException(response, parsedBody); +}, "throwDefaultError"); +var withBaseException = /* @__PURE__ */ __name((ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); }; - return referenceRecord[ref]; -}, "getReferenceValue"); +}, "withBaseException"); +var deserializeMetadata = /* @__PURE__ */ __name((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"] +}), "deserializeMetadata"); -// src/utils/evaluateExpression.ts -var evaluateExpression = /* @__PURE__ */ __name((obj, keyName, options) => { - if (typeof obj === "string") { - return evaluateTemplate(obj, options); - } else if (obj["fn"]) { - return callFunction(obj, options); - } else if (obj["ref"]) { - return getReferenceValue(obj, options); +// src/defaults-mode.ts +var loadConfigsForDefaultMode = /* @__PURE__ */ __name((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: 3e4 + }; + default: + return {}; } - throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); -}, "evaluateExpression"); +}, "loadConfigsForDefaultMode"); -// src/utils/callFunction.ts -var callFunction = /* @__PURE__ */ __name(({ fn, argv }, options) => { - const evaluatedArgs = argv.map( - (arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options) - ); - const fnSegments = fn.split("."); - if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) { - return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); +// src/emitWarningIfUnsupportedVersion.ts +var warningEmitted = false; +var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; } - return endpointFunctions[fn](...evaluatedArgs); -}, "callFunction"); +}, "emitWarningIfUnsupportedVersion"); -// src/utils/evaluateCondition.ts -var evaluateCondition = /* @__PURE__ */ __name(({ assign, ...fnArgs }, options) => { - if (assign && assign in options.referenceRecord) { - throw new EndpointError(`'${assign}' is already defined in Reference Record.`); +// src/extended-encode-uri-component.ts + + +// src/extensions/checksum.ts + +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in import_types.AlgorithmId) { + const algorithmId = import_types.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === void 0) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId] + }); } - const value = callFunction(fnArgs, options); - options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); return { - result: value === "" ? true : !!value, - ...assign != null && { toAssign: { name: assign, value } } + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + } }; -}, "evaluateCondition"); +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); -// src/utils/evaluateConditions.ts -var evaluateConditions = /* @__PURE__ */ __name((conditions = [], options) => { - const conditionsReferenceRecord = {}; - for (const condition of conditions) { - const { result, toAssign } = evaluateCondition(condition, { - ...options, - referenceRecord: { - ...options.referenceRecord, - ...conditionsReferenceRecord - } - }); - if (!result) { - return { result }; +// src/extensions/retry.ts +var getRetryConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; } - if (toAssign) { - conditionsReferenceRecord[toAssign.name] = toAssign.value; - options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); + }; +}, "getRetryConfiguration"); +var resolveRetryRuntimeConfig = /* @__PURE__ */ __name((retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}, "resolveRetryRuntimeConfig"); + +// src/extensions/defaultExtensionConfiguration.ts +var getDefaultExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}, "getDefaultExtensionConfiguration"); +var getDefaultClientConfiguration = getDefaultExtensionConfiguration; +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}, "resolveDefaultRuntimeConfig"); + +// src/get-array-if-single-item.ts +var getArrayIfSingleItem = /* @__PURE__ */ __name((mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray], "getArrayIfSingleItem"); + +// src/get-value-from-text-node.ts +var getValueFromTextNode = /* @__PURE__ */ __name((obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) { + obj[key] = obj[key][textNodeName]; + } else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); } } - return { result: true, referenceRecord: conditionsReferenceRecord }; -}, "evaluateConditions"); + return obj; +}, "getValueFromTextNode"); -// src/utils/getEndpointHeaders.ts -var getEndpointHeaders = /* @__PURE__ */ __name((headers, options) => Object.entries(headers).reduce( - (acc, [headerKey, headerVal]) => ({ - ...acc, - [headerKey]: headerVal.map((headerValEntry) => { - const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); - if (typeof processedExpr !== "string") { - throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); - } - return processedExpr; - }) - }), - {} -), "getEndpointHeaders"); +// src/is-serializable-header-value.ts +var isSerializableHeaderValue = /* @__PURE__ */ __name((value) => { + return value != null; +}, "isSerializableHeaderValue"); -// src/utils/getEndpointProperty.ts -var getEndpointProperty = /* @__PURE__ */ __name((property, options) => { - if (Array.isArray(property)) { - return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); +// src/NoOpLogger.ts +var NoOpLogger = class { + static { + __name(this, "NoOpLogger"); } - switch (typeof property) { - case "string": - return evaluateTemplate(property, options); - case "object": - if (property === null) { - throw new EndpointError(`Unexpected endpoint property: ${property}`); - } - return getEndpointProperties(property, options); - case "boolean": - return property; - default: - throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); + trace() { } -}, "getEndpointProperty"); - -// src/utils/getEndpointProperties.ts -var getEndpointProperties = /* @__PURE__ */ __name((properties, options) => Object.entries(properties).reduce( - (acc, [propertyKey, propertyVal]) => ({ - ...acc, - [propertyKey]: getEndpointProperty(propertyVal, options) - }), - {} -), "getEndpointProperties"); - -// src/utils/getEndpointUrl.ts -var getEndpointUrl = /* @__PURE__ */ __name((endpointUrl, options) => { - const expression = 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; - } + debug() { } - throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); -}, "getEndpointUrl"); - -// src/utils/evaluateEndpointRule.ts -var evaluateEndpointRule = /* @__PURE__ */ __name((endpointRule, options) => { - const { conditions, endpoint } = endpointRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; + info() { } - const endpointRuleOptions = { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord } - }; - const { url, properties, headers } = endpoint; - options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); - return { - ...headers != void 0 && { - headers: getEndpointHeaders(headers, endpointRuleOptions) - }, - ...properties != void 0 && { - properties: getEndpointProperties(properties, endpointRuleOptions) - }, - url: getEndpointUrl(url, endpointRuleOptions) - }; -}, "evaluateEndpointRule"); - -// src/utils/evaluateErrorRule.ts -var evaluateErrorRule = /* @__PURE__ */ __name((errorRule, options) => { - const { conditions, error } = errorRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; + warn() { } - throw new EndpointError( - evaluateExpression(error, "Error", { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord } - }) - ); -}, "evaluateErrorRule"); - -// src/utils/evaluateTreeRule.ts -var evaluateTreeRule = /* @__PURE__ */ __name((treeRule, options) => { - const { conditions, rules } = treeRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; + error() { } - return evaluateRules(rules, { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord } - }); -}, "evaluateTreeRule"); +}; -// src/utils/evaluateRules.ts -var evaluateRules = /* @__PURE__ */ __name((rules, options) => { - for (const rule of rules) { - if (rule.type === "endpoint") { - const endpointOrUndefined = evaluateEndpointRule(rule, options); - if (endpointOrUndefined) { - return endpointOrUndefined; - } - } else if (rule.type === "error") { - evaluateErrorRule(rule, options); - } else if (rule.type === "tree") { - const endpointOrUndefined = evaluateTreeRule(rule, options); - if (endpointOrUndefined) { - return endpointOrUndefined; - } +// src/object-mapping.ts +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 { - throw new EndpointError(`Unknown endpoint rule: ${rule}`); + instructions = arg1; } } - throw new EndpointError(`Rules evaluation failed`); -}, "evaluateRules"); - -// src/resolveEndpoint.ts -var resolveEndpoint = /* @__PURE__ */ __name((ruleSetObject, options) => { - const { endpointParams, logger } = options; - const { parameters, rules } = ruleSetObject; - options.logger?.debug?.(`${debugId} Initial EndpointParams: ${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] = endpointParams[paramKey] ?? paramDefaultValue; + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; } + applyInstruction(target, null, instructions, key); } - const requiredParams = Object.entries(parameters).filter(([, v]) => v.required).map(([k]) => k); - for (const requiredParam of requiredParams) { - if (endpointParams[requiredParam] == null) { - throw new EndpointError(`Missing required parameter: '${requiredParam}'`); + return target; +} +__name(map, "map"); +var convertMap = /* @__PURE__ */ __name((target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}, "convertMap"); +var take = /* @__PURE__ */ __name((source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; +}, "take"); +var mapWithFilter = /* @__PURE__ */ __name((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; + }, + {} + ) + ); +}, "mapWithFilter"); +var applyInstruction = /* @__PURE__ */ __name((target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; } + const [filter2 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if (typeof filter2 === "function" && filter2(source[sourceKey]) || typeof filter2 !== "function" && !!filter2) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; } - const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} }); - options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); - return endpoint; -}, "resolveEndpoint"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === void 0 && (_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 === void 0 && value != null; + const customFilterPassed = typeof filter === "function" && !!filter(value) || typeof filter !== "function" && !!filter; + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } +}, "applyInstruction"); +var nonNullish = /* @__PURE__ */ __name((_) => _ != null, "nonNullish"); +var pass = /* @__PURE__ */ __name((_) => _, "pass"); -/***/ }), +// src/resolve-path.ts -/***/ 5364: -/***/ ((module) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/ser-utils.ts +var serializeFloat = /* @__PURE__ */ __name((value) => { + if (value !== value) { + return "NaN"; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}, "serializeFloat"); +var serializeDateTime = /* @__PURE__ */ __name((date) => date.toISOString().replace(".000Z", "Z"), "serializeDateTime"); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromHex: () => fromHex, - toHex: () => toHex -}); -module.exports = __toCommonJS(src_exports); -var SHORT_TO_HEX = {}; -var HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; +// src/serde-json.ts +var _json = /* @__PURE__ */ __name((obj) => { + if (obj == null) { + return {}; } - 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"); + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); } - 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`); + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); } + return target; } - return out; -} -__name(fromHex, "fromHex"); -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; - } - return out; -} -__name(toHex, "toHex"); + return obj; +}, "_json"); + +// src/index.ts +__reExport(src_exports, __nccwpck_require__(7669), module.exports); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -67381,8 +53465,8 @@ __name(toHex, "toHex"); /***/ }), -/***/ 2390: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5756: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -67406,22 +53490,113 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - getSmithyContext: () => getSmithyContext, - normalizeProvider: () => normalizeProvider + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig }); module.exports = __toCommonJS(src_exports); -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(5756); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") - return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); + +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); + +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: () => "sha256" /* SHA256 */, + checksumConstructor: () => runtimeConfig.sha256 + }); + } + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: () => "md5" /* MD5 */, + checksumConstructor: () => runtimeConfig.md5 + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + } + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); + +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); + +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); + +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; + +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); + +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -67430,7 +53605,7 @@ var normalizeProvider = /* @__PURE__ */ __name((input) => { /***/ }), -/***/ 4902: +/***/ 4681: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -67455,321 +53630,27 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - AdaptiveRetryStrategy: () => AdaptiveRetryStrategy, - ConfiguredRetryStrategy: () => ConfiguredRetryStrategy, - DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS, - DEFAULT_RETRY_DELAY_BASE: () => DEFAULT_RETRY_DELAY_BASE, - DEFAULT_RETRY_MODE: () => DEFAULT_RETRY_MODE, - DefaultRateLimiter: () => DefaultRateLimiter, - INITIAL_RETRY_TOKENS: () => INITIAL_RETRY_TOKENS, - INVOCATION_ID_HEADER: () => INVOCATION_ID_HEADER, - MAXIMUM_RETRY_DELAY: () => MAXIMUM_RETRY_DELAY, - NO_RETRY_INCREMENT: () => NO_RETRY_INCREMENT, - REQUEST_HEADER: () => REQUEST_HEADER, - RETRY_COST: () => RETRY_COST, - RETRY_MODES: () => RETRY_MODES, - StandardRetryStrategy: () => StandardRetryStrategy, - THROTTLING_RETRY_DELAY_BASE: () => THROTTLING_RETRY_DELAY_BASE, - TIMEOUT_RETRY_COST: () => TIMEOUT_RETRY_COST + parseUrl: () => parseUrl }); module.exports = __toCommonJS(src_exports); - -// src/config.ts -var RETRY_MODES = /* @__PURE__ */ ((RETRY_MODES2) => { - RETRY_MODES2["STANDARD"] = "standard"; - RETRY_MODES2["ADAPTIVE"] = "adaptive"; - return RETRY_MODES2; -})(RETRY_MODES || {}); -var DEFAULT_MAX_ATTEMPTS = 3; -var DEFAULT_RETRY_MODE = "standard" /* STANDARD */; - -// src/DefaultRateLimiter.ts -var import_service_error_classification = __nccwpck_require__(6375); -var DefaultRateLimiter = class _DefaultRateLimiter { - constructor(options) { - // Pre-set state variables - this.currentCapacity = 0; - this.enabled = false; - this.lastMaxRate = 0; - this.measuredTxRate = 0; - this.requestCount = 0; - this.lastTimestamp = 0; - this.timeWindow = 0; - this.beta = options?.beta ?? 0.7; - this.minCapacity = options?.minCapacity ?? 1; - this.minFillRate = options?.minFillRate ?? 0.5; - this.scaleConstant = options?.scaleConstant ?? 0.4; - this.smooth = options?.smooth ?? 0.8; - const currentTimeInSeconds = this.getCurrentTimeInSeconds(); - this.lastThrottleTime = currentTimeInSeconds; - this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); - this.fillRate = this.minFillRate; - this.maxCapacity = this.minCapacity; - } - static { - __name(this, "DefaultRateLimiter"); - } - static { - /** - * Only used in testing. - */ - this.setTimeoutFn = setTimeout; - } - getCurrentTimeInSeconds() { - return Date.now() / 1e3; - } - 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 * 1e3; - await new Promise((resolve) => _DefaultRateLimiter.setTimeoutFn(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, import_service_error_classification.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; - } +var import_querystring_parser = __nccwpck_require__(4769); +var parseUrl = /* @__PURE__ */ __name((url) => { + if (typeof url === "string") { + return parseUrl(new URL(url)); } - getPrecise(num) { - return parseFloat(num.toFixed(8)); + const { hostname, pathname, port, protocol, search } = url; + let query; + if (search) { + query = (0, import_querystring_parser.parseQueryString)(search); } -}; - -// src/constants.ts -var DEFAULT_RETRY_DELAY_BASE = 100; -var MAXIMUM_RETRY_DELAY = 20 * 1e3; -var THROTTLING_RETRY_DELAY_BASE = 500; -var INITIAL_RETRY_TOKENS = 500; -var RETRY_COST = 5; -var TIMEOUT_RETRY_COST = 10; -var NO_RETRY_INCREMENT = 1; -var INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; -var REQUEST_HEADER = "amz-sdk-request"; - -// src/defaultRetryBackoffStrategy.ts -var getDefaultRetryBackoffStrategy = /* @__PURE__ */ __name(() => { - let delayBase = DEFAULT_RETRY_DELAY_BASE; - const computeNextBackoffDelay = /* @__PURE__ */ __name((attempts) => { - return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); - }, "computeNextBackoffDelay"); - const setDelayBase = /* @__PURE__ */ __name((delay) => { - delayBase = delay; - }, "setDelayBase"); - return { - computeNextBackoffDelay, - setDelayBase - }; -}, "getDefaultRetryBackoffStrategy"); - -// src/defaultRetryToken.ts -var createDefaultRetryToken = /* @__PURE__ */ __name(({ - retryDelay, - retryCount, - retryCost -}) => { - const getRetryCount = /* @__PURE__ */ __name(() => retryCount, "getRetryCount"); - const getRetryDelay = /* @__PURE__ */ __name(() => Math.min(MAXIMUM_RETRY_DELAY, retryDelay), "getRetryDelay"); - const getRetryCost = /* @__PURE__ */ __name(() => retryCost, "getRetryCost"); return { - getRetryCount, - getRetryDelay, - getRetryCost + hostname, + port: port ? parseInt(port) : void 0, + protocol, + path: pathname, + query }; -}, "createDefaultRetryToken"); - -// src/StandardRetryStrategy.ts -var StandardRetryStrategy = class { - constructor(maxAttempts) { - this.maxAttempts = maxAttempts; - this.mode = "standard" /* STANDARD */; - this.capacity = INITIAL_RETRY_TOKENS; - this.retryBackoffStrategy = getDefaultRetryBackoffStrategy(); - this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts; - } - static { - __name(this, "StandardRetryStrategy"); - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async acquireInitialRetryToken(retryTokenScope) { - return createDefaultRetryToken({ - retryDelay: 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" ? THROTTLING_RETRY_DELAY_BASE : 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 createDefaultRetryToken({ - retryDelay, - retryCount: token.getRetryCount() + 1, - retryCost: capacityCost - }); - } - throw new Error("No retry token available"); - } - recordSuccess(token) { - this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); - } - /** - * @returns the current available retry capacity. - * - * This number decreases when retries are executed and refills when requests or retries succeed. - */ - getCapacity() { - return this.capacity; - } - async getMaxAttempts() { - try { - return await this.maxAttemptsProvider(); - } catch (error) { - console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); - return 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" ? TIMEOUT_RETRY_COST : RETRY_COST; - } - isRetryableError(errorType) { - return errorType === "THROTTLING" || errorType === "TRANSIENT"; - } -}; - -// src/AdaptiveRetryStrategy.ts -var AdaptiveRetryStrategy = class { - constructor(maxAttemptsProvider, options) { - this.maxAttemptsProvider = maxAttemptsProvider; - this.mode = "adaptive" /* ADAPTIVE */; - const { rateLimiter } = options ?? {}; - this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); - this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider); - } - static { - __name(this, "AdaptiveRetryStrategy"); - } - 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); - } -}; - -// src/ConfiguredRetryStrategy.ts -var ConfiguredRetryStrategy = class extends StandardRetryStrategy { - static { - __name(this, "ConfiguredRetryStrategy"); - } - /** - * @param maxAttempts - the maximum number of retry attempts allowed. - * e.g., if set to 3, then 4 total requests are possible. - * @param computeNextBackoffDelay - a millisecond delay for each retry or a function that takes the retry attempt - * and returns the delay. - * - * @example exponential backoff. - * ```js - * new Client({ - * retryStrategy: new ConfiguredRetryStrategy(3, (attempt) => attempt ** 2) - * }); - * ``` - * @example constant delay. - * ```js - * new Client({ - * retryStrategy: new ConfiguredRetryStrategy(3, 2000) - * }); - * ``` - */ - constructor(maxAttempts, computeNextBackoffDelay = 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; - } -}; +}, "parseUrl"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -67778,505 +53659,451 @@ var ConfiguredRetryStrategy = class extends StandardRetryStrategy { /***/ }), -/***/ 9361: -/***/ ((__unused_webpack_module, exports) => { +/***/ 305: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ByteArrayCollector = void 0; -class ByteArrayCollector { - constructor(allocByteArray) { - this.allocByteArray = allocByteArray; - this.byteLength = 0; - this.byteArrays = []; - } - push(byteArray) { - this.byteArrays.push(byteArray); - this.byteLength += byteArray.byteLength; - } - flush() { - if (this.byteArrays.length === 1) { - const bytes = this.byteArrays[0]; - this.reset(); - return bytes; - } - const aggregation = this.allocByteArray(this.byteLength); - let cursor = 0; - for (let i = 0; i < this.byteArrays.length; ++i) { - const bytes = this.byteArrays[i]; - aggregation.set(bytes, cursor); - cursor += bytes.byteLength; - } - this.reset(); - return aggregation; +exports.fromBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(1381); +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.`); } - reset() { - this.byteArrays = []; - this.byteLength = 0; + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); } -} -exports.ByteArrayCollector = ByteArrayCollector; + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; /***/ }), -/***/ 8551: -/***/ ((__unused_webpack_module, exports) => { +/***/ 5600: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +module.exports = __toCommonJS(src_exports); +__reExport(src_exports, __nccwpck_require__(305), module.exports); +__reExport(src_exports, __nccwpck_require__(4730), module.exports); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; -class ChecksumStream extends ReadableStreamRef { -} -exports.ChecksumStream = ChecksumStream; /***/ }), -/***/ 6982: +/***/ 4730: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(5600); -const stream_1 = __nccwpck_require__(2781); -class ChecksumStream extends stream_1.Duplex { - constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { - var _a, _b; - super(); - if (typeof source.pipe === "function") { - this.source = source; - } - else { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - this.expectedChecksum = expectedChecksum; - this.checksum = checksum; - this.checksumSourceLocation = checksumSourceLocation; - this.source.pipe(this); +exports.toBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(1381); +const util_utf8_1 = __nccwpck_require__(1895); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); } - _read(size) { } - _write(chunk, encoding, callback) { - try { - this.checksum.update(chunk); - this.push(chunk); - } - catch (e) { - return callback(e); - } - return callback(); + else { + input = _input; } - async _final(callback) { - try { - const digest = await this.checksum.digest(); - const received = this.base64Encoder(digest); - if (this.expectedChecksum !== received) { - return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + - ` in response header "${this.checksumSourceLocation}".`)); - } - } - catch (e) { - return callback(e); - } - this.push(null); - return callback(); + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); } -} -exports.ChecksumStream = ChecksumStream; + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; /***/ }), -/***/ 2313: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 713: +/***/ ((module) => { -"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(5600); -const stream_type_check_1 = __nccwpck_require__(2370); -const ChecksumStream_browser_1 = __nccwpck_require__(8551); -const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { - var _a, _b; - if (!(0, stream_type_check_1.isReadableStream)(source)) { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + calculateBodyLength: () => calculateBodyLength +}); +module.exports = __toCommonJS(src_exports); + +// src/calculateBodyLength.ts +var TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder() : null; +var calculateBodyLength = /* @__PURE__ */ __name((body) => { + if (typeof body === "string") { + if (TEXT_ENCODER) { + return TEXT_ENCODER.encode(body).byteLength; } - const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - if (typeof TransformStream !== "function") { - throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + let len = body.length; + for (let i = len - 1; i >= 0; i--) { + const code = body.charCodeAt(i); + if (code > 127 && code <= 2047) + len++; + else if (code > 2047 && code <= 65535) + len += 2; + if (code >= 56320 && code <= 57343) + i--; } - const transform = new TransformStream({ - start() { }, - async transform(chunk, controller) { - checksum.update(chunk); - controller.enqueue(chunk); - }, - async flush(controller) { - const digest = await checksum.digest(); - const received = encoder(digest); - if (expectedChecksum !== received) { - const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + - ` in response header "${checksumSourceLocation}".`); - controller.error(error); - } - else { - controller.terminate(); - } - }, - }); - source.pipeThrough(transform); - const readable = transform.readable; - Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); - return readable; -}; -exports.createChecksumStream = createChecksumStream; + return len; + } else if (typeof body.byteLength === "number") { + return body.byteLength; + } else if (typeof body.size === "number") { + return body.size; + } + throw new Error(`Body Length computation failed for ${body}`); +}, "calculateBodyLength"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 1927: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 8075: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + calculateBodyLength: () => calculateBodyLength +}); +module.exports = __toCommonJS(src_exports); + +// src/calculateBodyLength.ts +var import_fs = __nccwpck_require__(7147); +var calculateBodyLength = /* @__PURE__ */ __name((body) => { + if (!body) { + return 0; + } + if (typeof body === "string") { + return Buffer.byteLength(body); + } 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, import_fs.lstatSync)(body.path).size; + } else if (typeof body.fd === "number") { + return (0, import_fs.fstatSync)(body.fd).size; + } + throw new Error(`Body Length computation failed for ${body}`); +}, "calculateBodyLength"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = createChecksumStream; -const stream_type_check_1 = __nccwpck_require__(2370); -const ChecksumStream_1 = __nccwpck_require__(6982); -const createChecksumStream_browser_1 = __nccwpck_require__(2313); -function createChecksumStream(init) { - if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { - return (0, createChecksumStream_browser_1.createChecksumStream)(init); - } - return new ChecksumStream_1.ChecksumStream(init); -} /***/ }), -/***/ 3259: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 1381: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromArrayBuffer: () => fromArrayBuffer, + fromString: () => fromString +}); +module.exports = __toCommonJS(src_exports); +var import_is_array_buffer = __nccwpck_require__(780); +var import_buffer = __nccwpck_require__(4300); +var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { + if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return import_buffer.Buffer.from(input, offset, length); +}, "fromArrayBuffer"); +var fromString = /* @__PURE__ */ __name((input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); +}, "fromString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = createBufferedReadable; -const node_stream_1 = __nccwpck_require__(4492); -const ByteArrayCollector_1 = __nccwpck_require__(9361); -const createBufferedReadableStream_1 = __nccwpck_require__(2558); -const stream_type_check_1 = __nccwpck_require__(2370); -function createBufferedReadable(upstream, size, logger) { - if ((0, stream_type_check_1.isReadableStream)(upstream)) { - return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); - } - const downstream = new node_stream_1.Readable({ read() { } }); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = [ - "", - new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), - new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), - ]; - let mode = -1; - upstream.on("data", (chunk) => { - const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); - if (mode !== chunkMode) { - if (mode >= 0) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - downstream.push(chunk); - return; - } - const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); - bytesSeen += chunkSize; - const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - downstream.push(chunk); - } - else { - const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - } - }); - upstream.on("end", () => { - if (mode !== -1) { - const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); - if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { - downstream.push(remainder); - } - } - downstream.push(null); - }); - return downstream; -} /***/ }), -/***/ 2558: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 3375: +/***/ ((module) => { -"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = void 0; -exports.createBufferedReadableStream = createBufferedReadableStream; -exports.merge = merge; -exports.flush = flush; -exports.sizeOf = sizeOf; -exports.modeOf = modeOf; -const ByteArrayCollector_1 = __nccwpck_require__(9361); -function createBufferedReadableStream(upstream, size, logger) { - const reader = upstream.getReader(); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; - let mode = -1; - const pull = async (controller) => { - const { value, done } = await reader.read(); - const chunk = value; - if (done) { - if (mode !== -1) { - const remainder = flush(buffers, mode); - if (sizeOf(remainder) > 0) { - controller.enqueue(remainder); - } - } - controller.close(); - } - else { - const chunkMode = modeOf(chunk, false); - if (mode !== chunkMode) { - if (mode >= 0) { - controller.enqueue(flush(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - controller.enqueue(chunk); - return; - } - const chunkSize = sizeOf(chunk); - bytesSeen += chunkSize; - const bufferSize = sizeOf(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - controller.enqueue(chunk); - } - else { - const newSize = merge(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - controller.enqueue(flush(buffers, mode)); - } - else { - await pull(controller); - } - } - } - }; - return new ReadableStream({ - pull, - }); -} -exports.createBufferedReadable = createBufferedReadableStream; -function merge(buffers, mode, chunk) { - switch (mode) { - case 0: - buffers[0] += chunk; - return sizeOf(buffers[0]); - case 1: - case 2: - buffers[mode].push(chunk); - return sizeOf(buffers[mode]); - } -} -function flush(buffers, mode) { - switch (mode) { - case 0: - const s = buffers[0]; - buffers[0] = ""; - return s; - case 1: - case 2: - return buffers[mode].flush(); - } - throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); -} -function sizeOf(chunk) { - var _a, _b; - return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; -} -function modeOf(chunk, allowBuffer = true) { - if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { - return 2; - } - if (chunk instanceof Uint8Array) { - return 1; - } - if (typeof chunk === "string") { - return 0; - } - return -1; -} +// src/index.ts +var src_exports = {}; +__export(src_exports, { + SelectorType: () => SelectorType, + booleanSelector: () => booleanSelector, + numberSelector: () => numberSelector +}); +module.exports = __toCommonJS(src_exports); +// src/booleanSelector.ts +var booleanSelector = /* @__PURE__ */ __name((obj, key, type) => { + if (!(key in obj)) + return void 0; + 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]}.`); +}, "booleanSelector"); -/***/ }), +// src/numberSelector.ts +var numberSelector = /* @__PURE__ */ __name((obj, key, type) => { + if (!(key in obj)) + return void 0; + const numberValue = parseInt(obj[key], 10); + if (Number.isNaN(numberValue)) { + throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); + } + return numberValue; +}, "numberSelector"); -/***/ 3636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/types.ts +var SelectorType = /* @__PURE__ */ ((SelectorType2) => { + SelectorType2["ENV"] = "env"; + SelectorType2["CONFIG"] = "shared config entry"; + return SelectorType2; +})(SelectorType || {}); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getAwsChunkedEncodingStream = void 0; -const stream_1 = __nccwpck_require__(2781); -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; /***/ }), -/***/ 6711: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; +/***/ 2429: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = headStream; -async function headStream(stream, bytes) { - var _a; - let byteLengthCounter = 0; - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; - } - if (byteLengthCounter >= bytes) { - break; - } - isDone = done; - } - reader.releaseLock(); - const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); - let offset = 0; - for (const chunk of chunks) { - if (chunk.byteLength > collected.byteLength - offset) { - collected.set(chunk.subarray(0, collected.byteLength - offset), offset); - break; - } - else { - collected.set(chunk, offset); - } - offset += chunk.length; - } - return collected; -} +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + resolveDefaultsModeConfig: () => resolveDefaultsModeConfig +}); +module.exports = __toCommonJS(src_exports); -/***/ }), +// src/resolveDefaultsModeConfig.ts +var import_config_resolver = __nccwpck_require__(3098); +var import_node_config_provider = __nccwpck_require__(3461); +var import_property_provider = __nccwpck_require__(9721); -/***/ 6708: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/constants.ts +var AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; +var AWS_REGION_ENV = "AWS_REGION"; +var AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; +var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; +var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; +var IMDS_REGION_PATH = "/latest/meta-data/placement/region"; -"use strict"; +// src/defaultsModeConfig.ts +var AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; +var AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; +var NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => { + return env[AWS_DEFAULTS_MODE_ENV]; + }, + configFileSelector: (profile) => { + return profile[AWS_DEFAULTS_MODE_CONFIG]; + }, + default: "legacy" +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = void 0; -const stream_1 = __nccwpck_require__(2781); -const headStream_browser_1 = __nccwpck_require__(6711); -const stream_type_check_1 = __nccwpck_require__(2370); -const headStream = (stream, bytes) => { - if ((0, stream_type_check_1.isReadableStream)(stream)) { - return (0, headStream_browser_1.headStream)(stream, bytes); +// src/resolveDefaultsModeConfig.ts +var resolveDefaultsModeConfig = /* @__PURE__ */ __name(({ + region = (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_REGION_CONFIG_OPTIONS), + defaultsMode = (0, import_node_config_provider.loadConfig)(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) +} = {}) => (0, import_property_provider.memoize)(async () => { + const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; + switch (mode?.toLowerCase()) { + case "auto": + return resolveNodeDefaultsModeAuto(region); + case "in-region": + case "cross-region": + case "mobile": + case "standard": + case "legacy": + return Promise.resolve(mode?.toLocaleLowerCase()); + case void 0: + return Promise.resolve("legacy"); + default: + throw new Error( + `Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}` + ); + } +}), "resolveDefaultsModeConfig"); +var resolveNodeDefaultsModeAuto = /* @__PURE__ */ __name(async (clientRegion) => { + if (clientRegion) { + const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; + const inferredRegion = await inferPhysicalRegion(); + if (!inferredRegion) { + return "standard"; } - return new Promise((resolve, reject) => { - const collector = new Collector(); - collector.limit = bytes; - 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.buffers)); - resolve(bytes); - }); - }); -}; -exports.headStream = headStream; -class Collector extends stream_1.Writable { - constructor() { - super(...arguments); - this.buffers = []; - this.limit = Infinity; - this.bytesBuffered = 0; + if (resolvedRegion === inferredRegion) { + return "in-region"; + } else { + return "cross-region"; } - _write(chunk, encoding, callback) { - var _a; - this.buffers.push(chunk); - this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; - if (this.bytesBuffered >= this.limit) { - const excess = this.bytesBuffered - this.limit; - const tailBuffer = this.buffers[this.buffers.length - 1]; - this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); - this.emit("finish"); - } - callback(); + } + return "standard"; +}, "resolveNodeDefaultsModeAuto"); +var inferPhysicalRegion = /* @__PURE__ */ __name(async () => { + if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { + return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; + } + if (!process.env[ENV_IMDS_DISABLED]) { + try { + const { getInstanceMetadataEndpoint, httpRequest } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); + const endpoint = await getInstanceMetadataEndpoint(); + return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString(); + } catch (e) { } -} + } +}, "inferPhysicalRegion"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 6607: +/***/ 5473: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -68296,396 +54123,522 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { - Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter + EndpointCache: () => EndpointCache, + EndpointError: () => EndpointError, + customEndpointFunctions: () => customEndpointFunctions, + isIpAddress: () => isIpAddress, + isValidHostLabel: () => isValidHostLabel, + resolveEndpoint: () => resolveEndpoint }); module.exports = __toCommonJS(src_exports); -// src/blob/transforms.ts -var import_util_base64 = __nccwpck_require__(5600); -var import_util_utf8 = __nccwpck_require__(1895); -function transformToString(payload, encoding = "utf-8") { - if (encoding === "base64") { - return (0, import_util_base64.toBase64)(payload); - } - return (0, import_util_utf8.toUtf8)(payload); -} -__name(transformToString, "transformToString"); -function transformFromString(str, encoding) { - if (encoding === "base64") { - return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); +// src/cache/EndpointCache.ts +var EndpointCache = class { + /** + * @param [size] - desired average maximum capacity. A buffer of 10 additional keys will be allowed + * before keys are dropped. + * @param [params] - list of params to consider as part of the cache key. + * + * If the params list is not populated, no caching will happen. + * This may be out of order depending on how the object is created and arrives to this class. + */ + constructor({ size, params }) { + this.data = /* @__PURE__ */ new Map(); + this.parameters = []; + this.capacity = size ?? 50; + if (params) { + this.parameters = params; + } } - return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); -} -__name(transformFromString, "transformFromString"); - -// src/blob/Uint8ArrayBlobAdapter.ts -var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { static { - __name(this, "Uint8ArrayBlobAdapter"); + __name(this, "EndpointCache"); } /** - * @param source - such as a string or Stream. - * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. + * @param endpointParams - query for endpoint. + * @param resolver - provider of the value if not present. + * @returns endpoint corresponding to the query. */ - static fromString(source, encoding = "utf-8") { - switch (typeof source) { - case "string": - return transformFromString(source, encoding); - default: - throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + get(endpointParams, resolver) { + const key = this.hash(endpointParams); + if (key === false) { + return resolver(); + } + if (!this.data.has(key)) { + if (this.data.size > this.capacity + 10) { + const keys = this.data.keys(); + let i = 0; + while (true) { + const { value, done } = keys.next(); + this.data.delete(value); + if (done || ++i > 10) { + break; + } + } + } + this.data.set(key, resolver()); } + return this.data.get(key); } - /** - * @param source - Uint8Array to be mutated. - * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. - */ - static mutate(source) { - Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); - return source; + size() { + return this.data.size; } /** - * @param encoding - default 'utf-8'. - * @returns the blob as string. + * @returns cache key or false if not cachable. */ - transformToString(encoding = "utf-8") { - return transformToString(this, encoding); - } -}; - -// src/index.ts -__reExport(src_exports, __nccwpck_require__(6982), module.exports); -__reExport(src_exports, __nccwpck_require__(1927), module.exports); -__reExport(src_exports, __nccwpck_require__(3259), module.exports); -__reExport(src_exports, __nccwpck_require__(3636), module.exports); -__reExport(src_exports, __nccwpck_require__(6708), module.exports); -__reExport(src_exports, __nccwpck_require__(4515), module.exports); -__reExport(src_exports, __nccwpck_require__(8321), module.exports); -__reExport(src_exports, __nccwpck_require__(2370), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 2942: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const fetch_http_handler_1 = __nccwpck_require__(2687); -const util_base64_1 = __nccwpck_require__(5600); -const util_hex_encoding_1 = __nccwpck_require__(5364); -const util_utf8_1 = __nccwpck_require__(1895); -const stream_type_check_1 = __nccwpck_require__(2370); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { - 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 Blob or ReadableStream, got ${name}`); + hash(endpointParams) { + let buffer = ""; + const { parameters } = this; + if (parameters.length === 0) { + return false; } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, fetch_http_handler_1.streamCollector)(stream); - }; - const blobToWebStream = (blob) => { - if (typeof blob.stream !== "function") { - throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + - "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); - } - return blob.stream(); - }; - return Object.assign(stream, { - transformToByteArray: transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === "base64") { - return (0, util_base64_1.toBase64)(buf); - } - else if (encoding === "hex") { - return (0, util_hex_encoding_1.toHex)(buf); - } - else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { - return (0, util_utf8_1.toUtf8)(buf); - } - else if (typeof TextDecoder === "function") { - return new TextDecoder(encoding).decode(buf); - } - else { - throw new Error("TextDecoder is not available, please make sure polyfill is provided."); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - if (isBlobInstance(stream)) { - return blobToWebStream(stream); - } - else if ((0, stream_type_check_1.isReadableStream)(stream)) { - return stream; - } - else { - throw new Error(`Cannot transform payload to web stream, got ${stream}`); - } - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; -const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; - - -/***/ }), - -/***/ 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__(258); -const util_buffer_from_1 = __nccwpck_require__(1381); -const stream_1 = __nccwpck_require__(2781); -const sdk_stream_mixin_browser_1 = __nccwpck_require__(2942); -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)) { - try { - return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); - } - catch (e) { - 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}`); - } + for (const param of parameters) { + const val = String(endpointParams[param] ?? ""); + if (val.includes("|;")) { + return false; + } + buffer += val + "|;"; } - 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 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 ensure a polyfill is available."); - } - transformed = true; - return stream_1.Readable.toWeb(stream); - }, - }); + return buffer; + } }; -exports.sdkStreamMixin = sdkStreamMixin; +// src/lib/isIpAddress.ts +var 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}$` +); +var isIpAddress = /* @__PURE__ */ __name((value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"), "isIpAddress"); -/***/ }), +// src/lib/isValidHostLabel.ts +var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); +var isValidHostLabel = /* @__PURE__ */ __name((value, allowSubDomains = false) => { + if (!allowSubDomains) { + return VALID_HOST_LABEL_REGEX.test(value); + } + const labels = value.split("."); + for (const label of labels) { + if (!isValidHostLabel(label)) { + return false; + } + } + return true; +}, "isValidHostLabel"); -/***/ 4693: -/***/ ((__unused_webpack_module, exports) => { +// src/utils/customEndpointFunctions.ts +var customEndpointFunctions = {}; -"use strict"; +// src/debug/debugId.ts +var debugId = "endpoints"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -async function splitStream(stream) { - if (typeof stream.stream === "function") { - stream = stream.stream(); - } - const readableStream = stream; - return readableStream.tee(); +// src/debug/toDebugString.ts +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); } +__name(toDebugString, "toDebugString"); +// src/types/EndpointError.ts +var EndpointError = class extends Error { + static { + __name(this, "EndpointError"); + } + constructor(message) { + super(message); + this.name = "EndpointError"; + } +}; -/***/ }), - -/***/ 8321: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +// src/lib/booleanEquals.ts +var booleanEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "booleanEquals"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = splitStream; -const stream_1 = __nccwpck_require__(2781); -const splitStream_browser_1 = __nccwpck_require__(4693); -const stream_type_check_1 = __nccwpck_require__(2370); -async function splitStream(stream) { - if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { - return (0, splitStream_browser_1.splitStream)(stream); +// src/lib/getAttrPathList.ts +var getAttrPathList = /* @__PURE__ */ __name((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 EndpointError(`Path: '${path}' does not end with ']'`); + } + const arrayIndex = part.slice(squareBracketIndex + 1, -1); + if (Number.isNaN(parseInt(arrayIndex))) { + throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); + } + if (squareBracketIndex !== 0) { + pathList.push(part.slice(0, squareBracketIndex)); + } + pathList.push(arrayIndex); + } else { + pathList.push(part); } - const stream1 = new stream_1.PassThrough(); - const stream2 = new stream_1.PassThrough(); - stream.pipe(stream1); - stream.pipe(stream2); - return [stream1, stream2]; -} - + } + return pathList; +}, "getAttrPathList"); -/***/ }), +// src/lib/getAttr.ts +var getAttr = /* @__PURE__ */ __name((value, path) => getAttrPathList(path).reduce((acc, index) => { + if (typeof acc !== "object") { + throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); + } else if (Array.isArray(acc)) { + return acc[parseInt(index)]; + } + return acc[index]; +}, value), "getAttr"); -/***/ 2370: -/***/ ((__unused_webpack_module, exports) => { +// src/lib/isSet.ts +var isSet = /* @__PURE__ */ __name((value) => value != null, "isSet"); -"use strict"; +// src/lib/not.ts +var not = /* @__PURE__ */ __name((value) => !value, "not"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isBlob = exports.isReadableStream = void 0; -const isReadableStream = (stream) => { - var _a; - return typeof ReadableStream === "function" && - (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); -}; -exports.isReadableStream = isReadableStream; -const isBlob = (blob) => { - var _a; - return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); +// src/lib/parseURL.ts +var import_types3 = __nccwpck_require__(5756); +var DEFAULT_PORTS = { + [import_types3.EndpointURLScheme.HTTP]: 80, + [import_types3.EndpointURLScheme.HTTPS]: 443 }; -exports.isBlob = isBlob; +var parseURL = /* @__PURE__ */ __name((value) => { + const whatwgURL = (() => { + try { + if (value instanceof URL) { + return value; + } + if (typeof value === "object" && "hostname" in value) { + const { hostname: hostname2, port, protocol: protocol2 = "", path = "", query = {} } = value; + const url = new URL(`${protocol2}//${hostname2}${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(import_types3.EndpointURLScheme).includes(scheme)) { + return null; + } + const isIp = 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 + }; +}, "parseURL"); +// src/lib/stringEquals.ts +var stringEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "stringEquals"); -/***/ }), +// src/lib/substring.ts +var substring = /* @__PURE__ */ __name((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); +}, "substring"); -/***/ 4197: -/***/ ((module) => { +// src/lib/uriEncode.ts +var uriEncode = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`), "uriEncode"); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); +// src/utils/endpointFunctions.ts +var endpointFunctions = { + booleanEquals, + getAttr, + isSet, + isValidHostLabel, + not, + parseURL, + stringEquals, + substring, + uriEncode }; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + +// src/utils/evaluateTemplate.ts +var evaluateTemplate = /* @__PURE__ */ __name((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(getAttr(templateContext[refName], attrName)); + } else { + evaluatedTemplateArr.push(templateContext[parameterName]); + } + currentIndex = closingBraceIndex + 1; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + return evaluatedTemplateArr.join(""); +}, "evaluateTemplate"); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - escapeUri: () => escapeUri, - escapeUriPath: () => escapeUriPath -}); -module.exports = __toCommonJS(src_exports); +// src/utils/getReferenceValue.ts +var getReferenceValue = /* @__PURE__ */ __name(({ ref }, options) => { + const referenceRecord = { + ...options.endpointParams, + ...options.referenceRecord + }; + return referenceRecord[ref]; +}, "getReferenceValue"); -// src/escape-uri.ts -var escapeUri = /* @__PURE__ */ __name((uri) => ( - // AWS percent-encodes some extra non-standard characters in a URI - encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) -), "escapeUri"); -var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); +// src/utils/evaluateExpression.ts +var evaluateExpression = /* @__PURE__ */ __name((obj, keyName, options) => { + if (typeof obj === "string") { + return evaluateTemplate(obj, options); + } else if (obj["fn"]) { + return callFunction(obj, options); + } else if (obj["ref"]) { + return getReferenceValue(obj, options); + } + throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); +}, "evaluateExpression"); -// src/escape-uri-path.ts -var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); -// Annotate the CommonJS export names for ESM import in node: +// src/utils/callFunction.ts +var callFunction = /* @__PURE__ */ __name(({ fn, argv }, options) => { + const evaluatedArgs = argv.map( + (arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options) + ); + const fnSegments = fn.split("."); + if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) { + return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); + } + return endpointFunctions[fn](...evaluatedArgs); +}, "callFunction"); -0 && (0); +// src/utils/evaluateCondition.ts +var evaluateCondition = /* @__PURE__ */ __name(({ assign, ...fnArgs }, options) => { + if (assign && assign in options.referenceRecord) { + throw new EndpointError(`'${assign}' is already defined in Reference Record.`); + } + const value = callFunction(fnArgs, options); + options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); + return { + result: value === "" ? true : !!value, + ...assign != null && { toAssign: { name: assign, value } } + }; +}, "evaluateCondition"); +// src/utils/evaluateConditions.ts +var evaluateConditions = /* @__PURE__ */ __name((conditions = [], options) => { + const conditionsReferenceRecord = {}; + for (const condition of conditions) { + const { result, toAssign } = evaluateCondition(condition, { + ...options, + referenceRecord: { + ...options.referenceRecord, + ...conditionsReferenceRecord + } + }); + if (!result) { + return { result }; + } + if (toAssign) { + conditionsReferenceRecord[toAssign.name] = toAssign.value; + options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); + } + } + return { result: true, referenceRecord: conditionsReferenceRecord }; +}, "evaluateConditions"); +// src/utils/getEndpointHeaders.ts +var getEndpointHeaders = /* @__PURE__ */ __name((headers, options) => Object.entries(headers).reduce( + (acc, [headerKey, headerVal]) => ({ + ...acc, + [headerKey]: headerVal.map((headerValEntry) => { + const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); + if (typeof processedExpr !== "string") { + throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); + } + return processedExpr; + }) + }), + {} +), "getEndpointHeaders"); -/***/ }), +// src/utils/getEndpointProperty.ts +var getEndpointProperty = /* @__PURE__ */ __name((property, options) => { + if (Array.isArray(property)) { + return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); + } + switch (typeof property) { + case "string": + return evaluateTemplate(property, options); + case "object": + if (property === null) { + throw new EndpointError(`Unexpected endpoint property: ${property}`); + } + return getEndpointProperties(property, options); + case "boolean": + return property; + default: + throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); + } +}, "getEndpointProperty"); -/***/ 1895: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// src/utils/getEndpointProperties.ts +var getEndpointProperties = /* @__PURE__ */ __name((properties, options) => Object.entries(properties).reduce( + (acc, [propertyKey, propertyVal]) => ({ + ...acc, + [propertyKey]: getEndpointProperty(propertyVal, options) + }), + {} +), "getEndpointProperties"); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +// src/utils/getEndpointUrl.ts +var getEndpointUrl = /* @__PURE__ */ __name((endpointUrl, options) => { + const expression = 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; + } } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 -}); -module.exports = __toCommonJS(src_exports); + throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); +}, "getEndpointUrl"); -// src/fromUtf8.ts -var import_util_buffer_from = __nccwpck_require__(1381); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); +// src/utils/evaluateEndpointRule.ts +var evaluateEndpointRule = /* @__PURE__ */ __name((endpointRule, options) => { + const { conditions, endpoint } = endpointRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const endpointRuleOptions = { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord } + }; + const { url, properties, headers } = endpoint; + options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); + return { + ...headers != void 0 && { + headers: getEndpointHeaders(headers, endpointRuleOptions) + }, + ...properties != void 0 && { + properties: getEndpointProperties(properties, endpointRuleOptions) + }, + url: getEndpointUrl(url, endpointRuleOptions) + }; +}, "evaluateEndpointRule"); -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); +// src/utils/evaluateErrorRule.ts +var evaluateErrorRule = /* @__PURE__ */ __name((errorRule, options) => { + const { conditions, error } = errorRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + throw new EndpointError( + evaluateExpression(error, "Error", { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord } + }) + ); +}, "evaluateErrorRule"); + +// src/utils/evaluateTreeRule.ts +var evaluateTreeRule = /* @__PURE__ */ __name((treeRule, options) => { + const { conditions, rules } = treeRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; } - return new Uint8Array(data); -}, "toUint8Array"); + return evaluateRules(rules, { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord } + }); +}, "evaluateTreeRule"); -// src/toUtf8.ts +// src/utils/evaluateRules.ts +var evaluateRules = /* @__PURE__ */ __name((rules, options) => { + for (const rule of rules) { + if (rule.type === "endpoint") { + const endpointOrUndefined = evaluateEndpointRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } else if (rule.type === "error") { + evaluateErrorRule(rule, options); + } else if (rule.type === "tree") { + const endpointOrUndefined = evaluateTreeRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } else { + throw new EndpointError(`Unknown endpoint rule: ${rule}`); + } + } + throw new EndpointError(`Rules evaluation failed`); +}, "evaluateRules"); -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; +// src/resolveEndpoint.ts +var resolveEndpoint = /* @__PURE__ */ __name((ruleSetObject, options) => { + const { endpointParams, logger } = options; + const { parameters, rules } = ruleSetObject; + options.logger?.debug?.(`${debugId} Initial EndpointParams: ${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] = endpointParams[paramKey] ?? paramDefaultValue; + } } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + const requiredParams = Object.entries(parameters).filter(([, v]) => v.required).map(([k]) => k); + for (const requiredParam of requiredParams) { + if (endpointParams[requiredParam] == null) { + throw new EndpointError(`Missing required parameter: '${requiredParam}'`); + } } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); + const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} }); + options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); + return endpoint; +}, "resolveEndpoint"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -68694,7 +54647,7 @@ var toUtf8 = /* @__PURE__ */ __name((input) => { /***/ }), -/***/ 8011: +/***/ 5364: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -68719,179 +54672,44 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - WaiterState: () => WaiterState, - checkExceptions: () => checkExceptions, - createWaiter: () => createWaiter, - waiterServiceDefaults: () => waiterServiceDefaults + fromHex: () => fromHex, + toHex: () => toHex }); module.exports = __toCommonJS(src_exports); - -// src/utils/sleep.ts -var sleep = /* @__PURE__ */ __name((seconds) => { - return new Promise((resolve) => setTimeout(resolve, seconds * 1e3)); -}, "sleep"); - -// src/waiter.ts -var waiterServiceDefaults = { - minDelay: 2, - maxDelay: 120 -}; -var WaiterState = /* @__PURE__ */ ((WaiterState2) => { - WaiterState2["ABORTED"] = "ABORTED"; - WaiterState2["FAILURE"] = "FAILURE"; - WaiterState2["SUCCESS"] = "SUCCESS"; - WaiterState2["RETRY"] = "RETRY"; - WaiterState2["TIMEOUT"] = "TIMEOUT"; - return WaiterState2; -})(WaiterState || {}); -var checkExceptions = /* @__PURE__ */ __name((result) => { - if (result.state === "ABORTED" /* ABORTED */) { - const abortError = new Error( - `${JSON.stringify({ - ...result, - reason: "Request was aborted" - })}` - ); - abortError.name = "AbortError"; - throw abortError; - } else if (result.state === "TIMEOUT" /* TIMEOUT */) { - const timeoutError = new Error( - `${JSON.stringify({ - ...result, - reason: "Waiter has timed out" - })}` - ); - timeoutError.name = "TimeoutError"; - throw timeoutError; - } else if (result.state !== "SUCCESS" /* SUCCESS */) { - throw new Error(`${JSON.stringify(result)}`); - } - return result; -}, "checkExceptions"); - -// src/poller.ts -var exponentialBackoffWithJitter = /* @__PURE__ */ __name((minDelay, maxDelay, attemptCeiling, attempt) => { - if (attempt > attemptCeiling) - return maxDelay; - const delay = minDelay * 2 ** (attempt - 1); - return randomInRange(minDelay, delay); -}, "exponentialBackoffWithJitter"); -var randomInRange = /* @__PURE__ */ __name((min, max) => min + Math.random() * (max - min), "randomInRange"); -var runPolling = /* @__PURE__ */ __name(async ({ minDelay, maxDelay, maxWaitTime, abortController, client, abortSignal }, input, acceptorChecks) => { - const observedResponses = {}; - const { state, reason } = await acceptorChecks(client, input); - if (reason) { - const message = createMessageFromResponse(reason); - observedResponses[message] |= 0; - observedResponses[message] += 1; - } - if (state !== "RETRY" /* RETRY */) { - return { state, reason, observedResponses }; - } - let currentAttempt = 1; - const waitUntil = Date.now() + maxWaitTime * 1e3; - const attemptCeiling = Math.log(maxDelay / minDelay) / Math.log(2) + 1; - while (true) { - if (abortController?.signal?.aborted || abortSignal?.aborted) { - const message = "AbortController signal aborted."; - observedResponses[message] |= 0; - observedResponses[message] += 1; - return { state: "ABORTED" /* ABORTED */, observedResponses }; - } - const delay = exponentialBackoffWithJitter(minDelay, maxDelay, attemptCeiling, currentAttempt); - if (Date.now() + delay * 1e3 > waitUntil) { - return { state: "TIMEOUT" /* TIMEOUT */, observedResponses }; - } - await sleep(delay); - const { state: state2, reason: reason2 } = await acceptorChecks(client, input); - if (reason2) { - const message = createMessageFromResponse(reason2); - observedResponses[message] |= 0; - observedResponses[message] += 1; - } - if (state2 !== "RETRY" /* RETRY */) { - return { state: state2, reason: reason2, observedResponses }; - } - currentAttempt += 1; - } -}, "runPolling"); -var createMessageFromResponse = /* @__PURE__ */ __name((reason) => { - if (reason?.$responseBodyText) { - return `Deserialization error for body: ${reason.$responseBodyText}`; - } - if (reason?.$metadata?.httpStatusCode) { - if (reason.$response || reason.message) { - return `${reason.$response.statusCode ?? reason.$metadata.httpStatusCode ?? "Unknown"}: ${reason.message}`; - } - return `${reason.$metadata.httpStatusCode}: OK`; +var SHORT_TO_HEX = {}; +var HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; } - return String(reason?.message ?? JSON.stringify(reason) ?? "Unknown"); -}, "createMessageFromResponse"); - -// src/utils/validate.ts -var validateWaiterOptions = /* @__PURE__ */ __name((options) => { - if (options.maxWaitTime <= 0) { - throw new Error(`WaiterConfiguration.maxWaitTime must be greater than 0`); - } else if (options.minDelay <= 0) { - throw new Error(`WaiterConfiguration.minDelay must be greater than 0`); - } else if (options.maxDelay <= 0) { - throw new Error(`WaiterConfiguration.maxDelay must be greater than 0`); - } else if (options.maxWaitTime <= options.minDelay) { - throw new Error( - `WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter` - ); - } else if (options.maxDelay < options.minDelay) { - throw new Error( - `WaiterConfiguration.maxDelay [${options.maxDelay}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter` - ); + 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"); } -}, "validateWaiterOptions"); - -// src/createWaiter.ts -var abortTimeout = /* @__PURE__ */ __name((abortSignal) => { - let onAbort; - const promise = new Promise((resolve) => { - onAbort = /* @__PURE__ */ __name(() => resolve({ state: "ABORTED" /* ABORTED */ }), "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - abortSignal.addEventListener("abort", onAbort); + 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 { - abortSignal.onabort = onAbort; + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); } - }); - return { - clearListener() { - if (typeof abortSignal.removeEventListener === "function") { - abortSignal.removeEventListener("abort", onAbort); - } - }, - aborted: promise - }; -}, "abortTimeout"); -var createWaiter = /* @__PURE__ */ __name(async (options, input, acceptorChecks) => { - const params = { - ...waiterServiceDefaults, - ...options - }; - validateWaiterOptions(params); - const exitConditions = [runPolling(params, input, acceptorChecks)]; - const finalize = []; - if (options.abortSignal) { - const { aborted, clearListener } = abortTimeout(options.abortSignal); - finalize.push(clearListener); - exitConditions.push(aborted); } - if (options.abortController?.signal) { - const { aborted, clearListener } = abortTimeout(options.abortController.signal); - finalize.push(clearListener); - exitConditions.push(aborted); + return out; +} +__name(fromHex, "fromHex"); +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; } - return Promise.race(exitConditions).then((result) => { - for (const fn of finalize) { - fn(); - } - return result; - }); -}, "createWaiter"); + return out; +} +__name(toHex, "toHex"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -68900,2070 +54718,2474 @@ var createWaiter = /* @__PURE__ */ __name(async (options, input, acceptorChecks) /***/ }), -/***/ 6761: +/***/ 2390: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const Utils = __nccwpck_require__(5182); -const pth = __nccwpck_require__(1017); -const ZipEntry = __nccwpck_require__(4057); -const ZipFile = __nccwpck_require__(7744); - -const get_Bool = (...val) => Utils.findLast(val, (c) => typeof c === "boolean"); -const get_Str = (...val) => Utils.findLast(val, (c) => typeof c === "string"); -const get_Fun = (...val) => Utils.findLast(val, (c) => typeof c === "function"); - -const defaultOptions = { - // option "noSort" : if true it disables files sorting - noSort: false, - // read entries during load (initial loading may be slower) - readEntries: false, - // default method is none - method: Utils.Constants.NONE, - // file system - fs: null -}; - -module.exports = function (/**String*/ input, /** object */ options) { - let inBuffer = null; - - // create object based default options, allowing them to be overwritten - const opts = Object.assign(Object.create(null), defaultOptions); - - // test input variable - if (input && "object" === typeof input) { - // if value is not buffer we accept it to be object with options - if (!(input instanceof Uint8Array)) { - Object.assign(opts, input); - input = opts.input ? opts.input : undefined; - if (opts.input) delete opts.input; - } - - // if input is buffer - if (Buffer.isBuffer(input)) { - inBuffer = input; - opts.method = Utils.Constants.BUFFER; - input = undefined; - } - } - - // assign options - Object.assign(opts, options); - - // instanciate utils filesystem - const filetools = new Utils(opts); - - if (typeof opts.decoder !== "object" || typeof opts.decoder.encode !== "function" || typeof opts.decoder.decode !== "function") { - opts.decoder = Utils.decoder; - } - - // if input is file name we retrieve its content - if (input && "string" === typeof input) { - // load zip file - if (filetools.fs.existsSync(input)) { - opts.method = Utils.Constants.FILE; - opts.filename = input; - inBuffer = filetools.fs.readFileSync(input); - } else { - throw Utils.Errors.INVALID_FILENAME(); - } - } - - // create variable - const _zip = new ZipFile(inBuffer, opts); - - const { canonical, sanitize, zipnamefix } = Utils; - - function getEntry(/**Object*/ entry) { - if (entry && _zip) { - var item; - // If entry was given as a file name - if (typeof entry === "string") item = _zip.getEntry(pth.posix.normalize(entry)); - // if entry was given as a ZipEntry object - if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") item = _zip.getEntry(entry.entryName); - - if (item) { - return item; - } - } - return null; - } - - function fixPath(zipPath) { - const { join, normalize, sep } = pth.posix; - // convert windows file separators and normalize - return join(".", normalize(sep + zipPath.split("\\").join(sep) + sep)); - } - - function filenameFilter(filterfn) { - if (filterfn instanceof RegExp) { - // if filter is RegExp wrap it - return (function (rx) { - return function (filename) { - return rx.test(filename); - }; - })(filterfn); - } else if ("function" !== typeof filterfn) { - // if filter is not function we will replace it - return () => true; - } - return filterfn; - } - - // keep last character on folders - const relativePath = (local, entry) => { - let lastChar = entry.slice(-1); - lastChar = lastChar === filetools.sep ? filetools.sep : ""; - return pth.relative(local, entry) + lastChar; - }; - - return { - /** - * Extracts the given entry from the archive and returns the content as a Buffer object - * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry - * @param {Buffer|string} [pass] - password - * @return Buffer or Null in case of error - */ - readFile: function (entry, pass) { - var item = getEntry(entry); - return (item && item.getData(pass)) || null; - }, - - /** - * Returns how many child elements has on entry (directories) on files it is always 0 - * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry - * @returns {integer} - */ - childCount: function (entry) { - const item = getEntry(entry); - if (item) { - return _zip.getChildCount(item); - } - }, - - /** - * Asynchronous readFile - * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry - * @param {callback} callback - * - * @return Buffer or Null in case of error - */ - readFileAsync: function (entry, callback) { - var item = getEntry(entry); - if (item) { - item.getDataAsync(callback); - } else { - callback(null, "getEntry failed for:" + entry); - } - }, - - /** - * Extracts the given entry from the archive and returns the content as plain text in the given encoding - * @param {ZipEntry|string} entry - ZipEntry object or String with the full path of the entry - * @param {string} encoding - Optional. If no encoding is specified utf8 is used - * - * @return String - */ - readAsText: function (entry, encoding) { - var item = getEntry(entry); - if (item) { - var data = item.getData(); - if (data && data.length) { - return data.toString(encoding || "utf8"); - } - } - return ""; - }, - - /** - * Asynchronous readAsText - * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry - * @param {callback} callback - * @param {string} [encoding] - Optional. If no encoding is specified utf8 is used - * - * @return String - */ - readAsTextAsync: function (entry, callback, encoding) { - var item = getEntry(entry); - if (item) { - item.getDataAsync(function (data, err) { - if (err) { - callback(data, err); - return; - } - - if (data && data.length) { - callback(data.toString(encoding || "utf8")); - } else { - callback(""); - } - }); - } else { - callback(""); - } - }, - - /** - * Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory - * - * @param {ZipEntry|string} entry - * @returns {void} - */ - deleteFile: function (entry, withsubfolders = true) { - // @TODO: test deleteFile - var item = getEntry(entry); - if (item) { - _zip.deleteFile(item.entryName, withsubfolders); - } - }, - - /** - * Remove the entry from the file or directory without affecting any nested entries - * - * @param {ZipEntry|string} entry - * @returns {void} - */ - deleteEntry: function (entry) { - // @TODO: test deleteEntry - var item = getEntry(entry); - if (item) { - _zip.deleteEntry(item.entryName); - } - }, - - /** - * Adds a comment to the zip. The zip must be rewritten after adding the comment. - * - * @param {string} comment - */ - addZipComment: function (comment) { - // @TODO: test addZipComment - _zip.comment = comment; - }, - - /** - * Returns the zip comment - * - * @return String - */ - getZipComment: function () { - return _zip.comment || ""; - }, - - /** - * Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment - * The comment cannot exceed 65535 characters in length - * - * @param {ZipEntry} entry - * @param {string} comment - */ - addZipEntryComment: function (entry, comment) { - var item = getEntry(entry); - if (item) { - item.comment = comment; - } - }, - - /** - * Returns the comment of the specified entry - * - * @param {ZipEntry} entry - * @return String - */ - getZipEntryComment: function (entry) { - var item = getEntry(entry); - if (item) { - return item.comment || ""; - } - return ""; - }, - - /** - * Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content - * - * @param {ZipEntry} entry - * @param {Buffer} content - */ - updateFile: function (entry, content) { - var item = getEntry(entry); - if (item) { - item.setData(content); - } - }, - - /** - * Adds a file from the disk to the archive - * - * @param {string} localPath File to add to zip - * @param {string} [zipPath] Optional path inside the zip - * @param {string} [zipName] Optional name for the file - * @param {string} [comment] Optional file comment - */ - addLocalFile: function (localPath, zipPath, zipName, comment) { - if (filetools.fs.existsSync(localPath)) { - // fix ZipPath - zipPath = zipPath ? fixPath(zipPath) : ""; - - // p - local file name - const p = pth.win32.basename(pth.win32.normalize(localPath)); - - // add file name into zippath - zipPath += zipName ? zipName : p; - - // read file attributes - const _attr = filetools.fs.statSync(localPath); +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - // get file content - const data = _attr.isFile() ? filetools.fs.readFileSync(localPath) : Buffer.alloc(0); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + getSmithyContext: () => getSmithyContext, + normalizeProvider: () => normalizeProvider +}); +module.exports = __toCommonJS(src_exports); - // if folder - if (_attr.isDirectory()) zipPath += filetools.sep; +// src/getSmithyContext.ts +var import_types = __nccwpck_require__(5756); +var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); - // add file into zip file - this.addFile(zipPath, data, comment, _attr); - } else { - throw Utils.Errors.FILE_NOT_FOUND(localPath); - } - }, +// src/normalizeProvider.ts +var normalizeProvider = /* @__PURE__ */ __name((input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}, "normalizeProvider"); +// Annotate the CommonJS export names for ESM import in node: - /** - * Callback for showing if everything was done. - * - * @callback doneCallback - * @param {Error} err - Error object - * @param {boolean} done - was request fully completed - */ +0 && (0); - /** - * Adds a file from the disk to the archive - * - * @param {(object|string)} options - options object, if it is string it us used as localPath. - * @param {string} options.localPath - Local path to the file. - * @param {string} [options.comment] - Optional file comment. - * @param {string} [options.zipPath] - Optional path inside the zip - * @param {string} [options.zipName] - Optional name for the file - * @param {doneCallback} callback - The callback that handles the response. - */ - addLocalFileAsync: function (options, callback) { - options = typeof options === "object" ? options : { localPath: options }; - const localPath = pth.resolve(options.localPath); - const { comment } = options; - let { zipPath, zipName } = options; - const self = this; - filetools.fs.stat(localPath, function (err, stats) { - if (err) return callback(err, false); - // fix ZipPath - zipPath = zipPath ? fixPath(zipPath) : ""; - // p - local file name - const p = pth.win32.basename(pth.win32.normalize(localPath)); - // add file name into zippath - zipPath += zipName ? zipName : p; - if (stats.isFile()) { - filetools.fs.readFile(localPath, function (err, data) { - if (err) return callback(err, false); - self.addFile(zipPath, data, comment, stats); - return setImmediate(callback, undefined, true); - }); - } else if (stats.isDirectory()) { - zipPath += filetools.sep; - self.addFile(zipPath, Buffer.alloc(0), comment, stats); - return setImmediate(callback, undefined, true); - } - }); - }, +/***/ }), - /** - * Adds a local directory and all its nested files and directories to the archive - * - * @param {string} localPath - local path to the folder - * @param {string} [zipPath] - optional path inside zip - * @param {(RegExp|function)} [filter] - optional RegExp or Function if files match will be included. - */ - addLocalFolder: function (localPath, zipPath, filter) { - // Prepare filter - filter = filenameFilter(filter); +/***/ 4902: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // fix ZipPath - zipPath = zipPath ? fixPath(zipPath) : ""; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - // normalize the path first - localPath = pth.normalize(localPath); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + AdaptiveRetryStrategy: () => AdaptiveRetryStrategy, + ConfiguredRetryStrategy: () => ConfiguredRetryStrategy, + DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS, + DEFAULT_RETRY_DELAY_BASE: () => DEFAULT_RETRY_DELAY_BASE, + DEFAULT_RETRY_MODE: () => DEFAULT_RETRY_MODE, + DefaultRateLimiter: () => DefaultRateLimiter, + INITIAL_RETRY_TOKENS: () => INITIAL_RETRY_TOKENS, + INVOCATION_ID_HEADER: () => INVOCATION_ID_HEADER, + MAXIMUM_RETRY_DELAY: () => MAXIMUM_RETRY_DELAY, + NO_RETRY_INCREMENT: () => NO_RETRY_INCREMENT, + REQUEST_HEADER: () => REQUEST_HEADER, + RETRY_COST: () => RETRY_COST, + RETRY_MODES: () => RETRY_MODES, + StandardRetryStrategy: () => StandardRetryStrategy, + THROTTLING_RETRY_DELAY_BASE: () => THROTTLING_RETRY_DELAY_BASE, + TIMEOUT_RETRY_COST: () => TIMEOUT_RETRY_COST +}); +module.exports = __toCommonJS(src_exports); - if (filetools.fs.existsSync(localPath)) { - const items = filetools.findFiles(localPath); - const self = this; +// src/config.ts +var RETRY_MODES = /* @__PURE__ */ ((RETRY_MODES2) => { + RETRY_MODES2["STANDARD"] = "standard"; + RETRY_MODES2["ADAPTIVE"] = "adaptive"; + return RETRY_MODES2; +})(RETRY_MODES || {}); +var DEFAULT_MAX_ATTEMPTS = 3; +var DEFAULT_RETRY_MODE = "standard" /* STANDARD */; - if (items.length) { - for (const filepath of items) { - const p = pth.join(zipPath, relativePath(localPath, filepath)); - if (filter(p)) { - self.addLocalFile(filepath, pth.dirname(p)); - } - } - } - } else { - throw Utils.Errors.FILE_NOT_FOUND(localPath); - } - }, +// src/DefaultRateLimiter.ts +var import_service_error_classification = __nccwpck_require__(6375); +var DefaultRateLimiter = class _DefaultRateLimiter { + constructor(options) { + // Pre-set state variables + this.currentCapacity = 0; + this.enabled = false; + this.lastMaxRate = 0; + this.measuredTxRate = 0; + this.requestCount = 0; + this.lastTimestamp = 0; + this.timeWindow = 0; + this.beta = options?.beta ?? 0.7; + this.minCapacity = options?.minCapacity ?? 1; + this.minFillRate = options?.minFillRate ?? 0.5; + this.scaleConstant = options?.scaleConstant ?? 0.4; + this.smooth = options?.smooth ?? 0.8; + const currentTimeInSeconds = this.getCurrentTimeInSeconds(); + this.lastThrottleTime = currentTimeInSeconds; + this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); + this.fillRate = this.minFillRate; + this.maxCapacity = this.minCapacity; + } + static { + __name(this, "DefaultRateLimiter"); + } + static { + /** + * Only used in testing. + */ + this.setTimeoutFn = setTimeout; + } + getCurrentTimeInSeconds() { + return Date.now() / 1e3; + } + 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 * 1e3; + await new Promise((resolve) => _DefaultRateLimiter.setTimeoutFn(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, import_service_error_classification.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)); + } +}; - /** - * Asynchronous addLocalFolder - * @param {string} localPath - * @param {callback} callback - * @param {string} [zipPath] optional path inside zip - * @param {RegExp|function} [filter] optional RegExp or Function if files match will - * be included. - */ - addLocalFolderAsync: function (localPath, callback, zipPath, filter) { - // Prepare filter - filter = filenameFilter(filter); +// src/constants.ts +var DEFAULT_RETRY_DELAY_BASE = 100; +var MAXIMUM_RETRY_DELAY = 20 * 1e3; +var THROTTLING_RETRY_DELAY_BASE = 500; +var INITIAL_RETRY_TOKENS = 500; +var RETRY_COST = 5; +var TIMEOUT_RETRY_COST = 10; +var NO_RETRY_INCREMENT = 1; +var INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; +var REQUEST_HEADER = "amz-sdk-request"; - // fix ZipPath - zipPath = zipPath ? fixPath(zipPath) : ""; +// src/defaultRetryBackoffStrategy.ts +var getDefaultRetryBackoffStrategy = /* @__PURE__ */ __name(() => { + let delayBase = DEFAULT_RETRY_DELAY_BASE; + const computeNextBackoffDelay = /* @__PURE__ */ __name((attempts) => { + return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); + }, "computeNextBackoffDelay"); + const setDelayBase = /* @__PURE__ */ __name((delay) => { + delayBase = delay; + }, "setDelayBase"); + return { + computeNextBackoffDelay, + setDelayBase + }; +}, "getDefaultRetryBackoffStrategy"); - // normalize the path first - localPath = pth.normalize(localPath); +// src/defaultRetryToken.ts +var createDefaultRetryToken = /* @__PURE__ */ __name(({ + retryDelay, + retryCount, + retryCost +}) => { + const getRetryCount = /* @__PURE__ */ __name(() => retryCount, "getRetryCount"); + const getRetryDelay = /* @__PURE__ */ __name(() => Math.min(MAXIMUM_RETRY_DELAY, retryDelay), "getRetryDelay"); + const getRetryCost = /* @__PURE__ */ __name(() => retryCost, "getRetryCost"); + return { + getRetryCount, + getRetryDelay, + getRetryCost + }; +}, "createDefaultRetryToken"); - var self = this; - filetools.fs.open(localPath, "r", function (err) { - if (err && err.code === "ENOENT") { - callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath)); - } else if (err) { - callback(undefined, err); - } else { - var items = filetools.findFiles(localPath); - var i = -1; +// src/StandardRetryStrategy.ts +var StandardRetryStrategy = class { + constructor(maxAttempts) { + this.maxAttempts = maxAttempts; + this.mode = "standard" /* STANDARD */; + this.capacity = INITIAL_RETRY_TOKENS; + this.retryBackoffStrategy = getDefaultRetryBackoffStrategy(); + this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts; + } + static { + __name(this, "StandardRetryStrategy"); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async acquireInitialRetryToken(retryTokenScope) { + return createDefaultRetryToken({ + retryDelay: 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" ? THROTTLING_RETRY_DELAY_BASE : 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 createDefaultRetryToken({ + retryDelay, + retryCount: token.getRetryCount() + 1, + retryCost: capacityCost + }); + } + throw new Error("No retry token available"); + } + recordSuccess(token) { + this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); + } + /** + * @returns the current available retry capacity. + * + * This number decreases when retries are executed and refills when requests or retries succeed. + */ + getCapacity() { + return this.capacity; + } + async getMaxAttempts() { + try { + return await this.maxAttemptsProvider(); + } catch (error) { + console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); + return 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" ? TIMEOUT_RETRY_COST : RETRY_COST; + } + isRetryableError(errorType) { + return errorType === "THROTTLING" || errorType === "TRANSIENT"; + } +}; - var next = function () { - i += 1; - if (i < items.length) { - var filepath = items[i]; - var p = relativePath(localPath, filepath).split("\\").join("/"); //windows fix - p = p - .normalize("NFD") - .replace(/[\u0300-\u036f]/g, "") - .replace(/[^\x20-\x7E]/g, ""); // accent fix - if (filter(p)) { - filetools.fs.stat(filepath, function (er0, stats) { - if (er0) callback(undefined, er0); - if (stats.isFile()) { - filetools.fs.readFile(filepath, function (er1, data) { - if (er1) { - callback(undefined, er1); - } else { - self.addFile(zipPath + p, data, "", stats); - next(); - } - }); - } else { - self.addFile(zipPath + p + "/", Buffer.alloc(0), "", stats); - next(); - } - }); - } else { - process.nextTick(() => { - next(); - }); - } - } else { - callback(true, undefined); - } - }; +// src/AdaptiveRetryStrategy.ts +var AdaptiveRetryStrategy = class { + constructor(maxAttemptsProvider, options) { + this.maxAttemptsProvider = maxAttemptsProvider; + this.mode = "adaptive" /* ADAPTIVE */; + const { rateLimiter } = options ?? {}; + this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); + this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider); + } + static { + __name(this, "AdaptiveRetryStrategy"); + } + 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); + } +}; - next(); - } - }); - }, +// src/ConfiguredRetryStrategy.ts +var ConfiguredRetryStrategy = class extends StandardRetryStrategy { + static { + __name(this, "ConfiguredRetryStrategy"); + } + /** + * @param maxAttempts - the maximum number of retry attempts allowed. + * e.g., if set to 3, then 4 total requests are possible. + * @param computeNextBackoffDelay - a millisecond delay for each retry or a function that takes the retry attempt + * and returns the delay. + * + * @example exponential backoff. + * ```js + * new Client({ + * retryStrategy: new ConfiguredRetryStrategy(3, (attempt) => attempt ** 2) + * }); + * ``` + * @example constant delay. + * ```js + * new Client({ + * retryStrategy: new ConfiguredRetryStrategy(3, 2000) + * }); + * ``` + */ + constructor(maxAttempts, computeNextBackoffDelay = 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; + } +}; +// Annotate the CommonJS export names for ESM import in node: - /** - * Adds a local directory and all its nested files and directories to the archive - * - * @param {object | string} options - options object, if it is string it us used as localPath. - * @param {string} options.localPath - Local path to the folder. - * @param {string} [options.zipPath] - optional path inside zip. - * @param {RegExp|function} [options.filter] - optional RegExp or Function if files match will be included. - * @param {function|string} [options.namefix] - optional function to help fix filename - * @param {doneCallback} callback - The callback that handles the response. - * - */ - addLocalFolderAsync2: function (options, callback) { - const self = this; - options = typeof options === "object" ? options : { localPath: options }; - localPath = pth.resolve(fixPath(options.localPath)); - let { zipPath, filter, namefix } = options; +0 && (0); - if (filter instanceof RegExp) { - filter = (function (rx) { - return function (filename) { - return rx.test(filename); - }; - })(filter); - } else if ("function" !== typeof filter) { - filter = function () { - return true; - }; - } - // fix ZipPath - zipPath = zipPath ? fixPath(zipPath) : ""; - // Check Namefix function - if (namefix == "latin1") { - namefix = (str) => - str - .normalize("NFD") - .replace(/[\u0300-\u036f]/g, "") - .replace(/[^\x20-\x7E]/g, ""); // accent fix (latin1 characers only) - } +/***/ }), - if (typeof namefix !== "function") namefix = (str) => str; +/***/ 9361: +/***/ ((__unused_webpack_module, exports) => { - // internal, create relative path + fix the name - const relPathFix = (entry) => pth.join(zipPath, namefix(relativePath(localPath, entry))); - const fileNameFix = (entry) => pth.win32.basename(pth.win32.normalize(namefix(entry))); +"use strict"; - filetools.fs.open(localPath, "r", function (err) { - if (err && err.code === "ENOENT") { - callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath)); - } else if (err) { - callback(undefined, err); - } else { - filetools.findFilesAsync(localPath, function (err, fileEntries) { - if (err) return callback(err); - fileEntries = fileEntries.filter((dir) => filter(relPathFix(dir))); - if (!fileEntries.length) callback(undefined, false); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ByteArrayCollector = void 0; +class ByteArrayCollector { + constructor(allocByteArray) { + this.allocByteArray = allocByteArray; + this.byteLength = 0; + this.byteArrays = []; + } + push(byteArray) { + this.byteArrays.push(byteArray); + this.byteLength += byteArray.byteLength; + } + flush() { + if (this.byteArrays.length === 1) { + const bytes = this.byteArrays[0]; + this.reset(); + return bytes; + } + const aggregation = this.allocByteArray(this.byteLength); + let cursor = 0; + for (let i = 0; i < this.byteArrays.length; ++i) { + const bytes = this.byteArrays[i]; + aggregation.set(bytes, cursor); + cursor += bytes.byteLength; + } + this.reset(); + return aggregation; + } + reset() { + this.byteArrays = []; + this.byteLength = 0; + } +} +exports.ByteArrayCollector = ByteArrayCollector; - setImmediate( - fileEntries.reverse().reduce(function (next, entry) { - return function (err, done) { - if (err || done === false) return setImmediate(next, err, false); - self.addLocalFileAsync( - { - localPath: entry, - zipPath: pth.dirname(relPathFix(entry)), - zipName: fileNameFix(entry) - }, - next - ); - }; - }, callback) - ); - }); - } - }); - }, +/***/ }), - /** - * Adds a local directory and all its nested files and directories to the archive - * - * @param {string} localPath - path where files will be extracted - * @param {object} props - optional properties - * @param {string} [props.zipPath] - optional path inside zip - * @param {RegExp|function} [props.filter] - optional RegExp or Function if files match will be included. - * @param {function|string} [props.namefix] - optional function to help fix filename - */ - addLocalFolderPromise: function (localPath, props) { - return new Promise((resolve, reject) => { - this.addLocalFolderAsync2(Object.assign({ localPath }, props), (err, done) => { - if (err) reject(err); - if (done) resolve(this); - }); - }); - }, +/***/ 8551: +/***/ ((__unused_webpack_module, exports) => { - /** - * Allows you to create a entry (file or directory) in the zip file. - * If you want to create a directory the entryName must end in / and a null buffer should be provided. - * Comment and attributes are optional - * - * @param {string} entryName - * @param {Buffer | string} content - file content as buffer or utf8 coded string - * @param {string} [comment] - file comment - * @param {number | object} [attr] - number as unix file permissions, object as filesystem Stats object - */ - addFile: function (entryName, content, comment, attr) { - entryName = zipnamefix(entryName); - let entry = getEntry(entryName); - const update = entry != null; +"use strict"; - // prepare new entry - if (!update) { - entry = new ZipEntry(opts); - entry.entryName = entryName; - } - entry.comment = comment || ""; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; +class ChecksumStream extends ReadableStreamRef { +} +exports.ChecksumStream = ChecksumStream; - const isStat = "object" === typeof attr && attr instanceof filetools.fs.Stats; - // last modification time from file stats - if (isStat) { - entry.header.time = attr.mtime; - } +/***/ }), - // Set file attribute - var fileattr = entry.isDirectory ? 0x10 : 0; // (MS-DOS directory flag) +/***/ 6982: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // extended attributes field for Unix - // set file type either S_IFDIR / S_IFREG - let unix = entry.isDirectory ? 0x4000 : 0x8000; +"use strict"; - if (isStat) { - // File attributes from file stats - unix |= 0xfff & attr.mode; - } else if ("number" === typeof attr) { - // attr from given attr values - unix |= 0xfff & attr; - } else { - // Default values: - unix |= entry.isDirectory ? 0o755 : 0o644; // permissions (drwxr-xr-x) or (-r-wr--r--) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(5600); +const stream_1 = __nccwpck_require__(2781); +class ChecksumStream extends stream_1.Duplex { + constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { + var _a, _b; + super(); + if (typeof source.pipe === "function") { + this.source = source; + } + else { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); + } + this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + this.expectedChecksum = expectedChecksum; + this.checksum = checksum; + this.checksumSourceLocation = checksumSourceLocation; + this.source.pipe(this); + } + _read(size) { } + _write(chunk, encoding, callback) { + try { + this.checksum.update(chunk); + this.push(chunk); + } + catch (e) { + return callback(e); + } + return callback(); + } + async _final(callback) { + try { + const digest = await this.checksum.digest(); + const received = this.base64Encoder(digest); + if (this.expectedChecksum !== received) { + return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + + ` in response header "${this.checksumSourceLocation}".`)); } + } + catch (e) { + return callback(e); + } + this.push(null); + return callback(); + } +} +exports.ChecksumStream = ChecksumStream; - fileattr = (fileattr | (unix << 16)) >>> 0; // add attributes - entry.attr = fileattr; +/***/ }), - entry.setData(content); - if (!update) _zip.setEntry(entry); +/***/ 2313: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return entry; - }, +"use strict"; - /** - * Returns an array of ZipEntry objects representing the files and folders inside the archive - * - * @param {string} [password] - * @returns Array - */ - getEntries: function (password) { - _zip.password = password; - return _zip ? _zip.entries : []; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(5600); +const stream_type_check_1 = __nccwpck_require__(2370); +const ChecksumStream_browser_1 = __nccwpck_require__(8551); +const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { + var _a, _b; + if (!(0, stream_type_check_1.isReadableStream)(source)) { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); + } + const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + if (typeof TransformStream !== "function") { + throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + } + const transform = new TransformStream({ + start() { }, + async transform(chunk, controller) { + checksum.update(chunk); + controller.enqueue(chunk); }, - - /** - * Returns a ZipEntry object representing the file or folder specified by ``name``. - * - * @param {string} name - * @return ZipEntry - */ - getEntry: function (/**String*/ name) { - return getEntry(name); + async flush(controller) { + const digest = await checksum.digest(); + const received = encoder(digest); + if (expectedChecksum !== received) { + const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + + ` in response header "${checksumSourceLocation}".`); + controller.error(error); + } + else { + controller.terminate(); + } }, + }); + source.pipeThrough(transform); + const readable = transform.readable; + Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); + return readable; +}; +exports.createChecksumStream = createChecksumStream; - getEntryCount: function () { - return _zip.getEntryCount(); - }, - forEach: function (callback) { - return _zip.forEach(callback); - }, +/***/ }), - /** - * Extracts the given entry to the given targetPath - * If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted - * - * @param {string|ZipEntry} entry - ZipEntry object or String with the full path of the entry - * @param {string} targetPath - Target folder where to write the file - * @param {boolean} [maintainEntryPath=true] - If maintainEntryPath is true and the entry is inside a folder, the entry folder will be created in targetPath as well. Default is TRUE - * @param {boolean} [overwrite=false] - If the file already exists at the target path, the file will be overwriten if this is true. - * @param {boolean} [keepOriginalPermission=false] - The file will be set as the permission from the entry if this is true. - * @param {string} [outFileName] - String If set will override the filename of the extracted file (Only works if the entry is a file) - * - * @return Boolean - */ - extractEntryTo: function (entry, targetPath, maintainEntryPath, overwrite, keepOriginalPermission, outFileName) { - overwrite = get_Bool(false, overwrite); - keepOriginalPermission = get_Bool(false, keepOriginalPermission); - maintainEntryPath = get_Bool(true, maintainEntryPath); - outFileName = get_Str(keepOriginalPermission, outFileName); +/***/ 1927: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var item = getEntry(entry); - if (!item) { - throw Utils.Errors.NO_ENTRY(); - } +"use strict"; - var entryName = canonical(item.entryName); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = createChecksumStream; +const stream_type_check_1 = __nccwpck_require__(2370); +const ChecksumStream_1 = __nccwpck_require__(6982); +const createChecksumStream_browser_1 = __nccwpck_require__(2313); +function createChecksumStream(init) { + if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { + return (0, createChecksumStream_browser_1.createChecksumStream)(init); + } + return new ChecksumStream_1.ChecksumStream(init); +} - var target = sanitize(targetPath, outFileName && !item.isDirectory ? outFileName : maintainEntryPath ? entryName : pth.basename(entryName)); - if (item.isDirectory) { - var children = _zip.getEntryChildren(item); - children.forEach(function (child) { - if (child.isDirectory) return; - var content = child.getData(); - if (!content) { - throw Utils.Errors.CANT_EXTRACT_FILE(); - } - var name = canonical(child.entryName); - var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name)); - // The reverse operation for attr depend on method addFile() - const fileAttr = keepOriginalPermission ? child.header.fileAttr : undefined; - filetools.writeFileTo(childName, content, overwrite, fileAttr); - }); - return true; - } +/***/ }), - var content = item.getData(_zip.password); - if (!content) throw Utils.Errors.CANT_EXTRACT_FILE(); +/***/ 3259: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (filetools.fs.existsSync(target) && !overwrite) { - throw Utils.Errors.CANT_OVERRIDE(); +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = createBufferedReadable; +const node_stream_1 = __nccwpck_require__(4492); +const ByteArrayCollector_1 = __nccwpck_require__(9361); +const createBufferedReadableStream_1 = __nccwpck_require__(2558); +const stream_type_check_1 = __nccwpck_require__(2370); +function createBufferedReadable(upstream, size, logger) { + if ((0, stream_type_check_1.isReadableStream)(upstream)) { + return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); + } + const downstream = new node_stream_1.Readable({ read() { } }); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = [ + "", + new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), + new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), + ]; + let mode = -1; + upstream.on("data", (chunk) => { + const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); + if (mode !== chunkMode) { + if (mode >= 0) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); } - // The reverse operation for attr depend on method addFile() - const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; - filetools.writeFileTo(target, content, overwrite, fileAttr); + mode = chunkMode; + } + if (mode === -1) { + downstream.push(chunk); + return; + } + const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); + bytesSeen += chunkSize; + const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + downstream.push(chunk); + } + else { + const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + } + }); + upstream.on("end", () => { + if (mode !== -1) { + const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); + if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { + downstream.push(remainder); + } + } + downstream.push(null); + }); + return downstream; +} - return true; - }, - /** - * Test the archive - * @param {string} [pass] - */ - test: function (pass) { - if (!_zip) { - return false; - } +/***/ }), - for (var entry in _zip.entries) { - try { - if (entry.isDirectory) { - continue; - } - var content = _zip.entries[entry].getData(pass); - if (!content) { - return false; - } - } catch (err) { - return false; - } - } - return true; - }, +/***/ 2558: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Extracts the entire archive to the given location - * - * @param {string} targetPath Target location - * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true. - * Default is FALSE - * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true. - * Default is FALSE - * @param {string|Buffer} [pass] password - */ - extractAllTo: function (targetPath, overwrite, keepOriginalPermission, pass) { - keepOriginalPermission = get_Bool(false, keepOriginalPermission); - pass = get_Str(keepOriginalPermission, pass); - overwrite = get_Bool(false, overwrite); - if (!_zip) throw Utils.Errors.NO_ZIP(); +"use strict"; - _zip.entries.forEach(function (entry) { - var entryName = sanitize(targetPath, canonical(entry.entryName)); - if (entry.isDirectory) { - filetools.makeDir(entryName); - return; - } - var content = entry.getData(pass); - if (!content) { - throw Utils.Errors.CANT_EXTRACT_FILE(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = void 0; +exports.createBufferedReadableStream = createBufferedReadableStream; +exports.merge = merge; +exports.flush = flush; +exports.sizeOf = sizeOf; +exports.modeOf = modeOf; +const ByteArrayCollector_1 = __nccwpck_require__(9361); +function createBufferedReadableStream(upstream, size, logger) { + const reader = upstream.getReader(); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; + let mode = -1; + const pull = async (controller) => { + const { value, done } = await reader.read(); + const chunk = value; + if (done) { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + controller.enqueue(remainder); } - // The reverse operation for attr depend on method addFile() - const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; - filetools.writeFileTo(entryName, content, overwrite, fileAttr); - try { - filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time); - } catch (err) { - throw Utils.Errors.CANT_EXTRACT_FILE(); + } + controller.close(); + } + else { + const chunkMode = modeOf(chunk, false); + if (mode !== chunkMode) { + if (mode >= 0) { + controller.enqueue(flush(buffers, mode)); } - }); - }, - - /** - * Asynchronous extractAllTo - * - * @param {string} targetPath Target location - * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true. - * Default is FALSE - * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true. - * Default is FALSE - * @param {function} callback The callback will be executed when all entries are extracted successfully or any error is thrown. - */ - extractAllToAsync: function (targetPath, overwrite, keepOriginalPermission, callback) { - callback = get_Fun(overwrite, keepOriginalPermission, callback); - keepOriginalPermission = get_Bool(false, keepOriginalPermission); - overwrite = get_Bool(false, overwrite); - if (!callback) { - return new Promise((resolve, reject) => { - this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function (err) { - if (err) { - reject(err); - } else { - resolve(this); - } - }); - }); + mode = chunkMode; } - if (!_zip) { - callback(Utils.Errors.NO_ZIP()); + if (mode === -1) { + controller.enqueue(chunk); return; } - - targetPath = pth.resolve(targetPath); - // convert entryName to - const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName))); - const getError = (msg, file) => new Error(msg + ': "' + file + '"'); - - // separate directories from files - const dirEntries = []; - const fileEntries = []; - _zip.entries.forEach((e) => { - if (e.isDirectory) { - dirEntries.push(e); - } else { - fileEntries.push(e); + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + controller.enqueue(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); } - }); - - // Create directory entries first synchronously - // this prevents race condition and assures folders are there before writing files - for (const entry of dirEntries) { - const dirPath = getPath(entry); - // The reverse operation for attr depend on method addFile() - const dirAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; - try { - filetools.makeDir(dirPath); - if (dirAttr) filetools.fs.chmodSync(dirPath, dirAttr); - // in unix timestamp will change if files are later added to folder, but still - filetools.fs.utimesSync(dirPath, entry.header.time, entry.header.time); - } catch (er) { - callback(getError("Unable to create folder", dirPath)); + if (newSize >= size) { + controller.enqueue(flush(buffers, mode)); + } + else { + await pull(controller); } } + } + }; + return new ReadableStream({ + pull, + }); +} +exports.createBufferedReadable = createBufferedReadableStream; +function merge(buffers, mode, chunk) { + switch (mode) { + case 0: + buffers[0] += chunk; + return sizeOf(buffers[0]); + case 1: + case 2: + buffers[mode].push(chunk); + return sizeOf(buffers[mode]); + } +} +function flush(buffers, mode) { + switch (mode) { + case 0: + const s = buffers[0]; + buffers[0] = ""; + return s; + case 1: + case 2: + return buffers[mode].flush(); + } + throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); +} +function sizeOf(chunk) { + var _a, _b; + return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; +} +function modeOf(chunk, allowBuffer = true) { + if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { + return 2; + } + if (chunk instanceof Uint8Array) { + return 1; + } + if (typeof chunk === "string") { + return 0; + } + return -1; +} - fileEntries.reverse().reduce(function (next, entry) { - return function (err) { - if (err) { - next(err); - } else { - const entryName = pth.normalize(canonical(entry.entryName)); - const filePath = sanitize(targetPath, entryName); - entry.getDataAsync(function (content, err_1) { - if (err_1) { - next(err_1); - } else if (!content) { - next(Utils.Errors.CANT_EXTRACT_FILE()); - } else { - // The reverse operation for attr depend on method addFile() - const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; - filetools.writeFileToAsync(filePath, content, overwrite, fileAttr, function (succ) { - if (!succ) { - next(getError("Unable to write file", filePath)); - } - filetools.fs.utimes(filePath, entry.header.time, entry.header.time, function (err_2) { - if (err_2) { - next(getError("Unable to set times", filePath)); - } else { - next(); - } - }); - }); - } - }); - } - }; - }, callback)(); - }, - /** - * Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip - * - * @param {string} targetFileName - * @param {function} callback - */ - writeZip: function (targetFileName, callback) { - if (arguments.length === 1) { - if (typeof targetFileName === "function") { - callback = targetFileName; - targetFileName = ""; - } - } +/***/ }), - if (!targetFileName && opts.filename) { - targetFileName = opts.filename; - } - if (!targetFileName) return; +/***/ 3636: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var zipData = _zip.compressToBuffer(); - if (zipData) { - var ok = filetools.writeFileTo(targetFileName, zipData, true); - if (typeof callback === "function") callback(!ok ? new Error("failed") : null, ""); - } - }, +"use strict"; - /** - * - * @param {string} targetFileName - * @param {object} [props] - * @param {boolean} [props.overwrite=true] If the file already exists at the target path, the file will be overwriten if this is true. - * @param {boolean} [props.perm] The file will be set as the permission from the entry if this is true. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getAwsChunkedEncodingStream = void 0; +const stream_1 = __nccwpck_require__(2781); +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; - * @returns {Promise} - */ - writeZipPromise: function (/**String*/ targetFileName, /* object */ props) { - const { overwrite, perm } = Object.assign({ overwrite: true }, props); - return new Promise((resolve, reject) => { - // find file name - if (!targetFileName && opts.filename) targetFileName = opts.filename; - if (!targetFileName) reject("ADM-ZIP: ZIP File Name Missing"); +/***/ }), - this.toBufferPromise().then((zipData) => { - const ret = (done) => (done ? resolve(done) : reject("ADM-ZIP: Wasn't able to write zip file")); - filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret); - }, reject); - }); - }, +/***/ 6711: +/***/ ((__unused_webpack_module, exports) => { - /** - * @returns {Promise} A promise to the Buffer. - */ - toBufferPromise: function () { - return new Promise((resolve, reject) => { - _zip.toAsyncBuffer(resolve, reject); - }); - }, +"use strict"; - /** - * Returns the content of the entire zip file as a Buffer object - * - * @prop {function} [onSuccess] - * @prop {function} [onFail] - * @prop {function} [onItemStart] - * @prop {function} [onItemEnd] - * @returns {Buffer} - */ - toBuffer: function (onSuccess, onFail, onItemStart, onItemEnd) { - if (typeof onSuccess === "function") { - _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd); - return null; - } - return _zip.compressToBuffer(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = headStream; +async function headStream(stream, bytes) { + var _a; + let byteLengthCounter = 0; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; } - }; + if (byteLengthCounter >= bytes) { + break; + } + isDone = done; + } + reader.releaseLock(); + const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); + let offset = 0; + for (const chunk of chunks) { + if (chunk.byteLength > collected.byteLength - offset) { + collected.set(chunk.subarray(0, collected.byteLength - offset), offset); + break; + } + else { + collected.set(chunk, offset); + } + offset += chunk.length; + } + return collected; +} + + +/***/ }), + +/***/ 6708: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = void 0; +const stream_1 = __nccwpck_require__(2781); +const headStream_browser_1 = __nccwpck_require__(6711); +const stream_type_check_1 = __nccwpck_require__(2370); +const headStream = (stream, bytes) => { + if ((0, stream_type_check_1.isReadableStream)(stream)) { + return (0, headStream_browser_1.headStream)(stream, bytes); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + collector.limit = bytes; + 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.buffers)); + resolve(bytes); + }); + }); }; +exports.headStream = headStream; +class Collector extends stream_1.Writable { + constructor() { + super(...arguments); + this.buffers = []; + this.limit = Infinity; + this.bytesBuffered = 0; + } + _write(chunk, encoding, callback) { + var _a; + this.buffers.push(chunk); + this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; + if (this.bytesBuffered >= this.limit) { + const excess = this.bytesBuffered - this.limit; + const tailBuffer = this.buffers[this.buffers.length - 1]; + this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); + this.emit("finish"); + } + callback(); + } +} /***/ }), -/***/ 9032: +/***/ 6607: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var Utils = __nccwpck_require__(5182), - Constants = Utils.Constants; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -/* The central directory file header */ -module.exports = function () { - var _verMade = 20, // v2.0 - _version = 10, // v1.0 - _flags = 0, - _method = 0, - _time = 0, - _crc = 0, - _compressedSize = 0, - _size = 0, - _fnameLen = 0, - _extraLen = 0, - _comLen = 0, - _diskStart = 0, - _inattr = 0, - _attr = 0, - _offset = 0; +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter +}); +module.exports = __toCommonJS(src_exports); - _verMade |= Utils.isWin ? 0x0a00 : 0x0300; +// src/blob/transforms.ts +var import_util_base64 = __nccwpck_require__(5600); +var import_util_utf8 = __nccwpck_require__(1895); +function transformToString(payload, encoding = "utf-8") { + if (encoding === "base64") { + return (0, import_util_base64.toBase64)(payload); + } + return (0, import_util_utf8.toUtf8)(payload); +} +__name(transformToString, "transformToString"); +function transformFromString(str, encoding) { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); + } + return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); +} +__name(transformFromString, "transformFromString"); - // Set EFS flag since filename and comment fields are all by default encoded using UTF-8. - // Without it file names may be corrupted for other apps when file names use unicode chars - _flags |= Constants.FLG_EFS; +// src/blob/Uint8ArrayBlobAdapter.ts +var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { + static { + __name(this, "Uint8ArrayBlobAdapter"); + } + /** + * @param source - such as a string or Stream. + * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. + */ + static fromString(source, encoding = "utf-8") { + switch (typeof source) { + case "string": + return transformFromString(source, encoding); + default: + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } + } + /** + * @param source - Uint8Array to be mutated. + * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. + */ + static mutate(source) { + Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); + return source; + } + /** + * @param encoding - default 'utf-8'. + * @returns the blob as string. + */ + transformToString(encoding = "utf-8") { + return transformToString(this, encoding); + } +}; - const _localHeader = { - extraLen: 0 - }; +// src/index.ts +__reExport(src_exports, __nccwpck_require__(6982), module.exports); +__reExport(src_exports, __nccwpck_require__(1927), module.exports); +__reExport(src_exports, __nccwpck_require__(3259), module.exports); +__reExport(src_exports, __nccwpck_require__(3636), module.exports); +__reExport(src_exports, __nccwpck_require__(6708), module.exports); +__reExport(src_exports, __nccwpck_require__(4515), module.exports); +__reExport(src_exports, __nccwpck_require__(8321), module.exports); +__reExport(src_exports, __nccwpck_require__(2370), module.exports); +// Annotate the CommonJS export names for ESM import in node: - // casting - const uint32 = (val) => Math.max(0, val) >>> 0; - const uint16 = (val) => Math.max(0, val) & 0xffff; - const uint8 = (val) => Math.max(0, val) & 0xff; +0 && (0); - _time = Utils.fromDate2DOS(new Date()); - return { - get made() { - return _verMade; + +/***/ }), + +/***/ 2942: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const fetch_http_handler_1 = __nccwpck_require__(2687); +const util_base64_1 = __nccwpck_require__(5600); +const util_hex_encoding_1 = __nccwpck_require__(5364); +const util_utf8_1 = __nccwpck_require__(1895); +const stream_type_check_1 = __nccwpck_require__(2370); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { + 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 Blob or ReadableStream, got ${name}`); + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, fetch_http_handler_1.streamCollector)(stream); + }; + const blobToWebStream = (blob) => { + if (typeof blob.stream !== "function") { + throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); + } + return blob.stream(); + }; + return Object.assign(stream, { + transformToByteArray: transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === "base64") { + return (0, util_base64_1.toBase64)(buf); + } + else if (encoding === "hex") { + return (0, util_hex_encoding_1.toHex)(buf); + } + else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { + return (0, util_utf8_1.toUtf8)(buf); + } + else if (typeof TextDecoder === "function") { + return new TextDecoder(encoding).decode(buf); + } + else { + throw new Error("TextDecoder is not available, please make sure polyfill is provided."); + } }, - set made(val) { - _verMade = val; + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + if (isBlobInstance(stream)) { + return blobToWebStream(stream); + } + else if ((0, stream_type_check_1.isReadableStream)(stream)) { + return stream; + } + else { + throw new Error(`Cannot transform payload to web stream, got ${stream}`); + } }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; +const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; - get version() { - return _version; - }, - set version(val) { - _version = val; - }, - get flags() { - return _flags; - }, - set flags(val) { - _flags = val; - }, +/***/ }), - get flags_efs() { - return (_flags & Constants.FLG_EFS) > 0; - }, - set flags_efs(val) { - if (val) { - _flags |= Constants.FLG_EFS; - } else { - _flags &= ~Constants.FLG_EFS; - } - }, +/***/ 4515: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - get flags_desc() { - return (_flags & Constants.FLG_DESC) > 0; - }, - set flags_desc(val) { - if (val) { - _flags |= Constants.FLG_DESC; - } else { - _flags &= ~Constants.FLG_DESC; - } - }, +"use strict"; - get method() { - return _method; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const node_http_handler_1 = __nccwpck_require__(258); +const util_buffer_from_1 = __nccwpck_require__(1381); +const stream_1 = __nccwpck_require__(2781); +const sdk_stream_mixin_browser_1 = __nccwpck_require__(2942); +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)) { + try { + return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); + } + catch (e) { + 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 TextDecoder(encoding); + return decoder.decode(buf); + } }, - set method(val) { - switch (val) { - case Constants.STORED: - this.version = 10; - case Constants.DEFLATED: - default: - this.version = 20; + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } - _method = val; + 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 ensure a polyfill is available."); + } + transformed = true; + return stream_1.Readable.toWeb(stream); }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; - get time() { - return Utils.fromDOS2Date(this.timeval); - }, - set time(val) { - this.timeval = Utils.fromDate2DOS(val); - }, - get timeval() { - return _time; - }, - set timeval(val) { - _time = uint32(val); - }, +/***/ }), - get timeHighByte() { - return uint8(_time >>> 8); - }, - get crc() { - return _crc; - }, - set crc(val) { - _crc = uint32(val); - }, +/***/ 4693: +/***/ ((__unused_webpack_module, exports) => { - get compressedSize() { - return _compressedSize; - }, - set compressedSize(val) { - _compressedSize = uint32(val); - }, +"use strict"; - get size() { - return _size; - }, - set size(val) { - _size = uint32(val); - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = splitStream; +async function splitStream(stream) { + if (typeof stream.stream === "function") { + stream = stream.stream(); + } + const readableStream = stream; + return readableStream.tee(); +} - get fileNameLength() { - return _fnameLen; - }, - set fileNameLength(val) { - _fnameLen = val; - }, - get extraLength() { - return _extraLen; - }, - set extraLength(val) { - _extraLen = val; - }, +/***/ }), - get extraLocalLength() { - return _localHeader.extraLen; - }, - set extraLocalLength(val) { - _localHeader.extraLen = val; - }, +/***/ 8321: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - get commentLength() { - return _comLen; - }, - set commentLength(val) { - _comLen = val; - }, +"use strict"; - get diskNumStart() { - return _diskStart; - }, - set diskNumStart(val) { - _diskStart = uint32(val); - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = splitStream; +const stream_1 = __nccwpck_require__(2781); +const splitStream_browser_1 = __nccwpck_require__(4693); +const stream_type_check_1 = __nccwpck_require__(2370); +async function splitStream(stream) { + if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { + return (0, splitStream_browser_1.splitStream)(stream); + } + const stream1 = new stream_1.PassThrough(); + const stream2 = new stream_1.PassThrough(); + stream.pipe(stream1); + stream.pipe(stream2); + return [stream1, stream2]; +} - get inAttr() { - return _inattr; - }, - set inAttr(val) { - _inattr = uint32(val); - }, - get attr() { - return _attr; - }, - set attr(val) { - _attr = uint32(val); - }, +/***/ }), - // get Unix file permissions - get fileAttr() { - return (_attr || 0) >> 16 & 0xfff; - }, +/***/ 2370: +/***/ ((__unused_webpack_module, exports) => { - get offset() { - return _offset; - }, - set offset(val) { - _offset = uint32(val); - }, +"use strict"; - get encrypted() { - return (_flags & Constants.FLG_ENC) === Constants.FLG_ENC; - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isBlob = exports.isReadableStream = void 0; +const isReadableStream = (stream) => { + var _a; + return typeof ReadableStream === "function" && + (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); +}; +exports.isReadableStream = isReadableStream; +const isBlob = (blob) => { + var _a; + return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); +}; +exports.isBlob = isBlob; - get centralHeaderSize() { - return Constants.CENHDR + _fnameLen + _extraLen + _comLen; - }, - get realDataOffset() { - return _offset + Constants.LOCHDR + _localHeader.fnameLen + _localHeader.extraLen; - }, +/***/ }), - get localHeader() { - return _localHeader; - }, +/***/ 4197: +/***/ ((module) => { - loadLocalHeaderFromBinary: function (/*Buffer*/ input) { - var data = input.slice(_offset, _offset + Constants.LOCHDR); - // 30 bytes and should start with "PK\003\004" - if (data.readUInt32LE(0) !== Constants.LOCSIG) { - throw Utils.Errors.INVALID_LOC(); - } +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - // version needed to extract - _localHeader.version = data.readUInt16LE(Constants.LOCVER); - // general purpose bit flag - _localHeader.flags = data.readUInt16LE(Constants.LOCFLG); - // compression method - _localHeader.method = data.readUInt16LE(Constants.LOCHOW); - // modification time (2 bytes time, 2 bytes date) - _localHeader.time = data.readUInt32LE(Constants.LOCTIM); - // uncompressed file crc-32 valu - _localHeader.crc = data.readUInt32LE(Constants.LOCCRC); - // compressed size - _localHeader.compressedSize = data.readUInt32LE(Constants.LOCSIZ); - // uncompressed size - _localHeader.size = data.readUInt32LE(Constants.LOCLEN); - // filename length - _localHeader.fnameLen = data.readUInt16LE(Constants.LOCNAM); - // extra field length - _localHeader.extraLen = data.readUInt16LE(Constants.LOCEXT); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + escapeUri: () => escapeUri, + escapeUriPath: () => escapeUriPath +}); +module.exports = __toCommonJS(src_exports); - // read extra data - const extraStart = _offset + Constants.LOCHDR + _localHeader.fnameLen; - const extraEnd = extraStart + _localHeader.extraLen; - return input.slice(extraStart, extraEnd); - }, +// src/escape-uri.ts +var escapeUri = /* @__PURE__ */ __name((uri) => ( + // AWS percent-encodes some extra non-standard characters in a URI + encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) +), "escapeUri"); +var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); - loadFromBinary: function (/*Buffer*/ data) { - // data should be 46 bytes and start with "PK 01 02" - if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) { - throw Utils.Errors.INVALID_CEN(); - } - // version made by - _verMade = data.readUInt16LE(Constants.CENVEM); - // version needed to extract - _version = data.readUInt16LE(Constants.CENVER); - // encrypt, decrypt flags - _flags = data.readUInt16LE(Constants.CENFLG); - // compression method - _method = data.readUInt16LE(Constants.CENHOW); - // modification time (2 bytes time, 2 bytes date) - _time = data.readUInt32LE(Constants.CENTIM); - // uncompressed file crc-32 value - _crc = data.readUInt32LE(Constants.CENCRC); - // compressed size - _compressedSize = data.readUInt32LE(Constants.CENSIZ); - // uncompressed size - _size = data.readUInt32LE(Constants.CENLEN); - // filename length - _fnameLen = data.readUInt16LE(Constants.CENNAM); - // extra field length - _extraLen = data.readUInt16LE(Constants.CENEXT); - // file comment length - _comLen = data.readUInt16LE(Constants.CENCOM); - // volume number start - _diskStart = data.readUInt16LE(Constants.CENDSK); - // internal file attributes - _inattr = data.readUInt16LE(Constants.CENATT); - // external file attributes - _attr = data.readUInt32LE(Constants.CENATX); - // LOC header offset - _offset = data.readUInt32LE(Constants.CENOFF); - }, +// src/escape-uri-path.ts +var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); +// Annotate the CommonJS export names for ESM import in node: - localHeaderToBinary: function () { - // LOC header size (30 bytes) - var data = Buffer.alloc(Constants.LOCHDR); - // "PK\003\004" - data.writeUInt32LE(Constants.LOCSIG, 0); - // version needed to extract - data.writeUInt16LE(_version, Constants.LOCVER); - // general purpose bit flag - data.writeUInt16LE(_flags, Constants.LOCFLG); - // compression method - data.writeUInt16LE(_method, Constants.LOCHOW); - // modification time (2 bytes time, 2 bytes date) - data.writeUInt32LE(_time, Constants.LOCTIM); - // uncompressed file crc-32 value - data.writeUInt32LE(_crc, Constants.LOCCRC); - // compressed size - data.writeUInt32LE(_compressedSize, Constants.LOCSIZ); - // uncompressed size - data.writeUInt32LE(_size, Constants.LOCLEN); - // filename length - data.writeUInt16LE(_fnameLen, Constants.LOCNAM); - // extra field length - data.writeUInt16LE(_localHeader.extraLen, Constants.LOCEXT); - return data; - }, +0 && (0); - centralHeaderToBinary: function () { - // CEN header size (46 bytes) - var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen); - // "PK\001\002" - data.writeUInt32LE(Constants.CENSIG, 0); - // version made by - data.writeUInt16LE(_verMade, Constants.CENVEM); - // version needed to extract - data.writeUInt16LE(_version, Constants.CENVER); - // encrypt, decrypt flags - data.writeUInt16LE(_flags, Constants.CENFLG); - // compression method - data.writeUInt16LE(_method, Constants.CENHOW); - // modification time (2 bytes time, 2 bytes date) - data.writeUInt32LE(_time, Constants.CENTIM); - // uncompressed file crc-32 value - data.writeUInt32LE(_crc, Constants.CENCRC); - // compressed size - data.writeUInt32LE(_compressedSize, Constants.CENSIZ); - // uncompressed size - data.writeUInt32LE(_size, Constants.CENLEN); - // filename length - data.writeUInt16LE(_fnameLen, Constants.CENNAM); - // extra field length - data.writeUInt16LE(_extraLen, Constants.CENEXT); - // file comment length - data.writeUInt16LE(_comLen, Constants.CENCOM); - // volume number start - data.writeUInt16LE(_diskStart, Constants.CENDSK); - // internal file attributes - data.writeUInt16LE(_inattr, Constants.CENATT); - // external file attributes - data.writeUInt32LE(_attr, Constants.CENATX); - // LOC header offset - data.writeUInt32LE(_offset, Constants.CENOFF); - return data; - }, - toJSON: function () { - const bytes = function (nr) { - return nr + " bytes"; - }; - return { - made: _verMade, - version: _version, - flags: _flags, - method: Utils.methodToString(_method), - time: this.time, - crc: "0x" + _crc.toString(16).toUpperCase(), - compressedSize: bytes(_compressedSize), - size: bytes(_size), - fileNameLength: bytes(_fnameLen), - extraLength: bytes(_extraLen), - commentLength: bytes(_comLen), - diskNumStart: _diskStart, - inAttr: _inattr, - attr: _attr, - offset: _offset, - centralHeaderSize: bytes(Constants.CENHDR + _fnameLen + _extraLen + _comLen) - }; - }, +/***/ }), - toString: function () { - return JSON.stringify(this.toJSON(), null, "\t"); - } - }; +/***/ 1895: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; }; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromUtf8: () => fromUtf8, + toUint8Array: () => toUint8Array, + toUtf8: () => toUtf8 +}); +module.exports = __toCommonJS(src_exports); + +// src/fromUtf8.ts +var import_util_buffer_from = __nccwpck_require__(1381); +var fromUtf8 = /* @__PURE__ */ __name((input) => { + const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}, "fromUtf8"); + +// src/toUint8Array.ts +var toUint8Array = /* @__PURE__ */ __name((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); +}, "toUint8Array"); +// src/toUtf8.ts -/***/ }), +var toUtf8 = /* @__PURE__ */ __name((input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}, "toUtf8"); +// Annotate the CommonJS export names for ESM import in node: -/***/ 4958: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +0 && (0); -exports.EntryHeader = __nccwpck_require__(9032); -exports.MainHeader = __nccwpck_require__(8952); /***/ }), -/***/ 8952: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var Utils = __nccwpck_require__(5182), - Constants = Utils.Constants; +/***/ 8011: +/***/ ((module) => { -/* The entries in the end of central directory */ -module.exports = function () { - var _volumeEntries = 0, - _totalEntries = 0, - _size = 0, - _offset = 0, - _commentLength = 0; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - return { - get diskEntries() { - return _volumeEntries; - }, - set diskEntries(/*Number*/ val) { - _volumeEntries = _totalEntries = val; - }, +// src/index.ts +var src_exports = {}; +__export(src_exports, { + WaiterState: () => WaiterState, + checkExceptions: () => checkExceptions, + createWaiter: () => createWaiter, + waiterServiceDefaults: () => waiterServiceDefaults +}); +module.exports = __toCommonJS(src_exports); - get totalEntries() { - return _totalEntries; - }, - set totalEntries(/*Number*/ val) { - _totalEntries = _volumeEntries = val; - }, +// src/utils/sleep.ts +var sleep = /* @__PURE__ */ __name((seconds) => { + return new Promise((resolve) => setTimeout(resolve, seconds * 1e3)); +}, "sleep"); - get size() { - return _size; - }, - set size(/*Number*/ val) { - _size = val; - }, +// src/waiter.ts +var waiterServiceDefaults = { + minDelay: 2, + maxDelay: 120 +}; +var WaiterState = /* @__PURE__ */ ((WaiterState2) => { + WaiterState2["ABORTED"] = "ABORTED"; + WaiterState2["FAILURE"] = "FAILURE"; + WaiterState2["SUCCESS"] = "SUCCESS"; + WaiterState2["RETRY"] = "RETRY"; + WaiterState2["TIMEOUT"] = "TIMEOUT"; + return WaiterState2; +})(WaiterState || {}); +var checkExceptions = /* @__PURE__ */ __name((result) => { + if (result.state === "ABORTED" /* ABORTED */) { + const abortError = new Error( + `${JSON.stringify({ + ...result, + reason: "Request was aborted" + })}` + ); + abortError.name = "AbortError"; + throw abortError; + } else if (result.state === "TIMEOUT" /* TIMEOUT */) { + const timeoutError = new Error( + `${JSON.stringify({ + ...result, + reason: "Waiter has timed out" + })}` + ); + timeoutError.name = "TimeoutError"; + throw timeoutError; + } else if (result.state !== "SUCCESS" /* SUCCESS */) { + throw new Error(`${JSON.stringify(result)}`); + } + return result; +}, "checkExceptions"); - get offset() { - return _offset; - }, - set offset(/*Number*/ val) { - _offset = val; - }, +// src/poller.ts +var exponentialBackoffWithJitter = /* @__PURE__ */ __name((minDelay, maxDelay, attemptCeiling, attempt) => { + if (attempt > attemptCeiling) + return maxDelay; + const delay = minDelay * 2 ** (attempt - 1); + return randomInRange(minDelay, delay); +}, "exponentialBackoffWithJitter"); +var randomInRange = /* @__PURE__ */ __name((min, max) => min + Math.random() * (max - min), "randomInRange"); +var runPolling = /* @__PURE__ */ __name(async ({ minDelay, maxDelay, maxWaitTime, abortController, client, abortSignal }, input, acceptorChecks) => { + const observedResponses = {}; + const { state, reason } = await acceptorChecks(client, input); + if (reason) { + const message = createMessageFromResponse(reason); + observedResponses[message] |= 0; + observedResponses[message] += 1; + } + if (state !== "RETRY" /* RETRY */) { + return { state, reason, observedResponses }; + } + let currentAttempt = 1; + const waitUntil = Date.now() + maxWaitTime * 1e3; + const attemptCeiling = Math.log(maxDelay / minDelay) / Math.log(2) + 1; + while (true) { + if (abortController?.signal?.aborted || abortSignal?.aborted) { + const message = "AbortController signal aborted."; + observedResponses[message] |= 0; + observedResponses[message] += 1; + return { state: "ABORTED" /* ABORTED */, observedResponses }; + } + const delay = exponentialBackoffWithJitter(minDelay, maxDelay, attemptCeiling, currentAttempt); + if (Date.now() + delay * 1e3 > waitUntil) { + return { state: "TIMEOUT" /* TIMEOUT */, observedResponses }; + } + await sleep(delay); + const { state: state2, reason: reason2 } = await acceptorChecks(client, input); + if (reason2) { + const message = createMessageFromResponse(reason2); + observedResponses[message] |= 0; + observedResponses[message] += 1; + } + if (state2 !== "RETRY" /* RETRY */) { + return { state: state2, reason: reason2, observedResponses }; + } + currentAttempt += 1; + } +}, "runPolling"); +var createMessageFromResponse = /* @__PURE__ */ __name((reason) => { + if (reason?.$responseBodyText) { + return `Deserialization error for body: ${reason.$responseBodyText}`; + } + if (reason?.$metadata?.httpStatusCode) { + if (reason.$response || reason.message) { + return `${reason.$response.statusCode ?? reason.$metadata.httpStatusCode ?? "Unknown"}: ${reason.message}`; + } + return `${reason.$metadata.httpStatusCode}: OK`; + } + return String(reason?.message ?? JSON.stringify(reason) ?? "Unknown"); +}, "createMessageFromResponse"); - get commentLength() { - return _commentLength; - }, - set commentLength(/*Number*/ val) { - _commentLength = val; - }, +// src/utils/validate.ts +var validateWaiterOptions = /* @__PURE__ */ __name((options) => { + if (options.maxWaitTime <= 0) { + throw new Error(`WaiterConfiguration.maxWaitTime must be greater than 0`); + } else if (options.minDelay <= 0) { + throw new Error(`WaiterConfiguration.minDelay must be greater than 0`); + } else if (options.maxDelay <= 0) { + throw new Error(`WaiterConfiguration.maxDelay must be greater than 0`); + } else if (options.maxWaitTime <= options.minDelay) { + throw new Error( + `WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter` + ); + } else if (options.maxDelay < options.minDelay) { + throw new Error( + `WaiterConfiguration.maxDelay [${options.maxDelay}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter` + ); + } +}, "validateWaiterOptions"); - get mainHeaderSize() { - return Constants.ENDHDR + _commentLength; - }, +// src/createWaiter.ts +var abortTimeout = /* @__PURE__ */ __name((abortSignal) => { + let onAbort; + const promise = new Promise((resolve) => { + onAbort = /* @__PURE__ */ __name(() => resolve({ state: "ABORTED" /* ABORTED */ }), "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + abortSignal.addEventListener("abort", onAbort); + } else { + abortSignal.onabort = onAbort; + } + }); + return { + clearListener() { + if (typeof abortSignal.removeEventListener === "function") { + abortSignal.removeEventListener("abort", onAbort); + } + }, + aborted: promise + }; +}, "abortTimeout"); +var createWaiter = /* @__PURE__ */ __name(async (options, input, acceptorChecks) => { + const params = { + ...waiterServiceDefaults, + ...options + }; + validateWaiterOptions(params); + const exitConditions = [runPolling(params, input, acceptorChecks)]; + const finalize = []; + if (options.abortSignal) { + const { aborted, clearListener } = abortTimeout(options.abortSignal); + finalize.push(clearListener); + exitConditions.push(aborted); + } + if (options.abortController?.signal) { + const { aborted, clearListener } = abortTimeout(options.abortController.signal); + finalize.push(clearListener); + exitConditions.push(aborted); + } + return Promise.race(exitConditions).then((result) => { + for (const fn of finalize) { + fn(); + } + return result; + }); +}, "createWaiter"); +// Annotate the CommonJS export names for ESM import in node: - loadFromBinary: function (/*Buffer*/ data) { - // data should be 22 bytes and start with "PK 05 06" - // or be 56+ bytes and start with "PK 06 06" for Zip64 - if ( - (data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) && - (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG) - ) { - throw Utils.Errors.INVALID_END(); - } +0 && (0); - if (data.readUInt32LE(0) === Constants.ENDSIG) { - // number of entries on this volume - _volumeEntries = data.readUInt16LE(Constants.ENDSUB); - // total number of entries - _totalEntries = data.readUInt16LE(Constants.ENDTOT); - // central directory size in bytes - _size = data.readUInt32LE(Constants.ENDSIZ); - // offset of first CEN header - _offset = data.readUInt32LE(Constants.ENDOFF); - // zip file comment length - _commentLength = data.readUInt16LE(Constants.ENDCOM); - } else { - // number of entries on this volume - _volumeEntries = Utils.readBigUInt64LE(data, Constants.ZIP64SUB); - // total number of entries - _totalEntries = Utils.readBigUInt64LE(data, Constants.ZIP64TOT); - // central directory size in bytes - _size = Utils.readBigUInt64LE(data, Constants.ZIP64SIZE); - // offset of first CEN header - _offset = Utils.readBigUInt64LE(data, Constants.ZIP64OFF); - _commentLength = 0; - } - }, - toBinary: function () { - var b = Buffer.alloc(Constants.ENDHDR + _commentLength); - // "PK 05 06" signature - b.writeUInt32LE(Constants.ENDSIG, 0); - b.writeUInt32LE(0, 4); - // number of entries on this volume - b.writeUInt16LE(_volumeEntries, Constants.ENDSUB); - // total number of entries - b.writeUInt16LE(_totalEntries, Constants.ENDTOT); - // central directory size in bytes - b.writeUInt32LE(_size, Constants.ENDSIZ); - // offset of first CEN header - b.writeUInt32LE(_offset, Constants.ENDOFF); - // zip file comment length - b.writeUInt16LE(_commentLength, Constants.ENDCOM); - // fill comment memory with spaces so no garbage is left there - b.fill(" ", Constants.ENDHDR); +/***/ }), - return b; - }, +/***/ 6761: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - toJSON: function () { - // creates 0x0000 style output - const offset = function (nr, len) { - let offs = nr.toString(16).toUpperCase(); - while (offs.length < len) offs = "0" + offs; - return "0x" + offs; - }; +const Utils = __nccwpck_require__(5182); +const pth = __nccwpck_require__(1017); +const ZipEntry = __nccwpck_require__(4057); +const ZipFile = __nccwpck_require__(7744); - return { - diskEntries: _volumeEntries, - totalEntries: _totalEntries, - size: _size + " bytes", - offset: offset(_offset, 4), - commentLength: _commentLength - }; - }, +const get_Bool = (...val) => Utils.findLast(val, (c) => typeof c === "boolean"); +const get_Str = (...val) => Utils.findLast(val, (c) => typeof c === "string"); +const get_Fun = (...val) => Utils.findLast(val, (c) => typeof c === "function"); - toString: function () { - return JSON.stringify(this.toJSON(), null, "\t"); - } - }; +const defaultOptions = { + // option "noSort" : if true it disables files sorting + noSort: false, + // read entries during load (initial loading may be slower) + readEntries: false, + // default method is none + method: Utils.Constants.NONE, + // file system + fs: null }; -// Misspelled +module.exports = function (/**String*/ input, /** object */ options) { + let inBuffer = null; -/***/ }), + // create object based default options, allowing them to be overwritten + const opts = Object.assign(Object.create(null), defaultOptions); -/***/ 7686: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // test input variable + if (input && "object" === typeof input) { + // if value is not buffer we accept it to be object with options + if (!(input instanceof Uint8Array)) { + Object.assign(opts, input); + input = opts.input ? opts.input : undefined; + if (opts.input) delete opts.input; + } -module.exports = function (/*Buffer*/ inbuf) { - var zlib = __nccwpck_require__(9796); + // if input is buffer + if (Buffer.isBuffer(input)) { + inBuffer = input; + opts.method = Utils.Constants.BUFFER; + input = undefined; + } + } - var opts = { chunkSize: (parseInt(inbuf.length / 1024) + 1) * 1024 }; + // assign options + Object.assign(opts, options); - return { - deflate: function () { - return zlib.deflateRawSync(inbuf, opts); - }, + // instanciate utils filesystem + const filetools = new Utils(opts); - deflateAsync: function (/*Function*/ callback) { - var tmp = zlib.createDeflateRaw(opts), - parts = [], - total = 0; - tmp.on("data", function (data) { - parts.push(data); - total += data.length; - }); - tmp.on("end", function () { - var buf = Buffer.alloc(total), - written = 0; - buf.fill(0); - for (var i = 0; i < parts.length; i++) { - var part = parts[i]; - part.copy(buf, written); - written += part.length; - } - callback && callback(buf); - }); - tmp.end(inbuf); + if (typeof opts.decoder !== "object" || typeof opts.decoder.encode !== "function" || typeof opts.decoder.decode !== "function") { + opts.decoder = Utils.decoder; + } + + // if input is file name we retrieve its content + if (input && "string" === typeof input) { + // load zip file + if (filetools.fs.existsSync(input)) { + opts.method = Utils.Constants.FILE; + opts.filename = input; + inBuffer = filetools.fs.readFileSync(input); + } else { + throw Utils.Errors.INVALID_FILENAME(); } - }; -}; + } + // create variable + const _zip = new ZipFile(inBuffer, opts); -/***/ }), + const { canonical, sanitize, zipnamefix } = Utils; -/***/ 3928: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + function getEntry(/**Object*/ entry) { + if (entry && _zip) { + var item; + // If entry was given as a file name + if (typeof entry === "string") item = _zip.getEntry(pth.posix.normalize(entry)); + // if entry was given as a ZipEntry object + if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") item = _zip.getEntry(entry.entryName); -exports.Deflater = __nccwpck_require__(7686); -exports.Inflater = __nccwpck_require__(2153); -exports.ZipCrypto = __nccwpck_require__(3228); + if (item) { + return item; + } + } + return null; + } + function fixPath(zipPath) { + const { join, normalize, sep } = pth.posix; + // convert windows file separators and normalize + return join(".", normalize(sep + zipPath.split("\\").join(sep) + sep)); + } -/***/ }), + function filenameFilter(filterfn) { + if (filterfn instanceof RegExp) { + // if filter is RegExp wrap it + return (function (rx) { + return function (filename) { + return rx.test(filename); + }; + })(filterfn); + } else if ("function" !== typeof filterfn) { + // if filter is not function we will replace it + return () => true; + } + return filterfn; + } -/***/ 2153: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // keep last character on folders + const relativePath = (local, entry) => { + let lastChar = entry.slice(-1); + lastChar = lastChar === filetools.sep ? filetools.sep : ""; + return pth.relative(local, entry) + lastChar; + }; -const version = +(process.versions ? process.versions.node : "").split(".")[0] || 0; + return { + /** + * Extracts the given entry from the archive and returns the content as a Buffer object + * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry + * @param {Buffer|string} [pass] - password + * @return Buffer or Null in case of error + */ + readFile: function (entry, pass) { + var item = getEntry(entry); + return (item && item.getData(pass)) || null; + }, -module.exports = function (/*Buffer*/ inbuf, /*number*/ expectedLength) { - var zlib = __nccwpck_require__(9796); - const option = version >= 15 && expectedLength > 0 ? { maxOutputLength: expectedLength } : {}; + /** + * Returns how many child elements has on entry (directories) on files it is always 0 + * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry + * @returns {integer} + */ + childCount: function (entry) { + const item = getEntry(entry); + if (item) { + return _zip.getChildCount(item); + } + }, - return { - inflate: function () { - return zlib.inflateRawSync(inbuf, option); + /** + * Asynchronous readFile + * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry + * @param {callback} callback + * + * @return Buffer or Null in case of error + */ + readFileAsync: function (entry, callback) { + var item = getEntry(entry); + if (item) { + item.getDataAsync(callback); + } else { + callback(null, "getEntry failed for:" + entry); + } }, - inflateAsync: function (/*Function*/ callback) { - var tmp = zlib.createInflateRaw(option), - parts = [], - total = 0; - tmp.on("data", function (data) { - parts.push(data); - total += data.length; - }); - tmp.on("end", function () { - var buf = Buffer.alloc(total), - written = 0; - buf.fill(0); - for (var i = 0; i < parts.length; i++) { - var part = parts[i]; - part.copy(buf, written); - written += part.length; + /** + * Extracts the given entry from the archive and returns the content as plain text in the given encoding + * @param {ZipEntry|string} entry - ZipEntry object or String with the full path of the entry + * @param {string} encoding - Optional. If no encoding is specified utf8 is used + * + * @return String + */ + readAsText: function (entry, encoding) { + var item = getEntry(entry); + if (item) { + var data = item.getData(); + if (data && data.length) { + return data.toString(encoding || "utf8"); } - callback && callback(buf); - }); - tmp.end(inbuf); - } - }; -}; - - -/***/ }), + } + return ""; + }, -/***/ 3228: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Asynchronous readAsText + * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry + * @param {callback} callback + * @param {string} [encoding] - Optional. If no encoding is specified utf8 is used + * + * @return String + */ + readAsTextAsync: function (entry, callback, encoding) { + var item = getEntry(entry); + if (item) { + item.getDataAsync(function (data, err) { + if (err) { + callback(data, err); + return; + } -"use strict"; + if (data && data.length) { + callback(data.toString(encoding || "utf8")); + } else { + callback(""); + } + }); + } else { + callback(""); + } + }, + /** + * Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory + * + * @param {ZipEntry|string} entry + * @returns {void} + */ + deleteFile: function (entry, withsubfolders = true) { + // @TODO: test deleteFile + var item = getEntry(entry); + if (item) { + _zip.deleteFile(item.entryName, withsubfolders); + } + }, -// node crypt, we use it for generate salt -// eslint-disable-next-line node/no-unsupported-features/node-builtins -const { randomFillSync } = __nccwpck_require__(6113); -const Errors = __nccwpck_require__(1255); + /** + * Remove the entry from the file or directory without affecting any nested entries + * + * @param {ZipEntry|string} entry + * @returns {void} + */ + deleteEntry: function (entry) { + // @TODO: test deleteEntry + var item = getEntry(entry); + if (item) { + _zip.deleteEntry(item.entryName); + } + }, -// generate CRC32 lookup table -const crctable = new Uint32Array(256).map((t, crc) => { - for (let j = 0; j < 8; j++) { - if (0 !== (crc & 1)) { - crc = (crc >>> 1) ^ 0xedb88320; - } else { - crc >>>= 1; - } - } - return crc >>> 0; -}); + /** + * Adds a comment to the zip. The zip must be rewritten after adding the comment. + * + * @param {string} comment + */ + addZipComment: function (comment) { + // @TODO: test addZipComment + _zip.comment = comment; + }, -// C-style uInt32 Multiply (discards higher bits, when JS multiply discards lower bits) -const uMul = (a, b) => Math.imul(a, b) >>> 0; + /** + * Returns the zip comment + * + * @return String + */ + getZipComment: function () { + return _zip.comment || ""; + }, -// crc32 byte single update (actually same function is part of utils.crc32 function :) ) -const crc32update = (pCrc32, bval) => { - return crctable[(pCrc32 ^ bval) & 0xff] ^ (pCrc32 >>> 8); -}; + /** + * Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment + * The comment cannot exceed 65535 characters in length + * + * @param {ZipEntry} entry + * @param {string} comment + */ + addZipEntryComment: function (entry, comment) { + var item = getEntry(entry); + if (item) { + item.comment = comment; + } + }, -// function for generating salt for encrytion header -const genSalt = () => { - if ("function" === typeof randomFillSync) { - return randomFillSync(Buffer.alloc(12)); - } else { - // fallback if function is not defined - return genSalt.node(); - } -}; + /** + * Returns the comment of the specified entry + * + * @param {ZipEntry} entry + * @return String + */ + getZipEntryComment: function (entry) { + var item = getEntry(entry); + if (item) { + return item.comment || ""; + } + return ""; + }, -// salt generation with node random function (mainly as fallback) -genSalt.node = () => { - const salt = Buffer.alloc(12); - const len = salt.length; - for (let i = 0; i < len; i++) salt[i] = (Math.random() * 256) & 0xff; - return salt; -}; + /** + * Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content + * + * @param {ZipEntry} entry + * @param {Buffer} content + */ + updateFile: function (entry, content) { + var item = getEntry(entry); + if (item) { + item.setData(content); + } + }, -// general config -const config = { - genSalt -}; + /** + * Adds a file from the disk to the archive + * + * @param {string} localPath File to add to zip + * @param {string} [zipPath] Optional path inside the zip + * @param {string} [zipName] Optional name for the file + * @param {string} [comment] Optional file comment + */ + addLocalFile: function (localPath, zipPath, zipName, comment) { + if (filetools.fs.existsSync(localPath)) { + // fix ZipPath + zipPath = zipPath ? fixPath(zipPath) : ""; -// Class Initkeys handles same basic ops with keys -function Initkeys(pw) { - const pass = Buffer.isBuffer(pw) ? pw : Buffer.from(pw); - this.keys = new Uint32Array([0x12345678, 0x23456789, 0x34567890]); - for (let i = 0; i < pass.length; i++) { - this.updateKeys(pass[i]); - } -} + // p - local file name + const p = pth.win32.basename(pth.win32.normalize(localPath)); -Initkeys.prototype.updateKeys = function (byteValue) { - const keys = this.keys; - keys[0] = crc32update(keys[0], byteValue); - keys[1] += keys[0] & 0xff; - keys[1] = uMul(keys[1], 134775813) + 1; - keys[2] = crc32update(keys[2], keys[1] >>> 24); - return byteValue; -}; + // add file name into zippath + zipPath += zipName ? zipName : p; -Initkeys.prototype.next = function () { - const k = (this.keys[2] | 2) >>> 0; // key - return (uMul(k, k ^ 1) >> 8) & 0xff; // decode -}; + // read file attributes + const _attr = filetools.fs.statSync(localPath); -function make_decrypter(/*Buffer*/ pwd) { - // 1. Stage initialize key - const keys = new Initkeys(pwd); + // get file content + const data = _attr.isFile() ? filetools.fs.readFileSync(localPath) : Buffer.alloc(0); - // return decrypter function - return function (/*Buffer*/ data) { - // result - we create new Buffer for results - const result = Buffer.alloc(data.length); - let pos = 0; - // process input data - for (let c of data) { - //c ^= keys.next(); - //result[pos++] = c; // decode & Save Value - result[pos++] = keys.updateKeys(c ^ keys.next()); // update keys with decoded byte - } - return result; - }; -} + // if folder + if (_attr.isDirectory()) zipPath += filetools.sep; -function make_encrypter(/*Buffer*/ pwd) { - // 1. Stage initialize key - const keys = new Initkeys(pwd); + // add file into zip file + this.addFile(zipPath, data, comment, _attr); + } else { + throw Utils.Errors.FILE_NOT_FOUND(localPath); + } + }, - // return encrypting function, result and pos is here so we dont have to merge buffers later - return function (/*Buffer*/ data, /*Buffer*/ result, /* Number */ pos = 0) { - // result - we create new Buffer for results - if (!result) result = Buffer.alloc(data.length); - // process input data - for (let c of data) { - const k = keys.next(); // save key byte - result[pos++] = c ^ k; // save val - keys.updateKeys(c); // update keys with decoded byte - } - return result; - }; -} + /** + * Callback for showing if everything was done. + * + * @callback doneCallback + * @param {Error} err - Error object + * @param {boolean} done - was request fully completed + */ -function decrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd) { - if (!data || !Buffer.isBuffer(data) || data.length < 12) { - return Buffer.alloc(0); - } + /** + * Adds a file from the disk to the archive + * + * @param {(object|string)} options - options object, if it is string it us used as localPath. + * @param {string} options.localPath - Local path to the file. + * @param {string} [options.comment] - Optional file comment. + * @param {string} [options.zipPath] - Optional path inside the zip + * @param {string} [options.zipName] - Optional name for the file + * @param {doneCallback} callback - The callback that handles the response. + */ + addLocalFileAsync: function (options, callback) { + options = typeof options === "object" ? options : { localPath: options }; + const localPath = pth.resolve(options.localPath); + const { comment } = options; + let { zipPath, zipName } = options; + const self = this; - // 1. We Initialize and generate decrypting function - const decrypter = make_decrypter(pwd); + filetools.fs.stat(localPath, function (err, stats) { + if (err) return callback(err, false); + // fix ZipPath + zipPath = zipPath ? fixPath(zipPath) : ""; + // p - local file name + const p = pth.win32.basename(pth.win32.normalize(localPath)); + // add file name into zippath + zipPath += zipName ? zipName : p; - // 2. decrypt salt what is always 12 bytes and is a part of file content - const salt = decrypter(data.slice(0, 12)); + if (stats.isFile()) { + filetools.fs.readFile(localPath, function (err, data) { + if (err) return callback(err, false); + self.addFile(zipPath, data, comment, stats); + return setImmediate(callback, undefined, true); + }); + } else if (stats.isDirectory()) { + zipPath += filetools.sep; + self.addFile(zipPath, Buffer.alloc(0), comment, stats); + return setImmediate(callback, undefined, true); + } + }); + }, - // if bit 3 (0x08) of the general-purpose flags field is set, check salt[11] with the high byte of the header time - // 2 byte data block (as per Info-Zip spec), otherwise check with the high byte of the header entry - const verifyByte = (header.flags & 0x8) === 0x8 ? header.timeHighByte : header.crc >>> 24; + /** + * Adds a local directory and all its nested files and directories to the archive + * + * @param {string} localPath - local path to the folder + * @param {string} [zipPath] - optional path inside zip + * @param {(RegExp|function)} [filter] - optional RegExp or Function if files match will be included. + */ + addLocalFolder: function (localPath, zipPath, filter) { + // Prepare filter + filter = filenameFilter(filter); - //3. does password meet expectations - if (salt[11] !== verifyByte) { - throw Errors.WRONG_PASSWORD(); - } + // fix ZipPath + zipPath = zipPath ? fixPath(zipPath) : ""; - // 4. decode content - return decrypter(data.slice(12)); -} + // normalize the path first + localPath = pth.normalize(localPath); -// lets add way to populate salt, NOT RECOMMENDED for production but maybe useful for testing general functionality -function _salter(data) { - if (Buffer.isBuffer(data) && data.length >= 12) { - // be aware - currently salting buffer data is modified - config.genSalt = function () { - return data.slice(0, 12); - }; - } else if (data === "node") { - // test salt generation with node random function - config.genSalt = genSalt.node; - } else { - // if value is not acceptable config gets reset. - config.genSalt = genSalt; - } -} + if (filetools.fs.existsSync(localPath)) { + const items = filetools.findFiles(localPath); + const self = this; -function encrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd, /*Boolean*/ oldlike = false) { - // 1. test data if data is not Buffer we make buffer from it - if (data == null) data = Buffer.alloc(0); - // if data is not buffer be make buffer from it - if (!Buffer.isBuffer(data)) data = Buffer.from(data.toString()); + if (items.length) { + for (const filepath of items) { + const p = pth.join(zipPath, relativePath(localPath, filepath)); + if (filter(p)) { + self.addLocalFile(filepath, pth.dirname(p)); + } + } + } + } else { + throw Utils.Errors.FILE_NOT_FOUND(localPath); + } + }, - // 2. We Initialize and generate encrypting function - const encrypter = make_encrypter(pwd); + /** + * Asynchronous addLocalFolder + * @param {string} localPath + * @param {callback} callback + * @param {string} [zipPath] optional path inside zip + * @param {RegExp|function} [filter] optional RegExp or Function if files match will + * be included. + */ + addLocalFolderAsync: function (localPath, callback, zipPath, filter) { + // Prepare filter + filter = filenameFilter(filter); - // 3. generate salt (12-bytes of random data) - const salt = config.genSalt(); - salt[11] = (header.crc >>> 24) & 0xff; + // fix ZipPath + zipPath = zipPath ? fixPath(zipPath) : ""; - // old implementations (before PKZip 2.04g) used two byte check - if (oldlike) salt[10] = (header.crc >>> 16) & 0xff; + // normalize the path first + localPath = pth.normalize(localPath); - // 4. create output - const result = Buffer.alloc(data.length + 12); - encrypter(salt, result); + var self = this; + filetools.fs.open(localPath, "r", function (err) { + if (err && err.code === "ENOENT") { + callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath)); + } else if (err) { + callback(undefined, err); + } else { + var items = filetools.findFiles(localPath); + var i = -1; - // finally encode content - return encrypter(data, result, 12); -} + var next = function () { + i += 1; + if (i < items.length) { + var filepath = items[i]; + var p = relativePath(localPath, filepath).split("\\").join("/"); //windows fix + p = p + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") + .replace(/[^\x20-\x7E]/g, ""); // accent fix + if (filter(p)) { + filetools.fs.stat(filepath, function (er0, stats) { + if (er0) callback(undefined, er0); + if (stats.isFile()) { + filetools.fs.readFile(filepath, function (er1, data) { + if (er1) { + callback(undefined, er1); + } else { + self.addFile(zipPath + p, data, "", stats); + next(); + } + }); + } else { + self.addFile(zipPath + p + "/", Buffer.alloc(0), "", stats); + next(); + } + }); + } else { + process.nextTick(() => { + next(); + }); + } + } else { + callback(true, undefined); + } + }; -module.exports = { decrypt, encrypt, _salter }; + next(); + } + }); + }, + /** + * Adds a local directory and all its nested files and directories to the archive + * + * @param {object | string} options - options object, if it is string it us used as localPath. + * @param {string} options.localPath - Local path to the folder. + * @param {string} [options.zipPath] - optional path inside zip. + * @param {RegExp|function} [options.filter] - optional RegExp or Function if files match will be included. + * @param {function|string} [options.namefix] - optional function to help fix filename + * @param {doneCallback} callback - The callback that handles the response. + * + */ + addLocalFolderAsync2: function (options, callback) { + const self = this; + options = typeof options === "object" ? options : { localPath: options }; + localPath = pth.resolve(fixPath(options.localPath)); + let { zipPath, filter, namefix } = options; -/***/ }), + if (filter instanceof RegExp) { + filter = (function (rx) { + return function (filename) { + return rx.test(filename); + }; + })(filter); + } else if ("function" !== typeof filter) { + filter = function () { + return true; + }; + } -/***/ 4522: -/***/ ((module) => { + // fix ZipPath + zipPath = zipPath ? fixPath(zipPath) : ""; -module.exports = { - /* The local file header */ - LOCHDR : 30, // LOC header size - LOCSIG : 0x04034b50, // "PK\003\004" - LOCVER : 4, // version needed to extract - LOCFLG : 6, // general purpose bit flag - LOCHOW : 8, // compression method - LOCTIM : 10, // modification time (2 bytes time, 2 bytes date) - LOCCRC : 14, // uncompressed file crc-32 value - LOCSIZ : 18, // compressed size - LOCLEN : 22, // uncompressed size - LOCNAM : 26, // filename length - LOCEXT : 28, // extra field length + // Check Namefix function + if (namefix == "latin1") { + namefix = (str) => + str + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") + .replace(/[^\x20-\x7E]/g, ""); // accent fix (latin1 characers only) + } - /* The Data descriptor */ - EXTSIG : 0x08074b50, // "PK\007\008" - EXTHDR : 16, // EXT header size - EXTCRC : 4, // uncompressed file crc-32 value - EXTSIZ : 8, // compressed size - EXTLEN : 12, // uncompressed size + if (typeof namefix !== "function") namefix = (str) => str; - /* The central directory file header */ - CENHDR : 46, // CEN header size - CENSIG : 0x02014b50, // "PK\001\002" - CENVEM : 4, // version made by - CENVER : 6, // version needed to extract - CENFLG : 8, // encrypt, decrypt flags - CENHOW : 10, // compression method - CENTIM : 12, // modification time (2 bytes time, 2 bytes date) - CENCRC : 16, // uncompressed file crc-32 value - CENSIZ : 20, // compressed size - CENLEN : 24, // uncompressed size - CENNAM : 28, // filename length - CENEXT : 30, // extra field length - CENCOM : 32, // file comment length - CENDSK : 34, // volume number start - CENATT : 36, // internal file attributes - CENATX : 38, // external file attributes (host system dependent) - CENOFF : 42, // LOC header offset + // internal, create relative path + fix the name + const relPathFix = (entry) => pth.join(zipPath, namefix(relativePath(localPath, entry))); + const fileNameFix = (entry) => pth.win32.basename(pth.win32.normalize(namefix(entry))); - /* The entries in the end of central directory */ - ENDHDR : 22, // END header size - ENDSIG : 0x06054b50, // "PK\005\006" - ENDSUB : 8, // number of entries on this disk - ENDTOT : 10, // total number of entries - ENDSIZ : 12, // central directory size in bytes - ENDOFF : 16, // offset of first CEN header - ENDCOM : 20, // zip file comment length + filetools.fs.open(localPath, "r", function (err) { + if (err && err.code === "ENOENT") { + callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath)); + } else if (err) { + callback(undefined, err); + } else { + filetools.findFilesAsync(localPath, function (err, fileEntries) { + if (err) return callback(err); + fileEntries = fileEntries.filter((dir) => filter(relPathFix(dir))); + if (!fileEntries.length) callback(undefined, false); - END64HDR : 20, // zip64 END header size - END64SIG : 0x07064b50, // zip64 Locator signature, "PK\006\007" - END64START : 4, // number of the disk with the start of the zip64 - END64OFF : 8, // relative offset of the zip64 end of central directory - END64NUMDISKS : 16, // total number of disks + setImmediate( + fileEntries.reverse().reduce(function (next, entry) { + return function (err, done) { + if (err || done === false) return setImmediate(next, err, false); - ZIP64SIG : 0x06064b50, // zip64 signature, "PK\006\006" - ZIP64HDR : 56, // zip64 record minimum size - ZIP64LEAD : 12, // leading bytes at the start of the record, not counted by the value stored in ZIP64SIZE - ZIP64SIZE : 4, // zip64 size of the central directory record - ZIP64VEM : 12, // zip64 version made by - ZIP64VER : 14, // zip64 version needed to extract - ZIP64DSK : 16, // zip64 number of this disk - ZIP64DSKDIR : 20, // number of the disk with the start of the record directory - ZIP64SUB : 24, // number of entries on this disk - ZIP64TOT : 32, // total number of entries - ZIP64SIZB : 40, // zip64 central directory size in bytes - ZIP64OFF : 48, // offset of start of central directory with respect to the starting disk number - ZIP64EXTRA : 56, // extensible data sector + self.addLocalFileAsync( + { + localPath: entry, + zipPath: pth.dirname(relPathFix(entry)), + zipName: fileNameFix(entry) + }, + next + ); + }; + }, callback) + ); + }); + } + }); + }, - /* Compression methods */ - STORED : 0, // no compression - SHRUNK : 1, // shrunk - REDUCED1 : 2, // reduced with compression factor 1 - REDUCED2 : 3, // reduced with compression factor 2 - REDUCED3 : 4, // reduced with compression factor 3 - REDUCED4 : 5, // reduced with compression factor 4 - IMPLODED : 6, // imploded - // 7 reserved for Tokenizing compression algorithm - DEFLATED : 8, // deflated - ENHANCED_DEFLATED: 9, // enhanced deflated - PKWARE : 10,// PKWare DCL imploded - // 11 reserved by PKWARE - BZIP2 : 12, // compressed using BZIP2 - // 13 reserved by PKWARE - LZMA : 14, // LZMA - // 15-17 reserved by PKWARE - IBM_TERSE : 18, // compressed using IBM TERSE - IBM_LZ77 : 19, // IBM LZ77 z - AES_ENCRYPT : 99, // WinZIP AES encryption method + /** + * Adds a local directory and all its nested files and directories to the archive + * + * @param {string} localPath - path where files will be extracted + * @param {object} props - optional properties + * @param {string} [props.zipPath] - optional path inside zip + * @param {RegExp|function} [props.filter] - optional RegExp or Function if files match will be included. + * @param {function|string} [props.namefix] - optional function to help fix filename + */ + addLocalFolderPromise: function (localPath, props) { + return new Promise((resolve, reject) => { + this.addLocalFolderAsync2(Object.assign({ localPath }, props), (err, done) => { + if (err) reject(err); + if (done) resolve(this); + }); + }); + }, - /* General purpose bit flag */ - // values can obtained with expression 2**bitnr - FLG_ENC : 1, // Bit 0: encrypted file - FLG_COMP1 : 2, // Bit 1, compression option - FLG_COMP2 : 4, // Bit 2, compression option - FLG_DESC : 8, // Bit 3, data descriptor - FLG_ENH : 16, // Bit 4, enhanced deflating - FLG_PATCH : 32, // Bit 5, indicates that the file is compressed patched data. - FLG_STR : 64, // Bit 6, strong encryption (patented) - // Bits 7-10: Currently unused. - FLG_EFS : 2048, // Bit 11: Language encoding flag (EFS) - // Bit 12: Reserved by PKWARE for enhanced compression. - // Bit 13: encrypted the Central Directory (patented). - // Bits 14-15: Reserved by PKWARE. - FLG_MSK : 4096, // mask header values + /** + * Allows you to create a entry (file or directory) in the zip file. + * If you want to create a directory the entryName must end in / and a null buffer should be provided. + * Comment and attributes are optional + * + * @param {string} entryName + * @param {Buffer | string} content - file content as buffer or utf8 coded string + * @param {string} [comment] - file comment + * @param {number | object} [attr] - number as unix file permissions, object as filesystem Stats object + */ + addFile: function (entryName, content, comment, attr) { + entryName = zipnamefix(entryName); + let entry = getEntry(entryName); + const update = entry != null; - /* Load type */ - FILE : 2, - BUFFER : 1, - NONE : 0, + // prepare new entry + if (!update) { + entry = new ZipEntry(opts); + entry.entryName = entryName; + } + entry.comment = comment || ""; - /* 4.5 Extensible data fields */ - EF_ID : 0, - EF_SIZE : 2, + const isStat = "object" === typeof attr && attr instanceof filetools.fs.Stats; - /* Header IDs */ - ID_ZIP64 : 0x0001, - ID_AVINFO : 0x0007, - ID_PFS : 0x0008, - ID_OS2 : 0x0009, - ID_NTFS : 0x000a, - ID_OPENVMS : 0x000c, - ID_UNIX : 0x000d, - ID_FORK : 0x000e, - ID_PATCH : 0x000f, - ID_X509_PKCS7 : 0x0014, - ID_X509_CERTID_F : 0x0015, - ID_X509_CERTID_C : 0x0016, - ID_STRONGENC : 0x0017, - ID_RECORD_MGT : 0x0018, - ID_X509_PKCS7_RL : 0x0019, - ID_IBM1 : 0x0065, - ID_IBM2 : 0x0066, - ID_POSZIP : 0x4690, + // last modification time from file stats + if (isStat) { + entry.header.time = attr.mtime; + } - EF_ZIP64_OR_32 : 0xffffffff, - EF_ZIP64_OR_16 : 0xffff, - EF_ZIP64_SUNCOMP : 0, - EF_ZIP64_SCOMP : 8, - EF_ZIP64_RHO : 16, - EF_ZIP64_DSN : 24 -}; + // Set file attribute + var fileattr = entry.isDirectory ? 0x10 : 0; // (MS-DOS directory flag) + // extended attributes field for Unix + // set file type either S_IFDIR / S_IFREG + let unix = entry.isDirectory ? 0x4000 : 0x8000; -/***/ }), + if (isStat) { + // File attributes from file stats + unix |= 0xfff & attr.mode; + } else if ("number" === typeof attr) { + // attr from given attr values + unix |= 0xfff & attr; + } else { + // Default values: + unix |= entry.isDirectory ? 0o755 : 0o644; // permissions (drwxr-xr-x) or (-r-wr--r--) + } -/***/ 7396: -/***/ ((module) => { + fileattr = (fileattr | (unix << 16)) >>> 0; // add attributes -module.exports = { - efs: true, - encode: (data) => Buffer.from(data, "utf8"), - decode: (data) => data.toString("utf8") -}; + entry.attr = fileattr; + entry.setData(content); + if (!update) _zip.setEntry(entry); -/***/ }), + return entry; + }, -/***/ 1255: -/***/ ((__unused_webpack_module, exports) => { + /** + * Returns an array of ZipEntry objects representing the files and folders inside the archive + * + * @param {string} [password] + * @returns Array + */ + getEntries: function (password) { + _zip.password = password; + return _zip ? _zip.entries : []; + }, -const errors = { - /* Header error messages */ - INVALID_LOC: "Invalid LOC header (bad signature)", - INVALID_CEN: "Invalid CEN header (bad signature)", - INVALID_END: "Invalid END header (bad signature)", + /** + * Returns a ZipEntry object representing the file or folder specified by ``name``. + * + * @param {string} name + * @return ZipEntry + */ + getEntry: function (/**String*/ name) { + return getEntry(name); + }, - /* Descriptor */ - DESCRIPTOR_NOT_EXIST: "No descriptor present", - DESCRIPTOR_UNKNOWN: "Unknown descriptor format", - DESCRIPTOR_FAULTY: "Descriptor data is malformed", + getEntryCount: function () { + return _zip.getEntryCount(); + }, - /* ZipEntry error messages*/ - NO_DATA: "Nothing to decompress", - BAD_CRC: "CRC32 checksum failed {0}", - FILE_IN_THE_WAY: "There is a file in the way: {0}", - UNKNOWN_METHOD: "Invalid/unsupported compression method", + forEach: function (callback) { + return _zip.forEach(callback); + }, - /* Inflater error messages */ - AVAIL_DATA: "inflate::Available inflate data did not terminate", - INVALID_DISTANCE: "inflate::Invalid literal/length or distance code in fixed or dynamic block", - TO_MANY_CODES: "inflate::Dynamic block code description: too many length or distance codes", - INVALID_REPEAT_LEN: "inflate::Dynamic block code description: repeat more than specified lengths", - INVALID_REPEAT_FIRST: "inflate::Dynamic block code description: repeat lengths with no first length", - INCOMPLETE_CODES: "inflate::Dynamic block code description: code lengths codes incomplete", - INVALID_DYN_DISTANCE: "inflate::Dynamic block code description: invalid distance code lengths", - INVALID_CODES_LEN: "inflate::Dynamic block code description: invalid literal/length code lengths", - INVALID_STORE_BLOCK: "inflate::Stored block length did not match one's complement", - INVALID_BLOCK_TYPE: "inflate::Invalid block type (type == 3)", + /** + * Extracts the given entry to the given targetPath + * If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted + * + * @param {string|ZipEntry} entry - ZipEntry object or String with the full path of the entry + * @param {string} targetPath - Target folder where to write the file + * @param {boolean} [maintainEntryPath=true] - If maintainEntryPath is true and the entry is inside a folder, the entry folder will be created in targetPath as well. Default is TRUE + * @param {boolean} [overwrite=false] - If the file already exists at the target path, the file will be overwriten if this is true. + * @param {boolean} [keepOriginalPermission=false] - The file will be set as the permission from the entry if this is true. + * @param {string} [outFileName] - String If set will override the filename of the extracted file (Only works if the entry is a file) + * + * @return Boolean + */ + extractEntryTo: function (entry, targetPath, maintainEntryPath, overwrite, keepOriginalPermission, outFileName) { + overwrite = get_Bool(false, overwrite); + keepOriginalPermission = get_Bool(false, keepOriginalPermission); + maintainEntryPath = get_Bool(true, maintainEntryPath); + outFileName = get_Str(keepOriginalPermission, outFileName); - /* ADM-ZIP error messages */ - CANT_EXTRACT_FILE: "Could not extract the file", - CANT_OVERRIDE: "Target file already exists", - DISK_ENTRY_TOO_LARGE: "Number of disk entries is too large", - NO_ZIP: "No zip file was loaded", - NO_ENTRY: "Entry doesn't exist", - DIRECTORY_CONTENT_ERROR: "A directory cannot have content", - FILE_NOT_FOUND: 'File not found: "{0}"', - NOT_IMPLEMENTED: "Not implemented", - INVALID_FILENAME: "Invalid filename", - INVALID_FORMAT: "Invalid or unsupported zip format. No END header found", - INVALID_PASS_PARAM: "Incompatible password parameter", - WRONG_PASSWORD: "Wrong Password", + var item = getEntry(entry); + if (!item) { + throw Utils.Errors.NO_ENTRY(); + } - /* ADM-ZIP */ - COMMENT_TOO_LONG: "Comment is too long", // Comment can be max 65535 bytes long (NOTE: some non-US characters may take more space) - EXTRA_FIELD_PARSE_ERROR: "Extra field parsing error" -}; + var entryName = canonical(item.entryName); -// template -function E(message) { - return function (...args) { - if (args.length) { // Allow {0} .. {9} arguments in error message, based on argument number - message = message.replace(/\{(\d)\}/g, (_, n) => args[n] || ''); - } + var target = sanitize(targetPath, outFileName && !item.isDirectory ? outFileName : maintainEntryPath ? entryName : pth.basename(entryName)); - return new Error('ADM-ZIP: ' + message); - }; -} + if (item.isDirectory) { + var children = _zip.getEntryChildren(item); + children.forEach(function (child) { + if (child.isDirectory) return; + var content = child.getData(); + if (!content) { + throw Utils.Errors.CANT_EXTRACT_FILE(); + } + var name = canonical(child.entryName); + var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name)); + // The reverse operation for attr depend on method addFile() + const fileAttr = keepOriginalPermission ? child.header.fileAttr : undefined; + filetools.writeFileTo(childName, content, overwrite, fileAttr); + }); + return true; + } -// Init errors with template -for (const msg of Object.keys(errors)) { - exports[msg] = E(errors[msg]); -} + var content = item.getData(_zip.password); + if (!content) throw Utils.Errors.CANT_EXTRACT_FILE(); + if (filetools.fs.existsSync(target) && !overwrite) { + throw Utils.Errors.CANT_OVERRIDE(); + } + // The reverse operation for attr depend on method addFile() + const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; + filetools.writeFileTo(target, content, overwrite, fileAttr); -/***/ }), + return true; + }, -/***/ 5781: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Test the archive + * @param {string} [pass] + */ + test: function (pass) { + if (!_zip) { + return false; + } -const pth = __nccwpck_require__(1017); + for (var entry in _zip.entries) { + try { + if (entry.isDirectory) { + continue; + } + var content = _zip.entries[entry].getData(pass); + if (!content) { + return false; + } + } catch (err) { + return false; + } + } + return true; + }, -module.exports = function (/*String*/ path, /*Utils object*/ { fs }) { - var _path = path || "", - _obj = newAttr(), - _stat = null; + /** + * Extracts the entire archive to the given location + * + * @param {string} targetPath Target location + * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true. + * Default is FALSE + * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true. + * Default is FALSE + * @param {string|Buffer} [pass] password + */ + extractAllTo: function (targetPath, overwrite, keepOriginalPermission, pass) { + keepOriginalPermission = get_Bool(false, keepOriginalPermission); + pass = get_Str(keepOriginalPermission, pass); + overwrite = get_Bool(false, overwrite); + if (!_zip) throw Utils.Errors.NO_ZIP(); - function newAttr() { - return { - directory: false, - readonly: false, - hidden: false, - executable: false, - mtime: 0, - atime: 0 - }; - } + _zip.entries.forEach(function (entry) { + var entryName = sanitize(targetPath, canonical(entry.entryName)); + if (entry.isDirectory) { + filetools.makeDir(entryName); + return; + } + var content = entry.getData(pass); + if (!content) { + throw Utils.Errors.CANT_EXTRACT_FILE(); + } + // The reverse operation for attr depend on method addFile() + const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; + filetools.writeFileTo(entryName, content, overwrite, fileAttr); + try { + filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time); + } catch (err) { + throw Utils.Errors.CANT_EXTRACT_FILE(); + } + }); + }, - if (_path && fs.existsSync(_path)) { - _stat = fs.statSync(_path); - _obj.directory = _stat.isDirectory(); - _obj.mtime = _stat.mtime; - _obj.atime = _stat.atime; - _obj.executable = (0o111 & _stat.mode) !== 0; // file is executable who ever har right not just owner - _obj.readonly = (0o200 & _stat.mode) === 0; // readonly if owner has no write right - _obj.hidden = pth.basename(_path)[0] === "."; - } else { - console.warn("Invalid path: " + _path); - } + /** + * Asynchronous extractAllTo + * + * @param {string} targetPath Target location + * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true. + * Default is FALSE + * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true. + * Default is FALSE + * @param {function} callback The callback will be executed when all entries are extracted successfully or any error is thrown. + */ + extractAllToAsync: function (targetPath, overwrite, keepOriginalPermission, callback) { + callback = get_Fun(overwrite, keepOriginalPermission, callback); + keepOriginalPermission = get_Bool(false, keepOriginalPermission); + overwrite = get_Bool(false, overwrite); + if (!callback) { + return new Promise((resolve, reject) => { + this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function (err) { + if (err) { + reject(err); + } else { + resolve(this); + } + }); + }); + } + if (!_zip) { + callback(Utils.Errors.NO_ZIP()); + return; + } - return { - get directory() { - return _obj.directory; + targetPath = pth.resolve(targetPath); + // convert entryName to + const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName))); + const getError = (msg, file) => new Error(msg + ': "' + file + '"'); + + // separate directories from files + const dirEntries = []; + const fileEntries = []; + _zip.entries.forEach((e) => { + if (e.isDirectory) { + dirEntries.push(e); + } else { + fileEntries.push(e); + } + }); + + // Create directory entries first synchronously + // this prevents race condition and assures folders are there before writing files + for (const entry of dirEntries) { + const dirPath = getPath(entry); + // The reverse operation for attr depend on method addFile() + const dirAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; + try { + filetools.makeDir(dirPath); + if (dirAttr) filetools.fs.chmodSync(dirPath, dirAttr); + // in unix timestamp will change if files are later added to folder, but still + filetools.fs.utimesSync(dirPath, entry.header.time, entry.header.time); + } catch (er) { + callback(getError("Unable to create folder", dirPath)); + } + } + + fileEntries.reverse().reduce(function (next, entry) { + return function (err) { + if (err) { + next(err); + } else { + const entryName = pth.normalize(canonical(entry.entryName)); + const filePath = sanitize(targetPath, entryName); + entry.getDataAsync(function (content, err_1) { + if (err_1) { + next(err_1); + } else if (!content) { + next(Utils.Errors.CANT_EXTRACT_FILE()); + } else { + // The reverse operation for attr depend on method addFile() + const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; + filetools.writeFileToAsync(filePath, content, overwrite, fileAttr, function (succ) { + if (!succ) { + next(getError("Unable to write file", filePath)); + } + filetools.fs.utimes(filePath, entry.header.time, entry.header.time, function (err_2) { + if (err_2) { + next(getError("Unable to set times", filePath)); + } else { + next(); + } + }); + }); + } + }); + } + }; + }, callback)(); }, - get readOnly() { - return _obj.readonly; - }, + /** + * Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip + * + * @param {string} targetFileName + * @param {function} callback + */ + writeZip: function (targetFileName, callback) { + if (arguments.length === 1) { + if (typeof targetFileName === "function") { + callback = targetFileName; + targetFileName = ""; + } + } - get hidden() { - return _obj.hidden; - }, + if (!targetFileName && opts.filename) { + targetFileName = opts.filename; + } + if (!targetFileName) return; - get mtime() { - return _obj.mtime; + var zipData = _zip.compressToBuffer(); + if (zipData) { + var ok = filetools.writeFileTo(targetFileName, zipData, true); + if (typeof callback === "function") callback(!ok ? new Error("failed") : null, ""); + } }, - get atime() { - return _obj.atime; - }, + /** + * + * @param {string} targetFileName + * @param {object} [props] + * @param {boolean} [props.overwrite=true] If the file already exists at the target path, the file will be overwriten if this is true. + * @param {boolean} [props.perm] The file will be set as the permission from the entry if this is true. - get executable() { - return _obj.executable; - }, + * @returns {Promise} + */ + writeZipPromise: function (/**String*/ targetFileName, /* object */ props) { + const { overwrite, perm } = Object.assign({ overwrite: true }, props); - decodeAttributes: function () {}, + return new Promise((resolve, reject) => { + // find file name + if (!targetFileName && opts.filename) targetFileName = opts.filename; + if (!targetFileName) reject("ADM-ZIP: ZIP File Name Missing"); - encodeAttributes: function () {}, + this.toBufferPromise().then((zipData) => { + const ret = (done) => (done ? resolve(done) : reject("ADM-ZIP: Wasn't able to write zip file")); + filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret); + }, reject); + }); + }, - toJSON: function () { - return { - path: _path, - isDirectory: _obj.directory, - isReadOnly: _obj.readonly, - isHidden: _obj.hidden, - isExecutable: _obj.executable, - mTime: _obj.mtime, - aTime: _obj.atime - }; + /** + * @returns {Promise} A promise to the Buffer. + */ + toBufferPromise: function () { + return new Promise((resolve, reject) => { + _zip.toAsyncBuffer(resolve, reject); + }); }, - toString: function () { - return JSON.stringify(this.toJSON(), null, "\t"); + /** + * Returns the content of the entire zip file as a Buffer object + * + * @prop {function} [onSuccess] + * @prop {function} [onFail] + * @prop {function} [onItemStart] + * @prop {function} [onItemEnd] + * @returns {Buffer} + */ + toBuffer: function (onSuccess, onFail, onItemStart, onItemEnd) { + if (typeof onSuccess === "function") { + _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd); + return null; + } + return _zip.compressToBuffer(); } }; }; @@ -70971,761 +57193,520 @@ module.exports = function (/*String*/ path, /*Utils object*/ { fs }) { /***/ }), -/***/ 5182: +/***/ 9032: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = __nccwpck_require__(1291); -module.exports.Constants = __nccwpck_require__(4522); -module.exports.Errors = __nccwpck_require__(1255); -module.exports.FileAttr = __nccwpck_require__(5781); -module.exports.decoder = __nccwpck_require__(7396); - - -/***/ }), - -/***/ 1291: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var Utils = __nccwpck_require__(5182), + Constants = Utils.Constants; -const fsystem = __nccwpck_require__(7147); -const pth = __nccwpck_require__(1017); -const Constants = __nccwpck_require__(4522); -const Errors = __nccwpck_require__(1255); -const isWin = typeof process === "object" && "win32" === process.platform; +/* The central directory file header */ +module.exports = function () { + var _verMade = 20, // v2.0 + _version = 10, // v1.0 + _flags = 0, + _method = 0, + _time = 0, + _crc = 0, + _compressedSize = 0, + _size = 0, + _fnameLen = 0, + _extraLen = 0, + _comLen = 0, + _diskStart = 0, + _inattr = 0, + _attr = 0, + _offset = 0; -const is_Obj = (obj) => typeof obj === "object" && obj !== null; + _verMade |= Utils.isWin ? 0x0a00 : 0x0300; -// generate CRC32 lookup table -const crcTable = new Uint32Array(256).map((t, c) => { - for (let k = 0; k < 8; k++) { - if ((c & 1) !== 0) { - c = 0xedb88320 ^ (c >>> 1); - } else { - c >>>= 1; - } - } - return c >>> 0; -}); + // Set EFS flag since filename and comment fields are all by default encoded using UTF-8. + // Without it file names may be corrupted for other apps when file names use unicode chars + _flags |= Constants.FLG_EFS; -// UTILS functions + const _localHeader = { + extraLen: 0 + }; -function Utils(opts) { - this.sep = pth.sep; - this.fs = fsystem; + // casting + const uint32 = (val) => Math.max(0, val) >>> 0; + const uint16 = (val) => Math.max(0, val) & 0xffff; + const uint8 = (val) => Math.max(0, val) & 0xff; - if (is_Obj(opts)) { - // custom filesystem - if (is_Obj(opts.fs) && typeof opts.fs.statSync === "function") { - this.fs = opts.fs; - } - } -} + _time = Utils.fromDate2DOS(new Date()); -module.exports = Utils; + return { + get made() { + return _verMade; + }, + set made(val) { + _verMade = val; + }, -// INSTANTIABLE functions + get version() { + return _version; + }, + set version(val) { + _version = val; + }, -Utils.prototype.makeDir = function (/*String*/ folder) { - const self = this; + get flags() { + return _flags; + }, + set flags(val) { + _flags = val; + }, - // Sync - make directories tree - function mkdirSync(/*String*/ fpath) { - let resolvedPath = fpath.split(self.sep)[0]; - fpath.split(self.sep).forEach(function (name) { - if (!name || name.substr(-1, 1) === ":") return; - resolvedPath += self.sep + name; - var stat; - try { - stat = self.fs.statSync(resolvedPath); - } catch (e) { - self.fs.mkdirSync(resolvedPath); + get flags_efs() { + return (_flags & Constants.FLG_EFS) > 0; + }, + set flags_efs(val) { + if (val) { + _flags |= Constants.FLG_EFS; + } else { + _flags &= ~Constants.FLG_EFS; } - if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`); - }); - } - - mkdirSync(folder); -}; - -Utils.prototype.writeFileTo = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr) { - const self = this; - if (self.fs.existsSync(path)) { - if (!overwrite) return false; // cannot overwrite - - var stat = self.fs.statSync(path); - if (stat.isDirectory()) { - return false; - } - } - var folder = pth.dirname(path); - if (!self.fs.existsSync(folder)) { - self.makeDir(folder); - } - - var fd; - try { - fd = self.fs.openSync(path, "w", 0o666); // 0666 - } catch (e) { - self.fs.chmodSync(path, 0o666); - fd = self.fs.openSync(path, "w", 0o666); - } - if (fd) { - try { - self.fs.writeSync(fd, content, 0, content.length, 0); - } finally { - self.fs.closeSync(fd); - } - } - self.fs.chmodSync(path, attr || 0o666); - return true; -}; - -Utils.prototype.writeFileToAsync = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr, /*Function*/ callback) { - if (typeof attr === "function") { - callback = attr; - attr = undefined; - } - - const self = this; - - self.fs.exists(path, function (exist) { - if (exist && !overwrite) return callback(false); + }, - self.fs.stat(path, function (err, stat) { - if (exist && stat.isDirectory()) { - return callback(false); + get flags_desc() { + return (_flags & Constants.FLG_DESC) > 0; + }, + set flags_desc(val) { + if (val) { + _flags |= Constants.FLG_DESC; + } else { + _flags &= ~Constants.FLG_DESC; } + }, - var folder = pth.dirname(path); - self.fs.exists(folder, function (exists) { - if (!exists) self.makeDir(folder); - - self.fs.open(path, "w", 0o666, function (err, fd) { - if (err) { - self.fs.chmod(path, 0o666, function () { - self.fs.open(path, "w", 0o666, function (err, fd) { - self.fs.write(fd, content, 0, content.length, 0, function () { - self.fs.close(fd, function () { - self.fs.chmod(path, attr || 0o666, function () { - callback(true); - }); - }); - }); - }); - }); - } else if (fd) { - self.fs.write(fd, content, 0, content.length, 0, function () { - self.fs.close(fd, function () { - self.fs.chmod(path, attr || 0o666, function () { - callback(true); - }); - }); - }); - } else { - self.fs.chmod(path, attr || 0o666, function () { - callback(true); - }); - } - }); - }); - }); - }); -}; - -Utils.prototype.findFiles = function (/*String*/ path) { - const self = this; - - function findSync(/*String*/ dir, /*RegExp*/ pattern, /*Boolean*/ recursive) { - if (typeof pattern === "boolean") { - recursive = pattern; - pattern = undefined; - } - let files = []; - self.fs.readdirSync(dir).forEach(function (file) { - const path = pth.join(dir, file); - const stat = self.fs.statSync(path); - - if (!pattern || pattern.test(path)) { - files.push(pth.normalize(path) + (stat.isDirectory() ? self.sep : "")); + get method() { + return _method; + }, + set method(val) { + switch (val) { + case Constants.STORED: + this.version = 10; + case Constants.DEFLATED: + default: + this.version = 20; } + _method = val; + }, - if (stat.isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive)); - }); - return files; - } - - return findSync(path, undefined, true); -}; - -/** - * Callback for showing if everything was done. - * - * @callback filelistCallback - * @param {Error} err - Error object - * @param {string[]} list - was request fully completed - */ - -/** - * - * @param {string} dir - * @param {filelistCallback} cb - */ -Utils.prototype.findFilesAsync = function (dir, cb) { - const self = this; - let results = []; - self.fs.readdir(dir, function (err, list) { - if (err) return cb(err); - let list_length = list.length; - if (!list_length) return cb(null, results); - list.forEach(function (file) { - file = pth.join(dir, file); - self.fs.stat(file, function (err, stat) { - if (err) return cb(err); - if (stat) { - results.push(pth.normalize(file) + (stat.isDirectory() ? self.sep : "")); - if (stat.isDirectory()) { - self.findFilesAsync(file, function (err, res) { - if (err) return cb(err); - results = results.concat(res); - if (!--list_length) cb(null, results); - }); - } else { - if (!--list_length) cb(null, results); - } - } - }); - }); - }); -}; - -Utils.prototype.getAttributes = function () {}; - -Utils.prototype.setAttributes = function () {}; - -// STATIC functions - -// crc32 single update (it is part of crc32) -Utils.crc32update = function (crc, byte) { - return crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8); -}; - -Utils.crc32 = function (buf) { - if (typeof buf === "string") { - buf = Buffer.from(buf, "utf8"); - } - - let len = buf.length; - let crc = ~0; - for (let off = 0; off < len; ) crc = Utils.crc32update(crc, buf[off++]); - // xor and cast as uint32 number - return ~crc >>> 0; -}; - -Utils.methodToString = function (/*Number*/ method) { - switch (method) { - case Constants.STORED: - return "STORED (" + method + ")"; - case Constants.DEFLATED: - return "DEFLATED (" + method + ")"; - default: - return "UNSUPPORTED (" + method + ")"; - } -}; - -/** - * removes ".." style path elements - * @param {string} path - fixable path - * @returns string - fixed filepath - */ -Utils.canonical = function (/*string*/ path) { - if (!path) return ""; - // trick normalize think path is absolute - const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); - return pth.join(".", safeSuffix); -}; - -/** - * fix file names in achive - * @param {string} path - fixable path - * @returns string - fixed filepath - */ - -Utils.zipnamefix = function (path) { - if (!path) return ""; - // trick normalize think path is absolute - const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); - return pth.posix.join(".", safeSuffix); -}; - -/** - * - * @param {Array} arr - * @param {function} callback - * @returns - */ -Utils.findLast = function (arr, callback) { - if (!Array.isArray(arr)) throw new TypeError("arr is not array"); + get time() { + return Utils.fromDOS2Date(this.timeval); + }, + set time(val) { + this.timeval = Utils.fromDate2DOS(val); + }, - const len = arr.length >>> 0; - for (let i = len - 1; i >= 0; i--) { - if (callback(arr[i], i, arr)) { - return arr[i]; - } - } - return void 0; -}; + get timeval() { + return _time; + }, + set timeval(val) { + _time = uint32(val); + }, -// make abolute paths taking prefix as root folder -Utils.sanitize = function (/*string*/ prefix, /*string*/ name) { - prefix = pth.resolve(pth.normalize(prefix)); - var parts = name.split("/"); - for (var i = 0, l = parts.length; i < l; i++) { - var path = pth.normalize(pth.join(prefix, parts.slice(i, l).join(pth.sep))); - if (path.indexOf(prefix) === 0) { - return path; - } - } - return pth.normalize(pth.join(prefix, pth.basename(name))); -}; + get timeHighByte() { + return uint8(_time >>> 8); + }, + get crc() { + return _crc; + }, + set crc(val) { + _crc = uint32(val); + }, -// converts buffer, Uint8Array, string types to buffer -Utils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input, /* function */ encoder) { - if (Buffer.isBuffer(input)) { - return input; - } else if (input instanceof Uint8Array) { - return Buffer.from(input); - } else { - // expect string all other values are invalid and return empty buffer - return typeof input === "string" ? encoder(input) : Buffer.alloc(0); - } -}; + get compressedSize() { + return _compressedSize; + }, + set compressedSize(val) { + _compressedSize = uint32(val); + }, -Utils.readBigUInt64LE = function (/*Buffer*/ buffer, /*int*/ index) { - var slice = Buffer.from(buffer.slice(index, index + 8)); - slice.swap64(); + get size() { + return _size; + }, + set size(val) { + _size = uint32(val); + }, - return parseInt(`0x${slice.toString("hex")}`); -}; + get fileNameLength() { + return _fnameLen; + }, + set fileNameLength(val) { + _fnameLen = val; + }, -Utils.fromDOS2Date = function (val) { - return new Date(((val >> 25) & 0x7f) + 1980, Math.max(((val >> 21) & 0x0f) - 1, 0), Math.max((val >> 16) & 0x1f, 1), (val >> 11) & 0x1f, (val >> 5) & 0x3f, (val & 0x1f) << 1); -}; + get extraLength() { + return _extraLen; + }, + set extraLength(val) { + _extraLen = val; + }, -Utils.fromDate2DOS = function (val) { - let date = 0; - let time = 0; - if (val.getFullYear() > 1979) { - date = (((val.getFullYear() - 1980) & 0x7f) << 9) | ((val.getMonth() + 1) << 5) | val.getDate(); - time = (val.getHours() << 11) | (val.getMinutes() << 5) | (val.getSeconds() >> 1); - } - return (date << 16) | time; -}; + get extraLocalLength() { + return _localHeader.extraLen; + }, + set extraLocalLength(val) { + _localHeader.extraLen = val; + }, -Utils.isWin = isWin; // Do we have windows system -Utils.crcTable = crcTable; + get commentLength() { + return _comLen; + }, + set commentLength(val) { + _comLen = val; + }, + get diskNumStart() { + return _diskStart; + }, + set diskNumStart(val) { + _diskStart = uint32(val); + }, -/***/ }), + get inAttr() { + return _inattr; + }, + set inAttr(val) { + _inattr = uint32(val); + }, -/***/ 4057: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + get attr() { + return _attr; + }, + set attr(val) { + _attr = uint32(val); + }, -var Utils = __nccwpck_require__(5182), - Headers = __nccwpck_require__(4958), - Constants = Utils.Constants, - Methods = __nccwpck_require__(3928); + // get Unix file permissions + get fileAttr() { + return (_attr || 0) >> 16 & 0xfff; + }, -module.exports = function (/** object */ options, /*Buffer*/ input) { - var _centralHeader = new Headers.EntryHeader(), - _entryName = Buffer.alloc(0), - _comment = Buffer.alloc(0), - _isDirectory = false, - uncompressedData = null, - _extra = Buffer.alloc(0), - _extralocal = Buffer.alloc(0), - _efs = true; + get offset() { + return _offset; + }, + set offset(val) { + _offset = uint32(val); + }, - // assign options - const opts = options; + get encrypted() { + return (_flags & Constants.FLG_ENC) === Constants.FLG_ENC; + }, - const decoder = typeof opts.decoder === "object" ? opts.decoder : Utils.decoder; - _efs = decoder.hasOwnProperty("efs") ? decoder.efs : false; + get centralHeaderSize() { + return Constants.CENHDR + _fnameLen + _extraLen + _comLen; + }, - function getCompressedDataFromZip() { - //if (!input || !Buffer.isBuffer(input)) { - if (!input || !(input instanceof Uint8Array)) { - return Buffer.alloc(0); - } - _extralocal = _centralHeader.loadLocalHeaderFromBinary(input); - return input.slice(_centralHeader.realDataOffset, _centralHeader.realDataOffset + _centralHeader.compressedSize); - } + get realDataOffset() { + return _offset + Constants.LOCHDR + _localHeader.fnameLen + _localHeader.extraLen; + }, - function crc32OK(data) { - // if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the local header is written - if (!_centralHeader.flags_desc) { - if (Utils.crc32(data) !== _centralHeader.localHeader.crc) { - return false; - } - } else { - const descriptor = {}; - const dataEndOffset = _centralHeader.realDataOffset + _centralHeader.compressedSize; - // no descriptor after compressed data, instead new local header - if (input.readUInt32LE(dataEndOffset) == Constants.LOCSIG || input.readUInt32LE(dataEndOffset) == Constants.CENSIG) { - throw Utils.Errors.DESCRIPTOR_NOT_EXIST(); - } + get localHeader() { + return _localHeader; + }, - // get decriptor data - if (input.readUInt32LE(dataEndOffset) == Constants.EXTSIG) { - // descriptor with signature - descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC); - descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ); - descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN); - } else if (input.readUInt16LE(dataEndOffset + 12) === 0x4b50) { - // descriptor without signature (we check is new header starting where we expect) - descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC - 4); - descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ - 4); - descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN - 4); - } else { - throw Utils.Errors.DESCRIPTOR_UNKNOWN(); + loadLocalHeaderFromBinary: function (/*Buffer*/ input) { + var data = input.slice(_offset, _offset + Constants.LOCHDR); + // 30 bytes and should start with "PK\003\004" + if (data.readUInt32LE(0) !== Constants.LOCSIG) { + throw Utils.Errors.INVALID_LOC(); } - // check data integrity - if (descriptor.compressedSize !== _centralHeader.compressedSize || descriptor.size !== _centralHeader.size || descriptor.crc !== _centralHeader.crc) { - throw Utils.Errors.DESCRIPTOR_FAULTY(); - } - if (Utils.crc32(data) !== descriptor.crc) { - return false; - } + // version needed to extract + _localHeader.version = data.readUInt16LE(Constants.LOCVER); + // general purpose bit flag + _localHeader.flags = data.readUInt16LE(Constants.LOCFLG); + // compression method + _localHeader.method = data.readUInt16LE(Constants.LOCHOW); + // modification time (2 bytes time, 2 bytes date) + _localHeader.time = data.readUInt32LE(Constants.LOCTIM); + // uncompressed file crc-32 valu + _localHeader.crc = data.readUInt32LE(Constants.LOCCRC); + // compressed size + _localHeader.compressedSize = data.readUInt32LE(Constants.LOCSIZ); + // uncompressed size + _localHeader.size = data.readUInt32LE(Constants.LOCLEN); + // filename length + _localHeader.fnameLen = data.readUInt16LE(Constants.LOCNAM); + // extra field length + _localHeader.extraLen = data.readUInt16LE(Constants.LOCEXT); - // @TODO: zip64 bit descriptor fields - // if bit 3 is set and any value in local header "zip64 Extended information" extra field are set 0 (place holder) - // then 64-bit descriptor format is used instead of 32-bit - // central header - "zip64 Extended information" extra field should store real values and not place holders - } - return true; - } + // read extra data + const extraStart = _offset + Constants.LOCHDR + _localHeader.fnameLen; + const extraEnd = extraStart + _localHeader.extraLen; + return input.slice(extraStart, extraEnd); + }, - function decompress(/*Boolean*/ async, /*Function*/ callback, /*String, Buffer*/ pass) { - if (typeof callback === "undefined" && typeof async === "string") { - pass = async; - async = void 0; - } - if (_isDirectory) { - if (async && callback) { - callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR()); //si added error. + loadFromBinary: function (/*Buffer*/ data) { + // data should be 46 bytes and start with "PK 01 02" + if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) { + throw Utils.Errors.INVALID_CEN(); } - return Buffer.alloc(0); - } + // version made by + _verMade = data.readUInt16LE(Constants.CENVEM); + // version needed to extract + _version = data.readUInt16LE(Constants.CENVER); + // encrypt, decrypt flags + _flags = data.readUInt16LE(Constants.CENFLG); + // compression method + _method = data.readUInt16LE(Constants.CENHOW); + // modification time (2 bytes time, 2 bytes date) + _time = data.readUInt32LE(Constants.CENTIM); + // uncompressed file crc-32 value + _crc = data.readUInt32LE(Constants.CENCRC); + // compressed size + _compressedSize = data.readUInt32LE(Constants.CENSIZ); + // uncompressed size + _size = data.readUInt32LE(Constants.CENLEN); + // filename length + _fnameLen = data.readUInt16LE(Constants.CENNAM); + // extra field length + _extraLen = data.readUInt16LE(Constants.CENEXT); + // file comment length + _comLen = data.readUInt16LE(Constants.CENCOM); + // volume number start + _diskStart = data.readUInt16LE(Constants.CENDSK); + // internal file attributes + _inattr = data.readUInt16LE(Constants.CENATT); + // external file attributes + _attr = data.readUInt32LE(Constants.CENATX); + // LOC header offset + _offset = data.readUInt32LE(Constants.CENOFF); + }, - var compressedData = getCompressedDataFromZip(); + localHeaderToBinary: function () { + // LOC header size (30 bytes) + var data = Buffer.alloc(Constants.LOCHDR); + // "PK\003\004" + data.writeUInt32LE(Constants.LOCSIG, 0); + // version needed to extract + data.writeUInt16LE(_version, Constants.LOCVER); + // general purpose bit flag + data.writeUInt16LE(_flags, Constants.LOCFLG); + // compression method + data.writeUInt16LE(_method, Constants.LOCHOW); + // modification time (2 bytes time, 2 bytes date) + data.writeUInt32LE(_time, Constants.LOCTIM); + // uncompressed file crc-32 value + data.writeUInt32LE(_crc, Constants.LOCCRC); + // compressed size + data.writeUInt32LE(_compressedSize, Constants.LOCSIZ); + // uncompressed size + data.writeUInt32LE(_size, Constants.LOCLEN); + // filename length + data.writeUInt16LE(_fnameLen, Constants.LOCNAM); + // extra field length + data.writeUInt16LE(_localHeader.extraLen, Constants.LOCEXT); + return data; + }, - if (compressedData.length === 0) { - // File is empty, nothing to decompress. - if (async && callback) callback(compressedData); - return compressedData; - } + centralHeaderToBinary: function () { + // CEN header size (46 bytes) + var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen); + // "PK\001\002" + data.writeUInt32LE(Constants.CENSIG, 0); + // version made by + data.writeUInt16LE(_verMade, Constants.CENVEM); + // version needed to extract + data.writeUInt16LE(_version, Constants.CENVER); + // encrypt, decrypt flags + data.writeUInt16LE(_flags, Constants.CENFLG); + // compression method + data.writeUInt16LE(_method, Constants.CENHOW); + // modification time (2 bytes time, 2 bytes date) + data.writeUInt32LE(_time, Constants.CENTIM); + // uncompressed file crc-32 value + data.writeUInt32LE(_crc, Constants.CENCRC); + // compressed size + data.writeUInt32LE(_compressedSize, Constants.CENSIZ); + // uncompressed size + data.writeUInt32LE(_size, Constants.CENLEN); + // filename length + data.writeUInt16LE(_fnameLen, Constants.CENNAM); + // extra field length + data.writeUInt16LE(_extraLen, Constants.CENEXT); + // file comment length + data.writeUInt16LE(_comLen, Constants.CENCOM); + // volume number start + data.writeUInt16LE(_diskStart, Constants.CENDSK); + // internal file attributes + data.writeUInt16LE(_inattr, Constants.CENATT); + // external file attributes + data.writeUInt32LE(_attr, Constants.CENATX); + // LOC header offset + data.writeUInt32LE(_offset, Constants.CENOFF); + return data; + }, - if (_centralHeader.encrypted) { - if ("string" !== typeof pass && !Buffer.isBuffer(pass)) { - throw Utils.Errors.INVALID_PASS_PARAM(); - } - compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass); - } + toJSON: function () { + const bytes = function (nr) { + return nr + " bytes"; + }; - var data = Buffer.alloc(_centralHeader.size); + return { + made: _verMade, + version: _version, + flags: _flags, + method: Utils.methodToString(_method), + time: this.time, + crc: "0x" + _crc.toString(16).toUpperCase(), + compressedSize: bytes(_compressedSize), + size: bytes(_size), + fileNameLength: bytes(_fnameLen), + extraLength: bytes(_extraLen), + commentLength: bytes(_comLen), + diskNumStart: _diskStart, + inAttr: _inattr, + attr: _attr, + offset: _offset, + centralHeaderSize: bytes(Constants.CENHDR + _fnameLen + _extraLen + _comLen) + }; + }, - switch (_centralHeader.method) { - case Utils.Constants.STORED: - compressedData.copy(data); - if (!crc32OK(data)) { - if (async && callback) callback(data, Utils.Errors.BAD_CRC()); //si added error - throw Utils.Errors.BAD_CRC(); - } else { - //si added otherwise did not seem to return data. - if (async && callback) callback(data); - return data; - } - case Utils.Constants.DEFLATED: - var inflater = new Methods.Inflater(compressedData, _centralHeader.size); - if (!async) { - const result = inflater.inflate(data); - result.copy(data, 0); - if (!crc32OK(data)) { - throw Utils.Errors.BAD_CRC(`"${decoder.decode(_entryName)}"`); - } - return data; - } else { - inflater.inflateAsync(function (result) { - result.copy(result, 0); - if (callback) { - if (!crc32OK(result)) { - callback(result, Utils.Errors.BAD_CRC()); //si added error - } else { - callback(result); - } - } - }); - } - break; - default: - if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD()); - throw Utils.Errors.UNKNOWN_METHOD(); + toString: function () { + return JSON.stringify(this.toJSON(), null, "\t"); } - } + }; +}; - function compress(/*Boolean*/ async, /*Function*/ callback) { - if ((!uncompressedData || !uncompressedData.length) && Buffer.isBuffer(input)) { - // no data set or the data wasn't changed to require recompression - if (async && callback) callback(getCompressedDataFromZip()); - return getCompressedDataFromZip(); - } - if (uncompressedData.length && !_isDirectory) { - var compressedData; - // Local file header - switch (_centralHeader.method) { - case Utils.Constants.STORED: - _centralHeader.compressedSize = _centralHeader.size; +/***/ }), - compressedData = Buffer.alloc(uncompressedData.length); - uncompressedData.copy(compressedData); +/***/ 4958: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (async && callback) callback(compressedData); - return compressedData; - default: - case Utils.Constants.DEFLATED: - var deflater = new Methods.Deflater(uncompressedData); - if (!async) { - var deflated = deflater.deflate(); - _centralHeader.compressedSize = deflated.length; - return deflated; - } else { - deflater.deflateAsync(function (data) { - compressedData = Buffer.alloc(data.length); - _centralHeader.compressedSize = data.length; - data.copy(compressedData); - callback && callback(compressedData); - }); - } - deflater = null; - break; - } - } else if (async && callback) { - callback(Buffer.alloc(0)); - } else { - return Buffer.alloc(0); - } - } +exports.EntryHeader = __nccwpck_require__(9032); +exports.MainHeader = __nccwpck_require__(8952); - function readUInt64LE(buffer, offset) { - return (buffer.readUInt32LE(offset + 4) << 4) + buffer.readUInt32LE(offset); - } - function parseExtra(data) { - try { - var offset = 0; - var signature, size, part; - while (offset + 4 < data.length) { - signature = data.readUInt16LE(offset); - offset += 2; - size = data.readUInt16LE(offset); - offset += 2; - part = data.slice(offset, offset + size); - offset += size; - if (Constants.ID_ZIP64 === signature) { - parseZip64ExtendedInformation(part); - } - } - } catch (error) { - throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR(); - } - } +/***/ }), - //Override header field values with values from the ZIP64 extra field - function parseZip64ExtendedInformation(data) { - var size, compressedSize, offset, diskNumStart; +/***/ 8952: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (data.length >= Constants.EF_ZIP64_SCOMP) { - size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP); - if (_centralHeader.size === Constants.EF_ZIP64_OR_32) { - _centralHeader.size = size; - } - } - if (data.length >= Constants.EF_ZIP64_RHO) { - compressedSize = readUInt64LE(data, Constants.EF_ZIP64_SCOMP); - if (_centralHeader.compressedSize === Constants.EF_ZIP64_OR_32) { - _centralHeader.compressedSize = compressedSize; - } - } - if (data.length >= Constants.EF_ZIP64_DSN) { - offset = readUInt64LE(data, Constants.EF_ZIP64_RHO); - if (_centralHeader.offset === Constants.EF_ZIP64_OR_32) { - _centralHeader.offset = offset; - } - } - if (data.length >= Constants.EF_ZIP64_DSN + 4) { - diskNumStart = data.readUInt32LE(Constants.EF_ZIP64_DSN); - if (_centralHeader.diskNumStart === Constants.EF_ZIP64_OR_16) { - _centralHeader.diskNumStart = diskNumStart; - } - } - } +var Utils = __nccwpck_require__(5182), + Constants = Utils.Constants; + +/* The entries in the end of central directory */ +module.exports = function () { + var _volumeEntries = 0, + _totalEntries = 0, + _size = 0, + _offset = 0, + _commentLength = 0; return { - get entryName() { - return decoder.decode(_entryName); - }, - get rawEntryName() { - return _entryName; - }, - set entryName(val) { - _entryName = Utils.toBuffer(val, decoder.encode); - var lastChar = _entryName[_entryName.length - 1]; - _isDirectory = lastChar === 47 || lastChar === 92; - _centralHeader.fileNameLength = _entryName.length; + get diskEntries() { + return _volumeEntries; }, - - get efs() { - if (typeof _efs === "function") { - return _efs(this.entryName); - } else { - return _efs; - } + set diskEntries(/*Number*/ val) { + _volumeEntries = _totalEntries = val; }, - get extra() { - return _extra; + get totalEntries() { + return _totalEntries; }, - set extra(val) { - _extra = val; - _centralHeader.extraLength = val.length; - parseExtra(val); + set totalEntries(/*Number*/ val) { + _totalEntries = _volumeEntries = val; }, - get comment() { - return decoder.decode(_comment); + get size() { + return _size; }, - set comment(val) { - _comment = Utils.toBuffer(val, decoder.encode); - _centralHeader.commentLength = _comment.length; - if (_comment.length > 0xffff) throw Utils.Errors.COMMENT_TOO_LONG(); + set size(/*Number*/ val) { + _size = val; }, - get name() { - var n = decoder.decode(_entryName); - return _isDirectory - ? n - .substr(n.length - 1) - .split("/") - .pop() - : n.split("/").pop(); + get offset() { + return _offset; }, - get isDirectory() { - return _isDirectory; + set offset(/*Number*/ val) { + _offset = val; }, - getCompressedData: function () { - return compress(false, null); + get commentLength() { + return _commentLength; }, - - getCompressedDataAsync: function (/*Function*/ callback) { - compress(true, callback); + set commentLength(/*Number*/ val) { + _commentLength = val; }, - setData: function (value) { - uncompressedData = Utils.toBuffer(value, Utils.decoder.encode); - if (!_isDirectory && uncompressedData.length) { - _centralHeader.size = uncompressedData.length; - _centralHeader.method = Utils.Constants.DEFLATED; - _centralHeader.crc = Utils.crc32(value); - _centralHeader.changed = true; - } else { - // folders and blank files should be stored - _centralHeader.method = Utils.Constants.STORED; - } + get mainHeaderSize() { + return Constants.ENDHDR + _commentLength; }, - getData: function (pass) { - if (_centralHeader.changed) { - return uncompressedData; - } else { - return decompress(false, null, pass); + loadFromBinary: function (/*Buffer*/ data) { + // data should be 22 bytes and start with "PK 05 06" + // or be 56+ bytes and start with "PK 06 06" for Zip64 + if ( + (data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) && + (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG) + ) { + throw Utils.Errors.INVALID_END(); } - }, - getDataAsync: function (/*Function*/ callback, pass) { - if (_centralHeader.changed) { - callback(uncompressedData); + if (data.readUInt32LE(0) === Constants.ENDSIG) { + // number of entries on this volume + _volumeEntries = data.readUInt16LE(Constants.ENDSUB); + // total number of entries + _totalEntries = data.readUInt16LE(Constants.ENDTOT); + // central directory size in bytes + _size = data.readUInt32LE(Constants.ENDSIZ); + // offset of first CEN header + _offset = data.readUInt32LE(Constants.ENDOFF); + // zip file comment length + _commentLength = data.readUInt16LE(Constants.ENDCOM); } else { - decompress(true, callback, pass); - } - }, - - set attr(attr) { - _centralHeader.attr = attr; - }, - get attr() { - return _centralHeader.attr; - }, - - set header(/*Buffer*/ data) { - _centralHeader.loadFromBinary(data); - }, - - get header() { - return _centralHeader; - }, + // number of entries on this volume + _volumeEntries = Utils.readBigUInt64LE(data, Constants.ZIP64SUB); + // total number of entries + _totalEntries = Utils.readBigUInt64LE(data, Constants.ZIP64TOT); + // central directory size in bytes + _size = Utils.readBigUInt64LE(data, Constants.ZIP64SIZE); + // offset of first CEN header + _offset = Utils.readBigUInt64LE(data, Constants.ZIP64OFF); - packCentralHeader: function () { - _centralHeader.flags_efs = this.efs; - _centralHeader.extraLength = _extra.length; - // 1. create header (buffer) - var header = _centralHeader.centralHeaderToBinary(); - var addpos = Utils.Constants.CENHDR; - // 2. add file name - _entryName.copy(header, addpos); - addpos += _entryName.length; - // 3. add extra data - _extra.copy(header, addpos); - addpos += _centralHeader.extraLength; - // 4. add file comment - _comment.copy(header, addpos); - return header; + _commentLength = 0; + } }, - packLocalHeader: function () { - let addpos = 0; - _centralHeader.flags_efs = this.efs; - _centralHeader.extraLocalLength = _extralocal.length; - // 1. construct local header Buffer - const localHeaderBuf = _centralHeader.localHeaderToBinary(); - // 2. localHeader - crate header buffer - const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _centralHeader.extraLocalLength); - // 2.1 add localheader - localHeaderBuf.copy(localHeader, addpos); - addpos += localHeaderBuf.length; - // 2.2 add file name - _entryName.copy(localHeader, addpos); - addpos += _entryName.length; - // 2.3 add extra field - _extralocal.copy(localHeader, addpos); - addpos += _extralocal.length; + toBinary: function () { + var b = Buffer.alloc(Constants.ENDHDR + _commentLength); + // "PK 05 06" signature + b.writeUInt32LE(Constants.ENDSIG, 0); + b.writeUInt32LE(0, 4); + // number of entries on this volume + b.writeUInt16LE(_volumeEntries, Constants.ENDSUB); + // total number of entries + b.writeUInt16LE(_totalEntries, Constants.ENDTOT); + // central directory size in bytes + b.writeUInt32LE(_size, Constants.ENDSIZ); + // offset of first CEN header + b.writeUInt32LE(_offset, Constants.ENDOFF); + // zip file comment length + b.writeUInt16LE(_commentLength, Constants.ENDCOM); + // fill comment memory with spaces so no garbage is left there + b.fill(" ", Constants.ENDHDR); - return localHeader; + return b; }, toJSON: function () { - const bytes = function (nr) { - return "<" + ((nr && nr.length + " bytes buffer") || "null") + ">"; + // creates 0x0000 style output + const offset = function (nr, len) { + let offs = nr.toString(16).toUpperCase(); + while (offs.length < len) offs = "0" + offs; + return "0x" + offs; }; return { - entryName: this.entryName, - name: this.name, - comment: this.comment, - isDirectory: this.isDirectory, - header: _centralHeader.toJSON(), - compressedData: bytes(input), - data: bytes(uncompressedData) + diskEntries: _volumeEntries, + totalEntries: _totalEntries, + size: _size + " bytes", + offset: offset(_offset, 4), + commentLength: _commentLength }; }, @@ -71734,456 +57715,592 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { } }; }; +// Misspelled /***/ }), -/***/ 7744: +/***/ 7686: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const ZipEntry = __nccwpck_require__(4057); -const Headers = __nccwpck_require__(4958); -const Utils = __nccwpck_require__(5182); +module.exports = function (/*Buffer*/ inbuf) { + var zlib = __nccwpck_require__(9796); -module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { - var entryList = [], - entryTable = {}, - _comment = Buffer.alloc(0), - mainHeader = new Headers.MainHeader(), - loadedEntries = false; - var password = null; - const temporary = new Set(); + var opts = { chunkSize: (parseInt(inbuf.length / 1024) + 1) * 1024 }; - // assign options - const opts = options; + return { + deflate: function () { + return zlib.deflateRawSync(inbuf, opts); + }, - const { noSort, decoder } = opts; + deflateAsync: function (/*Function*/ callback) { + var tmp = zlib.createDeflateRaw(opts), + parts = [], + total = 0; + tmp.on("data", function (data) { + parts.push(data); + total += data.length; + }); + tmp.on("end", function () { + var buf = Buffer.alloc(total), + written = 0; + buf.fill(0); + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + part.copy(buf, written); + written += part.length; + } + callback && callback(buf); + }); + tmp.end(inbuf); + } + }; +}; - if (inBuffer) { - // is a memory buffer - readMainHeader(opts.readEntries); + +/***/ }), + +/***/ 3928: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +exports.Deflater = __nccwpck_require__(7686); +exports.Inflater = __nccwpck_require__(2153); +exports.ZipCrypto = __nccwpck_require__(3228); + + +/***/ }), + +/***/ 2153: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const version = +(process.versions ? process.versions.node : "").split(".")[0] || 0; + +module.exports = function (/*Buffer*/ inbuf, /*number*/ expectedLength) { + var zlib = __nccwpck_require__(9796); + const option = version >= 15 && expectedLength > 0 ? { maxOutputLength: expectedLength } : {}; + + return { + inflate: function () { + return zlib.inflateRawSync(inbuf, option); + }, + + inflateAsync: function (/*Function*/ callback) { + var tmp = zlib.createInflateRaw(option), + parts = [], + total = 0; + tmp.on("data", function (data) { + parts.push(data); + total += data.length; + }); + tmp.on("end", function () { + var buf = Buffer.alloc(total), + written = 0; + buf.fill(0); + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + part.copy(buf, written); + written += part.length; + } + callback && callback(buf); + }); + tmp.end(inbuf); + } + }; +}; + + +/***/ }), + +/***/ 3228: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +// node crypt, we use it for generate salt +// eslint-disable-next-line node/no-unsupported-features/node-builtins +const { randomFillSync } = __nccwpck_require__(6113); +const Errors = __nccwpck_require__(1255); + +// generate CRC32 lookup table +const crctable = new Uint32Array(256).map((t, crc) => { + for (let j = 0; j < 8; j++) { + if (0 !== (crc & 1)) { + crc = (crc >>> 1) ^ 0xedb88320; + } else { + crc >>>= 1; + } + } + return crc >>> 0; +}); + +// C-style uInt32 Multiply (discards higher bits, when JS multiply discards lower bits) +const uMul = (a, b) => Math.imul(a, b) >>> 0; + +// crc32 byte single update (actually same function is part of utils.crc32 function :) ) +const crc32update = (pCrc32, bval) => { + return crctable[(pCrc32 ^ bval) & 0xff] ^ (pCrc32 >>> 8); +}; + +// function for generating salt for encrytion header +const genSalt = () => { + if ("function" === typeof randomFillSync) { + return randomFillSync(Buffer.alloc(12)); } else { - // none. is a new file - loadedEntries = true; + // fallback if function is not defined + return genSalt.node(); } +}; - function makeTemporaryFolders() { - const foldersList = new Set(); +// salt generation with node random function (mainly as fallback) +genSalt.node = () => { + const salt = Buffer.alloc(12); + const len = salt.length; + for (let i = 0; i < len; i++) salt[i] = (Math.random() * 256) & 0xff; + return salt; +}; - // Make list of all folders in file - for (const elem of Object.keys(entryTable)) { - const elements = elem.split("/"); - elements.pop(); // filename - if (!elements.length) continue; // no folders - for (let i = 0; i < elements.length; i++) { - const sub = elements.slice(0, i + 1).join("/") + "/"; - foldersList.add(sub); - } +// general config +const config = { + genSalt +}; + +// Class Initkeys handles same basic ops with keys +function Initkeys(pw) { + const pass = Buffer.isBuffer(pw) ? pw : Buffer.from(pw); + this.keys = new Uint32Array([0x12345678, 0x23456789, 0x34567890]); + for (let i = 0; i < pass.length; i++) { + this.updateKeys(pass[i]); + } +} + +Initkeys.prototype.updateKeys = function (byteValue) { + const keys = this.keys; + keys[0] = crc32update(keys[0], byteValue); + keys[1] += keys[0] & 0xff; + keys[1] = uMul(keys[1], 134775813) + 1; + keys[2] = crc32update(keys[2], keys[1] >>> 24); + return byteValue; +}; + +Initkeys.prototype.next = function () { + const k = (this.keys[2] | 2) >>> 0; // key + return (uMul(k, k ^ 1) >> 8) & 0xff; // decode +}; + +function make_decrypter(/*Buffer*/ pwd) { + // 1. Stage initialize key + const keys = new Initkeys(pwd); + + // return decrypter function + return function (/*Buffer*/ data) { + // result - we create new Buffer for results + const result = Buffer.alloc(data.length); + let pos = 0; + // process input data + for (let c of data) { + //c ^= keys.next(); + //result[pos++] = c; // decode & Save Value + result[pos++] = keys.updateKeys(c ^ keys.next()); // update keys with decoded byte } + return result; + }; +} - // create missing folders as temporary - for (const elem of foldersList) { - if (!(elem in entryTable)) { - const tempfolder = new ZipEntry(opts); - tempfolder.entryName = elem; - tempfolder.attr = 0x10; - tempfolder.temporary = true; - entryList.push(tempfolder); - entryTable[tempfolder.entryName] = tempfolder; - temporary.add(tempfolder); - } +function make_encrypter(/*Buffer*/ pwd) { + // 1. Stage initialize key + const keys = new Initkeys(pwd); + + // return encrypting function, result and pos is here so we dont have to merge buffers later + return function (/*Buffer*/ data, /*Buffer*/ result, /* Number */ pos = 0) { + // result - we create new Buffer for results + if (!result) result = Buffer.alloc(data.length); + // process input data + for (let c of data) { + const k = keys.next(); // save key byte + result[pos++] = c ^ k; // save val + keys.updateKeys(c); // update keys with decoded byte } + return result; + }; +} + +function decrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd) { + if (!data || !Buffer.isBuffer(data) || data.length < 12) { + return Buffer.alloc(0); } - function readEntries() { - loadedEntries = true; - entryTable = {}; - if (mainHeader.diskEntries > (inBuffer.length - mainHeader.offset) / Utils.Constants.CENHDR) { - throw Utils.Errors.DISK_ENTRY_TOO_LARGE(); - } - entryList = new Array(mainHeader.diskEntries); // total number of entries - var index = mainHeader.offset; // offset of first CEN header - for (var i = 0; i < entryList.length; i++) { - var tmp = index, - entry = new ZipEntry(opts, inBuffer); - entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR)); + // 1. We Initialize and generate decrypting function + const decrypter = make_decrypter(pwd); - entry.entryName = inBuffer.slice(tmp, (tmp += entry.header.fileNameLength)); + // 2. decrypt salt what is always 12 bytes and is a part of file content + const salt = decrypter(data.slice(0, 12)); - if (entry.header.extraLength) { - entry.extra = inBuffer.slice(tmp, (tmp += entry.header.extraLength)); - } + // if bit 3 (0x08) of the general-purpose flags field is set, check salt[11] with the high byte of the header time + // 2 byte data block (as per Info-Zip spec), otherwise check with the high byte of the header entry + const verifyByte = (header.flags & 0x8) === 0x8 ? header.timeHighByte : header.crc >>> 24; - if (entry.header.commentLength) entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength); + //3. does password meet expectations + if (salt[11] !== verifyByte) { + throw Errors.WRONG_PASSWORD(); + } - index += entry.header.centralHeaderSize; + // 4. decode content + return decrypter(data.slice(12)); +} - entryList[i] = entry; - entryTable[entry.entryName] = entry; - } - temporary.clear(); - makeTemporaryFolders(); +// lets add way to populate salt, NOT RECOMMENDED for production but maybe useful for testing general functionality +function _salter(data) { + if (Buffer.isBuffer(data) && data.length >= 12) { + // be aware - currently salting buffer data is modified + config.genSalt = function () { + return data.slice(0, 12); + }; + } else if (data === "node") { + // test salt generation with node random function + config.genSalt = genSalt.node; + } else { + // if value is not acceptable config gets reset. + config.genSalt = genSalt; } +} - function readMainHeader(/*Boolean*/ readNow) { - var i = inBuffer.length - Utils.Constants.ENDHDR, // END header size - max = Math.max(0, i - 0xffff), // 0xFFFF is the max zip file comment length - n = max, - endStart = inBuffer.length, - endOffset = -1, // Start offset of the END header - commentEnd = 0; +function encrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd, /*Boolean*/ oldlike = false) { + // 1. test data if data is not Buffer we make buffer from it + if (data == null) data = Buffer.alloc(0); + // if data is not buffer be make buffer from it + if (!Buffer.isBuffer(data)) data = Buffer.from(data.toString()); - // option to search header form entire file - const trailingSpace = typeof opts.trailingSpace === "boolean" ? opts.trailingSpace : false; - if (trailingSpace) max = 0; + // 2. We Initialize and generate encrypting function + const encrypter = make_encrypter(pwd); - for (i; i >= n; i--) { - if (inBuffer[i] !== 0x50) continue; // quick check that the byte is 'P' - if (inBuffer.readUInt32LE(i) === Utils.Constants.ENDSIG) { - // "PK\005\006" - endOffset = i; - commentEnd = i; - endStart = i + Utils.Constants.ENDHDR; - // We already found a regular signature, let's look just a bit further to check if there's any zip64 signature - n = i - Utils.Constants.END64HDR; - continue; - } + // 3. generate salt (12-bytes of random data) + const salt = config.genSalt(); + salt[11] = (header.crc >>> 24) & 0xff; - if (inBuffer.readUInt32LE(i) === Utils.Constants.END64SIG) { - // Found a zip64 signature, let's continue reading the whole zip64 record - n = max; - continue; - } + // old implementations (before PKZip 2.04g) used two byte check + if (oldlike) salt[10] = (header.crc >>> 16) & 0xff; - if (inBuffer.readUInt32LE(i) === Utils.Constants.ZIP64SIG) { - // Found the zip64 record, let's determine it's size - endOffset = i; - endStart = i + Utils.readBigUInt64LE(inBuffer, i + Utils.Constants.ZIP64SIZE) + Utils.Constants.ZIP64LEAD; - break; - } - } + // 4. create output + const result = Buffer.alloc(data.length + 12); + encrypter(salt, result); - if (endOffset == -1) throw Utils.Errors.INVALID_FORMAT(); + // finally encode content + return encrypter(data, result, 12); +} - mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart)); - if (mainHeader.commentLength) { - _comment = inBuffer.slice(commentEnd + Utils.Constants.ENDHDR); - } - if (readNow) readEntries(); - } +module.exports = { decrypt, encrypt, _salter }; - function sortEntries() { - if (entryList.length > 1 && !noSort) { - entryList.sort((a, b) => a.entryName.toLowerCase().localeCompare(b.entryName.toLowerCase())); - } - } - return { - /** - * Returns an array of ZipEntry objects existent in the current opened archive - * @return Array - */ - get entries() { - if (!loadedEntries) { - readEntries(); - } - return entryList.filter((e) => !temporary.has(e)); - }, +/***/ }), - /** - * Archive comment - * @return {String} - */ - get comment() { - return decoder.decode(_comment); - }, - set comment(val) { - _comment = Utils.toBuffer(val, decoder.encode); - mainHeader.commentLength = _comment.length; - }, +/***/ 4522: +/***/ ((module) => { - getEntryCount: function () { - if (!loadedEntries) { - return mainHeader.diskEntries; - } +module.exports = { + /* The local file header */ + LOCHDR : 30, // LOC header size + LOCSIG : 0x04034b50, // "PK\003\004" + LOCVER : 4, // version needed to extract + LOCFLG : 6, // general purpose bit flag + LOCHOW : 8, // compression method + LOCTIM : 10, // modification time (2 bytes time, 2 bytes date) + LOCCRC : 14, // uncompressed file crc-32 value + LOCSIZ : 18, // compressed size + LOCLEN : 22, // uncompressed size + LOCNAM : 26, // filename length + LOCEXT : 28, // extra field length - return entryList.length; - }, + /* The Data descriptor */ + EXTSIG : 0x08074b50, // "PK\007\008" + EXTHDR : 16, // EXT header size + EXTCRC : 4, // uncompressed file crc-32 value + EXTSIZ : 8, // compressed size + EXTLEN : 12, // uncompressed size - forEach: function (callback) { - this.entries.forEach(callback); - }, + /* The central directory file header */ + CENHDR : 46, // CEN header size + CENSIG : 0x02014b50, // "PK\001\002" + CENVEM : 4, // version made by + CENVER : 6, // version needed to extract + CENFLG : 8, // encrypt, decrypt flags + CENHOW : 10, // compression method + CENTIM : 12, // modification time (2 bytes time, 2 bytes date) + CENCRC : 16, // uncompressed file crc-32 value + CENSIZ : 20, // compressed size + CENLEN : 24, // uncompressed size + CENNAM : 28, // filename length + CENEXT : 30, // extra field length + CENCOM : 32, // file comment length + CENDSK : 34, // volume number start + CENATT : 36, // internal file attributes + CENATX : 38, // external file attributes (host system dependent) + CENOFF : 42, // LOC header offset - /** - * Returns a reference to the entry with the given name or null if entry is inexistent - * - * @param entryName - * @return ZipEntry - */ - getEntry: function (/*String*/ entryName) { - if (!loadedEntries) { - readEntries(); - } - return entryTable[entryName] || null; - }, + /* The entries in the end of central directory */ + ENDHDR : 22, // END header size + ENDSIG : 0x06054b50, // "PK\005\006" + ENDSUB : 8, // number of entries on this disk + ENDTOT : 10, // total number of entries + ENDSIZ : 12, // central directory size in bytes + ENDOFF : 16, // offset of first CEN header + ENDCOM : 20, // zip file comment length - /** - * Adds the given entry to the entry list - * - * @param entry - */ - setEntry: function (/*ZipEntry*/ entry) { - if (!loadedEntries) { - readEntries(); - } - entryList.push(entry); - entryTable[entry.entryName] = entry; - mainHeader.totalEntries = entryList.length; - }, + END64HDR : 20, // zip64 END header size + END64SIG : 0x07064b50, // zip64 Locator signature, "PK\006\007" + END64START : 4, // number of the disk with the start of the zip64 + END64OFF : 8, // relative offset of the zip64 end of central directory + END64NUMDISKS : 16, // total number of disks - /** - * Removes the file with the given name from the entry list. - * - * If the entry is a directory, then all nested files and directories will be removed - * @param entryName - * @returns {void} - */ - deleteFile: function (/*String*/ entryName, withsubfolders = true) { - if (!loadedEntries) { - readEntries(); - } - const entry = entryTable[entryName]; - const list = this.getEntryChildren(entry, withsubfolders).map((child) => child.entryName); + ZIP64SIG : 0x06064b50, // zip64 signature, "PK\006\006" + ZIP64HDR : 56, // zip64 record minimum size + ZIP64LEAD : 12, // leading bytes at the start of the record, not counted by the value stored in ZIP64SIZE + ZIP64SIZE : 4, // zip64 size of the central directory record + ZIP64VEM : 12, // zip64 version made by + ZIP64VER : 14, // zip64 version needed to extract + ZIP64DSK : 16, // zip64 number of this disk + ZIP64DSKDIR : 20, // number of the disk with the start of the record directory + ZIP64SUB : 24, // number of entries on this disk + ZIP64TOT : 32, // total number of entries + ZIP64SIZB : 40, // zip64 central directory size in bytes + ZIP64OFF : 48, // offset of start of central directory with respect to the starting disk number + ZIP64EXTRA : 56, // extensible data sector - list.forEach(this.deleteEntry); - }, + /* Compression methods */ + STORED : 0, // no compression + SHRUNK : 1, // shrunk + REDUCED1 : 2, // reduced with compression factor 1 + REDUCED2 : 3, // reduced with compression factor 2 + REDUCED3 : 4, // reduced with compression factor 3 + REDUCED4 : 5, // reduced with compression factor 4 + IMPLODED : 6, // imploded + // 7 reserved for Tokenizing compression algorithm + DEFLATED : 8, // deflated + ENHANCED_DEFLATED: 9, // enhanced deflated + PKWARE : 10,// PKWare DCL imploded + // 11 reserved by PKWARE + BZIP2 : 12, // compressed using BZIP2 + // 13 reserved by PKWARE + LZMA : 14, // LZMA + // 15-17 reserved by PKWARE + IBM_TERSE : 18, // compressed using IBM TERSE + IBM_LZ77 : 19, // IBM LZ77 z + AES_ENCRYPT : 99, // WinZIP AES encryption method - /** - * Removes the entry with the given name from the entry list. - * - * @param {string} entryName - * @returns {void} - */ - deleteEntry: function (/*String*/ entryName) { - if (!loadedEntries) { - readEntries(); - } - const entry = entryTable[entryName]; - const index = entryList.indexOf(entry); - if (index >= 0) { - entryList.splice(index, 1); - delete entryTable[entryName]; - mainHeader.totalEntries = entryList.length; - } - }, + /* General purpose bit flag */ + // values can obtained with expression 2**bitnr + FLG_ENC : 1, // Bit 0: encrypted file + FLG_COMP1 : 2, // Bit 1, compression option + FLG_COMP2 : 4, // Bit 2, compression option + FLG_DESC : 8, // Bit 3, data descriptor + FLG_ENH : 16, // Bit 4, enhanced deflating + FLG_PATCH : 32, // Bit 5, indicates that the file is compressed patched data. + FLG_STR : 64, // Bit 6, strong encryption (patented) + // Bits 7-10: Currently unused. + FLG_EFS : 2048, // Bit 11: Language encoding flag (EFS) + // Bit 12: Reserved by PKWARE for enhanced compression. + // Bit 13: encrypted the Central Directory (patented). + // Bits 14-15: Reserved by PKWARE. + FLG_MSK : 4096, // mask header values - /** - * Iterates and returns all nested files and directories of the given entry - * - * @param entry - * @return Array - */ - getEntryChildren: function (/*ZipEntry*/ entry, subfolders = true) { - if (!loadedEntries) { - readEntries(); - } - if (typeof entry === "object") { - if (entry.isDirectory && subfolders) { - const list = []; - const name = entry.entryName; + /* Load type */ + FILE : 2, + BUFFER : 1, + NONE : 0, - for (const zipEntry of entryList) { - if (zipEntry.entryName.startsWith(name)) { - list.push(zipEntry); - } - } - return list; - } else { - return [entry]; - } - } - return []; - }, + /* 4.5 Extensible data fields */ + EF_ID : 0, + EF_SIZE : 2, - /** - * How many child elements entry has - * - * @param {ZipEntry} entry - * @return {integer} - */ - getChildCount: function (entry) { - if (entry && entry.isDirectory) { - const list = this.getEntryChildren(entry); - return list.includes(entry) ? list.length - 1 : list.length; - } - return 0; - }, + /* Header IDs */ + ID_ZIP64 : 0x0001, + ID_AVINFO : 0x0007, + ID_PFS : 0x0008, + ID_OS2 : 0x0009, + ID_NTFS : 0x000a, + ID_OPENVMS : 0x000c, + ID_UNIX : 0x000d, + ID_FORK : 0x000e, + ID_PATCH : 0x000f, + ID_X509_PKCS7 : 0x0014, + ID_X509_CERTID_F : 0x0015, + ID_X509_CERTID_C : 0x0016, + ID_STRONGENC : 0x0017, + ID_RECORD_MGT : 0x0018, + ID_X509_PKCS7_RL : 0x0019, + ID_IBM1 : 0x0065, + ID_IBM2 : 0x0066, + ID_POSZIP : 0x4690, - /** - * Returns the zip file - * - * @return Buffer - */ - compressToBuffer: function () { - if (!loadedEntries) { - readEntries(); - } - sortEntries(); + EF_ZIP64_OR_32 : 0xffffffff, + EF_ZIP64_OR_16 : 0xffff, + EF_ZIP64_SUNCOMP : 0, + EF_ZIP64_SCOMP : 8, + EF_ZIP64_RHO : 16, + EF_ZIP64_DSN : 24 +}; - const dataBlock = []; - const headerBlocks = []; - let totalSize = 0; - let dindex = 0; - mainHeader.size = 0; - mainHeader.offset = 0; - let totalEntries = 0; +/***/ }), - for (const entry of this.entries) { - // compress data and set local and entry header accordingly. Reason why is called first - const compressedData = entry.getCompressedData(); - entry.header.offset = dindex; +/***/ 7396: +/***/ ((module) => { - // 1. construct local header - const localHeader = entry.packLocalHeader(); +module.exports = { + efs: true, + encode: (data) => Buffer.from(data, "utf8"), + decode: (data) => data.toString("utf8") +}; - // 2. offsets - const dataLength = localHeader.length + compressedData.length; - dindex += dataLength; - // 3. store values in sequence - dataBlock.push(localHeader); - dataBlock.push(compressedData); +/***/ }), - // 4. construct central header - const centralHeader = entry.packCentralHeader(); - headerBlocks.push(centralHeader); - // 5. update main header - mainHeader.size += centralHeader.length; - totalSize += dataLength + centralHeader.length; - totalEntries++; - } +/***/ 1255: +/***/ ((__unused_webpack_module, exports) => { - totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length - // point to end of data and beginning of central directory first record - mainHeader.offset = dindex; - mainHeader.totalEntries = totalEntries; +const errors = { + /* Header error messages */ + INVALID_LOC: "Invalid LOC header (bad signature)", + INVALID_CEN: "Invalid CEN header (bad signature)", + INVALID_END: "Invalid END header (bad signature)", - dindex = 0; - const outBuffer = Buffer.alloc(totalSize); - // write data blocks - for (const content of dataBlock) { - content.copy(outBuffer, dindex); - dindex += content.length; - } + /* Descriptor */ + DESCRIPTOR_NOT_EXIST: "No descriptor present", + DESCRIPTOR_UNKNOWN: "Unknown descriptor format", + DESCRIPTOR_FAULTY: "Descriptor data is malformed", - // write central directory entries - for (const content of headerBlocks) { - content.copy(outBuffer, dindex); - dindex += content.length; - } + /* ZipEntry error messages*/ + NO_DATA: "Nothing to decompress", + BAD_CRC: "CRC32 checksum failed {0}", + FILE_IN_THE_WAY: "There is a file in the way: {0}", + UNKNOWN_METHOD: "Invalid/unsupported compression method", - // write main header - const mh = mainHeader.toBinary(); - if (_comment) { - _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment - } - mh.copy(outBuffer, dindex); + /* Inflater error messages */ + AVAIL_DATA: "inflate::Available inflate data did not terminate", + INVALID_DISTANCE: "inflate::Invalid literal/length or distance code in fixed or dynamic block", + TO_MANY_CODES: "inflate::Dynamic block code description: too many length or distance codes", + INVALID_REPEAT_LEN: "inflate::Dynamic block code description: repeat more than specified lengths", + INVALID_REPEAT_FIRST: "inflate::Dynamic block code description: repeat lengths with no first length", + INCOMPLETE_CODES: "inflate::Dynamic block code description: code lengths codes incomplete", + INVALID_DYN_DISTANCE: "inflate::Dynamic block code description: invalid distance code lengths", + INVALID_CODES_LEN: "inflate::Dynamic block code description: invalid literal/length code lengths", + INVALID_STORE_BLOCK: "inflate::Stored block length did not match one's complement", + INVALID_BLOCK_TYPE: "inflate::Invalid block type (type == 3)", - // Since we update entry and main header offsets, - // they are no longer valid and we have to reset content - // (Issue 64) + /* ADM-ZIP error messages */ + CANT_EXTRACT_FILE: "Could not extract the file", + CANT_OVERRIDE: "Target file already exists", + DISK_ENTRY_TOO_LARGE: "Number of disk entries is too large", + NO_ZIP: "No zip file was loaded", + NO_ENTRY: "Entry doesn't exist", + DIRECTORY_CONTENT_ERROR: "A directory cannot have content", + FILE_NOT_FOUND: 'File not found: "{0}"', + NOT_IMPLEMENTED: "Not implemented", + INVALID_FILENAME: "Invalid filename", + INVALID_FORMAT: "Invalid or unsupported zip format. No END header found", + INVALID_PASS_PARAM: "Incompatible password parameter", + WRONG_PASSWORD: "Wrong Password", - inBuffer = outBuffer; - loadedEntries = false; + /* ADM-ZIP */ + COMMENT_TOO_LONG: "Comment is too long", // Comment can be max 65535 bytes long (NOTE: some non-US characters may take more space) + EXTRA_FIELD_PARSE_ERROR: "Extra field parsing error" +}; - return outBuffer; - }, +// template +function E(message) { + return function (...args) { + if (args.length) { // Allow {0} .. {9} arguments in error message, based on argument number + message = message.replace(/\{(\d)\}/g, (_, n) => args[n] || ''); + } - toAsyncBuffer: function (/*Function*/ onSuccess, /*Function*/ onFail, /*Function*/ onItemStart, /*Function*/ onItemEnd) { - try { - if (!loadedEntries) { - readEntries(); - } - sortEntries(); + return new Error('ADM-ZIP: ' + message); + }; +} - const dataBlock = []; - const centralHeaders = []; - let totalSize = 0; - let dindex = 0; - let totalEntries = 0; +// Init errors with template +for (const msg of Object.keys(errors)) { + exports[msg] = E(errors[msg]); +} - mainHeader.size = 0; - mainHeader.offset = 0; - const compress2Buffer = function (entryLists) { - if (entryLists.length > 0) { - const entry = entryLists.shift(); - const name = entry.entryName + entry.extra.toString(); - if (onItemStart) onItemStart(name); - entry.getCompressedDataAsync(function (compressedData) { - if (onItemEnd) onItemEnd(name); - entry.header.offset = dindex; +/***/ }), - // 1. construct local header - const localHeader = entry.packLocalHeader(); +/***/ 5781: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 2. offsets - const dataLength = localHeader.length + compressedData.length; - dindex += dataLength; +const pth = __nccwpck_require__(1017); - // 3. store values in sequence - dataBlock.push(localHeader); - dataBlock.push(compressedData); +module.exports = function (/*String*/ path, /*Utils object*/ { fs }) { + var _path = path || "", + _obj = newAttr(), + _stat = null; - // central header - const centalHeader = entry.packCentralHeader(); - centralHeaders.push(centalHeader); - mainHeader.size += centalHeader.length; - totalSize += dataLength + centalHeader.length; - totalEntries++; + function newAttr() { + return { + directory: false, + readonly: false, + hidden: false, + executable: false, + mtime: 0, + atime: 0 + }; + } - compress2Buffer(entryLists); - }); - } else { - totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length - // point to end of data and beginning of central directory first record - mainHeader.offset = dindex; - mainHeader.totalEntries = totalEntries; + if (_path && fs.existsSync(_path)) { + _stat = fs.statSync(_path); + _obj.directory = _stat.isDirectory(); + _obj.mtime = _stat.mtime; + _obj.atime = _stat.atime; + _obj.executable = (0o111 & _stat.mode) !== 0; // file is executable who ever har right not just owner + _obj.readonly = (0o200 & _stat.mode) === 0; // readonly if owner has no write right + _obj.hidden = pth.basename(_path)[0] === "."; + } else { + console.warn("Invalid path: " + _path); + } - dindex = 0; - const outBuffer = Buffer.alloc(totalSize); - dataBlock.forEach(function (content) { - content.copy(outBuffer, dindex); // write data blocks - dindex += content.length; - }); - centralHeaders.forEach(function (content) { - content.copy(outBuffer, dindex); // write central directory entries - dindex += content.length; - }); + return { + get directory() { + return _obj.directory; + }, - const mh = mainHeader.toBinary(); - if (_comment) { - _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment - } + get readOnly() { + return _obj.readonly; + }, - mh.copy(outBuffer, dindex); // write main header + get hidden() { + return _obj.hidden; + }, - // Since we update entry and main header offsets, they are no - // longer valid and we have to reset content using our new buffer - // (Issue 64) + get mtime() { + return _obj.mtime; + }, - inBuffer = outBuffer; - loadedEntries = false; + get atime() { + return _obj.atime; + }, - onSuccess(outBuffer); - } - }; + get executable() { + return _obj.executable; + }, - compress2Buffer(Array.from(this.entries)); - } catch (e) { - onFail(e); - } + decodeAttributes: function () {}, + + encodeAttributes: function () {}, + + toJSON: function () { + return { + path: _path, + isDirectory: _obj.directory, + isReadOnly: _obj.readonly, + isHidden: _obj.hidden, + isExecutable: _obj.executable, + mTime: _obj.mtime, + aTime: _obj.atime + }; + }, + + toString: function () { + return JSON.stringify(this.toJSON(), null, "\t"); } }; }; @@ -72191,2121 +58308,1223 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { /***/ }), -/***/ 2603: +/***/ 5182: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +module.exports = __nccwpck_require__(1291); +module.exports.Constants = __nccwpck_require__(4522); +module.exports.Errors = __nccwpck_require__(1255); +module.exports.FileAttr = __nccwpck_require__(5781); +module.exports.decoder = __nccwpck_require__(7396); -const validator = __nccwpck_require__(1739); -const XMLParser = __nccwpck_require__(2380); -const XMLBuilder = __nccwpck_require__(660); +/***/ }), -module.exports = { - XMLParser: XMLParser, - XMLValidator: validator, - XMLBuilder: XMLBuilder -} +/***/ 1291: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), +const fsystem = __nccwpck_require__(7147); +const pth = __nccwpck_require__(1017); +const Constants = __nccwpck_require__(4522); +const Errors = __nccwpck_require__(1255); +const isWin = typeof process === "object" && "win32" === process.platform; -/***/ 8280: -/***/ ((__unused_webpack_module, exports) => { +const is_Obj = (obj) => typeof obj === "object" && obj !== null; -"use strict"; +// generate CRC32 lookup table +const crcTable = new Uint32Array(256).map((t, c) => { + for (let k = 0; k < 8; k++) { + if ((c & 1) !== 0) { + c = 0xedb88320 ^ (c >>> 1); + } else { + c >>>= 1; + } + } + return c >>> 0; +}); +// UTILS functions -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 + '$'); +function Utils(opts) { + this.sep = pth.sep; + this.fs = fsystem; -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]); + if (is_Obj(opts)) { + // custom filesystem + if (is_Obj(opts.fs) && typeof opts.fs.statSync === "function") { + this.fs = opts.fs; + } } - matches.push(allmatches); - match = regex.exec(string); - } - return matches; -}; +} -const isName = function(string) { - const match = regexName.exec(string); - return !(match === null || typeof match === 'undefined'); -}; +module.exports = Utils; -exports.isExist = function(v) { - return typeof v !== 'undefined'; -}; +// INSTANTIABLE functions -exports.isEmptyObject = function(obj) { - return Object.keys(obj).length === 0; -}; +Utils.prototype.makeDir = function (/*String*/ folder) { + const self = this; -/** - * 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]]; - } + // Sync - make directories tree + function mkdirSync(/*String*/ fpath) { + let resolvedPath = fpath.split(self.sep)[0]; + fpath.split(self.sep).forEach(function (name) { + if (!name || name.substr(-1, 1) === ":") return; + resolvedPath += self.sep + name; + var stat; + try { + stat = self.fs.statSync(resolvedPath); + } catch (e) { + self.fs.mkdirSync(resolvedPath); + } + if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`); + }); } - } -}; -/* exports.merge =function (b,a){ - return Object.assign(b,a); -} */ -exports.getValue = function(v) { - if (exports.isExist(v)) { - return v; - } else { - return ''; - } + mkdirSync(folder); }; -// const fakeCall = function(a) {return a;}; -// const fakeCallNoReturn = function() {}; +Utils.prototype.writeFileTo = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr) { + const self = this; + if (self.fs.existsSync(path)) { + if (!overwrite) return false; // cannot overwrite -exports.isName = isName; -exports.getAllMatches = getAllMatches; -exports.nameRegexp = nameRegexp; + var stat = self.fs.statSync(path); + if (stat.isDirectory()) { + return false; + } + } + var folder = pth.dirname(path); + if (!self.fs.existsSync(folder)) { + self.makeDir(folder); + } + var fd; + try { + fd = self.fs.openSync(path, "w", 0o666); // 0666 + } catch (e) { + self.fs.chmodSync(path, 0o666); + fd = self.fs.openSync(path, "w", 0o666); + } + if (fd) { + try { + self.fs.writeSync(fd, content, 0, content.length, 0); + } finally { + self.fs.closeSync(fd); + } + } + self.fs.chmodSync(path, attr || 0o666); + return true; +}; -/***/ }), +Utils.prototype.writeFileToAsync = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr, /*Function*/ callback) { + if (typeof attr === "function") { + callback = attr; + attr = undefined; + } -/***/ 1739: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const self = this; -"use strict"; + self.fs.exists(path, function (exist) { + if (exist && !overwrite) return callback(false); + self.fs.stat(path, function (err, stat) { + if (exist && stat.isDirectory()) { + return callback(false); + } -const util = __nccwpck_require__(8280); + var folder = pth.dirname(path); + self.fs.exists(folder, function (exists) { + if (!exists) self.makeDir(folder); -const defaultOptions = { - allowBooleanAttributes: false, //A tag can have attributes without any value - unpairedTags: [] + self.fs.open(path, "w", 0o666, function (err, fd) { + if (err) { + self.fs.chmod(path, 0o666, function () { + self.fs.open(path, "w", 0o666, function (err, fd) { + self.fs.write(fd, content, 0, content.length, 0, function () { + self.fs.close(fd, function () { + self.fs.chmod(path, attr || 0o666, function () { + callback(true); + }); + }); + }); + }); + }); + } else if (fd) { + self.fs.write(fd, content, 0, content.length, 0, function () { + self.fs.close(fd, function () { + self.fs.chmod(path, attr || 0o666, function () { + callback(true); + }); + }); + }); + } else { + self.fs.chmod(path, attr || 0o666, function () { + callback(true); + }); + } + }); + }); + }); + }); }; -//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)); - } +Utils.prototype.findFiles = function (/*String*/ path) { + const self = this; - const result = readAttributeStr(xmlData, i); - if (result === false) { - return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i)); + function findSync(/*String*/ dir, /*RegExp*/ pattern, /*Boolean*/ recursive) { + if (typeof pattern === "boolean") { + recursive = pattern; + pattern = undefined; } - let attrStr = result.value; - i = result.index; - - if (attrStr[attrStr.length - 1] === '/') { - //self closing tag - const attrStrStart = i - attrStr.length; - attrStr = attrStr.substring(0, attrStr.length - 1); - const isValid = validateAttributeString(attrStr, options); - if (isValid === true) { - tagFound = true; - //continue; //text may presents after self closing tag - } else { - //the result from the nested function returns the position of the error within the attribute - //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute - //this gives us the absolute index in the entire xml, which we can use to find the line at last - return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); - } - } else if (closingTag) { - if (!result.tagClosed) { - return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); - } else if (attrStr.trim().length > 0) { - return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); - } else if (tags.length === 0) { - return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); - } else { - const otg = tags.pop(); - if (tagName !== otg.tagName) { - let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); - return getErrorObject('InvalidTag', - "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.", - getLineNumberForPosition(xmlData, tagStartPos)); - } + let files = []; + self.fs.readdirSync(dir).forEach(function (file) { + const path = pth.join(dir, file); + const stat = self.fs.statSync(path); - //when there are no more tags, we reached the root level. - if (tags.length == 0) { - reachedRoot = true; + if (!pattern || pattern.test(path)) { + files.push(pth.normalize(path) + (stat.isDirectory() ? self.sep : "")); } - } - } 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 (stat.isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive)); + }); + return files; } - } - - 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; + return findSync(path, undefined, 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 + * Callback for showing if everything was done. + * + * @callback filelistCallback + * @param {Error} err - Error object + * @param {string[]} list - was request fully completed */ -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. + * + * @param {string} dir + * @param {filelistCallback} cb */ -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) */; -} +Utils.prototype.findFilesAsync = function (dir, cb) { + const self = this; + let results = []; + self.fs.readdir(dir, function (err, list) { + if (err) return cb(err); + let list_length = list.length; + if (!list_length) return cb(null, results); + list.forEach(function (file) { + file = pth.join(dir, file); + self.fs.stat(file, function (err, stat) { + if (err) return cb(err); + if (stat) { + results.push(pth.normalize(file) + (stat.isDirectory() ? self.sep : "")); + if (stat.isDirectory()) { + self.findFilesAsync(file, function (err, res) { + if (err) return cb(err); + results = results.concat(res); + if (!--list_length) cb(null, results); + }); + } else { + if (!--list_length) cb(null, results); + } + } + }); + }); + }); +}; -//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, +Utils.prototype.getAttributes = function () {}; - // column number is last line's length + 1, because column numbering starts at 1: - col: lines[lines.length - 1].length + 1 - }; -} +Utils.prototype.setAttributes = function () {}; -//this function returns the position of the first character of match within attrStr -function getPositionFromMatch(match) { - return match.startIndex + match[1].length; -} +// STATIC functions +// crc32 single update (it is part of crc32) +Utils.crc32update = function (crc, byte) { + return crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8); +}; -/***/ }), +Utils.crc32 = function (buf) { + if (typeof buf === "string") { + buf = Buffer.from(buf, "utf8"); + } -/***/ 660: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + let len = buf.length; + let crc = ~0; + for (let off = 0; off < len; ) crc = Utils.crc32update(crc, buf[off++]); + // xor and cast as uint32 number + return ~crc >>> 0; +}; -"use strict"; +Utils.methodToString = function (/*Number*/ method) { + switch (method) { + case Constants.STORED: + return "STORED (" + method + ")"; + case Constants.DEFLATED: + return "DEFLATED (" + method + ")"; + default: + return "UNSUPPORTED (" + method + ")"; + } +}; -//parse Empty Node as self closing node -const buildFromOrderedJs = __nccwpck_require__(2462); +/** + * removes ".." style path elements + * @param {string} path - fixable path + * @returns string - fixed filepath + */ +Utils.canonical = function (/*string*/ path) { + if (!path) return ""; + // trick normalize think path is absolute + const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); + return pth.join(".", safeSuffix); +}; -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; - } +/** + * fix file names in achive + * @param {string} path - fixable path + * @returns string - fixed filepath + */ - this.processTextOrObjNode = processTextOrObjNode +Utils.zipnamefix = function (path) { + if (!path) return ""; + // trick normalize think path is absolute + const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); + return pth.posix.join(".", safeSuffix); +}; - if (this.options.format) { - this.indentate = indentate; - this.tagEndChar = '>\n'; - this.newLine = '\n'; - } else { - this.indentate = function() { - return ''; - }; - this.tagEndChar = '>'; - this.newLine = ''; - } -} +/** + * + * @param {Array} arr + * @param {function} callback + * @returns + */ +Utils.findLast = function (arr, callback) { + if (!Array.isArray(arr)) throw new TypeError("arr is not array"); -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 - } + const len = arr.length >>> 0; + for (let i = len - 1; i >= 0; i--) { + if (callback(arr[i], i, arr)) { + return arr[i]; + } } - return this.j2x(jObj, 0).val; - } + return void 0; }; -Builder.prototype.j2x = function(jObj, level) { - let attrStr = ''; - let val = ''; - for (let key in jObj) { - if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue; - if (typeof jObj[key] === 'undefined') { - // supress undefined node only if it is not an attribute - if (this.isAttribute(key)) { - val += ''; - } - } else if (jObj[key] === null) { - // null attribute should be ignored by the attribute list, but should not cause the tag closing - if (this.isAttribute(key)) { - val += ''; - } else if (key[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 = ""; - let listTagAttr = ""; - for (let j = 0; j < arrLen; j++) { - const item = jObj[key][j]; - if (typeof item === 'undefined') { - // supress undefined node - } else if (item === null) { - if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; - else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; - // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; - } else if (typeof item === 'object') { - if(this.options.oneListGroup){ - const result = this.j2x(item, level + 1); - listTagVal += result.val; - if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { - listTagAttr += result.attrStr - } - }else{ - listTagVal += this.processTextOrObjNode(item, key, level) - } - } else { - if (this.options.oneListGroup) { - let textValue = this.options.tagValueProcessor(key, item); - textValue = this.replaceEntitiesValue(textValue); - listTagVal += textValue; - } else { - listTagVal += this.buildTextValNode(item, key, '', level); - } - } - } - if(this.options.oneListGroup){ - listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); - } - val += listTagVal; - } else { - //nested node - if (this.options.attributesGroupName && key === this.options.attributesGroupName) { - const Ks = Object.keys(jObj[key]); - const L = Ks.length; - for (let j = 0; j < L; j++) { - attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]); +// make abolute paths taking prefix as root folder +Utils.sanitize = function (/*string*/ prefix, /*string*/ name) { + prefix = pth.resolve(pth.normalize(prefix)); + var parts = name.split("/"); + for (var i = 0, l = parts.length; i < l; i++) { + var path = pth.normalize(pth.join(prefix, parts.slice(i, l).join(pth.sep))); + if (path.indexOf(prefix) === 0) { + return path; } - } else { - val += this.processTextOrObjNode(jObj[key], key, level) - } } - } - return {attrStr: attrStr, val: val}; + return pth.normalize(pth.join(prefix, pth.basename(name))); }; -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> 25) & 0x7f) + 1980, Math.max(((val >> 21) & 0x0f) - 1, 0), Math.max((val >> 16) & 0x1f, 1), (val >> 11) & 0x1f, (val >> 5) & 0x3f, (val & 0x1f) << 1); +}; -function isAttribute(name /*, options*/) { - if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) { - return name.substr(this.attrPrefixLen); - } else { - return false; - } -} +Utils.fromDate2DOS = function (val) { + let date = 0; + let time = 0; + if (val.getFullYear() > 1979) { + date = (((val.getFullYear() - 1980) & 0x7f) << 9) | ((val.getMonth() + 1) << 5) | val.getDate(); + time = (val.getHours() << 11) | (val.getMinutes() << 5) | (val.getSeconds() >> 1); + } + return (date << 16) | time; +}; -module.exports = Builder; +Utils.isWin = isWin; // Do we have windows system +Utils.crcTable = crcTable; /***/ }), -/***/ 2462: -/***/ ((module) => { +/***/ 4057: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Utils = __nccwpck_require__(5182), + Headers = __nccwpck_require__(4958), + Constants = Utils.Constants, + Methods = __nccwpck_require__(3928); -const EOL = "\n"; +module.exports = function (/** object */ options, /*Buffer*/ input) { + var _centralHeader = new Headers.EntryHeader(), + _entryName = Buffer.alloc(0), + _comment = Buffer.alloc(0), + _isDirectory = false, + uncompressedData = null, + _extra = Buffer.alloc(0), + _extralocal = Buffer.alloc(0), + _efs = true; -/** - * - * @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); -} + // assign options + const opts = options; -function arrToStr(arr, options, jPath, indentation) { - let xmlStr = ""; - let isPreviousElementTag = false; + const decoder = typeof opts.decoder === "object" ? opts.decoder : Utils.decoder; + _efs = decoder.hasOwnProperty("efs") ? decoder.efs : false; - for (let i = 0; i < arr.length; i++) { - const tagObj = arr[i]; - const tagName = propName(tagObj); - if(tagName === undefined) continue; + function getCompressedDataFromZip() { + //if (!input || !Buffer.isBuffer(input)) { + if (!input || !(input instanceof Uint8Array)) { + return Buffer.alloc(0); + } + _extralocal = _centralHeader.loadLocalHeaderFromBinary(input); + return input.slice(_centralHeader.realDataOffset, _centralHeader.realDataOffset + _centralHeader.compressedSize); + } - let newJPath = ""; - if (jPath.length === 0) newJPath = tagName - else newJPath = `${jPath}.${tagName}`; + function crc32OK(data) { + // if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the local header is written + if (!_centralHeader.flags_desc) { + if (Utils.crc32(data) !== _centralHeader.localHeader.crc) { + return false; + } + } else { + const descriptor = {}; + const dataEndOffset = _centralHeader.realDataOffset + _centralHeader.compressedSize; + // no descriptor after compressed data, instead new local header + if (input.readUInt32LE(dataEndOffset) == Constants.LOCSIG || input.readUInt32LE(dataEndOffset) == Constants.CENSIG) { + throw Utils.Errors.DESCRIPTOR_NOT_EXIST(); + } - if (tagName === options.textNodeName) { - let tagText = tagObj[tagName]; - if (!isStopNode(newJPath, options)) { - tagText = options.tagValueProcessor(tagName, tagText); - tagText = replaceEntitiesValue(tagText, options); + // get decriptor data + if (input.readUInt32LE(dataEndOffset) == Constants.EXTSIG) { + // descriptor with signature + descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC); + descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ); + descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN); + } else if (input.readUInt16LE(dataEndOffset + 12) === 0x4b50) { + // descriptor without signature (we check is new header starting where we expect) + descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC - 4); + descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ - 4); + descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN - 4); + } else { + throw Utils.Errors.DESCRIPTOR_UNKNOWN(); } - if (isPreviousElementTag) { - xmlStr += indentation; + + // check data integrity + if (descriptor.compressedSize !== _centralHeader.compressedSize || descriptor.size !== _centralHeader.size || descriptor.crc !== _centralHeader.crc) { + throw Utils.Errors.DESCRIPTOR_FAULTY(); } - xmlStr += tagText; - isPreviousElementTag = false; - continue; - } else if (tagName === options.cdataPropName) { - if (isPreviousElementTag) { - xmlStr += indentation; + if (Utils.crc32(data) !== descriptor.crc) { + return false; } - 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; + + // @TODO: zip64 bit descriptor fields + // if bit 3 is set and any value in local header "zip64 Extended information" extra field are set 0 (place holder) + // then 64-bit descriptor format is used instead of 32-bit + // central header - "zip64 Extended information" extra field should store real values and not place holders } - let newIdentation = indentation; - if (newIdentation !== "") { - newIdentation += options.indentBy; + return true; + } + + function decompress(/*Boolean*/ async, /*Function*/ callback, /*String, Buffer*/ pass) { + if (typeof callback === "undefined" && typeof async === "string") { + pass = async; + async = void 0; } - 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("`; + return Buffer.alloc(0); } - isPreviousElementTag = true; - } - return xmlStr; -} + var compressedData = getCompressedDataFromZip(); -function propName(obj) { - const keys = Object.keys(obj); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - if(!obj.hasOwnProperty(key)) continue; - if (key !== ":@") return key; - } -} + if (compressedData.length === 0) { + // File is empty, nothing to decompress. + if (async && callback) callback(compressedData); + return compressedData; + } -function attr_to_str(attrMap, options) { - let attrStr = ""; - if (attrMap && !options.ignoreAttributes) { - for (let attr in attrMap) { - if(!attrMap.hasOwnProperty(attr)) continue; - let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); - attrVal = replaceEntitiesValue(attrVal, options); - if (attrVal === true && options.suppressBooleanAttributes) { - attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; - } else { - attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; + if (_centralHeader.encrypted) { + if ("string" !== typeof pass && !Buffer.isBuffer(pass)) { + throw Utils.Errors.INVALID_PASS_PARAM(); } + compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass); } - } - 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; -} + var data = Buffer.alloc(_centralHeader.size); -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); + switch (_centralHeader.method) { + case Utils.Constants.STORED: + compressedData.copy(data); + if (!crc32OK(data)) { + if (async && callback) callback(data, Utils.Errors.BAD_CRC()); //si added error + throw Utils.Errors.BAD_CRC(); + } else { + //si added otherwise did not seem to return data. + if (async && callback) callback(data); + return data; + } + case Utils.Constants.DEFLATED: + var inflater = new Methods.Inflater(compressedData, _centralHeader.size); + if (!async) { + const result = inflater.inflate(data); + result.copy(data, 0); + if (!crc32OK(data)) { + throw Utils.Errors.BAD_CRC(`"${decoder.decode(_entryName)}"`); + } + return data; + } else { + inflater.inflateAsync(function (result) { + result.copy(result, 0); + if (callback) { + if (!crc32OK(result)) { + callback(result, Utils.Errors.BAD_CRC()); //si added error + } else { + callback(result); + } + } + }); + } + break; + default: + if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD()); + throw Utils.Errors.UNKNOWN_METHOD(); } } - return textValue; -} -module.exports = toXml; + function compress(/*Boolean*/ async, /*Function*/ callback) { + if ((!uncompressedData || !uncompressedData.length) && Buffer.isBuffer(input)) { + // no data set or the data wasn't changed to require recompression + if (async && callback) callback(getCompressedDataFromZip()); + return getCompressedDataFromZip(); + } -/***/ }), - -/***/ 6072: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (uncompressedData.length && !_isDirectory) { + var compressedData; + // Local file header + switch (_centralHeader.method) { + case Utils.Constants.STORED: + _centralHeader.compressedSize = _centralHeader.size; -const util = __nccwpck_require__(8280); + compressedData = Buffer.alloc(uncompressedData.length); + uncompressedData.copy(compressedData); -//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--; + if (async && callback) callback(compressedData); + return compressedData; + default: + case Utils.Constants.DEFLATED: + var deflater = new Methods.Deflater(uncompressedData); + if (!async) { + var deflated = deflater.deflate(); + _centralHeader.compressedSize = deflated.length; + return deflated; + } else { + deflater.deflateAsync(function (data) { + compressedData = Buffer.alloc(data.length); + _centralHeader.compressedSize = data.length; + data.copy(compressedData); + callback && callback(compressedData); + }); } - }else{ - angleBracketsCount--; - } - if (angleBracketsCount === 0) { - break; - } - }else if( xmlData[i] === '['){ - hasBody = true; - }else{ - exp += xmlData[i]; + deflater = null; + break; } + } else if (async && callback) { + callback(Buffer.alloc(0)); + } else { + return Buffer.alloc(0); } - 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 - // + function readUInt64LE(buffer, offset) { + return (buffer.readUInt32LE(offset + 4) << 4) + buffer.readUInt32LE(offset); + } - //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]; + function parseExtra(data) { + try { + var offset = 0; + var signature, size, part; + while (offset + 4 < data.length) { + signature = data.readUInt16LE(offset); + offset += 2; + size = data.readUInt16LE(offset); + offset += 2; + part = data.slice(offset, offset + size); + offset += size; + if (Constants.ID_ZIP64 === signature) { + parseZip64ExtendedInformation(part); + } + } + } catch (error) { + throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR(); + } } - 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]; + //Override header field values with values from the ZIP64 extra field + function parseZip64ExtendedInformation(data) { + var size, compressedSize, offset, diskNumStart; + + if (data.length >= Constants.EF_ZIP64_SCOMP) { + size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP); + if (_centralHeader.size === Constants.EF_ZIP64_OR_32) { + _centralHeader.size = size; + } + } + if (data.length >= Constants.EF_ZIP64_RHO) { + compressedSize = readUInt64LE(data, Constants.EF_ZIP64_SCOMP); + if (_centralHeader.compressedSize === Constants.EF_ZIP64_OR_32) { + _centralHeader.compressedSize = compressedSize; + } + } + if (data.length >= Constants.EF_ZIP64_DSN) { + offset = readUInt64LE(data, Constants.EF_ZIP64_RHO); + if (_centralHeader.offset === Constants.EF_ZIP64_OR_32) { + _centralHeader.offset = offset; + } + } + if (data.length >= Constants.EF_ZIP64_DSN + 4) { + diskNumStart = data.readUInt32LE(Constants.EF_ZIP64_DSN); + if (_centralHeader.diskNumStart === Constants.EF_ZIP64_OR_16) { + _centralHeader.diskNumStart = diskNumStart; + } + } } - 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 -} + return { + get entryName() { + return decoder.decode(_entryName); + }, + get rawEntryName() { + return _entryName; + }, + set entryName(val) { + _entryName = Utils.toBuffer(val, decoder.encode); + var lastChar = _entryName[_entryName.length - 1]; + _isDirectory = lastChar === 47 || lastChar === 92; + _centralHeader.fileNameLength = _entryName.length; + }, -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 -} + get efs() { + if (typeof _efs === "function") { + return _efs(this.entryName); + } else { + return _efs; + } + }, -function validateEntityName(name){ - if (util.isName(name)) - return name; - else - throw new Error(`Invalid entity name ${name}`); -} + get extra() { + return _extra; + }, + set extra(val) { + _extra = val; + _centralHeader.extraLength = val.length; + parseExtra(val); + }, -module.exports = readDocType; + get comment() { + return decoder.decode(_comment); + }, + set comment(val) { + _comment = Utils.toBuffer(val, decoder.encode); + _centralHeader.commentLength = _comment.length; + if (_comment.length > 0xffff) throw Utils.Errors.COMMENT_TOO_LONG(); + }, + get name() { + var n = decoder.decode(_entryName); + return _isDirectory + ? n + .substr(n.length - 1) + .split("/") + .pop() + : n.split("/").pop(); + }, + get isDirectory() { + return _isDirectory; + }, -/***/ }), + getCompressedData: function () { + return compress(false, null); + }, -/***/ 6993: -/***/ ((__unused_webpack_module, exports) => { + getCompressedDataAsync: function (/*Function*/ callback) { + compress(true, callback); + }, + setData: function (value) { + uncompressedData = Utils.toBuffer(value, Utils.decoder.encode); + if (!_isDirectory && uncompressedData.length) { + _centralHeader.size = uncompressedData.length; + _centralHeader.method = Utils.Constants.DEFLATED; + _centralHeader.crc = Utils.crc32(value); + _centralHeader.changed = true; + } else { + // folders and blank files should be stored + _centralHeader.method = Utils.Constants.STORED; + } + }, -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); -}; + getData: function (pass) { + if (_centralHeader.changed) { + return uncompressedData; + } else { + return decompress(false, null, pass); + } + }, -exports.buildOptions = buildOptions; -exports.defaultOptions = defaultOptions; + getDataAsync: function (/*Function*/ callback, pass) { + if (_centralHeader.changed) { + callback(uncompressedData); + } else { + decompress(true, callback, pass); + } + }, -/***/ }), + set attr(attr) { + _centralHeader.attr = attr; + }, + get attr() { + return _centralHeader.attr; + }, -/***/ 5832: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + set header(/*Buffer*/ data) { + _centralHeader.loadFromBinary(data); + }, -"use strict"; + get header() { + return _centralHeader; + }, -///@ts-check + packCentralHeader: function () { + _centralHeader.flags_efs = this.efs; + _centralHeader.extraLength = _extra.length; + // 1. create header (buffer) + var header = _centralHeader.centralHeaderToBinary(); + var addpos = Utils.Constants.CENHDR; + // 2. add file name + _entryName.copy(header, addpos); + addpos += _entryName.length; + // 3. add extra data + _extra.copy(header, addpos); + addpos += _centralHeader.extraLength; + // 4. add file comment + _comment.copy(header, addpos); + return header; + }, + + packLocalHeader: function () { + let addpos = 0; + _centralHeader.flags_efs = this.efs; + _centralHeader.extraLocalLength = _extralocal.length; + // 1. construct local header Buffer + const localHeaderBuf = _centralHeader.localHeaderToBinary(); + // 2. localHeader - crate header buffer + const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _centralHeader.extraLocalLength); + // 2.1 add localheader + localHeaderBuf.copy(localHeader, addpos); + addpos += localHeaderBuf.length; + // 2.2 add file name + _entryName.copy(localHeader, addpos); + addpos += _entryName.length; + // 2.3 add extra field + _extralocal.copy(localHeader, addpos); + addpos += _extralocal.length; -const util = __nccwpck_require__(8280); -const xmlNode = __nccwpck_require__(7462); -const readDocType = __nccwpck_require__(6072); -const toNumber = __nccwpck_require__(4526); + return localHeader; + }, -// const regx = -// '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)' -// .replace(/NAME/g, util.nameRegexp); + toJSON: function () { + const bytes = function (nr) { + return "<" + ((nr && nr.length + " bytes buffer") || "null") + ">"; + }; -//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g"); -//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g"); + return { + entryName: this.entryName, + name: this.name, + comment: this.comment, + isDirectory: this.isDirectory, + header: _centralHeader.toJSON(), + compressedData: bytes(input), + data: bytes(uncompressedData) + }; + }, -class OrderedObjParser{ - constructor(options){ - this.options = options; - this.currentNode = null; - this.tagsNodeStack = []; - this.docTypeEntities = {}; - this.lastEntities = { - "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"}, - "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"}, - "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"}, - "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""}, - }; - this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"}; - this.htmlEntities = { - "space": { regex: /&(nbsp|#160);/g, val: " " }, - // "lt" : { regex: /&(lt|#60);/g, val: "<" }, - // "gt" : { regex: /&(gt|#62);/g, val: ">" }, - // "amp" : { regex: /&(amp|#38);/g, val: "&" }, - // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, - // "apos" : { regex: /&(apos|#39);/g, val: "'" }, - "cent" : { regex: /&(cent|#162);/g, val: "¢" }, - "pound" : { regex: /&(pound|#163);/g, val: "£" }, - "yen" : { regex: /&(yen|#165);/g, val: "¥" }, - "euro" : { regex: /&(euro|#8364);/g, val: "€" }, - "copyright" : { regex: /&(copy|#169);/g, val: "©" }, - "reg" : { regex: /&(reg|#174);/g, val: "®" }, - "inr" : { regex: /&(inr|#8377);/g, val: "₹" }, - "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, - "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }, + toString: function () { + return JSON.stringify(this.toJSON(), null, "\t"); + } }; - 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; - } - } - } - } -} +/***/ 7744: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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; -} +const ZipEntry = __nccwpck_require__(4057); +const Headers = __nccwpck_require__(4958); +const Utils = __nccwpck_require__(5182); -//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'); +module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { + var entryList = [], + entryTable = {}, + _comment = Buffer.alloc(0), + mainHeader = new Headers.MainHeader(), + loadedEntries = false; + var password = null; + const temporary = new Set(); -function buildAttributesMap(attrStr, jPath, tagName) { - if (!this.options.ignoreAttributes && typeof attrStr === 'string') { - // attrStr = attrStr.replace(/\r?\n/g, ' '); - //attrStr = attrStr || attrStr.trim(); + // assign options + const opts = options; - 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; + const { noSort, decoder } = opts; + + if (inBuffer) { + // is a memory buffer + readMainHeader(opts.readEntries); + } else { + // none. is a new file + loadedEntries = true; } - 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); + function makeTemporaryFolders() { + const foldersList = new Set(); + + // Make list of all folders in file + for (const elem of Object.keys(entryTable)) { + const elements = elem.split("/"); + elements.pop(); // filename + if (!elements.length) continue; // no folders + for (let i = 0; i < elements.length; i++) { + const sub = elements.slice(0, i + 1).join("/") + "/"; + foldersList.add(sub); + } } - if(currentNode){ - textData = this.saveTextToParentTag(textData, currentNode, jPath); + // create missing folders as temporary + for (const elem of foldersList) { + if (!(elem in entryTable)) { + const tempfolder = new ZipEntry(opts); + tempfolder.entryName = elem; + tempfolder.attr = 0x10; + tempfolder.temporary = true; + entryList.push(tempfolder); + entryTable[tempfolder.entryName] = tempfolder; + temporary.add(tempfolder); + } } + } - //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("."); + function readEntries() { + loadedEntries = true; + entryTable = {}; + if (mainHeader.diskEntries > (inBuffer.length - mainHeader.offset) / Utils.Constants.CENHDR) { + throw Utils.Errors.DISK_ENTRY_TOO_LARGE(); } - jPath = jPath.substring(0, propIndex); + entryList = new Array(mainHeader.diskEntries); // total number of entries + var index = mainHeader.offset; // offset of first CEN header + for (var i = 0; i < entryList.length; i++) { + var tmp = index, + entry = new ZipEntry(opts, inBuffer); + entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR)); - currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope - textData = ""; - i = closeIndex; - } else if( xmlData[i+1] === '?') { + entry.entryName = inBuffer.slice(tmp, (tmp += entry.header.fileNameLength)); - let tagData = readTagExp(xmlData,i, false, "?>"); - if(!tagData) throw new Error("Pi Tag is not closed."); + if (entry.header.extraLength) { + entry.extra = inBuffer.slice(tmp, (tmp += entry.header.extraLength)); + } - textData = this.saveTextToParentTag(textData, currentNode, jPath); - if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){ + if (entry.header.commentLength) entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength); - }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) + index += entry.header.centralHeaderSize; + entryList[i] = entry; + entryTable[entry.entryName] = entry; } + temporary.clear(); + makeTemporaryFolders(); + } + function readMainHeader(/*Boolean*/ readNow) { + var i = inBuffer.length - Utils.Constants.ENDHDR, // END header size + max = Math.max(0, i - 0xffff), // 0xFFFF is the max zip file comment length + n = max, + endStart = inBuffer.length, + endOffset = -1, // Start offset of the END header + commentEnd = 0; - i = tagData.closeIndex + 1; - } else if(xmlData.substr(i + 1, 3) === '!--') { - const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.") - if(this.options.commentPropName){ - const comment = xmlData.substring(i + 4, endIndex - 2); - - textData = this.saveTextToParentTag(textData, currentNode, jPath); - - currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]); - } - i = endIndex; - } else if( xmlData.substr(i + 1, 2) === '!D') { - const result = readDocType(xmlData, i); - this.docTypeEntities = result.entities; - i = result.i; - }else if(xmlData.substr(i + 1, 2) === '![') { - const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; - const tagExp = xmlData.substring(i + 9,closeIndex); - - textData = this.saveTextToParentTag(textData, currentNode, jPath); - - let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); - if(val == undefined) val = ""; - - //cdata should be set even if it is 0 length string - if(this.options.cdataPropName){ - currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]); - }else{ - currentNode.add(this.options.textNodeName, val); - } - - i = closeIndex + 2; - }else {//Opening tag - let result = readTagExp(xmlData,i, this.options.removeNSPrefix); - let tagName= result.tagName; - const rawTagName = result.rawTagName; - let tagExp = result.tagExp; - let attrExpPresent = result.attrExpPresent; - let closeIndex = result.closeIndex; - - if (this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); - } - - //save text as child node - if (currentNode && textData) { - if(currentNode.tagname !== '!xml'){ - //when nested tag is found - textData = this.saveTextToParentTag(textData, currentNode, jPath, false); - } - } + // option to search header form entire file + const trailingSpace = typeof opts.trailingSpace === "boolean" ? opts.trailingSpace : false; + if (trailingSpace) max = 0; - //check if last tag was unpaired tag - const lastTag = currentNode; - if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){ - currentNode = this.tagsNodeStack.pop(); - jPath = jPath.substring(0, jPath.lastIndexOf(".")); - } - if(tagName !== xmlObj.tagname){ - jPath += jPath ? "." + tagName : tagName; - } - if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { - let tagContent = ""; - //self-closing tag - if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ - if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' - tagName = tagName.substr(0, tagName.length - 1); - jPath = jPath.substr(0, jPath.length - 1); - tagExp = tagName; - }else{ - tagExp = tagExp.substr(0, tagExp.length - 1); + for (i; i >= n; i--) { + if (inBuffer[i] !== 0x50) continue; // quick check that the byte is 'P' + if (inBuffer.readUInt32LE(i) === Utils.Constants.ENDSIG) { + // "PK\005\006" + endOffset = i; + commentEnd = i; + endStart = i + Utils.Constants.ENDHDR; + // We already found a regular signature, let's look just a bit further to check if there's any zip64 signature + n = i - Utils.Constants.END64HDR; + continue; } - i = result.closeIndex; - } - //unpaired tag - else if(this.options.unpairedTags.indexOf(tagName) !== -1){ - - i = result.closeIndex; - } - //normal tag - else{ - //read until closing tag is found - const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); - if(!result) throw new Error(`Unexpected end of ${rawTagName}`); - i = result.i; - tagContent = result.tagContent; - } - const childNode = new xmlNode(tagName); - if(tagName !== tagExp && attrExpPresent){ - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); - } - if(tagContent) { - tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); - } - - jPath = jPath.substr(0, jPath.lastIndexOf(".")); - childNode.add(this.options.textNodeName, tagContent); - - this.addChild(currentNode, childNode, jPath) - }else{ - //selfClosing tag - if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ - if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' - tagName = tagName.substr(0, tagName.length - 1); - jPath = jPath.substr(0, jPath.length - 1); - tagExp = tagName; - }else{ - tagExp = tagExp.substr(0, tagExp.length - 1); - } - - if(this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); + if (inBuffer.readUInt32LE(i) === Utils.Constants.END64SIG) { + // Found a zip64 signature, let's continue reading the whole zip64 record + n = max; + continue; } - 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); + if (inBuffer.readUInt32LE(i) === Utils.Constants.ZIP64SIG) { + // Found the zip64 record, let's determine it's size + endOffset = i; + endStart = i + Utils.readBigUInt64LE(inBuffer, i + Utils.Constants.ZIP64SIZE) + Utils.Constants.ZIP64LEAD; + break; } - 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 (endOffset == -1) throw Utils.Errors.INVALID_FORMAT(); - 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); + mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart)); + if (mainHeader.commentLength) { + _comment = inBuffer.slice(commentEnd + Utils.Constants.ENDHDR); + } + if (readNow) readEntries(); } - if(this.options.htmlEntities){ - for(let entityName in this.htmlEntities){ - const entity = this.htmlEntities[entityName]; - val = val.replace( entity.regex, entity.val); - } + + function sortEntries() { + if (entryList.length > 1 && !noSort) { + entryList.sort((a, b) => a.entryName.toLowerCase().localeCompare(b.entryName.toLowerCase())); + } } - 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; -} + return { + /** + * Returns an array of ZipEntry objects existent in the current opened archive + * @return Array + */ + get entries() { + if (!loadedEntries) { + readEntries(); + } + return entryList.filter((e) => !temporary.has(e)); + }, -//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; -} + /** + * Archive comment + * @return {String} + */ + get comment() { + return decoder.decode(_comment); + }, + set comment(val) { + _comment = Utils.toBuffer(val, decoder.encode); + mainHeader.commentLength = _comment.length; + }, -/** - * 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; - } -} + getEntryCount: function () { + if (!loadedEntries) { + return mainHeader.diskEntries; + } -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; - } -} + return entryList.length; + }, -function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){ - const result = tagExpWithClosingIndex(xmlData, i+1, closingChar); - if(!result) return; - let tagExp = result.data; - const closeIndex = result.index; - const separatorIndex = tagExp.search(/\s/); - let tagName = tagExp; - let attrExpPresent = true; - if(separatorIndex !== -1){//separate tag name and attributes expression - tagName = tagExp.substring(0, separatorIndex); - tagExp = tagExp.substring(separatorIndex + 1).trimStart(); - } + forEach: function (callback) { + this.entries.forEach(callback); + }, - const rawTagName = tagName; - if(removeNSPrefix){ - const colonIndex = tagName.indexOf(":"); - if(colonIndex !== -1){ - tagName = tagName.substr(colonIndex+1); - attrExpPresent = tagName !== result.data.substr(colonIndex + 1); - } - } + /** + * Returns a reference to the entry with the given name or null if entry is inexistent + * + * @param entryName + * @return ZipEntry + */ + getEntry: function (/*String*/ entryName) { + if (!loadedEntries) { + readEntries(); + } + return entryTable[entryName] || null; + }, - return { - tagName: tagName, - tagExp: tagExp, - closeIndex: closeIndex, - attrExpPresent: attrExpPresent, - rawTagName: rawTagName, - } -} -/** - * find paired tag for a stop node - * @param {string} xmlData - * @param {string} tagName - * @param {number} i - */ -function readStopNodeData(xmlData, tagName, i){ - const startIndex = i; - // Starting at 1 since we already have an open tag - let openTagCount = 1; - - for (; i < xmlData.length; i++) { - if( xmlData[i] === "<"){ - if (xmlData[i+1] === "/") {//close tag - const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`); - let closeTagName = xmlData.substring(i+2,closeIndex).trim(); - if(closeTagName === tagName){ - openTagCount--; - if (openTagCount === 0) { - return { - tagContent: xmlData.substring(startIndex, i), - i : closeIndex - } + /** + * Adds the given entry to the entry list + * + * @param entry + */ + setEntry: function (/*ZipEntry*/ entry) { + if (!loadedEntries) { + readEntries(); } - } - 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, '>') + entryList.push(entry); + entryTable[entry.entryName] = entry; + mainHeader.totalEntries = entryList.length; + }, - if (tagData) { - const openTagName = tagData && tagData.tagName; - if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") { - openTagCount++; + /** + * Removes the file with the given name from the entry list. + * + * If the entry is a directory, then all nested files and directories will be removed + * @param entryName + * @returns {void} + */ + deleteFile: function (/*String*/ entryName, withsubfolders = true) { + if (!loadedEntries) { + readEntries(); } - i=tagData.closeIndex; - } - } - } - }//end for loop -} + const entry = entryTable[entryName]; + const list = this.getEntryChildren(entry, withsubfolders).map((child) => child.entryName); -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 ''; - } - } -} + list.forEach(this.deleteEntry); + }, + /** + * Removes the entry with the given name from the entry list. + * + * @param {string} entryName + * @returns {void} + */ + deleteEntry: function (/*String*/ entryName) { + if (!loadedEntries) { + readEntries(); + } + const entry = entryTable[entryName]; + const index = entryList.indexOf(entry); + if (index >= 0) { + entryList.splice(index, 1); + delete entryTable[entryName]; + mainHeader.totalEntries = entryList.length; + } + }, -module.exports = OrderedObjParser; + /** + * Iterates and returns all nested files and directories of the given entry + * + * @param entry + * @return Array + */ + getEntryChildren: function (/*ZipEntry*/ entry, subfolders = true) { + if (!loadedEntries) { + readEntries(); + } + if (typeof entry === "object") { + if (entry.isDirectory && subfolders) { + const list = []; + const name = entry.entryName; + for (const zipEntry of entryList) { + if (zipEntry.entryName.startsWith(name)) { + list.push(zipEntry); + } + } + return list; + } else { + return [entry]; + } + } + return []; + }, -/***/ }), + /** + * How many child elements entry has + * + * @param {ZipEntry} entry + * @return {integer} + */ + getChildCount: function (entry) { + if (entry && entry.isDirectory) { + const list = this.getEntryChildren(entry); + return list.includes(entry) ? list.length - 1 : list.length; + } + return 0; + }, -/***/ 2380: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Returns the zip file + * + * @return Buffer + */ + compressToBuffer: function () { + if (!loadedEntries) { + readEntries(); + } + sortEntries(); -const { buildOptions} = __nccwpck_require__(6993); -const OrderedObjParser = __nccwpck_require__(5832); -const { prettify} = __nccwpck_require__(2882); -const validator = __nccwpck_require__(1739); + const dataBlock = []; + const headerBlocks = []; + let totalSize = 0; + let dindex = 0; -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); - } + mainHeader.size = 0; + mainHeader.offset = 0; + let totalEntries = 0; - /** - * 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; - } - } -} + for (const entry of this.entries) { + // compress data and set local and entry header accordingly. Reason why is called first + const compressedData = entry.getCompressedData(); + entry.header.offset = dindex; -module.exports = XMLParser; + // 1. construct local header + const localHeader = entry.packLocalHeader(); -/***/ }), + // 2. offsets + const dataLength = localHeader.length + compressedData.length; + dindex += dataLength; -/***/ 2882: -/***/ ((__unused_webpack_module, exports) => { + // 3. store values in sequence + dataBlock.push(localHeader); + dataBlock.push(compressedData); -"use strict"; + // 4. construct central header + const centralHeader = entry.packCentralHeader(); + headerBlocks.push(centralHeader); + // 5. update main header + mainHeader.size += centralHeader.length; + totalSize += dataLength + centralHeader.length; + totalEntries++; + } + totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length + // point to end of data and beginning of central directory first record + mainHeader.offset = dindex; + mainHeader.totalEntries = totalEntries; -/** - * - * @param {array} node - * @param {any} options - * @returns - */ -function prettify(node, options){ - return compress( node, options); -} + dindex = 0; + const outBuffer = Buffer.alloc(totalSize); + // write data blocks + for (const content of dataBlock) { + content.copy(outBuffer, dindex); + dindex += content.length; + } -/** - * - * @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; -} + // write central directory entries + for (const content of headerBlocks) { + content.copy(outBuffer, dindex); + dindex += content.length; + } -function propName(obj){ - const keys = Object.keys(obj); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - if(key !== ":@") return key; - } -} + // write main header + const mh = mainHeader.toBinary(); + if (_comment) { + _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment + } + mh.copy(outBuffer, dindex); -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]; - } - } - } -} + // Since we update entry and main header offsets, + // they are no longer valid and we have to reset content + // (Issue 64) -function isLeafTag(obj, options){ - const { textNodeName } = options; - const propCount = Object.keys(obj).length; - - if (propCount === 0) { - return true; - } + inBuffer = outBuffer; + loadedEntries = false; - if ( - propCount === 1 && - (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0) - ) { - return true; - } + return outBuffer; + }, - return false; -} -exports.prettify = prettify; + toAsyncBuffer: function (/*Function*/ onSuccess, /*Function*/ onFail, /*Function*/ onItemStart, /*Function*/ onItemEnd) { + try { + if (!loadedEntries) { + readEntries(); + } + sortEntries(); + const dataBlock = []; + const centralHeaders = []; + let totalSize = 0; + let dindex = 0; + let totalEntries = 0; -/***/ }), + mainHeader.size = 0; + mainHeader.offset = 0; -/***/ 7462: -/***/ ((module) => { + const compress2Buffer = function (entryLists) { + if (entryLists.length > 0) { + const entry = entryLists.shift(); + const name = entry.entryName + entry.extra.toString(); + if (onItemStart) onItemStart(name); + entry.getCompressedDataAsync(function (compressedData) { + if (onItemEnd) onItemEnd(name); + entry.header.offset = dindex; -"use strict"; + // 1. construct local header + const localHeader = entry.packLocalHeader(); + // 2. offsets + const dataLength = localHeader.length + compressedData.length; + dindex += dataLength; -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 }); - } - }; -}; + // 3. store values in sequence + dataBlock.push(localHeader); + dataBlock.push(compressedData); + // central header + const centalHeader = entry.packCentralHeader(); + centralHeaders.push(centalHeader); + mainHeader.size += centalHeader.length; + totalSize += dataLength + centalHeader.length; + totalEntries++; -module.exports = XmlNode; + compress2Buffer(entryLists); + }); + } else { + totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length + // point to end of data and beginning of central directory first record + mainHeader.offset = dindex; + mainHeader.totalEntries = totalEntries; -/***/ }), + dindex = 0; + const outBuffer = Buffer.alloc(totalSize); + dataBlock.forEach(function (content) { + content.copy(outBuffer, dindex); // write data blocks + dindex += content.length; + }); + centralHeaders.forEach(function (content) { + content.copy(outBuffer, dindex); // write central directory entries + dindex += content.length; + }); -/***/ 4526: -/***/ ((module) => { + const mh = mainHeader.toBinary(); + if (_comment) { + _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment + } -const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; -const numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/; -// const octRegex = /^0x[a-z0-9]+/; -// const binRegex = /0x[a-z0-9]+/; + mh.copy(outBuffer, dindex); // write main header - -const consider = { - hex : true, - // oct: false, - leadingZeros: true, - decimalPoint: "\.", - eNotation: true, - //skipLike: /regex/ -}; + // Since we update entry and main header offsets, they are no + // longer valid and we have to reset content using our new buffer + // (Issue 64) -function toNumber(str, options = {}){ - options = Object.assign({}, consider, options ); - if(!str || typeof str !== "string" ) return str; - - let trimmedStr = str.trim(); - - if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str; - else if(str==="0") return 0; - else if (options.hex && hexRegex.test(trimmedStr)) { - return parse_int(trimmedStr, 16); - // }else if (options.oct && octRegex.test(str)) { - // return Number.parseInt(val, 8); - }else if (trimmedStr.search(/[eE]/)!== -1) { //eNotation - const notation = trimmedStr.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/); - // +00.123 => [ , '+', '00', '.123', .. - if(notation){ - // console.log(notation) - if(options.leadingZeros){ //accept with leading zeros - trimmedStr = (notation[1] || "") + notation[3]; - }else{ - if(notation[2] === "0" && notation[3][0]=== "."){ //valid number - }else{ - return str; - } - } - return options.eNotation ? Number(trimmedStr) : str; - }else{ - return str; - } - // }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); - // +00.123 => [ , '+', '00', '.123', .. - 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 - - 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 if(options.leadingZeros && leadingZeros===str) return 0; //00 - - 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(trimmedStr.indexOf(".") !== -1){ //floating number - 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){ - return (numTrimmedByZeros === numStr) || (sign+numTrimmedByZeros === numStr) ? num : str - }else { - return (trimmedStr === numStr) || (trimmedStr === sign+numStr) ? num : str - } - } - }else{ //non-numeric string - return str; - } - } -} + inBuffer = outBuffer; + loadedEntries = false; -/** - * - * @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; -} + onSuccess(outBuffer); + } + }; -function parse_int(numStr, base){ - //polyfill - if(parseInt) return parseInt(numStr, base); - else if(Number.parseInt) return Number.parseInt(numStr, base); - else if(window && window.parseInt) return window.parseInt(numStr, base); - else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported") -} + compress2Buffer(Array.from(this.entries)); + } catch (e) { + onFail(e); + } + } + }; +}; -module.exports = toNumber; /***/ }), @@ -100125,28 +85344,7 @@ module.exports = parseParams /***/ }), -/***/ 2689: -/***/ ((module) => { - -(()=>{"use strict";var t={d:(e,n)=>{for(var i in n)t.o(n,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:n[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{XMLBuilder:()=>ft,XMLParser:()=>st,XMLValidator:()=>mt});const n=":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",i=new RegExp("^["+n+"]["+n+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function s(t,e){const n=[];let i=e.exec(t);for(;i;){const s=[];s.startIndex=e.lastIndex-i[0].length;const r=i.length;for(let t=0;t"!==t[o]&&" "!==t[o]&&"\t"!==t[o]&&"\n"!==t[o]&&"\r"!==t[o];o++)f+=t[o];if(f=f.trim(),"/"===f[f.length-1]&&(f=f.substring(0,f.length-1),o--),!r(f)){let e;return e=0===f.trim().length?"Invalid space after '<'.":"Tag '"+f+"' is an invalid name.",x("InvalidTag",e,N(t,o))}const p=c(t,o);if(!1===p)return x("InvalidAttr","Attributes for '"+f+"' have open quote.",N(t,o));let b=p.value;if(o=p.index,"/"===b[b.length-1]){const n=o-b.length;b=b.substring(0,b.length-1);const s=g(b,e);if(!0!==s)return x(s.err.code,s.err.msg,N(t,n+s.err.line));i=!0}else if(d){if(!p.tagClosed)return x("InvalidTag","Closing tag '"+f+"' doesn't have proper closing.",N(t,o));if(b.trim().length>0)return x("InvalidTag","Closing tag '"+f+"' can't have attributes or invalid starting.",N(t,a));if(0===n.length)return x("InvalidTag","Closing tag '"+f+"' has not been opened.",N(t,a));{const e=n.pop();if(f!==e.tagName){let n=N(t,e.tagStartPos);return x("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+f+"'.",N(t,a))}0==n.length&&(s=!0)}}else{const r=g(b,e);if(!0!==r)return x(r.err.code,r.err.msg,N(t,o-b.length+r.err.line));if(!0===s)return x("InvalidXml","Multiple possible root nodes found.",N(t,o));-1!==e.unpairedTags.indexOf(f)||n.push({tagName:f,tagStartPos:a}),i=!0}for(o++;o0)||x("InvalidXml","Invalid '"+JSON.stringify(n.map((t=>t.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):x("InvalidXml","Start tag expected.",1)}function l(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function u(t,e){const n=e;for(;e5&&"xml"===i)return x("InvalidXml","XML declaration allowed only at the start of the document.",N(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}}return e}function h(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let n=1;for(e+=8;e"===t[e]&&(n--,0===n))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}const d='"',f="'";function c(t,e){let n="",i="",s=!1;for(;e"===t[e]&&""===i){s=!0;break}n+=t[e]}return""===i&&{value:n,index:e,tagClosed:s}}const p=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function g(t,e){const n=s(t,p),i={};for(let t=0;t!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t},captureMetaData:!1};let y;y="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class T{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][y]={startIndex:e})}static getMetaDataSymbol(){return y}}function w(t,e){const n={};if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let i=1,s=!1,r=!1,o="";for(;e"===t[e]){if(r?"-"===t[e-1]&&"-"===t[e-2]&&(r=!1,i--):i--,0===i)break}else"["===t[e]?s=!0:o+=t[e];else{if(s&&C(t,"!ENTITY",e)){let i,s;e+=7,[i,s,e]=O(t,e+1),-1===s.indexOf("&")&&(n[i]={regx:RegExp(`&${i};`,"g"),val:s})}else if(s&&C(t,"!ELEMENT",e)){e+=8;const{index:n}=S(t,e+1);e=n}else if(s&&C(t,"!ATTLIST",e))e+=8;else if(s&&C(t,"!NOTATION",e)){e+=9;const{index:n}=A(t,e+1);e=n}else{if(!C(t,"!--",e))throw new Error("Invalid DOCTYPE");r=!0}i++,o=""}if(0!==i)throw new Error("Unclosed DOCTYPE")}return{entities:n,i:e}}const P=(t,e)=>{for(;e{for(const n of t){if("string"==typeof n&&e===n)return!0;if(n instanceof RegExp&&n.test(e))return!0}}:()=>!1}class k{constructor(t){this.options=t,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:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>String.fromCodePoint(Number.parseInt(e,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>String.fromCodePoint(Number.parseInt(e,16))}},this.addExternalEntities=F,this.parseXml=X,this.parseTextData=L,this.resolveNameSpace=B,this.buildAttributesMap=G,this.isItStopNode=Z,this.replaceEntitiesValue=R,this.readStopNodeData=J,this.saveTextToParentTag=q,this.addChild=Y,this.ignoreAttributesFn=_(this.options.ignoreAttributes)}}function F(t){const e=Object.keys(t);for(let n=0;n0)){o||(t=this.replaceEntitiesValue(t));const i=this.options.tagValueProcessor(e,t,n,s,r);return null==i?t:typeof i!=typeof t||i!==t?i:this.options.trimValues||t.trim()===t?H(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function B(t){if(this.options.removeNSPrefix){const e=t.split(":"),n="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=n+e[1])}return t}const U=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function G(t,e,n){if(!0!==this.options.ignoreAttributes&&"string"==typeof t){const n=s(t,U),i=n.length,r={};for(let t=0;t",r,"Closing Tag is not closed.");let o=t.substring(r+2,e).trim();if(this.options.removeNSPrefix){const t=o.indexOf(":");-1!==t&&(o=o.substr(t+1))}this.options.transformTagName&&(o=this.options.transformTagName(o)),n&&(i=this.saveTextToParentTag(i,n,s));const a=s.substring(s.lastIndexOf(".")+1);if(o&&-1!==this.options.unpairedTags.indexOf(o))throw new Error(`Unpaired tag can not be used as closing tag: `);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=s.lastIndexOf(".",s.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=s.lastIndexOf("."),s=s.substring(0,l),n=this.tagsNodeStack.pop(),i="",r=e}else if("?"===t[r+1]){let e=z(t,r,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,n,s),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new T(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,s,e.tagName)),this.addChild(n,t,s,r)}r=e.closeIndex+1}else if("!--"===t.substr(r+1,3)){const e=W(t,"--\x3e",r+4,"Comment is not closed.");if(this.options.commentPropName){const o=t.substring(r+4,e-2);i=this.saveTextToParentTag(i,n,s),n.add(this.options.commentPropName,[{[this.options.textNodeName]:o}])}r=e}else if("!D"===t.substr(r+1,2)){const e=w(t,r);this.docTypeEntities=e.entities,r=e.i}else if("!["===t.substr(r+1,2)){const e=W(t,"]]>",r,"CDATA is not closed.")-2,o=t.substring(r+9,e);i=this.saveTextToParentTag(i,n,s);let a=this.parseTextData(o,n.tagname,s,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:o}]):n.add(this.options.textNodeName,a),r=e+2}else{let o=z(t,r,this.options.removeNSPrefix),a=o.tagName;const l=o.rawTagName;let u=o.tagExp,h=o.attrExpPresent,d=o.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),n&&i&&"!xml"!==n.tagname&&(i=this.saveTextToParentTag(i,n,s,!1));const f=n;f&&-1!==this.options.unpairedTags.indexOf(f.tagname)&&(n=this.tagsNodeStack.pop(),s=s.substring(0,s.lastIndexOf("."))),a!==e.tagname&&(s+=s?"."+a:a);const c=r;if(this.isItStopNode(this.options.stopNodes,s,a)){let e="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),u=a):u=u.substr(0,u.length-1),r=o.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))r=o.closeIndex;else{const n=this.readStopNodeData(t,l,d+1);if(!n)throw new Error(`Unexpected end of ${l}`);r=n.i,e=n.tagContent}const i=new T(a);a!==u&&h&&(i[":@"]=this.buildAttributesMap(u,s,a)),e&&(e=this.parseTextData(e,a,s,!0,h,!0,!0)),s=s.substr(0,s.lastIndexOf(".")),i.add(this.options.textNodeName,e),this.addChild(n,i,s,c)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),u=a):u=u.substr(0,u.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const t=new T(a);a!==u&&h&&(t[":@"]=this.buildAttributesMap(u,s,a)),this.addChild(n,t,s,c),s=s.substr(0,s.lastIndexOf("."))}else{const t=new T(a);this.tagsNodeStack.push(n),a!==u&&h&&(t[":@"]=this.buildAttributesMap(u,s,a)),this.addChild(n,t,s,c),n=t}i="",r=d}}else i+=t[r];return e.child};function Y(t,e,n,i){this.options.captureMetaData||(i=void 0);const s=this.options.updateTag(e.tagname,n,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e,i)):t.addChild(e,i))}const R=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){const n=this.docTypeEntities[e];t=t.replace(n.regx,n.val)}for(let e in this.lastEntities){const n=this.lastEntities[e];t=t.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){const n=this.htmlEntities[e];t=t.replace(n.regex,n.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function q(t,e,n,i){return t&&(void 0===i&&(i=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,n,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,i))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function Z(t,e,n){const i="*."+n;for(const n in t){const s=t[n];if(i===s||e===s)return!0}return!1}function W(t,e,n,i){const s=t.indexOf(e,n);if(-1===s)throw new Error(i);return s+e.length-1}function z(t,e,n,i=">"){const s=function(t,e,n=">"){let i,s="";for(let r=e;r",n,`${e} is not closed`);if(t.substring(n+2,r).trim()===e&&(s--,0===s))return{tagContent:t.substring(i,n),i:r};n=r}else if("?"===t[n+1])n=W(t,"?>",n+1,"StopNode is not closed.");else if("!--"===t.substr(n+1,3))n=W(t,"--\x3e",n+3,"StopNode is not closed.");else if("!["===t.substr(n+1,2))n=W(t,"]]>",n,"StopNode is not closed.")-2;else{const i=z(t,n,">");i&&((i&&i.tagName)===e&&"/"!==i.tagExp[i.tagExp.length-1]&&s++,n=i.closeIndex)}}function H(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},V,e),!t||"string"!=typeof t)return t;let n=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(n))return t;if("0"===t)return 0;if(e.hex&&j.test(n))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(n);if(-1!==n.search(/.+[eE].+/))return function(t,e,n){if(!n.eNotation)return t;const i=e.match(M);if(i){let s=i[1]||"";const r=-1===i[3].indexOf("e")?"E":"e",o=i[2],a=s?t[o.length+1]===r:t[o.length]===r;return o.length>1&&a?t:1!==o.length||!i[3].startsWith(`.${r}`)&&i[3][0]!==r?n.leadingZeros&&!a?(e=(i[1]||"")+i[3],Number(e)):t:Number(e)}return t}(t,n,e);{const s=D.exec(n);if(s){const r=s[1]||"",o=s[2];let a=(i=s[3])&&-1!==i.indexOf(".")?("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1)),i):i;const l=r?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!l))return t;{const i=Number(n),s=String(i);if(0===i||-0===i)return i;if(-1!==s.search(/[eE]/))return e.eNotation?i:t;if(-1!==n.indexOf("."))return"0"===s||s===a||s===`${r}${a}`?i:t;let l=o?a:n;return o?l===s||r+l===s?i:t:l===s||l===r+s?i:t}}return t}var i}(t,n)}return void 0!==t?t:""}const K=T.getMetaDataSymbol();function Q(t,e){return tt(t,e)}function tt(t,e,n){let i;const s={};for(let r=0;r0&&(s[e.textNodeName]=i):void 0!==i&&(s[e.textNodeName]=i),s}function et(t){const e=Object.keys(t);for(let t=0;t0&&(n="\n"),ot(t,e,"",n)}function ot(t,e,n,i){let s="",r=!1;for(let o=0;o`,r=!1;continue}if(l===e.commentPropName){s+=i+`\x3c!--${a[l][0][e.textNodeName]}--\x3e`,r=!0;continue}if("?"===l[0]){const t=lt(a[":@"],e),n="?xml"===l?"":i;let o=a[l][0][e.textNodeName];o=0!==o.length?" "+o:"",s+=n+`<${l}${o}${t}?>`,r=!0;continue}let h=i;""!==h&&(h+=e.indentBy);const d=i+`<${l}${lt(a[":@"],e)}`,f=ot(a[l],e,u,h);-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?s+=d+">":s+=d+"/>":f&&0!==f.length||!e.suppressEmptyNode?f&&f.endsWith(">")?s+=d+`>${f}${i}`:(s+=d+">",f&&""!==i&&(f.includes("/>")||f.includes("`):s+=d+"/>",r=!0}return s}function at(t){const e=Object.keys(t);for(let n=0;n0&&e.processEntities)for(let n=0;n","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ft(t){this.options=Object.assign({},dt,t),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=_(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=gt),this.processTextOrObjNode=ct,this.options.format?(this.indentate=pt,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function ct(t,e,n,i){const s=this.j2x(t,n+1,i.concat(e));return void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,s.attrStr,n):this.buildObjectNode(s.val,e,s.attrStr,n)}function pt(t){return this.options.indentBy.repeat(t)}function gt(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}ft.prototype.build=function(t){return this.options.preserveOrder?rt(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0,[]).val)},ft.prototype.j2x=function(t,e,n){let i="",s="";const r=n.join(".");for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(void 0===t[o])this.isAttribute(o)&&(s+="");else if(null===t[o])this.isAttribute(o)||o===this.options.cdataPropName?s+="":"?"===o[0]?s+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)s+=this.buildTextValNode(t[o],o,"",e);else if("object"!=typeof t[o]){const n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,r))i+=this.buildAttrPairStr(n,""+t[o]);else if(!n)if(o===this.options.textNodeName){let e=this.options.tagValueProcessor(o,""+t[o]);s+=this.replaceEntitiesValue(e)}else s+=this.buildTextValNode(t[o],o,"",e)}else if(Array.isArray(t[o])){const i=t[o].length;let r="",a="";for(let l=0;l"+t+s}},ft.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(i)+`\x3c!--${t}--\x3e`+this.newLine;if("?"===e[0])return this.indentate(i)+"<"+e+n+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(e,t);return s=this.replaceEntitiesValue(s),""===s?this.indentate(i)+"<"+e+n+this.closeTag(e)+this.tagEndChar:this.indentate(i)+"<"+e+n+">"+s+"0&&this.options.processEntities)for(let e=0;e { - -(()=>{"use strict";var t={d:(e,n)=>{for(var i in n)t.o(n,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:n[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{XMLBuilder:()=>ft,XMLParser:()=>st,XMLValidator:()=>mt});const n=":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",i=new RegExp("^["+n+"]["+n+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function s(t,e){const n=[];let i=e.exec(t);for(;i;){const s=[];s.startIndex=e.lastIndex-i[0].length;const r=i.length;for(let t=0;t"!==t[o]&&" "!==t[o]&&"\t"!==t[o]&&"\n"!==t[o]&&"\r"!==t[o];o++)f+=t[o];if(f=f.trim(),"/"===f[f.length-1]&&(f=f.substring(0,f.length-1),o--),!r(f)){let e;return e=0===f.trim().length?"Invalid space after '<'.":"Tag '"+f+"' is an invalid name.",x("InvalidTag",e,N(t,o))}const p=c(t,o);if(!1===p)return x("InvalidAttr","Attributes for '"+f+"' have open quote.",N(t,o));let b=p.value;if(o=p.index,"/"===b[b.length-1]){const n=o-b.length;b=b.substring(0,b.length-1);const s=g(b,e);if(!0!==s)return x(s.err.code,s.err.msg,N(t,n+s.err.line));i=!0}else if(d){if(!p.tagClosed)return x("InvalidTag","Closing tag '"+f+"' doesn't have proper closing.",N(t,o));if(b.trim().length>0)return x("InvalidTag","Closing tag '"+f+"' can't have attributes or invalid starting.",N(t,a));if(0===n.length)return x("InvalidTag","Closing tag '"+f+"' has not been opened.",N(t,a));{const e=n.pop();if(f!==e.tagName){let n=N(t,e.tagStartPos);return x("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+f+"'.",N(t,a))}0==n.length&&(s=!0)}}else{const r=g(b,e);if(!0!==r)return x(r.err.code,r.err.msg,N(t,o-b.length+r.err.line));if(!0===s)return x("InvalidXml","Multiple possible root nodes found.",N(t,o));-1!==e.unpairedTags.indexOf(f)||n.push({tagName:f,tagStartPos:a}),i=!0}for(o++;o0)||x("InvalidXml","Invalid '"+JSON.stringify(n.map((t=>t.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):x("InvalidXml","Start tag expected.",1)}function l(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function u(t,e){const n=e;for(;e5&&"xml"===i)return x("InvalidXml","XML declaration allowed only at the start of the document.",N(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}}return e}function h(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let n=1;for(e+=8;e"===t[e]&&(n--,0===n))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}const d='"',f="'";function c(t,e){let n="",i="",s=!1;for(;e"===t[e]&&""===i){s=!0;break}n+=t[e]}return""===i&&{value:n,index:e,tagClosed:s}}const p=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function g(t,e){const n=s(t,p),i={};for(let t=0;t!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t},captureMetaData:!1};let y;y="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class T{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][y]={startIndex:e})}static getMetaDataSymbol(){return y}}function w(t,e){const n={};if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let i=1,s=!1,r=!1,o="";for(;e"===t[e]){if(r?"-"===t[e-1]&&"-"===t[e-2]&&(r=!1,i--):i--,0===i)break}else"["===t[e]?s=!0:o+=t[e];else{if(s&&C(t,"!ENTITY",e)){let i,s;e+=7,[i,s,e]=O(t,e+1),-1===s.indexOf("&")&&(n[i]={regx:RegExp(`&${i};`,"g"),val:s})}else if(s&&C(t,"!ELEMENT",e)){e+=8;const{index:n}=S(t,e+1);e=n}else if(s&&C(t,"!ATTLIST",e))e+=8;else if(s&&C(t,"!NOTATION",e)){e+=9;const{index:n}=A(t,e+1);e=n}else{if(!C(t,"!--",e))throw new Error("Invalid DOCTYPE");r=!0}i++,o=""}if(0!==i)throw new Error("Unclosed DOCTYPE")}return{entities:n,i:e}}const P=(t,e)=>{for(;e{for(const n of t){if("string"==typeof n&&e===n)return!0;if(n instanceof RegExp&&n.test(e))return!0}}:()=>!1}class k{constructor(t){this.options=t,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:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>String.fromCodePoint(Number.parseInt(e,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>String.fromCodePoint(Number.parseInt(e,16))}},this.addExternalEntities=F,this.parseXml=X,this.parseTextData=L,this.resolveNameSpace=B,this.buildAttributesMap=G,this.isItStopNode=Z,this.replaceEntitiesValue=R,this.readStopNodeData=J,this.saveTextToParentTag=q,this.addChild=Y,this.ignoreAttributesFn=_(this.options.ignoreAttributes)}}function F(t){const e=Object.keys(t);for(let n=0;n0)){o||(t=this.replaceEntitiesValue(t));const i=this.options.tagValueProcessor(e,t,n,s,r);return null==i?t:typeof i!=typeof t||i!==t?i:this.options.trimValues||t.trim()===t?H(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function B(t){if(this.options.removeNSPrefix){const e=t.split(":"),n="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=n+e[1])}return t}const U=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function G(t,e,n){if(!0!==this.options.ignoreAttributes&&"string"==typeof t){const n=s(t,U),i=n.length,r={};for(let t=0;t",r,"Closing Tag is not closed.");let o=t.substring(r+2,e).trim();if(this.options.removeNSPrefix){const t=o.indexOf(":");-1!==t&&(o=o.substr(t+1))}this.options.transformTagName&&(o=this.options.transformTagName(o)),n&&(i=this.saveTextToParentTag(i,n,s));const a=s.substring(s.lastIndexOf(".")+1);if(o&&-1!==this.options.unpairedTags.indexOf(o))throw new Error(`Unpaired tag can not be used as closing tag: `);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=s.lastIndexOf(".",s.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=s.lastIndexOf("."),s=s.substring(0,l),n=this.tagsNodeStack.pop(),i="",r=e}else if("?"===t[r+1]){let e=z(t,r,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,n,s),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new T(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,s,e.tagName)),this.addChild(n,t,s,r)}r=e.closeIndex+1}else if("!--"===t.substr(r+1,3)){const e=W(t,"--\x3e",r+4,"Comment is not closed.");if(this.options.commentPropName){const o=t.substring(r+4,e-2);i=this.saveTextToParentTag(i,n,s),n.add(this.options.commentPropName,[{[this.options.textNodeName]:o}])}r=e}else if("!D"===t.substr(r+1,2)){const e=w(t,r);this.docTypeEntities=e.entities,r=e.i}else if("!["===t.substr(r+1,2)){const e=W(t,"]]>",r,"CDATA is not closed.")-2,o=t.substring(r+9,e);i=this.saveTextToParentTag(i,n,s);let a=this.parseTextData(o,n.tagname,s,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:o}]):n.add(this.options.textNodeName,a),r=e+2}else{let o=z(t,r,this.options.removeNSPrefix),a=o.tagName;const l=o.rawTagName;let u=o.tagExp,h=o.attrExpPresent,d=o.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),n&&i&&"!xml"!==n.tagname&&(i=this.saveTextToParentTag(i,n,s,!1));const f=n;f&&-1!==this.options.unpairedTags.indexOf(f.tagname)&&(n=this.tagsNodeStack.pop(),s=s.substring(0,s.lastIndexOf("."))),a!==e.tagname&&(s+=s?"."+a:a);const c=r;if(this.isItStopNode(this.options.stopNodes,s,a)){let e="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),u=a):u=u.substr(0,u.length-1),r=o.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))r=o.closeIndex;else{const n=this.readStopNodeData(t,l,d+1);if(!n)throw new Error(`Unexpected end of ${l}`);r=n.i,e=n.tagContent}const i=new T(a);a!==u&&h&&(i[":@"]=this.buildAttributesMap(u,s,a)),e&&(e=this.parseTextData(e,a,s,!0,h,!0,!0)),s=s.substr(0,s.lastIndexOf(".")),i.add(this.options.textNodeName,e),this.addChild(n,i,s,c)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),u=a):u=u.substr(0,u.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const t=new T(a);a!==u&&h&&(t[":@"]=this.buildAttributesMap(u,s,a)),this.addChild(n,t,s,c),s=s.substr(0,s.lastIndexOf("."))}else{const t=new T(a);this.tagsNodeStack.push(n),a!==u&&h&&(t[":@"]=this.buildAttributesMap(u,s,a)),this.addChild(n,t,s,c),n=t}i="",r=d}}else i+=t[r];return e.child};function Y(t,e,n,i){this.options.captureMetaData||(i=void 0);const s=this.options.updateTag(e.tagname,n,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e,i)):t.addChild(e,i))}const R=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){const n=this.docTypeEntities[e];t=t.replace(n.regx,n.val)}for(let e in this.lastEntities){const n=this.lastEntities[e];t=t.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){const n=this.htmlEntities[e];t=t.replace(n.regex,n.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function q(t,e,n,i){return t&&(void 0===i&&(i=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,n,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,i))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function Z(t,e,n){const i="*."+n;for(const n in t){const s=t[n];if(i===s||e===s)return!0}return!1}function W(t,e,n,i){const s=t.indexOf(e,n);if(-1===s)throw new Error(i);return s+e.length-1}function z(t,e,n,i=">"){const s=function(t,e,n=">"){let i,s="";for(let r=e;r",n,`${e} is not closed`);if(t.substring(n+2,r).trim()===e&&(s--,0===s))return{tagContent:t.substring(i,n),i:r};n=r}else if("?"===t[n+1])n=W(t,"?>",n+1,"StopNode is not closed.");else if("!--"===t.substr(n+1,3))n=W(t,"--\x3e",n+3,"StopNode is not closed.");else if("!["===t.substr(n+1,2))n=W(t,"]]>",n,"StopNode is not closed.")-2;else{const i=z(t,n,">");i&&((i&&i.tagName)===e&&"/"!==i.tagExp[i.tagExp.length-1]&&s++,n=i.closeIndex)}}function H(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},V,e),!t||"string"!=typeof t)return t;let n=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(n))return t;if("0"===t)return 0;if(e.hex&&j.test(n))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(n);if(-1!==n.search(/.+[eE].+/))return function(t,e,n){if(!n.eNotation)return t;const i=e.match(M);if(i){let s=i[1]||"";const r=-1===i[3].indexOf("e")?"E":"e",o=i[2],a=s?t[o.length+1]===r:t[o.length]===r;return o.length>1&&a?t:1!==o.length||!i[3].startsWith(`.${r}`)&&i[3][0]!==r?n.leadingZeros&&!a?(e=(i[1]||"")+i[3],Number(e)):t:Number(e)}return t}(t,n,e);{const s=D.exec(n);if(s){const r=s[1]||"",o=s[2];let a=(i=s[3])&&-1!==i.indexOf(".")?("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1)),i):i;const l=r?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!l))return t;{const i=Number(n),s=String(i);if(0===i||-0===i)return i;if(-1!==s.search(/[eE]/))return e.eNotation?i:t;if(-1!==n.indexOf("."))return"0"===s||s===a||s===`${r}${a}`?i:t;let l=o?a:n;return o?l===s||r+l===s?i:t:l===s||l===r+s?i:t}}return t}var i}(t,n)}return void 0!==t?t:""}const K=T.getMetaDataSymbol();function Q(t,e){return tt(t,e)}function tt(t,e,n){let i;const s={};for(let r=0;r0&&(s[e.textNodeName]=i):void 0!==i&&(s[e.textNodeName]=i),s}function et(t){const e=Object.keys(t);for(let t=0;t0&&(n="\n"),ot(t,e,"",n)}function ot(t,e,n,i){let s="",r=!1;for(let o=0;o`,r=!1;continue}if(l===e.commentPropName){s+=i+`\x3c!--${a[l][0][e.textNodeName]}--\x3e`,r=!0;continue}if("?"===l[0]){const t=lt(a[":@"],e),n="?xml"===l?"":i;let o=a[l][0][e.textNodeName];o=0!==o.length?" "+o:"",s+=n+`<${l}${o}${t}?>`,r=!0;continue}let h=i;""!==h&&(h+=e.indentBy);const d=i+`<${l}${lt(a[":@"],e)}`,f=ot(a[l],e,u,h);-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?s+=d+">":s+=d+"/>":f&&0!==f.length||!e.suppressEmptyNode?f&&f.endsWith(">")?s+=d+`>${f}${i}`:(s+=d+">",f&&""!==i&&(f.includes("/>")||f.includes("`):s+=d+"/>",r=!0}return s}function at(t){const e=Object.keys(t);for(let n=0;n0&&e.processEntities)for(let n=0;n","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ft(t){this.options=Object.assign({},dt,t),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=_(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=gt),this.processTextOrObjNode=ct,this.options.format?(this.indentate=pt,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function ct(t,e,n,i){const s=this.j2x(t,n+1,i.concat(e));return void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,s.attrStr,n):this.buildObjectNode(s.val,e,s.attrStr,n)}function pt(t){return this.options.indentBy.repeat(t)}function gt(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}ft.prototype.build=function(t){return this.options.preserveOrder?rt(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0,[]).val)},ft.prototype.j2x=function(t,e,n){let i="",s="";const r=n.join(".");for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(void 0===t[o])this.isAttribute(o)&&(s+="");else if(null===t[o])this.isAttribute(o)||o===this.options.cdataPropName?s+="":"?"===o[0]?s+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)s+=this.buildTextValNode(t[o],o,"",e);else if("object"!=typeof t[o]){const n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,r))i+=this.buildAttrPairStr(n,""+t[o]);else if(!n)if(o===this.options.textNodeName){let e=this.options.tagValueProcessor(o,""+t[o]);s+=this.replaceEntitiesValue(e)}else s+=this.buildTextValNode(t[o],o,"",e)}else if(Array.isArray(t[o])){const i=t[o].length;let r="",a="";for(let l=0;l"+t+s}},ft.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(i)+`\x3c!--${t}--\x3e`+this.newLine;if("?"===e[0])return this.indentate(i)+"<"+e+n+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(e,t);return s=this.replaceEntitiesValue(s),""===s?this.indentate(i)+"<"+e+n+this.closeTag(e)+this.tagEndChar:this.indentate(i)+"<"+e+n+">"+s+"0&&this.options.processEntities)for(let e=0;e { - -(()=>{"use strict";var t={d:(e,n)=>{for(var i in n)t.o(n,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:n[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{XMLBuilder:()=>ft,XMLParser:()=>st,XMLValidator:()=>mt});const n=":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",i=new RegExp("^["+n+"]["+n+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function s(t,e){const n=[];let i=e.exec(t);for(;i;){const s=[];s.startIndex=e.lastIndex-i[0].length;const r=i.length;for(let t=0;t"!==t[o]&&" "!==t[o]&&"\t"!==t[o]&&"\n"!==t[o]&&"\r"!==t[o];o++)f+=t[o];if(f=f.trim(),"/"===f[f.length-1]&&(f=f.substring(0,f.length-1),o--),!r(f)){let e;return e=0===f.trim().length?"Invalid space after '<'.":"Tag '"+f+"' is an invalid name.",x("InvalidTag",e,N(t,o))}const p=c(t,o);if(!1===p)return x("InvalidAttr","Attributes for '"+f+"' have open quote.",N(t,o));let b=p.value;if(o=p.index,"/"===b[b.length-1]){const n=o-b.length;b=b.substring(0,b.length-1);const s=g(b,e);if(!0!==s)return x(s.err.code,s.err.msg,N(t,n+s.err.line));i=!0}else if(d){if(!p.tagClosed)return x("InvalidTag","Closing tag '"+f+"' doesn't have proper closing.",N(t,o));if(b.trim().length>0)return x("InvalidTag","Closing tag '"+f+"' can't have attributes or invalid starting.",N(t,a));if(0===n.length)return x("InvalidTag","Closing tag '"+f+"' has not been opened.",N(t,a));{const e=n.pop();if(f!==e.tagName){let n=N(t,e.tagStartPos);return x("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+f+"'.",N(t,a))}0==n.length&&(s=!0)}}else{const r=g(b,e);if(!0!==r)return x(r.err.code,r.err.msg,N(t,o-b.length+r.err.line));if(!0===s)return x("InvalidXml","Multiple possible root nodes found.",N(t,o));-1!==e.unpairedTags.indexOf(f)||n.push({tagName:f,tagStartPos:a}),i=!0}for(o++;o0)||x("InvalidXml","Invalid '"+JSON.stringify(n.map((t=>t.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):x("InvalidXml","Start tag expected.",1)}function l(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function u(t,e){const n=e;for(;e5&&"xml"===i)return x("InvalidXml","XML declaration allowed only at the start of the document.",N(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}}return e}function h(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let n=1;for(e+=8;e"===t[e]&&(n--,0===n))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}const d='"',f="'";function c(t,e){let n="",i="",s=!1;for(;e"===t[e]&&""===i){s=!0;break}n+=t[e]}return""===i&&{value:n,index:e,tagClosed:s}}const p=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function g(t,e){const n=s(t,p),i={};for(let t=0;t!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t},captureMetaData:!1};let y;y="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class T{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][y]={startIndex:e})}static getMetaDataSymbol(){return y}}function w(t,e){const n={};if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let i=1,s=!1,r=!1,o="";for(;e"===t[e]){if(r?"-"===t[e-1]&&"-"===t[e-2]&&(r=!1,i--):i--,0===i)break}else"["===t[e]?s=!0:o+=t[e];else{if(s&&C(t,"!ENTITY",e)){let i,s;e+=7,[i,s,e]=O(t,e+1),-1===s.indexOf("&")&&(n[i]={regx:RegExp(`&${i};`,"g"),val:s})}else if(s&&C(t,"!ELEMENT",e)){e+=8;const{index:n}=S(t,e+1);e=n}else if(s&&C(t,"!ATTLIST",e))e+=8;else if(s&&C(t,"!NOTATION",e)){e+=9;const{index:n}=A(t,e+1);e=n}else{if(!C(t,"!--",e))throw new Error("Invalid DOCTYPE");r=!0}i++,o=""}if(0!==i)throw new Error("Unclosed DOCTYPE")}return{entities:n,i:e}}const P=(t,e)=>{for(;e{for(const n of t){if("string"==typeof n&&e===n)return!0;if(n instanceof RegExp&&n.test(e))return!0}}:()=>!1}class k{constructor(t){this.options=t,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:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>String.fromCodePoint(Number.parseInt(e,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>String.fromCodePoint(Number.parseInt(e,16))}},this.addExternalEntities=F,this.parseXml=X,this.parseTextData=L,this.resolveNameSpace=B,this.buildAttributesMap=G,this.isItStopNode=Z,this.replaceEntitiesValue=R,this.readStopNodeData=J,this.saveTextToParentTag=q,this.addChild=Y,this.ignoreAttributesFn=_(this.options.ignoreAttributes)}}function F(t){const e=Object.keys(t);for(let n=0;n0)){o||(t=this.replaceEntitiesValue(t));const i=this.options.tagValueProcessor(e,t,n,s,r);return null==i?t:typeof i!=typeof t||i!==t?i:this.options.trimValues||t.trim()===t?H(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function B(t){if(this.options.removeNSPrefix){const e=t.split(":"),n="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=n+e[1])}return t}const U=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function G(t,e,n){if(!0!==this.options.ignoreAttributes&&"string"==typeof t){const n=s(t,U),i=n.length,r={};for(let t=0;t",r,"Closing Tag is not closed.");let o=t.substring(r+2,e).trim();if(this.options.removeNSPrefix){const t=o.indexOf(":");-1!==t&&(o=o.substr(t+1))}this.options.transformTagName&&(o=this.options.transformTagName(o)),n&&(i=this.saveTextToParentTag(i,n,s));const a=s.substring(s.lastIndexOf(".")+1);if(o&&-1!==this.options.unpairedTags.indexOf(o))throw new Error(`Unpaired tag can not be used as closing tag: `);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=s.lastIndexOf(".",s.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=s.lastIndexOf("."),s=s.substring(0,l),n=this.tagsNodeStack.pop(),i="",r=e}else if("?"===t[r+1]){let e=z(t,r,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,n,s),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new T(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,s,e.tagName)),this.addChild(n,t,s,r)}r=e.closeIndex+1}else if("!--"===t.substr(r+1,3)){const e=W(t,"--\x3e",r+4,"Comment is not closed.");if(this.options.commentPropName){const o=t.substring(r+4,e-2);i=this.saveTextToParentTag(i,n,s),n.add(this.options.commentPropName,[{[this.options.textNodeName]:o}])}r=e}else if("!D"===t.substr(r+1,2)){const e=w(t,r);this.docTypeEntities=e.entities,r=e.i}else if("!["===t.substr(r+1,2)){const e=W(t,"]]>",r,"CDATA is not closed.")-2,o=t.substring(r+9,e);i=this.saveTextToParentTag(i,n,s);let a=this.parseTextData(o,n.tagname,s,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:o}]):n.add(this.options.textNodeName,a),r=e+2}else{let o=z(t,r,this.options.removeNSPrefix),a=o.tagName;const l=o.rawTagName;let u=o.tagExp,h=o.attrExpPresent,d=o.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),n&&i&&"!xml"!==n.tagname&&(i=this.saveTextToParentTag(i,n,s,!1));const f=n;f&&-1!==this.options.unpairedTags.indexOf(f.tagname)&&(n=this.tagsNodeStack.pop(),s=s.substring(0,s.lastIndexOf("."))),a!==e.tagname&&(s+=s?"."+a:a);const c=r;if(this.isItStopNode(this.options.stopNodes,s,a)){let e="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),u=a):u=u.substr(0,u.length-1),r=o.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))r=o.closeIndex;else{const n=this.readStopNodeData(t,l,d+1);if(!n)throw new Error(`Unexpected end of ${l}`);r=n.i,e=n.tagContent}const i=new T(a);a!==u&&h&&(i[":@"]=this.buildAttributesMap(u,s,a)),e&&(e=this.parseTextData(e,a,s,!0,h,!0,!0)),s=s.substr(0,s.lastIndexOf(".")),i.add(this.options.textNodeName,e),this.addChild(n,i,s,c)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),u=a):u=u.substr(0,u.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const t=new T(a);a!==u&&h&&(t[":@"]=this.buildAttributesMap(u,s,a)),this.addChild(n,t,s,c),s=s.substr(0,s.lastIndexOf("."))}else{const t=new T(a);this.tagsNodeStack.push(n),a!==u&&h&&(t[":@"]=this.buildAttributesMap(u,s,a)),this.addChild(n,t,s,c),n=t}i="",r=d}}else i+=t[r];return e.child};function Y(t,e,n,i){this.options.captureMetaData||(i=void 0);const s=this.options.updateTag(e.tagname,n,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e,i)):t.addChild(e,i))}const R=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){const n=this.docTypeEntities[e];t=t.replace(n.regx,n.val)}for(let e in this.lastEntities){const n=this.lastEntities[e];t=t.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){const n=this.htmlEntities[e];t=t.replace(n.regex,n.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function q(t,e,n,i){return t&&(void 0===i&&(i=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,n,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,i))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function Z(t,e,n){const i="*."+n;for(const n in t){const s=t[n];if(i===s||e===s)return!0}return!1}function W(t,e,n,i){const s=t.indexOf(e,n);if(-1===s)throw new Error(i);return s+e.length-1}function z(t,e,n,i=">"){const s=function(t,e,n=">"){let i,s="";for(let r=e;r",n,`${e} is not closed`);if(t.substring(n+2,r).trim()===e&&(s--,0===s))return{tagContent:t.substring(i,n),i:r};n=r}else if("?"===t[n+1])n=W(t,"?>",n+1,"StopNode is not closed.");else if("!--"===t.substr(n+1,3))n=W(t,"--\x3e",n+3,"StopNode is not closed.");else if("!["===t.substr(n+1,2))n=W(t,"]]>",n,"StopNode is not closed.")-2;else{const i=z(t,n,">");i&&((i&&i.tagName)===e&&"/"!==i.tagExp[i.tagExp.length-1]&&s++,n=i.closeIndex)}}function H(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},V,e),!t||"string"!=typeof t)return t;let n=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(n))return t;if("0"===t)return 0;if(e.hex&&j.test(n))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(n);if(-1!==n.search(/.+[eE].+/))return function(t,e,n){if(!n.eNotation)return t;const i=e.match(M);if(i){let s=i[1]||"";const r=-1===i[3].indexOf("e")?"E":"e",o=i[2],a=s?t[o.length+1]===r:t[o.length]===r;return o.length>1&&a?t:1!==o.length||!i[3].startsWith(`.${r}`)&&i[3][0]!==r?n.leadingZeros&&!a?(e=(i[1]||"")+i[3],Number(e)):t:Number(e)}return t}(t,n,e);{const s=D.exec(n);if(s){const r=s[1]||"",o=s[2];let a=(i=s[3])&&-1!==i.indexOf(".")?("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1)),i):i;const l=r?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!l))return t;{const i=Number(n),s=String(i);if(0===i||-0===i)return i;if(-1!==s.search(/[eE]/))return e.eNotation?i:t;if(-1!==n.indexOf("."))return"0"===s||s===a||s===`${r}${a}`?i:t;let l=o?a:n;return o?l===s||r+l===s?i:t:l===s||l===r+s?i:t}}return t}var i}(t,n)}return void 0!==t?t:""}const K=T.getMetaDataSymbol();function Q(t,e){return tt(t,e)}function tt(t,e,n){let i;const s={};for(let r=0;r0&&(s[e.textNodeName]=i):void 0!==i&&(s[e.textNodeName]=i),s}function et(t){const e=Object.keys(t);for(let t=0;t0&&(n="\n"),ot(t,e,"",n)}function ot(t,e,n,i){let s="",r=!1;for(let o=0;o`,r=!1;continue}if(l===e.commentPropName){s+=i+`\x3c!--${a[l][0][e.textNodeName]}--\x3e`,r=!0;continue}if("?"===l[0]){const t=lt(a[":@"],e),n="?xml"===l?"":i;let o=a[l][0][e.textNodeName];o=0!==o.length?" "+o:"",s+=n+`<${l}${o}${t}?>`,r=!0;continue}let h=i;""!==h&&(h+=e.indentBy);const d=i+`<${l}${lt(a[":@"],e)}`,f=ot(a[l],e,u,h);-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?s+=d+">":s+=d+"/>":f&&0!==f.length||!e.suppressEmptyNode?f&&f.endsWith(">")?s+=d+`>${f}${i}`:(s+=d+">",f&&""!==i&&(f.includes("/>")||f.includes("`):s+=d+"/>",r=!0}return s}function at(t){const e=Object.keys(t);for(let n=0;n0&&e.processEntities)for(let n=0;n","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ft(t){this.options=Object.assign({},dt,t),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=_(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=gt),this.processTextOrObjNode=ct,this.options.format?(this.indentate=pt,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function ct(t,e,n,i){const s=this.j2x(t,n+1,i.concat(e));return void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,s.attrStr,n):this.buildObjectNode(s.val,e,s.attrStr,n)}function pt(t){return this.options.indentBy.repeat(t)}function gt(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}ft.prototype.build=function(t){return this.options.preserveOrder?rt(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0,[]).val)},ft.prototype.j2x=function(t,e,n){let i="",s="";const r=n.join(".");for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(void 0===t[o])this.isAttribute(o)&&(s+="");else if(null===t[o])this.isAttribute(o)||o===this.options.cdataPropName?s+="":"?"===o[0]?s+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)s+=this.buildTextValNode(t[o],o,"",e);else if("object"!=typeof t[o]){const n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,r))i+=this.buildAttrPairStr(n,""+t[o]);else if(!n)if(o===this.options.textNodeName){let e=this.options.tagValueProcessor(o,""+t[o]);s+=this.replaceEntitiesValue(e)}else s+=this.buildTextValNode(t[o],o,"",e)}else if(Array.isArray(t[o])){const i=t[o].length;let r="",a="";for(let l=0;l"+t+s}},ft.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(i)+`\x3c!--${t}--\x3e`+this.newLine;if("?"===e[0])return this.indentate(i)+"<"+e+n+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(e,t);return s=this.replaceEntitiesValue(s),""===s?this.indentate(i)+"<"+e+n+this.closeTag(e)+this.tagEndChar:this.indentate(i)+"<"+e+n+">"+s+"0&&this.options.processEntities)for(let e=0;e { (()=>{"use strict";var t={d:(e,n)=>{for(var i in n)t.o(n,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:n[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{XMLBuilder:()=>ft,XMLParser:()=>st,XMLValidator:()=>mt});const n=":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",i=new RegExp("^["+n+"]["+n+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function s(t,e){const n=[];let i=e.exec(t);for(;i;){const s=[];s.startIndex=e.lastIndex-i[0].length;const r=i.length;for(let t=0;t"!==t[o]&&" "!==t[o]&&"\t"!==t[o]&&"\n"!==t[o]&&"\r"!==t[o];o++)f+=t[o];if(f=f.trim(),"/"===f[f.length-1]&&(f=f.substring(0,f.length-1),o--),!r(f)){let e;return e=0===f.trim().length?"Invalid space after '<'.":"Tag '"+f+"' is an invalid name.",x("InvalidTag",e,N(t,o))}const p=c(t,o);if(!1===p)return x("InvalidAttr","Attributes for '"+f+"' have open quote.",N(t,o));let b=p.value;if(o=p.index,"/"===b[b.length-1]){const n=o-b.length;b=b.substring(0,b.length-1);const s=g(b,e);if(!0!==s)return x(s.err.code,s.err.msg,N(t,n+s.err.line));i=!0}else if(d){if(!p.tagClosed)return x("InvalidTag","Closing tag '"+f+"' doesn't have proper closing.",N(t,o));if(b.trim().length>0)return x("InvalidTag","Closing tag '"+f+"' can't have attributes or invalid starting.",N(t,a));if(0===n.length)return x("InvalidTag","Closing tag '"+f+"' has not been opened.",N(t,a));{const e=n.pop();if(f!==e.tagName){let n=N(t,e.tagStartPos);return x("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+f+"'.",N(t,a))}0==n.length&&(s=!0)}}else{const r=g(b,e);if(!0!==r)return x(r.err.code,r.err.msg,N(t,o-b.length+r.err.line));if(!0===s)return x("InvalidXml","Multiple possible root nodes found.",N(t,o));-1!==e.unpairedTags.indexOf(f)||n.push({tagName:f,tagStartPos:a}),i=!0}for(o++;o0)||x("InvalidXml","Invalid '"+JSON.stringify(n.map((t=>t.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):x("InvalidXml","Start tag expected.",1)}function l(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function u(t,e){const n=e;for(;e5&&"xml"===i)return x("InvalidXml","XML declaration allowed only at the start of the document.",N(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}}return e}function h(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let n=1;for(e+=8;e"===t[e]&&(n--,0===n))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}const d='"',f="'";function c(t,e){let n="",i="",s=!1;for(;e"===t[e]&&""===i){s=!0;break}n+=t[e]}return""===i&&{value:n,index:e,tagClosed:s}}const p=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function g(t,e){const n=s(t,p),i={};for(let t=0;t!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t},captureMetaData:!1};let y;y="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class T{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][y]={startIndex:e})}static getMetaDataSymbol(){return y}}function w(t,e){const n={};if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let i=1,s=!1,r=!1,o="";for(;e"===t[e]){if(r?"-"===t[e-1]&&"-"===t[e-2]&&(r=!1,i--):i--,0===i)break}else"["===t[e]?s=!0:o+=t[e];else{if(s&&C(t,"!ENTITY",e)){let i,s;e+=7,[i,s,e]=O(t,e+1),-1===s.indexOf("&")&&(n[i]={regx:RegExp(`&${i};`,"g"),val:s})}else if(s&&C(t,"!ELEMENT",e)){e+=8;const{index:n}=S(t,e+1);e=n}else if(s&&C(t,"!ATTLIST",e))e+=8;else if(s&&C(t,"!NOTATION",e)){e+=9;const{index:n}=A(t,e+1);e=n}else{if(!C(t,"!--",e))throw new Error("Invalid DOCTYPE");r=!0}i++,o=""}if(0!==i)throw new Error("Unclosed DOCTYPE")}return{entities:n,i:e}}const P=(t,e)=>{for(;e{for(const n of t){if("string"==typeof n&&e===n)return!0;if(n instanceof RegExp&&n.test(e))return!0}}:()=>!1}class k{constructor(t){this.options=t,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:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>String.fromCodePoint(Number.parseInt(e,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>String.fromCodePoint(Number.parseInt(e,16))}},this.addExternalEntities=F,this.parseXml=X,this.parseTextData=L,this.resolveNameSpace=B,this.buildAttributesMap=G,this.isItStopNode=Z,this.replaceEntitiesValue=R,this.readStopNodeData=J,this.saveTextToParentTag=q,this.addChild=Y,this.ignoreAttributesFn=_(this.options.ignoreAttributes)}}function F(t){const e=Object.keys(t);for(let n=0;n0)){o||(t=this.replaceEntitiesValue(t));const i=this.options.tagValueProcessor(e,t,n,s,r);return null==i?t:typeof i!=typeof t||i!==t?i:this.options.trimValues||t.trim()===t?H(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function B(t){if(this.options.removeNSPrefix){const e=t.split(":"),n="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=n+e[1])}return t}const U=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function G(t,e,n){if(!0!==this.options.ignoreAttributes&&"string"==typeof t){const n=s(t,U),i=n.length,r={};for(let t=0;t",r,"Closing Tag is not closed.");let o=t.substring(r+2,e).trim();if(this.options.removeNSPrefix){const t=o.indexOf(":");-1!==t&&(o=o.substr(t+1))}this.options.transformTagName&&(o=this.options.transformTagName(o)),n&&(i=this.saveTextToParentTag(i,n,s));const a=s.substring(s.lastIndexOf(".")+1);if(o&&-1!==this.options.unpairedTags.indexOf(o))throw new Error(`Unpaired tag can not be used as closing tag: `);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=s.lastIndexOf(".",s.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=s.lastIndexOf("."),s=s.substring(0,l),n=this.tagsNodeStack.pop(),i="",r=e}else if("?"===t[r+1]){let e=z(t,r,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,n,s),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new T(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,s,e.tagName)),this.addChild(n,t,s,r)}r=e.closeIndex+1}else if("!--"===t.substr(r+1,3)){const e=W(t,"--\x3e",r+4,"Comment is not closed.");if(this.options.commentPropName){const o=t.substring(r+4,e-2);i=this.saveTextToParentTag(i,n,s),n.add(this.options.commentPropName,[{[this.options.textNodeName]:o}])}r=e}else if("!D"===t.substr(r+1,2)){const e=w(t,r);this.docTypeEntities=e.entities,r=e.i}else if("!["===t.substr(r+1,2)){const e=W(t,"]]>",r,"CDATA is not closed.")-2,o=t.substring(r+9,e);i=this.saveTextToParentTag(i,n,s);let a=this.parseTextData(o,n.tagname,s,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:o}]):n.add(this.options.textNodeName,a),r=e+2}else{let o=z(t,r,this.options.removeNSPrefix),a=o.tagName;const l=o.rawTagName;let u=o.tagExp,h=o.attrExpPresent,d=o.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),n&&i&&"!xml"!==n.tagname&&(i=this.saveTextToParentTag(i,n,s,!1));const f=n;f&&-1!==this.options.unpairedTags.indexOf(f.tagname)&&(n=this.tagsNodeStack.pop(),s=s.substring(0,s.lastIndexOf("."))),a!==e.tagname&&(s+=s?"."+a:a);const c=r;if(this.isItStopNode(this.options.stopNodes,s,a)){let e="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),u=a):u=u.substr(0,u.length-1),r=o.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))r=o.closeIndex;else{const n=this.readStopNodeData(t,l,d+1);if(!n)throw new Error(`Unexpected end of ${l}`);r=n.i,e=n.tagContent}const i=new T(a);a!==u&&h&&(i[":@"]=this.buildAttributesMap(u,s,a)),e&&(e=this.parseTextData(e,a,s,!0,h,!0,!0)),s=s.substr(0,s.lastIndexOf(".")),i.add(this.options.textNodeName,e),this.addChild(n,i,s,c)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),u=a):u=u.substr(0,u.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const t=new T(a);a!==u&&h&&(t[":@"]=this.buildAttributesMap(u,s,a)),this.addChild(n,t,s,c),s=s.substr(0,s.lastIndexOf("."))}else{const t=new T(a);this.tagsNodeStack.push(n),a!==u&&h&&(t[":@"]=this.buildAttributesMap(u,s,a)),this.addChild(n,t,s,c),n=t}i="",r=d}}else i+=t[r];return e.child};function Y(t,e,n,i){this.options.captureMetaData||(i=void 0);const s=this.options.updateTag(e.tagname,n,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e,i)):t.addChild(e,i))}const R=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){const n=this.docTypeEntities[e];t=t.replace(n.regx,n.val)}for(let e in this.lastEntities){const n=this.lastEntities[e];t=t.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){const n=this.htmlEntities[e];t=t.replace(n.regex,n.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function q(t,e,n,i){return t&&(void 0===i&&(i=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,n,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,i))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function Z(t,e,n){const i="*."+n;for(const n in t){const s=t[n];if(i===s||e===s)return!0}return!1}function W(t,e,n,i){const s=t.indexOf(e,n);if(-1===s)throw new Error(i);return s+e.length-1}function z(t,e,n,i=">"){const s=function(t,e,n=">"){let i,s="";for(let r=e;r",n,`${e} is not closed`);if(t.substring(n+2,r).trim()===e&&(s--,0===s))return{tagContent:t.substring(i,n),i:r};n=r}else if("?"===t[n+1])n=W(t,"?>",n+1,"StopNode is not closed.");else if("!--"===t.substr(n+1,3))n=W(t,"--\x3e",n+3,"StopNode is not closed.");else if("!["===t.substr(n+1,2))n=W(t,"]]>",n,"StopNode is not closed.")-2;else{const i=z(t,n,">");i&&((i&&i.tagName)===e&&"/"!==i.tagExp[i.tagExp.length-1]&&s++,n=i.closeIndex)}}function H(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},V,e),!t||"string"!=typeof t)return t;let n=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(n))return t;if("0"===t)return 0;if(e.hex&&j.test(n))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(n);if(-1!==n.search(/.+[eE].+/))return function(t,e,n){if(!n.eNotation)return t;const i=e.match(M);if(i){let s=i[1]||"";const r=-1===i[3].indexOf("e")?"E":"e",o=i[2],a=s?t[o.length+1]===r:t[o.length]===r;return o.length>1&&a?t:1!==o.length||!i[3].startsWith(`.${r}`)&&i[3][0]!==r?n.leadingZeros&&!a?(e=(i[1]||"")+i[3],Number(e)):t:Number(e)}return t}(t,n,e);{const s=D.exec(n);if(s){const r=s[1]||"",o=s[2];let a=(i=s[3])&&-1!==i.indexOf(".")?("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1)),i):i;const l=r?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!l))return t;{const i=Number(n),s=String(i);if(0===i||-0===i)return i;if(-1!==s.search(/[eE]/))return e.eNotation?i:t;if(-1!==n.indexOf("."))return"0"===s||s===a||s===`${r}${a}`?i:t;let l=o?a:n;return o?l===s||r+l===s?i:t:l===s||l===r+s?i:t}}return t}var i}(t,n)}return void 0!==t?t:""}const K=T.getMetaDataSymbol();function Q(t,e){return tt(t,e)}function tt(t,e,n){let i;const s={};for(let r=0;r0&&(s[e.textNodeName]=i):void 0!==i&&(s[e.textNodeName]=i),s}function et(t){const e=Object.keys(t);for(let t=0;t0&&(n="\n"),ot(t,e,"",n)}function ot(t,e,n,i){let s="",r=!1;for(let o=0;o`,r=!1;continue}if(l===e.commentPropName){s+=i+`\x3c!--${a[l][0][e.textNodeName]}--\x3e`,r=!0;continue}if("?"===l[0]){const t=lt(a[":@"],e),n="?xml"===l?"":i;let o=a[l][0][e.textNodeName];o=0!==o.length?" "+o:"",s+=n+`<${l}${o}${t}?>`,r=!0;continue}let h=i;""!==h&&(h+=e.indentBy);const d=i+`<${l}${lt(a[":@"],e)}`,f=ot(a[l],e,u,h);-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?s+=d+">":s+=d+"/>":f&&0!==f.length||!e.suppressEmptyNode?f&&f.endsWith(">")?s+=d+`>${f}${i}`:(s+=d+">",f&&""!==i&&(f.includes("/>")||f.includes("`):s+=d+"/>",r=!0}return s}function at(t){const e=Object.keys(t);for(let n=0;n0&&e.processEntities)for(let n=0;n","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ft(t){this.options=Object.assign({},dt,t),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=_(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=gt),this.processTextOrObjNode=ct,this.options.format?(this.indentate=pt,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function ct(t,e,n,i){const s=this.j2x(t,n+1,i.concat(e));return void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,s.attrStr,n):this.buildObjectNode(s.val,e,s.attrStr,n)}function pt(t){return this.options.indentBy.repeat(t)}function gt(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}ft.prototype.build=function(t){return this.options.preserveOrder?rt(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0,[]).val)},ft.prototype.j2x=function(t,e,n){let i="",s="";const r=n.join(".");for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(void 0===t[o])this.isAttribute(o)&&(s+="");else if(null===t[o])this.isAttribute(o)||o===this.options.cdataPropName?s+="":"?"===o[0]?s+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)s+=this.buildTextValNode(t[o],o,"",e);else if("object"!=typeof t[o]){const n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,r))i+=this.buildAttrPairStr(n,""+t[o]);else if(!n)if(o===this.options.textNodeName){let e=this.options.tagValueProcessor(o,""+t[o]);s+=this.replaceEntitiesValue(e)}else s+=this.buildTextValNode(t[o],o,"",e)}else if(Array.isArray(t[o])){const i=t[o].length;let r="",a="";for(let l=0;l"+t+s}},ft.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(i)+`\x3c!--${t}--\x3e`+this.newLine;if("?"===e[0])return this.indentate(i)+"<"+e+n+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(e,t);return s=this.replaceEntitiesValue(s),""===s?this.indentate(i)+"<"+e+n+this.closeTag(e)+this.tagEndChar:this.indentate(i)+"<"+e+n+">"+s+"0&&this.options.processEntities)for(let e=0;e { "use strict"; -module.exports = JSON.parse('{"name":"@aws-sdk/client-lambda","description":"AWS SDK for JavaScript Lambda Client for Node.js, Browser and React Native","version":"3.826.0","scripts":{"build":"concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline client-lambda","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 lambda"},"main":"./dist-cjs/index.js","types":"./dist-types/index.d.ts","module":"./dist-es/index.js","sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.826.0","@aws-sdk/credential-provider-node":"3.826.0","@aws-sdk/middleware-host-header":"3.821.0","@aws-sdk/middleware-logger":"3.821.0","@aws-sdk/middleware-recursion-detection":"3.821.0","@aws-sdk/middleware-user-agent":"3.826.0","@aws-sdk/region-config-resolver":"3.821.0","@aws-sdk/types":"3.821.0","@aws-sdk/util-endpoints":"3.821.0","@aws-sdk/util-user-agent-browser":"3.821.0","@aws-sdk/util-user-agent-node":"3.826.0","@smithy/config-resolver":"^4.1.4","@smithy/core":"^3.5.3","@smithy/eventstream-serde-browser":"^4.0.4","@smithy/eventstream-serde-config-resolver":"^4.1.2","@smithy/eventstream-serde-node":"^4.0.4","@smithy/fetch-http-handler":"^5.0.4","@smithy/hash-node":"^4.0.4","@smithy/invalid-dependency":"^4.0.4","@smithy/middleware-content-length":"^4.0.4","@smithy/middleware-endpoint":"^4.1.11","@smithy/middleware-retry":"^4.1.12","@smithy/middleware-serde":"^4.0.8","@smithy/middleware-stack":"^4.0.4","@smithy/node-config-provider":"^4.1.3","@smithy/node-http-handler":"^4.0.6","@smithy/protocol-http":"^5.1.2","@smithy/smithy-client":"^4.4.3","@smithy/types":"^4.3.1","@smithy/url-parser":"^4.0.4","@smithy/util-base64":"^4.0.0","@smithy/util-body-length-browser":"^4.0.0","@smithy/util-body-length-node":"^4.0.0","@smithy/util-defaults-mode-browser":"^4.0.19","@smithy/util-defaults-mode-node":"^4.0.19","@smithy/util-endpoints":"^3.0.6","@smithy/util-middleware":"^4.0.4","@smithy/util-retry":"^4.0.5","@smithy/util-stream":"^4.2.2","@smithy/util-utf8":"^4.0.0","@smithy/util-waiter":"^4.0.5","tslib":"^2.6.2"},"devDependencies":{"@tsconfig/node18":"18.2.4","@types/node":"^18.19.69","concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"engines":{"node":">=18.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-lambda","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-lambda"}}'); - -/***/ }), - -/***/ 3859: -/***/ ((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.864.0","scripts":{"build":"concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline client-sso","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":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.864.0","@aws-sdk/middleware-host-header":"3.862.0","@aws-sdk/middleware-logger":"3.862.0","@aws-sdk/middleware-recursion-detection":"3.862.0","@aws-sdk/middleware-user-agent":"3.864.0","@aws-sdk/region-config-resolver":"3.862.0","@aws-sdk/types":"3.862.0","@aws-sdk/util-endpoints":"3.862.0","@aws-sdk/util-user-agent-browser":"3.862.0","@aws-sdk/util-user-agent-node":"3.864.0","@smithy/config-resolver":"^4.1.5","@smithy/core":"^3.8.0","@smithy/fetch-http-handler":"^5.1.1","@smithy/hash-node":"^4.0.5","@smithy/invalid-dependency":"^4.0.5","@smithy/middleware-content-length":"^4.0.5","@smithy/middleware-endpoint":"^4.1.18","@smithy/middleware-retry":"^4.1.19","@smithy/middleware-serde":"^4.0.9","@smithy/middleware-stack":"^4.0.5","@smithy/node-config-provider":"^4.1.4","@smithy/node-http-handler":"^4.1.1","@smithy/protocol-http":"^5.1.3","@smithy/smithy-client":"^4.4.10","@smithy/types":"^4.3.2","@smithy/url-parser":"^4.0.5","@smithy/util-base64":"^4.0.0","@smithy/util-body-length-browser":"^4.0.0","@smithy/util-body-length-node":"^4.0.0","@smithy/util-defaults-mode-browser":"^4.0.26","@smithy/util-defaults-mode-node":"^4.0.26","@smithy/util-endpoints":"^3.0.7","@smithy/util-middleware":"^4.0.5","@smithy/util-retry":"^4.0.7","@smithy/util-utf8":"^4.0.0","tslib":"^2.6.2"},"devDependencies":{"@tsconfig/node18":"18.2.4","@types/node":"^18.19.69","concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"engines":{"node":">=18.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"}}'); - -/***/ }), - -/***/ 3942: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"name":"@aws-sdk/nested-clients","version":"3.864.0","description":"Nested clients for AWS SDK packages.","main":"./dist-cjs/index.js","module":"./dist-es/index.js","types":"./dist-types/index.d.ts","scripts":{"build":"yarn lint && concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline nested-clients","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","lint":"node ../../scripts/validation/submodules-linter.js --pkg nested-clients","test":"yarn g:vitest run","test:watch":"yarn g:vitest watch"},"engines":{"node":">=18.0.0"},"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","dependencies":{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.864.0","@aws-sdk/middleware-host-header":"3.862.0","@aws-sdk/middleware-logger":"3.862.0","@aws-sdk/middleware-recursion-detection":"3.862.0","@aws-sdk/middleware-user-agent":"3.864.0","@aws-sdk/region-config-resolver":"3.862.0","@aws-sdk/types":"3.862.0","@aws-sdk/util-endpoints":"3.862.0","@aws-sdk/util-user-agent-browser":"3.862.0","@aws-sdk/util-user-agent-node":"3.864.0","@smithy/config-resolver":"^4.1.5","@smithy/core":"^3.8.0","@smithy/fetch-http-handler":"^5.1.1","@smithy/hash-node":"^4.0.5","@smithy/invalid-dependency":"^4.0.5","@smithy/middleware-content-length":"^4.0.5","@smithy/middleware-endpoint":"^4.1.18","@smithy/middleware-retry":"^4.1.19","@smithy/middleware-serde":"^4.0.9","@smithy/middleware-stack":"^4.0.5","@smithy/node-config-provider":"^4.1.4","@smithy/node-http-handler":"^4.1.1","@smithy/protocol-http":"^5.1.3","@smithy/smithy-client":"^4.4.10","@smithy/types":"^4.3.2","@smithy/url-parser":"^4.0.5","@smithy/util-base64":"^4.0.0","@smithy/util-body-length-browser":"^4.0.0","@smithy/util-body-length-node":"^4.0.0","@smithy/util-defaults-mode-browser":"^4.0.26","@smithy/util-defaults-mode-node":"^4.0.26","@smithy/util-endpoints":"^3.0.7","@smithy/util-middleware":"^4.0.5","@smithy/util-retry":"^4.0.7","@smithy/util-utf8":"^4.0.0","tslib":"^2.6.2"},"devDependencies":{"concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["./sso-oidc.d.ts","./sso-oidc.js","./sts.d.ts","./sts.js","dist-*/**"],"browser":{"./dist-es/submodules/sso-oidc/runtimeConfig":"./dist-es/submodules/sso-oidc/runtimeConfig.browser","./dist-es/submodules/sts/runtimeConfig":"./dist-es/submodules/sts/runtimeConfig.browser"},"react-native":{},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"packages/nested-clients"},"exports":{"./sso-oidc":{"types":"./dist-types/submodules/sso-oidc/index.d.ts","module":"./dist-es/submodules/sso-oidc/index.js","node":"./dist-cjs/submodules/sso-oidc/index.js","import":"./dist-es/submodules/sso-oidc/index.js","require":"./dist-cjs/submodules/sso-oidc/index.js"},"./sts":{"types":"./dist-types/submodules/sts/index.d.ts","module":"./dist-es/submodules/sts/index.js","node":"./dist-cjs/submodules/sts/index.js","import":"./dist-es/submodules/sts/index.js","require":"./dist-cjs/submodules/sts/index.js"}}}'); +module.exports = JSON.parse('{"name":"@aws-sdk/client-lambda","description":"AWS SDK for JavaScript Lambda Client for Node.js, Browser and React Native","version":"3.865.0","scripts":{"build":"concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline client-lambda","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 lambda"},"main":"./dist-cjs/index.js","types":"./dist-types/index.d.ts","module":"./dist-es/index.js","sideEffects":false,"dependencies":{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.864.0","@aws-sdk/credential-provider-node":"3.864.0","@aws-sdk/middleware-host-header":"3.862.0","@aws-sdk/middleware-logger":"3.862.0","@aws-sdk/middleware-recursion-detection":"3.862.0","@aws-sdk/middleware-user-agent":"3.864.0","@aws-sdk/region-config-resolver":"3.862.0","@aws-sdk/types":"3.862.0","@aws-sdk/util-endpoints":"3.862.0","@aws-sdk/util-user-agent-browser":"3.862.0","@aws-sdk/util-user-agent-node":"3.864.0","@smithy/config-resolver":"^4.1.5","@smithy/core":"^3.8.0","@smithy/eventstream-serde-browser":"^4.0.5","@smithy/eventstream-serde-config-resolver":"^4.1.3","@smithy/eventstream-serde-node":"^4.0.5","@smithy/fetch-http-handler":"^5.1.1","@smithy/hash-node":"^4.0.5","@smithy/invalid-dependency":"^4.0.5","@smithy/middleware-content-length":"^4.0.5","@smithy/middleware-endpoint":"^4.1.18","@smithy/middleware-retry":"^4.1.19","@smithy/middleware-serde":"^4.0.9","@smithy/middleware-stack":"^4.0.5","@smithy/node-config-provider":"^4.1.4","@smithy/node-http-handler":"^4.1.1","@smithy/protocol-http":"^5.1.3","@smithy/smithy-client":"^4.4.10","@smithy/types":"^4.3.2","@smithy/url-parser":"^4.0.5","@smithy/util-base64":"^4.0.0","@smithy/util-body-length-browser":"^4.0.0","@smithy/util-body-length-node":"^4.0.0","@smithy/util-defaults-mode-browser":"^4.0.26","@smithy/util-defaults-mode-node":"^4.0.26","@smithy/util-endpoints":"^3.0.7","@smithy/util-middleware":"^4.0.5","@smithy/util-retry":"^4.0.7","@smithy/util-stream":"^4.2.4","@smithy/util-utf8":"^4.0.0","@smithy/util-waiter":"^4.0.7","tslib":"^2.6.2"},"devDependencies":{"@tsconfig/node18":"18.2.4","@types/node":"^18.19.69","concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"engines":{"node":">=18.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-lambda","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"clients/client-lambda"}}'); /***/ }), @@ -100189,7 +85371,7 @@ module.exports = JSON.parse('{"name":"@aws-sdk/client-s3","description":"AWS SDK /***/ ((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.826.0","scripts":{"build":"concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline client-sso","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":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.826.0","@aws-sdk/middleware-host-header":"3.821.0","@aws-sdk/middleware-logger":"3.821.0","@aws-sdk/middleware-recursion-detection":"3.821.0","@aws-sdk/middleware-user-agent":"3.826.0","@aws-sdk/region-config-resolver":"3.821.0","@aws-sdk/types":"3.821.0","@aws-sdk/util-endpoints":"3.821.0","@aws-sdk/util-user-agent-browser":"3.821.0","@aws-sdk/util-user-agent-node":"3.826.0","@smithy/config-resolver":"^4.1.4","@smithy/core":"^3.5.3","@smithy/fetch-http-handler":"^5.0.4","@smithy/hash-node":"^4.0.4","@smithy/invalid-dependency":"^4.0.4","@smithy/middleware-content-length":"^4.0.4","@smithy/middleware-endpoint":"^4.1.11","@smithy/middleware-retry":"^4.1.12","@smithy/middleware-serde":"^4.0.8","@smithy/middleware-stack":"^4.0.4","@smithy/node-config-provider":"^4.1.3","@smithy/node-http-handler":"^4.0.6","@smithy/protocol-http":"^5.1.2","@smithy/smithy-client":"^4.4.3","@smithy/types":"^4.3.1","@smithy/url-parser":"^4.0.4","@smithy/util-base64":"^4.0.0","@smithy/util-body-length-browser":"^4.0.0","@smithy/util-body-length-node":"^4.0.0","@smithy/util-defaults-mode-browser":"^4.0.19","@smithy/util-defaults-mode-node":"^4.0.19","@smithy/util-endpoints":"^3.0.6","@smithy/util-middleware":"^4.0.4","@smithy/util-retry":"^4.0.5","@smithy/util-utf8":"^4.0.0","tslib":"^2.6.2"},"devDependencies":{"@tsconfig/node18":"18.2.4","@types/node":"^18.19.69","concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"engines":{"node":">=18.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"}}'); +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.864.0","scripts":{"build":"concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline client-sso","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":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.864.0","@aws-sdk/middleware-host-header":"3.862.0","@aws-sdk/middleware-logger":"3.862.0","@aws-sdk/middleware-recursion-detection":"3.862.0","@aws-sdk/middleware-user-agent":"3.864.0","@aws-sdk/region-config-resolver":"3.862.0","@aws-sdk/types":"3.862.0","@aws-sdk/util-endpoints":"3.862.0","@aws-sdk/util-user-agent-browser":"3.862.0","@aws-sdk/util-user-agent-node":"3.864.0","@smithy/config-resolver":"^4.1.5","@smithy/core":"^3.8.0","@smithy/fetch-http-handler":"^5.1.1","@smithy/hash-node":"^4.0.5","@smithy/invalid-dependency":"^4.0.5","@smithy/middleware-content-length":"^4.0.5","@smithy/middleware-endpoint":"^4.1.18","@smithy/middleware-retry":"^4.1.19","@smithy/middleware-serde":"^4.0.9","@smithy/middleware-stack":"^4.0.5","@smithy/node-config-provider":"^4.1.4","@smithy/node-http-handler":"^4.1.1","@smithy/protocol-http":"^5.1.3","@smithy/smithy-client":"^4.4.10","@smithy/types":"^4.3.2","@smithy/url-parser":"^4.0.5","@smithy/util-base64":"^4.0.0","@smithy/util-body-length-browser":"^4.0.0","@smithy/util-body-length-node":"^4.0.0","@smithy/util-defaults-mode-browser":"^4.0.26","@smithy/util-defaults-mode-node":"^4.0.26","@smithy/util-endpoints":"^3.0.7","@smithy/util-middleware":"^4.0.5","@smithy/util-retry":"^4.0.7","@smithy/util-utf8":"^4.0.0","tslib":"^2.6.2"},"devDependencies":{"@tsconfig/node18":"18.2.4","@types/node":"^18.19.69","concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"engines":{"node":">=18.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"}}'); /***/ }), @@ -100221,7 +85403,7 @@ module.exports = JSON.parse('{"name":"@aws-sdk/client-sts","description":"AWS SD /***/ ((module) => { "use strict"; -module.exports = JSON.parse('{"name":"@aws-sdk/nested-clients","version":"3.826.0","description":"Nested clients for AWS SDK packages.","main":"./dist-cjs/index.js","module":"./dist-es/index.js","types":"./dist-types/index.d.ts","scripts":{"build":"yarn lint && concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline nested-clients","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","lint":"node ../../scripts/validation/submodules-linter.js --pkg nested-clients","test":"yarn g:vitest run","test:watch":"yarn g:vitest watch"},"engines":{"node":">=18.0.0"},"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","dependencies":{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.826.0","@aws-sdk/middleware-host-header":"3.821.0","@aws-sdk/middleware-logger":"3.821.0","@aws-sdk/middleware-recursion-detection":"3.821.0","@aws-sdk/middleware-user-agent":"3.826.0","@aws-sdk/region-config-resolver":"3.821.0","@aws-sdk/types":"3.821.0","@aws-sdk/util-endpoints":"3.821.0","@aws-sdk/util-user-agent-browser":"3.821.0","@aws-sdk/util-user-agent-node":"3.826.0","@smithy/config-resolver":"^4.1.4","@smithy/core":"^3.5.3","@smithy/fetch-http-handler":"^5.0.4","@smithy/hash-node":"^4.0.4","@smithy/invalid-dependency":"^4.0.4","@smithy/middleware-content-length":"^4.0.4","@smithy/middleware-endpoint":"^4.1.11","@smithy/middleware-retry":"^4.1.12","@smithy/middleware-serde":"^4.0.8","@smithy/middleware-stack":"^4.0.4","@smithy/node-config-provider":"^4.1.3","@smithy/node-http-handler":"^4.0.6","@smithy/protocol-http":"^5.1.2","@smithy/smithy-client":"^4.4.3","@smithy/types":"^4.3.1","@smithy/url-parser":"^4.0.4","@smithy/util-base64":"^4.0.0","@smithy/util-body-length-browser":"^4.0.0","@smithy/util-body-length-node":"^4.0.0","@smithy/util-defaults-mode-browser":"^4.0.19","@smithy/util-defaults-mode-node":"^4.0.19","@smithy/util-endpoints":"^3.0.6","@smithy/util-middleware":"^4.0.4","@smithy/util-retry":"^4.0.5","@smithy/util-utf8":"^4.0.0","tslib":"^2.6.2"},"devDependencies":{"concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["./sso-oidc.d.ts","./sso-oidc.js","./sts.d.ts","./sts.js","dist-*/**"],"browser":{"./dist-es/submodules/sso-oidc/runtimeConfig":"./dist-es/submodules/sso-oidc/runtimeConfig.browser","./dist-es/submodules/sts/runtimeConfig":"./dist-es/submodules/sts/runtimeConfig.browser"},"react-native":{},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"packages/nested-clients"},"exports":{"./sso-oidc":{"types":"./dist-types/submodules/sso-oidc/index.d.ts","module":"./dist-es/submodules/sso-oidc/index.js","node":"./dist-cjs/submodules/sso-oidc/index.js","import":"./dist-es/submodules/sso-oidc/index.js","require":"./dist-cjs/submodules/sso-oidc/index.js"},"./sts":{"types":"./dist-types/submodules/sts/index.d.ts","module":"./dist-es/submodules/sts/index.js","node":"./dist-cjs/submodules/sts/index.js","import":"./dist-es/submodules/sts/index.js","require":"./dist-cjs/submodules/sts/index.js"}}}'); +module.exports = JSON.parse('{"name":"@aws-sdk/nested-clients","version":"3.864.0","description":"Nested clients for AWS SDK packages.","main":"./dist-cjs/index.js","module":"./dist-es/index.js","types":"./dist-types/index.d.ts","scripts":{"build":"yarn lint && concurrently \'yarn:build:cjs\' \'yarn:build:es\' \'yarn:build:types\'","build:cjs":"node ../../scripts/compilation/inline nested-clients","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","lint":"node ../../scripts/validation/submodules-linter.js --pkg nested-clients","test":"yarn g:vitest run","test:watch":"yarn g:vitest watch"},"engines":{"node":">=18.0.0"},"author":{"name":"AWS SDK for JavaScript Team","url":"https://aws.amazon.com/javascript/"},"license":"Apache-2.0","dependencies":{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"3.864.0","@aws-sdk/middleware-host-header":"3.862.0","@aws-sdk/middleware-logger":"3.862.0","@aws-sdk/middleware-recursion-detection":"3.862.0","@aws-sdk/middleware-user-agent":"3.864.0","@aws-sdk/region-config-resolver":"3.862.0","@aws-sdk/types":"3.862.0","@aws-sdk/util-endpoints":"3.862.0","@aws-sdk/util-user-agent-browser":"3.862.0","@aws-sdk/util-user-agent-node":"3.864.0","@smithy/config-resolver":"^4.1.5","@smithy/core":"^3.8.0","@smithy/fetch-http-handler":"^5.1.1","@smithy/hash-node":"^4.0.5","@smithy/invalid-dependency":"^4.0.5","@smithy/middleware-content-length":"^4.0.5","@smithy/middleware-endpoint":"^4.1.18","@smithy/middleware-retry":"^4.1.19","@smithy/middleware-serde":"^4.0.9","@smithy/middleware-stack":"^4.0.5","@smithy/node-config-provider":"^4.1.4","@smithy/node-http-handler":"^4.1.1","@smithy/protocol-http":"^5.1.3","@smithy/smithy-client":"^4.4.10","@smithy/types":"^4.3.2","@smithy/url-parser":"^4.0.5","@smithy/util-base64":"^4.0.0","@smithy/util-body-length-browser":"^4.0.0","@smithy/util-body-length-node":"^4.0.0","@smithy/util-defaults-mode-browser":"^4.0.26","@smithy/util-defaults-mode-node":"^4.0.26","@smithy/util-endpoints":"^3.0.7","@smithy/util-middleware":"^4.0.5","@smithy/util-retry":"^4.0.7","@smithy/util-utf8":"^4.0.0","tslib":"^2.6.2"},"devDependencies":{"concurrently":"7.0.0","downlevel-dts":"0.10.1","rimraf":"3.0.2","typescript":"~5.8.3"},"typesVersions":{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},"files":["./sso-oidc.d.ts","./sso-oidc.js","./sts.d.ts","./sts.js","dist-*/**"],"browser":{"./dist-es/submodules/sso-oidc/runtimeConfig":"./dist-es/submodules/sso-oidc/runtimeConfig.browser","./dist-es/submodules/sts/runtimeConfig":"./dist-es/submodules/sts/runtimeConfig.browser"},"react-native":{},"homepage":"https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients","repository":{"type":"git","url":"https://github.com/aws/aws-sdk-js-v3.git","directory":"packages/nested-clients"},"exports":{"./sso-oidc":{"types":"./dist-types/submodules/sso-oidc/index.d.ts","module":"./dist-es/submodules/sso-oidc/index.js","node":"./dist-cjs/submodules/sso-oidc/index.js","import":"./dist-es/submodules/sso-oidc/index.js","require":"./dist-cjs/submodules/sso-oidc/index.js"},"./sts":{"types":"./dist-types/submodules/sts/index.d.ts","module":"./dist-es/submodules/sts/index.js","node":"./dist-cjs/submodules/sts/index.js","import":"./dist-es/submodules/sts/index.js","require":"./dist-cjs/submodules/sts/index.js"}}}'); /***/ }), @@ -100229,7 +85411,7 @@ module.exports = JSON.parse('{"name":"@aws-sdk/nested-clients","version":"3.826. /***/ ((module) => { "use strict"; -module.exports = JSON.parse('{"name":"@amzn/github-action-lambda-deploy","version":"1.0.0","description":"GitHub Action for AWS Lambda Function Deployment","main":"index.js","scripts":{"build":"ncc build index.js -o dist","test":"jest","lint":"eslint .","lint:fix":"eslint . --fix"},"keywords":["aws","lambda","deployment"],"author":"","license":"MIT","dependencies":{"@actions/core":"^1.10.0","@actions/github":"^6.0.1","@aws-sdk/client-lambda":"^3.826.0","@aws-sdk/client-s3":"^3.864.0","@aws-sdk/util-retry":"^3.370.0","@smithy/node-http-handler":"^4.0.6","@aws-sdk/client-sts":"3.844.0","adm-zip":"^0.5.16","glob":"^11.0.2"},"devDependencies":{"@vercel/ncc":"^0.36.1","eslint":"^8.45.0","eslint-plugin-jest":"^27.2.2","jest":"^29.5.0"}}'); +module.exports = JSON.parse('{"name":"@amzn/github-action-lambda-deploy","version":"1.0.0","description":"GitHub Action for AWS Lambda Function Deployment","main":"index.js","scripts":{"build":"ncc build index.js -o dist","test":"jest","lint":"eslint .","lint:fix":"eslint . --fix"},"keywords":["aws","lambda","deployment"],"author":"","license":"MIT","dependencies":{"@actions/core":"^1.10.0","@actions/github":"^6.0.1","@aws-sdk/client-lambda":"^3.865.0","@aws-sdk/client-s3":"^3.864.0","@aws-sdk/util-retry":"^3.370.0","@smithy/node-http-handler":"^4.0.6","@aws-sdk/client-sts":"3.844.0","adm-zip":"^0.5.16","glob":"^11.0.2"},"devDependencies":{"@vercel/ncc":"^0.36.1","eslint":"^8.45.0","eslint-plugin-jest":"^27.2.2","jest":"^29.5.0"}}'); /***/ }) diff --git a/package-lock.json b/package-lock.json index 4420c1d..0622d6d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "dependencies": { "@actions/core": "^1.10.0", "@actions/github": "^6.0.1", - "@aws-sdk/client-lambda": "^3.826.0", + "@aws-sdk/client-lambda": "^3.865.0", "@aws-sdk/client-s3": "^3.864.0", "@aws-sdk/client-sts": "3.844.0", "@aws-sdk/util-retry": "^3.370.0", @@ -287,53 +287,54 @@ } }, "node_modules/@aws-sdk/client-lambda": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-lambda/-/client-lambda-3.826.0.tgz", - "integrity": "sha512-RWkzP6yZ7YZ856ibtab9TYC8zzm7uc0zOcG78moNrIwr3b9yacXrIjRAcRQ6RApYhiVEr4F5CIHyrjgwcDfelQ==", + "version": "3.865.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-lambda/-/client-lambda-3.865.0.tgz", + "integrity": "sha512-ncCEW/kNRV8yJA/45z5HO6WEeihADzFY7RISfezDbvP3/X4dZb2gycRVPmJIE6CBqf01jwTkbG36qO+/iHIELg==", + "license": "Apache-2.0", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.826.0", - "@aws-sdk/credential-provider-node": "3.826.0", - "@aws-sdk/middleware-host-header": "3.821.0", - "@aws-sdk/middleware-logger": "3.821.0", - "@aws-sdk/middleware-recursion-detection": "3.821.0", - "@aws-sdk/middleware-user-agent": "3.826.0", - "@aws-sdk/region-config-resolver": "3.821.0", - "@aws-sdk/types": "3.821.0", - "@aws-sdk/util-endpoints": "3.821.0", - "@aws-sdk/util-user-agent-browser": "3.821.0", - "@aws-sdk/util-user-agent-node": "3.826.0", - "@smithy/config-resolver": "^4.1.4", - "@smithy/core": "^3.5.3", - "@smithy/eventstream-serde-browser": "^4.0.4", - "@smithy/eventstream-serde-config-resolver": "^4.1.2", - "@smithy/eventstream-serde-node": "^4.0.4", - "@smithy/fetch-http-handler": "^5.0.4", - "@smithy/hash-node": "^4.0.4", - "@smithy/invalid-dependency": "^4.0.4", - "@smithy/middleware-content-length": "^4.0.4", - "@smithy/middleware-endpoint": "^4.1.11", - "@smithy/middleware-retry": "^4.1.12", - "@smithy/middleware-serde": "^4.0.8", - "@smithy/middleware-stack": "^4.0.4", - "@smithy/node-config-provider": "^4.1.3", - "@smithy/node-http-handler": "^4.0.6", - "@smithy/protocol-http": "^5.1.2", - "@smithy/smithy-client": "^4.4.3", - "@smithy/types": "^4.3.1", - "@smithy/url-parser": "^4.0.4", + "@aws-sdk/core": "3.864.0", + "@aws-sdk/credential-provider-node": "3.864.0", + "@aws-sdk/middleware-host-header": "3.862.0", + "@aws-sdk/middleware-logger": "3.862.0", + "@aws-sdk/middleware-recursion-detection": "3.862.0", + "@aws-sdk/middleware-user-agent": "3.864.0", + "@aws-sdk/region-config-resolver": "3.862.0", + "@aws-sdk/types": "3.862.0", + "@aws-sdk/util-endpoints": "3.862.0", + "@aws-sdk/util-user-agent-browser": "3.862.0", + "@aws-sdk/util-user-agent-node": "3.864.0", + "@smithy/config-resolver": "^4.1.5", + "@smithy/core": "^3.8.0", + "@smithy/eventstream-serde-browser": "^4.0.5", + "@smithy/eventstream-serde-config-resolver": "^4.1.3", + "@smithy/eventstream-serde-node": "^4.0.5", + "@smithy/fetch-http-handler": "^5.1.1", + "@smithy/hash-node": "^4.0.5", + "@smithy/invalid-dependency": "^4.0.5", + "@smithy/middleware-content-length": "^4.0.5", + "@smithy/middleware-endpoint": "^4.1.18", + "@smithy/middleware-retry": "^4.1.19", + "@smithy/middleware-serde": "^4.0.9", + "@smithy/middleware-stack": "^4.0.5", + "@smithy/node-config-provider": "^4.1.4", + "@smithy/node-http-handler": "^4.1.1", + "@smithy/protocol-http": "^5.1.3", + "@smithy/smithy-client": "^4.4.10", + "@smithy/types": "^4.3.2", + "@smithy/url-parser": "^4.0.5", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.19", - "@smithy/util-defaults-mode-node": "^4.0.19", - "@smithy/util-endpoints": "^3.0.6", - "@smithy/util-middleware": "^4.0.4", - "@smithy/util-retry": "^4.0.5", - "@smithy/util-stream": "^4.2.2", + "@smithy/util-defaults-mode-browser": "^4.0.26", + "@smithy/util-defaults-mode-node": "^4.0.26", + "@smithy/util-endpoints": "^3.0.7", + "@smithy/util-middleware": "^4.0.5", + "@smithy/util-retry": "^4.0.7", + "@smithy/util-stream": "^4.2.4", "@smithy/util-utf8": "^4.0.0", - "@smithy/util-waiter": "^4.0.5", + "@smithy/util-waiter": "^4.0.7", "tslib": "^2.6.2" }, "engines": { @@ -409,7 +410,20 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/client-sso": { + "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/xml-builder": { + "version": "3.862.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.862.0.tgz", + "integrity": "sha512-6Ed0kmC1NMbuFTEgNmamAUU1h5gShgxL1hBVLbEzUa3trX5aJBz1vU4bXaBTvOYUAnOHtiy1Ml4AMStd6hJnFA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.3.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-sso": { "version": "3.864.0", "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.864.0.tgz", "integrity": "sha512-THiOp0OpQROEKZ6IdDCDNNh3qnNn/kFFaTSOiugDpgcE5QdsOxh1/RXq7LmHpTJum3cmnFf8jG59PHcz9Tjnlw==", @@ -458,637 +472,172 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.864.0.tgz", - "integrity": "sha512-LFUREbobleHEln+Zf7IG83lAZwvHZG0stI7UU0CtwyuhQy5Yx0rKksHNOCmlM7MpTEbSCfntEhYi3jUaY5e5lg==", + "node_modules/@aws-sdk/client-sts": { + "version": "3.844.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.844.0.tgz", + "integrity": "sha512-hPxiovDv4QW+/Rn//U0Z8nbrxj4W7i3OHwZ2qEGey4YFcPISY3GYXqP3ko6x9LkzzWmY1fTdubylJi4MTjZGqQ==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.862.0", - "@aws-sdk/xml-builder": "3.862.0", - "@smithy/core": "^3.8.0", - "@smithy/node-config-provider": "^4.1.4", - "@smithy/property-provider": "^4.0.5", - "@smithy/protocol-http": "^5.1.3", - "@smithy/signature-v4": "^5.1.3", - "@smithy/smithy-client": "^4.4.10", - "@smithy/types": "^4.3.2", + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.844.0", + "@aws-sdk/credential-provider-node": "3.844.0", + "@aws-sdk/middleware-host-header": "3.840.0", + "@aws-sdk/middleware-logger": "3.840.0", + "@aws-sdk/middleware-recursion-detection": "3.840.0", + "@aws-sdk/middleware-user-agent": "3.844.0", + "@aws-sdk/region-config-resolver": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@aws-sdk/util-endpoints": "3.844.0", + "@aws-sdk/util-user-agent-browser": "3.840.0", + "@aws-sdk/util-user-agent-node": "3.844.0", + "@smithy/config-resolver": "^4.1.4", + "@smithy/core": "^3.7.0", + "@smithy/fetch-http-handler": "^5.1.0", + "@smithy/hash-node": "^4.0.4", + "@smithy/invalid-dependency": "^4.0.4", + "@smithy/middleware-content-length": "^4.0.4", + "@smithy/middleware-endpoint": "^4.1.14", + "@smithy/middleware-retry": "^4.1.15", + "@smithy/middleware-serde": "^4.0.8", + "@smithy/middleware-stack": "^4.0.4", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/node-http-handler": "^4.1.0", + "@smithy/protocol-http": "^5.1.2", + "@smithy/smithy-client": "^4.4.6", + "@smithy/types": "^4.3.1", + "@smithy/url-parser": "^4.0.4", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", - "@smithy/util-middleware": "^4.0.5", + "@smithy/util-body-length-node": "^4.0.0", + "@smithy/util-defaults-mode-browser": "^4.0.22", + "@smithy/util-defaults-mode-node": "^4.0.22", + "@smithy/util-endpoints": "^3.0.6", + "@smithy/util-middleware": "^4.0.4", + "@smithy/util-retry": "^4.0.6", "@smithy/util-utf8": "^4.0.0", - "fast-xml-parser": "5.2.5", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/credential-provider-env": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.864.0.tgz", - "integrity": "sha512-StJPOI2Rt8UE6lYjXUpg6tqSZaM72xg46ljPg8kIevtBAAfdtq9K20qT/kSliWGIBocMFAv0g2mC0hAa+ECyvg==", + "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/client-sso": { + "version": "3.844.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.844.0.tgz", + "integrity": "sha512-FktodSx+pfUfIqMjoNwZ6t1xqq/G3cfT7I4JJ0HKHoIIZdoCHQB52x0OzKDtHDJAnEQPInasdPS8PorZBZtHmg==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "3.864.0", - "@aws-sdk/types": "3.862.0", - "@smithy/property-provider": "^4.0.5", - "@smithy/types": "^4.3.2", + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.844.0", + "@aws-sdk/middleware-host-header": "3.840.0", + "@aws-sdk/middleware-logger": "3.840.0", + "@aws-sdk/middleware-recursion-detection": "3.840.0", + "@aws-sdk/middleware-user-agent": "3.844.0", + "@aws-sdk/region-config-resolver": "3.840.0", + "@aws-sdk/types": "3.840.0", + "@aws-sdk/util-endpoints": "3.844.0", + "@aws-sdk/util-user-agent-browser": "3.840.0", + "@aws-sdk/util-user-agent-node": "3.844.0", + "@smithy/config-resolver": "^4.1.4", + "@smithy/core": "^3.7.0", + "@smithy/fetch-http-handler": "^5.1.0", + "@smithy/hash-node": "^4.0.4", + "@smithy/invalid-dependency": "^4.0.4", + "@smithy/middleware-content-length": "^4.0.4", + "@smithy/middleware-endpoint": "^4.1.14", + "@smithy/middleware-retry": "^4.1.15", + "@smithy/middleware-serde": "^4.0.8", + "@smithy/middleware-stack": "^4.0.4", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/node-http-handler": "^4.1.0", + "@smithy/protocol-http": "^5.1.2", + "@smithy/smithy-client": "^4.4.6", + "@smithy/types": "^4.3.1", + "@smithy/url-parser": "^4.0.4", + "@smithy/util-base64": "^4.0.0", + "@smithy/util-body-length-browser": "^4.0.0", + "@smithy/util-body-length-node": "^4.0.0", + "@smithy/util-defaults-mode-browser": "^4.0.22", + "@smithy/util-defaults-mode-node": "^4.0.22", + "@smithy/util-endpoints": "^3.0.6", + "@smithy/util-middleware": "^4.0.4", + "@smithy/util-retry": "^4.0.6", + "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/credential-provider-http": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.864.0.tgz", - "integrity": "sha512-E/RFVxGTuGnuD+9pFPH2j4l6HvrXzPhmpL8H8nOoJUosjx7d4v93GJMbbl1v/fkDLqW9qN4Jx2cI6PAjohA6OA==", + "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/core": { + "version": "3.844.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.844.0.tgz", + "integrity": "sha512-pfpI54bG5Xf2NkqrDBC2REStXlDXNCw/whORhkEs+Tp5exU872D5QKguzjPA6hH+8Pvbq1qgt5zXMbduISTHJw==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "3.864.0", - "@aws-sdk/types": "3.862.0", - "@smithy/fetch-http-handler": "^5.1.1", - "@smithy/node-http-handler": "^4.1.1", - "@smithy/property-provider": "^4.0.5", - "@smithy/protocol-http": "^5.1.3", - "@smithy/smithy-client": "^4.4.10", - "@smithy/types": "^4.3.2", - "@smithy/util-stream": "^4.2.4", + "@aws-sdk/types": "3.840.0", + "@aws-sdk/xml-builder": "3.821.0", + "@smithy/core": "^3.7.0", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/property-provider": "^4.0.4", + "@smithy/protocol-http": "^5.1.2", + "@smithy/signature-v4": "^5.1.2", + "@smithy/smithy-client": "^4.4.6", + "@smithy/types": "^4.3.1", + "@smithy/util-base64": "^4.0.0", + "@smithy/util-body-length-browser": "^4.0.0", + "@smithy/util-middleware": "^4.0.4", + "@smithy/util-utf8": "^4.0.0", + "fast-xml-parser": "5.2.5", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.864.0.tgz", - "integrity": "sha512-PlxrijguR1gxyPd5EYam6OfWLarj2MJGf07DvCx9MAuQkw77HBnsu6+XbV8fQriFuoJVTBLn9ROhMr/ROAYfUg==", + "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/credential-provider-env": { + "version": "3.844.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.844.0.tgz", + "integrity": "sha512-WB94Ox86MqcZ4CnRjKgopzaSuZH4hMP0GqdOxG4s1it1lRWOIPOHOC1dPiM0Zbj1uqITIhbXUQVXyP/uaJeNkw==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "3.864.0", - "@aws-sdk/credential-provider-env": "3.864.0", - "@aws-sdk/credential-provider-http": "3.864.0", - "@aws-sdk/credential-provider-process": "3.864.0", - "@aws-sdk/credential-provider-sso": "3.864.0", - "@aws-sdk/credential-provider-web-identity": "3.864.0", - "@aws-sdk/nested-clients": "3.864.0", - "@aws-sdk/types": "3.862.0", - "@smithy/credential-provider-imds": "^4.0.7", - "@smithy/property-provider": "^4.0.5", - "@smithy/shared-ini-file-loader": "^4.0.5", - "@smithy/types": "^4.3.2", + "@aws-sdk/core": "3.844.0", + "@aws-sdk/types": "3.840.0", + "@smithy/property-provider": "^4.0.4", + "@smithy/types": "^4.3.1", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/credential-provider-node": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.864.0.tgz", - "integrity": "sha512-2BEymFeXURS+4jE9tP3vahPwbYRl0/1MVaFZcijj6pq+nf5EPGvkFillbdBRdc98ZI2NedZgSKu3gfZXgYdUhQ==", + "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/credential-provider-http": { + "version": "3.844.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.844.0.tgz", + "integrity": "sha512-e+efVqfkhpM8zxYeiLNgTUlX+tmtXzVm3bw1A02U9Z9cWBHyQNb8pi90M7QniLoqRURY1B0C2JqkOE61gd4KNg==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/credential-provider-env": "3.864.0", - "@aws-sdk/credential-provider-http": "3.864.0", - "@aws-sdk/credential-provider-ini": "3.864.0", - "@aws-sdk/credential-provider-process": "3.864.0", - "@aws-sdk/credential-provider-sso": "3.864.0", - "@aws-sdk/credential-provider-web-identity": "3.864.0", - "@aws-sdk/types": "3.862.0", - "@smithy/credential-provider-imds": "^4.0.7", - "@smithy/property-provider": "^4.0.5", - "@smithy/shared-ini-file-loader": "^4.0.5", - "@smithy/types": "^4.3.2", + "@aws-sdk/core": "3.844.0", + "@aws-sdk/types": "3.840.0", + "@smithy/fetch-http-handler": "^5.1.0", + "@smithy/node-http-handler": "^4.1.0", + "@smithy/property-provider": "^4.0.4", + "@smithy/protocol-http": "^5.1.2", + "@smithy/smithy-client": "^4.4.6", + "@smithy/types": "^4.3.1", + "@smithy/util-stream": "^4.2.3", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/credential-provider-process": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.864.0.tgz", - "integrity": "sha512-Zxnn1hxhq7EOqXhVYgkF4rI9MnaO3+6bSg/tErnBQ3F8kDpA7CFU24G1YxwaJXp2X4aX3LwthefmSJHwcVP/2g==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "3.864.0", - "@aws-sdk/types": "3.862.0", - "@smithy/property-provider": "^4.0.5", - "@smithy/shared-ini-file-loader": "^4.0.5", - "@smithy/types": "^4.3.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.864.0.tgz", - "integrity": "sha512-UPyPNQbxDwHVGmgWdGg9/9yvzuedRQVF5jtMkmP565YX9pKZ8wYAcXhcYdNPWFvH0GYdB0crKOmvib+bmCuwkw==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/client-sso": "3.864.0", - "@aws-sdk/core": "3.864.0", - "@aws-sdk/token-providers": "3.864.0", - "@aws-sdk/types": "3.862.0", - "@smithy/property-provider": "^4.0.5", - "@smithy/shared-ini-file-loader": "^4.0.5", - "@smithy/types": "^4.3.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/credential-provider-web-identity": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.864.0.tgz", - "integrity": "sha512-nNcjPN4SYg8drLwqK0vgVeSvxeGQiD0FxOaT38mV2H8cu0C5NzpvA+14Xy+W6vT84dxgmJYKk71Cr5QL2Oz+rA==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "3.864.0", - "@aws-sdk/nested-clients": "3.864.0", - "@aws-sdk/types": "3.862.0", - "@smithy/property-provider": "^4.0.5", - "@smithy/types": "^4.3.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/middleware-host-header": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.862.0.tgz", - "integrity": "sha512-jDje8dCFeFHfuCAxMDXBs8hy8q9NCTlyK4ThyyfAj3U4Pixly2mmzY2u7b7AyGhWsjJNx8uhTjlYq5zkQPQCYw==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "3.862.0", - "@smithy/protocol-http": "^5.1.3", - "@smithy/types": "^4.3.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/middleware-logger": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.862.0.tgz", - "integrity": "sha512-N/bXSJznNBR/i7Ofmf9+gM6dx/SPBK09ZWLKsW5iQjqKxAKn/2DozlnE54uiEs1saHZWoNDRg69Ww4XYYSlG1Q==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "3.862.0", - "@smithy/types": "^4.3.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/middleware-recursion-detection": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.862.0.tgz", - "integrity": "sha512-KVoo3IOzEkTq97YKM4uxZcYFSNnMkhW/qj22csofLegZi5fk90ztUnnaeKfaEJHfHp/tm1Y3uSoOXH45s++kKQ==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "3.862.0", - "@smithy/protocol-http": "^5.1.3", - "@smithy/types": "^4.3.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/middleware-user-agent": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.864.0.tgz", - "integrity": "sha512-wrddonw4EyLNSNBrApzEhpSrDwJiNfjxDm5E+bn8n32BbAojXASH8W8jNpxz/jMgNkkJNxCfyqybGKzBX0OhbQ==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "3.864.0", - "@aws-sdk/types": "3.862.0", - "@aws-sdk/util-endpoints": "3.862.0", - "@smithy/core": "^3.8.0", - "@smithy/protocol-http": "^5.1.3", - "@smithy/types": "^4.3.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/nested-clients": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.864.0.tgz", - "integrity": "sha512-H1C+NjSmz2y8Tbgh7Yy89J20yD/hVyk15hNoZDbCYkXg0M358KS7KVIEYs8E2aPOCr1sK3HBE819D/yvdMgokA==", - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.864.0", - "@aws-sdk/middleware-host-header": "3.862.0", - "@aws-sdk/middleware-logger": "3.862.0", - "@aws-sdk/middleware-recursion-detection": "3.862.0", - "@aws-sdk/middleware-user-agent": "3.864.0", - "@aws-sdk/region-config-resolver": "3.862.0", - "@aws-sdk/types": "3.862.0", - "@aws-sdk/util-endpoints": "3.862.0", - "@aws-sdk/util-user-agent-browser": "3.862.0", - "@aws-sdk/util-user-agent-node": "3.864.0", - "@smithy/config-resolver": "^4.1.5", - "@smithy/core": "^3.8.0", - "@smithy/fetch-http-handler": "^5.1.1", - "@smithy/hash-node": "^4.0.5", - "@smithy/invalid-dependency": "^4.0.5", - "@smithy/middleware-content-length": "^4.0.5", - "@smithy/middleware-endpoint": "^4.1.18", - "@smithy/middleware-retry": "^4.1.19", - "@smithy/middleware-serde": "^4.0.9", - "@smithy/middleware-stack": "^4.0.5", - "@smithy/node-config-provider": "^4.1.4", - "@smithy/node-http-handler": "^4.1.1", - "@smithy/protocol-http": "^5.1.3", - "@smithy/smithy-client": "^4.4.10", - "@smithy/types": "^4.3.2", - "@smithy/url-parser": "^4.0.5", - "@smithy/util-base64": "^4.0.0", - "@smithy/util-body-length-browser": "^4.0.0", - "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.26", - "@smithy/util-defaults-mode-node": "^4.0.26", - "@smithy/util-endpoints": "^3.0.7", - "@smithy/util-middleware": "^4.0.5", - "@smithy/util-retry": "^4.0.7", - "@smithy/util-utf8": "^4.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/region-config-resolver": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.862.0.tgz", - "integrity": "sha512-VisR+/HuVFICrBPY+q9novEiE4b3mvDofWqyvmxHcWM7HumTz9ZQSuEtnlB/92GVM3KDUrR9EmBHNRrfXYZkcQ==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "3.862.0", - "@smithy/node-config-provider": "^4.1.4", - "@smithy/types": "^4.3.2", - "@smithy/util-config-provider": "^4.0.0", - "@smithy/util-middleware": "^4.0.5", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/token-providers": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.864.0.tgz", - "integrity": "sha512-gTc2QHOBo05SCwVA65dUtnJC6QERvFaPiuppGDSxoF7O5AQNK0UR/kMSenwLqN8b5E1oLYvQTv3C1idJLRX0cg==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "3.864.0", - "@aws-sdk/nested-clients": "3.864.0", - "@aws-sdk/types": "3.862.0", - "@smithy/property-provider": "^4.0.5", - "@smithy/shared-ini-file-loader": "^4.0.5", - "@smithy/types": "^4.3.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/types": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.862.0.tgz", - "integrity": "sha512-Bei+RL0cDxxV+lW2UezLbCYYNeJm6Nzee0TpW0FfyTRBhH9C1XQh4+x+IClriXvgBnRquTMMYsmJfvx8iyLKrg==", - "license": "Apache-2.0", - "dependencies": { - "@smithy/types": "^4.3.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/util-endpoints": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.862.0.tgz", - "integrity": "sha512-eCZuScdE9MWWkHGM2BJxm726MCmWk/dlHjOKvkM0sN1zxBellBMw5JohNss1Z8/TUmnW2gb9XHTOiHuGjOdksA==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "3.862.0", - "@smithy/types": "^4.3.2", - "@smithy/url-parser": "^4.0.5", - "@smithy/util-endpoints": "^3.0.7", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/util-user-agent-browser": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.862.0.tgz", - "integrity": "sha512-BmPTlm0r9/10MMr5ND9E92r8KMZbq5ltYXYpVcUbAsnB1RJ8ASJuRoLne5F7mB3YMx0FJoOTuSq7LdQM3LgW3Q==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "3.862.0", - "@smithy/types": "^4.3.2", - "bowser": "^2.11.0", - "tslib": "^2.6.2" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/util-user-agent-node": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.864.0.tgz", - "integrity": "sha512-d+FjUm2eJEpP+FRpVR3z6KzMdx1qwxEYDz8jzNKwxYLBBquaBaP/wfoMtMQKAcbrR7aT9FZVZF7zDgzNxUvQlQ==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/middleware-user-agent": "3.864.0", - "@aws-sdk/types": "3.862.0", - "@smithy/node-config-provider": "^4.1.4", - "@smithy/types": "^4.3.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - }, - "peerDependencies": { - "aws-crt": ">=1.0.0" - }, - "peerDependenciesMeta": { - "aws-crt": { - "optional": true - } - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/xml-builder": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.862.0.tgz", - "integrity": "sha512-6Ed0kmC1NMbuFTEgNmamAUU1h5gShgxL1hBVLbEzUa3trX5aJBz1vU4bXaBTvOYUAnOHtiy1Ml4AMStd6hJnFA==", - "license": "Apache-2.0", - "dependencies": { - "@smithy/types": "^4.3.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/fast-xml-parser": { - "version": "5.2.5", - "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.2.5.tgz", - "integrity": "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "dependencies": { - "strnum": "^2.1.0" - }, - "bin": { - "fxparser": "src/cli/cli.js" - } - }, - "node_modules/@aws-sdk/client-s3/node_modules/strnum": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.1.1.tgz", - "integrity": "sha512-7ZvoFTiCnGxBtDqJ//Cu6fWtZtc7Y3x+QOirG15wztbdngGSkht27o2pyGWrVy0b4WAy3jbKmnoK6g5VlVNUUw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT" - }, - "node_modules/@aws-sdk/client-sso": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.826.0.tgz", - "integrity": "sha512-/FEKnUC3xPkLL4RuRydwzx+y4b55HIX6qLPbGnyIs+sNmCUyc/62ijtV1Ml+b++YzEF6jWNBsJOxeyZdgrJ3Ig==", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.826.0", - "@aws-sdk/middleware-host-header": "3.821.0", - "@aws-sdk/middleware-logger": "3.821.0", - "@aws-sdk/middleware-recursion-detection": "3.821.0", - "@aws-sdk/middleware-user-agent": "3.826.0", - "@aws-sdk/region-config-resolver": "3.821.0", - "@aws-sdk/types": "3.821.0", - "@aws-sdk/util-endpoints": "3.821.0", - "@aws-sdk/util-user-agent-browser": "3.821.0", - "@aws-sdk/util-user-agent-node": "3.826.0", - "@smithy/config-resolver": "^4.1.4", - "@smithy/core": "^3.5.3", - "@smithy/fetch-http-handler": "^5.0.4", - "@smithy/hash-node": "^4.0.4", - "@smithy/invalid-dependency": "^4.0.4", - "@smithy/middleware-content-length": "^4.0.4", - "@smithy/middleware-endpoint": "^4.1.11", - "@smithy/middleware-retry": "^4.1.12", - "@smithy/middleware-serde": "^4.0.8", - "@smithy/middleware-stack": "^4.0.4", - "@smithy/node-config-provider": "^4.1.3", - "@smithy/node-http-handler": "^4.0.6", - "@smithy/protocol-http": "^5.1.2", - "@smithy/smithy-client": "^4.4.3", - "@smithy/types": "^4.3.1", - "@smithy/url-parser": "^4.0.4", - "@smithy/util-base64": "^4.0.0", - "@smithy/util-body-length-browser": "^4.0.0", - "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.19", - "@smithy/util-defaults-mode-node": "^4.0.19", - "@smithy/util-endpoints": "^3.0.6", - "@smithy/util-middleware": "^4.0.4", - "@smithy/util-retry": "^4.0.5", - "@smithy/util-utf8": "^4.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-sts": { - "version": "3.844.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.844.0.tgz", - "integrity": "sha512-hPxiovDv4QW+/Rn//U0Z8nbrxj4W7i3OHwZ2qEGey4YFcPISY3GYXqP3ko6x9LkzzWmY1fTdubylJi4MTjZGqQ==", - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.844.0", - "@aws-sdk/credential-provider-node": "3.844.0", - "@aws-sdk/middleware-host-header": "3.840.0", - "@aws-sdk/middleware-logger": "3.840.0", - "@aws-sdk/middleware-recursion-detection": "3.840.0", - "@aws-sdk/middleware-user-agent": "3.844.0", - "@aws-sdk/region-config-resolver": "3.840.0", - "@aws-sdk/types": "3.840.0", - "@aws-sdk/util-endpoints": "3.844.0", - "@aws-sdk/util-user-agent-browser": "3.840.0", - "@aws-sdk/util-user-agent-node": "3.844.0", - "@smithy/config-resolver": "^4.1.4", - "@smithy/core": "^3.7.0", - "@smithy/fetch-http-handler": "^5.1.0", - "@smithy/hash-node": "^4.0.4", - "@smithy/invalid-dependency": "^4.0.4", - "@smithy/middleware-content-length": "^4.0.4", - "@smithy/middleware-endpoint": "^4.1.14", - "@smithy/middleware-retry": "^4.1.15", - "@smithy/middleware-serde": "^4.0.8", - "@smithy/middleware-stack": "^4.0.4", - "@smithy/node-config-provider": "^4.1.3", - "@smithy/node-http-handler": "^4.1.0", - "@smithy/protocol-http": "^5.1.2", - "@smithy/smithy-client": "^4.4.6", - "@smithy/types": "^4.3.1", - "@smithy/url-parser": "^4.0.4", - "@smithy/util-base64": "^4.0.0", - "@smithy/util-body-length-browser": "^4.0.0", - "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.22", - "@smithy/util-defaults-mode-node": "^4.0.22", - "@smithy/util-endpoints": "^3.0.6", - "@smithy/util-middleware": "^4.0.4", - "@smithy/util-retry": "^4.0.6", - "@smithy/util-utf8": "^4.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/client-sso": { - "version": "3.844.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.844.0.tgz", - "integrity": "sha512-FktodSx+pfUfIqMjoNwZ6t1xqq/G3cfT7I4JJ0HKHoIIZdoCHQB52x0OzKDtHDJAnEQPInasdPS8PorZBZtHmg==", - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.844.0", - "@aws-sdk/middleware-host-header": "3.840.0", - "@aws-sdk/middleware-logger": "3.840.0", - "@aws-sdk/middleware-recursion-detection": "3.840.0", - "@aws-sdk/middleware-user-agent": "3.844.0", - "@aws-sdk/region-config-resolver": "3.840.0", - "@aws-sdk/types": "3.840.0", - "@aws-sdk/util-endpoints": "3.844.0", - "@aws-sdk/util-user-agent-browser": "3.840.0", - "@aws-sdk/util-user-agent-node": "3.844.0", - "@smithy/config-resolver": "^4.1.4", - "@smithy/core": "^3.7.0", - "@smithy/fetch-http-handler": "^5.1.0", - "@smithy/hash-node": "^4.0.4", - "@smithy/invalid-dependency": "^4.0.4", - "@smithy/middleware-content-length": "^4.0.4", - "@smithy/middleware-endpoint": "^4.1.14", - "@smithy/middleware-retry": "^4.1.15", - "@smithy/middleware-serde": "^4.0.8", - "@smithy/middleware-stack": "^4.0.4", - "@smithy/node-config-provider": "^4.1.3", - "@smithy/node-http-handler": "^4.1.0", - "@smithy/protocol-http": "^5.1.2", - "@smithy/smithy-client": "^4.4.6", - "@smithy/types": "^4.3.1", - "@smithy/url-parser": "^4.0.4", - "@smithy/util-base64": "^4.0.0", - "@smithy/util-body-length-browser": "^4.0.0", - "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.22", - "@smithy/util-defaults-mode-node": "^4.0.22", - "@smithy/util-endpoints": "^3.0.6", - "@smithy/util-middleware": "^4.0.4", - "@smithy/util-retry": "^4.0.6", - "@smithy/util-utf8": "^4.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/core": { - "version": "3.844.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.844.0.tgz", - "integrity": "sha512-pfpI54bG5Xf2NkqrDBC2REStXlDXNCw/whORhkEs+Tp5exU872D5QKguzjPA6hH+8Pvbq1qgt5zXMbduISTHJw==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "3.840.0", - "@aws-sdk/xml-builder": "3.821.0", - "@smithy/core": "^3.7.0", - "@smithy/node-config-provider": "^4.1.3", - "@smithy/property-provider": "^4.0.4", - "@smithy/protocol-http": "^5.1.2", - "@smithy/signature-v4": "^5.1.2", - "@smithy/smithy-client": "^4.4.6", - "@smithy/types": "^4.3.1", - "@smithy/util-base64": "^4.0.0", - "@smithy/util-body-length-browser": "^4.0.0", - "@smithy/util-middleware": "^4.0.4", - "@smithy/util-utf8": "^4.0.0", - "fast-xml-parser": "5.2.5", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/credential-provider-env": { - "version": "3.844.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.844.0.tgz", - "integrity": "sha512-WB94Ox86MqcZ4CnRjKgopzaSuZH4hMP0GqdOxG4s1it1lRWOIPOHOC1dPiM0Zbj1uqITIhbXUQVXyP/uaJeNkw==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "3.844.0", - "@aws-sdk/types": "3.840.0", - "@smithy/property-provider": "^4.0.4", - "@smithy/types": "^4.3.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/credential-provider-http": { - "version": "3.844.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.844.0.tgz", - "integrity": "sha512-e+efVqfkhpM8zxYeiLNgTUlX+tmtXzVm3bw1A02U9Z9cWBHyQNb8pi90M7QniLoqRURY1B0C2JqkOE61gd4KNg==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "3.844.0", - "@aws-sdk/types": "3.840.0", - "@smithy/fetch-http-handler": "^5.1.0", - "@smithy/node-http-handler": "^4.1.0", - "@smithy/property-provider": "^4.0.4", - "@smithy/protocol-http": "^5.1.2", - "@smithy/smithy-client": "^4.4.6", - "@smithy/types": "^4.3.1", - "@smithy/util-stream": "^4.2.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.844.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.844.0.tgz", - "integrity": "sha512-jc5ArGz2HfAx5QPXD+Ep36+QWyCKzl2TG6Vtl87/vljfLhVD0gEHv8fRsqWEp3Rc6hVfKnCjLW5ayR2HYcow9w==", + "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.844.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.844.0.tgz", + "integrity": "sha512-jc5ArGz2HfAx5QPXD+Ep36+QWyCKzl2TG6Vtl87/vljfLhVD0gEHv8fRsqWEp3Rc6hVfKnCjLW5ayR2HYcow9w==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/core": "3.844.0", @@ -1297,247 +846,31 @@ } }, "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/region-config-resolver": { - "version": "3.840.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.840.0.tgz", - "integrity": "sha512-Qjnxd/yDv9KpIMWr90ZDPtRj0v75AqGC92Lm9+oHXZ8p1MjG5JE2CW0HL8JRgK9iKzgKBL7pPQRXI8FkvEVfrA==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "3.840.0", - "@smithy/node-config-provider": "^4.1.3", - "@smithy/types": "^4.3.1", - "@smithy/util-config-provider": "^4.0.0", - "@smithy/util-middleware": "^4.0.4", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/token-providers": { - "version": "3.844.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.844.0.tgz", - "integrity": "sha512-Kh728FEny0fil+LeH8U1offPJCTd/EDh8liBAvLtViLHt2WoX2xC8rk98D38Q5p79aIUhHb3Pf4n9IZfTu/Kog==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "3.844.0", - "@aws-sdk/nested-clients": "3.844.0", - "@aws-sdk/types": "3.840.0", - "@smithy/property-provider": "^4.0.4", - "@smithy/shared-ini-file-loader": "^4.0.4", - "@smithy/types": "^4.3.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/types": { - "version": "3.840.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.840.0.tgz", - "integrity": "sha512-xliuHaUFZxEx1NSXeLLZ9Dyu6+EJVQKEoD+yM+zqUo3YDZ7medKJWY6fIOKiPX/N7XbLdBYwajb15Q7IL8KkeA==", - "license": "Apache-2.0", - "dependencies": { - "@smithy/types": "^4.3.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/util-endpoints": { - "version": "3.844.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.844.0.tgz", - "integrity": "sha512-1DHh0WTUmxlysz3EereHKtKoxVUG9UC5BsfAw6Bm4/6qDlJiqtY3oa2vebkYN23yltKdfsCK65cwnBRU59mWVg==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "3.840.0", - "@smithy/types": "^4.3.1", - "@smithy/url-parser": "^4.0.4", - "@smithy/util-endpoints": "^3.0.6", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/util-user-agent-browser": { - "version": "3.840.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.840.0.tgz", - "integrity": "sha512-JdyZM3EhhL4PqwFpttZu1afDpPJCCc3eyZOLi+srpX11LsGj6sThf47TYQN75HT1CarZ7cCdQHGzP2uy3/xHfQ==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "3.840.0", - "@smithy/types": "^4.3.1", - "bowser": "^2.11.0", - "tslib": "^2.6.2" - } - }, - "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/util-user-agent-node": { - "version": "3.844.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.844.0.tgz", - "integrity": "sha512-0eTpURp9Gxbyyeqr78ogARZMSWS5KUMZuN+XMHxNpQLmn2S+J3g+MAyoklCcwhKXlbdQq2aMULEiy0mqIWytuw==", - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/middleware-user-agent": "3.844.0", - "@aws-sdk/types": "3.840.0", - "@smithy/node-config-provider": "^4.1.3", - "@smithy/types": "^4.3.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - }, - "peerDependencies": { - "aws-crt": ">=1.0.0" - }, - "peerDependenciesMeta": { - "aws-crt": { - "optional": true - } - } - }, - "node_modules/@aws-sdk/client-sts/node_modules/fast-xml-parser": { - "version": "5.2.5", - "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.2.5.tgz", - "integrity": "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "dependencies": { - "strnum": "^2.1.0" - }, - "bin": { - "fxparser": "src/cli/cli.js" - } - }, - "node_modules/@aws-sdk/client-sts/node_modules/strnum": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.1.1.tgz", - "integrity": "sha512-7ZvoFTiCnGxBtDqJ//Cu6fWtZtc7Y3x+QOirG15wztbdngGSkht27o2pyGWrVy0b4WAy3jbKmnoK6g5VlVNUUw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT" - }, - "node_modules/@aws-sdk/core": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.826.0.tgz", - "integrity": "sha512-BGbQYzWj3ps+dblq33FY5tz/SsgJCcXX0zjQlSC07tYvU1jHTUvsefphyig+fY38xZ4wdKjbTop+KUmXUYrOXw==", - "dependencies": { - "@aws-sdk/types": "3.821.0", - "@aws-sdk/xml-builder": "3.821.0", - "@smithy/core": "^3.5.3", - "@smithy/node-config-provider": "^4.1.3", - "@smithy/property-provider": "^4.0.4", - "@smithy/protocol-http": "^5.1.2", - "@smithy/signature-v4": "^5.1.2", - "@smithy/smithy-client": "^4.4.3", - "@smithy/types": "^4.3.1", - "@smithy/util-base64": "^4.0.0", - "@smithy/util-body-length-browser": "^4.0.0", - "@smithy/util-middleware": "^4.0.4", - "@smithy/util-utf8": "^4.0.0", - "fast-xml-parser": "4.4.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-env": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.826.0.tgz", - "integrity": "sha512-DK3pQY8+iKK3MGDdC3uOZQ2psU01obaKlTYhEwNu4VWzgwQL4Vi3sWj4xSWGEK41vqZxiRLq6fOq7ysRI+qEZA==", - "dependencies": { - "@aws-sdk/core": "3.826.0", - "@aws-sdk/types": "3.821.0", - "@smithy/property-provider": "^4.0.4", - "@smithy/types": "^4.3.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-http": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.826.0.tgz", - "integrity": "sha512-N+IVZBh+yx/9GbMZTKO/gErBi/FYZQtcFRItoLbY+6WU+0cSWyZYfkoeOxHmQV3iX9k65oljERIWUmL9x6OSQg==", - "dependencies": { - "@aws-sdk/core": "3.826.0", - "@aws-sdk/types": "3.821.0", - "@smithy/fetch-http-handler": "^5.0.4", - "@smithy/node-http-handler": "^4.0.6", - "@smithy/property-provider": "^4.0.4", - "@smithy/protocol-http": "^5.1.2", - "@smithy/smithy-client": "^4.4.3", - "@smithy/types": "^4.3.1", - "@smithy/util-stream": "^4.2.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.826.0.tgz", - "integrity": "sha512-g7n+qSklq/Lzjxe2Ke5QFNCgYn26a3ydZnbFIk8QqYin4pzG+qiunaqJjpV3c/EeHMlfK8bBc7MXAylKzGRccQ==", - "dependencies": { - "@aws-sdk/core": "3.826.0", - "@aws-sdk/credential-provider-env": "3.826.0", - "@aws-sdk/credential-provider-http": "3.826.0", - "@aws-sdk/credential-provider-process": "3.826.0", - "@aws-sdk/credential-provider-sso": "3.826.0", - "@aws-sdk/credential-provider-web-identity": "3.826.0", - "@aws-sdk/nested-clients": "3.826.0", - "@aws-sdk/types": "3.821.0", - "@smithy/credential-provider-imds": "^4.0.6", - "@smithy/property-provider": "^4.0.4", - "@smithy/shared-ini-file-loader": "^4.0.4", - "@smithy/types": "^4.3.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-node": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.826.0.tgz", - "integrity": "sha512-UfIJXxHjmSxH6bea00HBPLkjNI2D04enQA/xNLZvB+4xtzt1/gYdCis1P4/73f5aGVVVB4/zQMobBbnjkrmbQw==", - "dependencies": { - "@aws-sdk/credential-provider-env": "3.826.0", - "@aws-sdk/credential-provider-http": "3.826.0", - "@aws-sdk/credential-provider-ini": "3.826.0", - "@aws-sdk/credential-provider-process": "3.826.0", - "@aws-sdk/credential-provider-sso": "3.826.0", - "@aws-sdk/credential-provider-web-identity": "3.826.0", - "@aws-sdk/types": "3.821.0", - "@smithy/credential-provider-imds": "^4.0.6", - "@smithy/property-provider": "^4.0.4", - "@smithy/shared-ini-file-loader": "^4.0.4", + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.840.0.tgz", + "integrity": "sha512-Qjnxd/yDv9KpIMWr90ZDPtRj0v75AqGC92Lm9+oHXZ8p1MjG5JE2CW0HL8JRgK9iKzgKBL7pPQRXI8FkvEVfrA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.840.0", + "@smithy/node-config-provider": "^4.1.3", "@smithy/types": "^4.3.1", + "@smithy/util-config-provider": "^4.0.0", + "@smithy/util-middleware": "^4.0.4", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/credential-provider-process": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.826.0.tgz", - "integrity": "sha512-kURrc4amu3NLtw1yZw7EoLNEVhmOMRUTs+chaNcmS+ERm3yK0nKjaJzmKahmwlTQTSl3wJ8jjK7x962VPo+zWw==", + "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/token-providers": { + "version": "3.844.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.844.0.tgz", + "integrity": "sha512-Kh728FEny0fil+LeH8U1offPJCTd/EDh8liBAvLtViLHt2WoX2xC8rk98D38Q5p79aIUhHb3Pf4n9IZfTu/Kog==", + "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "3.826.0", - "@aws-sdk/types": "3.821.0", + "@aws-sdk/core": "3.844.0", + "@aws-sdk/nested-clients": "3.844.0", + "@aws-sdk/types": "3.840.0", "@smithy/property-provider": "^4.0.4", "@smithy/shared-ini-file-loader": "^4.0.4", "@smithy/types": "^4.3.1", @@ -1547,17 +880,12 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.826.0.tgz", - "integrity": "sha512-F19J3zcfoom6OnQ0MyAtvduVKQXPgkz9i5ExSO01J2CzjbyMhCDA99qAjHYe+LwhW+W7P/jzBPd0+uOQ2Nhh9Q==", - "dependencies": { - "@aws-sdk/client-sso": "3.826.0", - "@aws-sdk/core": "3.826.0", - "@aws-sdk/token-providers": "3.826.0", - "@aws-sdk/types": "3.821.0", - "@smithy/property-provider": "^4.0.4", - "@smithy/shared-ini-file-loader": "^4.0.4", + "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/types": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.840.0.tgz", + "integrity": "sha512-xliuHaUFZxEx1NSXeLLZ9Dyu6+EJVQKEoD+yM+zqUo3YDZ7medKJWY6fIOKiPX/N7XbLdBYwajb15Q7IL8KkeA==", + "license": "Apache-2.0", + "dependencies": { "@smithy/types": "^4.3.1", "tslib": "^2.6.2" }, @@ -1565,72 +893,88 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/credential-provider-web-identity": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.826.0.tgz", - "integrity": "sha512-o27GZ6Hy7qhuvMFVUL2eFEpBzf33Jaa/x3u3SHwU0nL7ko7jmbpeF0x4+wmagpI9X2IvVlUxIs0VaQ3YayPLEA==", + "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/util-endpoints": { + "version": "3.844.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.844.0.tgz", + "integrity": "sha512-1DHh0WTUmxlysz3EereHKtKoxVUG9UC5BsfAw6Bm4/6qDlJiqtY3oa2vebkYN23yltKdfsCK65cwnBRU59mWVg==", + "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "3.826.0", - "@aws-sdk/nested-clients": "3.826.0", - "@aws-sdk/types": "3.821.0", - "@smithy/property-provider": "^4.0.4", + "@aws-sdk/types": "3.840.0", "@smithy/types": "^4.3.1", + "@smithy/url-parser": "^4.0.4", + "@smithy/util-endpoints": "^3.0.6", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-bucket-endpoint": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-bucket-endpoint/-/middleware-bucket-endpoint-3.862.0.tgz", - "integrity": "sha512-Wcsc7VPLjImQw+CP1/YkwyofMs9Ab6dVq96iS8p0zv0C6YTaMjvillkau4zFfrrrTshdzFWKptIFhKK8Zsei1g==", + "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/util-user-agent-browser": { + "version": "3.840.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.840.0.tgz", + "integrity": "sha512-JdyZM3EhhL4PqwFpttZu1afDpPJCCc3eyZOLi+srpX11LsGj6sThf47TYQN75HT1CarZ7cCdQHGzP2uy3/xHfQ==", "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.862.0", - "@aws-sdk/util-arn-parser": "3.804.0", - "@smithy/node-config-provider": "^4.1.4", - "@smithy/protocol-http": "^5.1.3", - "@smithy/types": "^4.3.2", - "@smithy/util-config-provider": "^4.0.0", + "@aws-sdk/types": "3.840.0", + "@smithy/types": "^4.3.1", + "bowser": "^2.11.0", "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-bucket-endpoint/node_modules/@aws-sdk/types": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.862.0.tgz", - "integrity": "sha512-Bei+RL0cDxxV+lW2UezLbCYYNeJm6Nzee0TpW0FfyTRBhH9C1XQh4+x+IClriXvgBnRquTMMYsmJfvx8iyLKrg==", + "node_modules/@aws-sdk/client-sts/node_modules/@aws-sdk/util-user-agent-node": { + "version": "3.844.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.844.0.tgz", + "integrity": "sha512-0eTpURp9Gxbyyeqr78ogARZMSWS5KUMZuN+XMHxNpQLmn2S+J3g+MAyoklCcwhKXlbdQq2aMULEiy0mqIWytuw==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.3.2", + "@aws-sdk/middleware-user-agent": "3.844.0", + "@aws-sdk/types": "3.840.0", + "@smithy/node-config-provider": "^4.1.3", + "@smithy/types": "^4.3.1", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" + }, + "peerDependencies": { + "aws-crt": ">=1.0.0" + }, + "peerDependenciesMeta": { + "aws-crt": { + "optional": true + } } }, - "node_modules/@aws-sdk/middleware-expect-continue": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-expect-continue/-/middleware-expect-continue-3.862.0.tgz", - "integrity": "sha512-oG3AaVUJ+26p0ESU4INFn6MmqqiBFZGrebST66Or+YBhteed2rbbFl7mCfjtPWUFgquQlvT1UP19P3LjQKeKpw==", + "node_modules/@aws-sdk/core": { + "version": "3.864.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.864.0.tgz", + "integrity": "sha512-LFUREbobleHEln+Zf7IG83lAZwvHZG0stI7UU0CtwyuhQy5Yx0rKksHNOCmlM7MpTEbSCfntEhYi3jUaY5e5lg==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/types": "3.862.0", + "@aws-sdk/xml-builder": "3.862.0", + "@smithy/core": "^3.8.0", + "@smithy/node-config-provider": "^4.1.4", + "@smithy/property-provider": "^4.0.5", "@smithy/protocol-http": "^5.1.3", + "@smithy/signature-v4": "^5.1.3", + "@smithy/smithy-client": "^4.4.10", "@smithy/types": "^4.3.2", + "@smithy/util-base64": "^4.0.0", + "@smithy/util-body-length-browser": "^4.0.0", + "@smithy/util-middleware": "^4.0.5", + "@smithy/util-utf8": "^4.0.0", + "fast-xml-parser": "5.2.5", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-expect-continue/node_modules/@aws-sdk/types": { + "node_modules/@aws-sdk/core/node_modules/@aws-sdk/xml-builder": { "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.862.0.tgz", - "integrity": "sha512-Bei+RL0cDxxV+lW2UezLbCYYNeJm6Nzee0TpW0FfyTRBhH9C1XQh4+x+IClriXvgBnRquTMMYsmJfvx8iyLKrg==", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.862.0.tgz", + "integrity": "sha512-6Ed0kmC1NMbuFTEgNmamAUU1h5gShgxL1hBVLbEzUa3trX5aJBz1vU4bXaBTvOYUAnOHtiy1Ml4AMStd6hJnFA==", "license": "Apache-2.0", "dependencies": { "@smithy/types": "^4.3.2", @@ -1640,62 +984,60 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-flexible-checksums": { + "node_modules/@aws-sdk/credential-provider-env": { "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-flexible-checksums/-/middleware-flexible-checksums-3.864.0.tgz", - "integrity": "sha512-MvakvzPZi9uyP3YADuIqtk/FAcPFkyYFWVVMf5iFs/rCdk0CUzn02Qf4CSuyhbkS6Y0KrAsMgKR4MgklPU79Wg==", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.864.0.tgz", + "integrity": "sha512-StJPOI2Rt8UE6lYjXUpg6tqSZaM72xg46ljPg8kIevtBAAfdtq9K20qT/kSliWGIBocMFAv0g2mC0hAa+ECyvg==", "license": "Apache-2.0", "dependencies": { - "@aws-crypto/crc32": "5.2.0", - "@aws-crypto/crc32c": "5.2.0", - "@aws-crypto/util": "5.2.0", "@aws-sdk/core": "3.864.0", "@aws-sdk/types": "3.862.0", - "@smithy/is-array-buffer": "^4.0.0", - "@smithy/node-config-provider": "^4.1.4", - "@smithy/protocol-http": "^5.1.3", + "@smithy/property-provider": "^4.0.5", "@smithy/types": "^4.3.2", - "@smithy/util-middleware": "^4.0.5", - "@smithy/util-stream": "^4.2.4", - "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@aws-sdk/core": { + "node_modules/@aws-sdk/credential-provider-http": { "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.864.0.tgz", - "integrity": "sha512-LFUREbobleHEln+Zf7IG83lAZwvHZG0stI7UU0CtwyuhQy5Yx0rKksHNOCmlM7MpTEbSCfntEhYi3jUaY5e5lg==", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.864.0.tgz", + "integrity": "sha512-E/RFVxGTuGnuD+9pFPH2j4l6HvrXzPhmpL8H8nOoJUosjx7d4v93GJMbbl1v/fkDLqW9qN4Jx2cI6PAjohA6OA==", "license": "Apache-2.0", "dependencies": { + "@aws-sdk/core": "3.864.0", "@aws-sdk/types": "3.862.0", - "@aws-sdk/xml-builder": "3.862.0", - "@smithy/core": "^3.8.0", - "@smithy/node-config-provider": "^4.1.4", + "@smithy/fetch-http-handler": "^5.1.1", + "@smithy/node-http-handler": "^4.1.1", "@smithy/property-provider": "^4.0.5", "@smithy/protocol-http": "^5.1.3", - "@smithy/signature-v4": "^5.1.3", "@smithy/smithy-client": "^4.4.10", "@smithy/types": "^4.3.2", - "@smithy/util-base64": "^4.0.0", - "@smithy/util-body-length-browser": "^4.0.0", - "@smithy/util-middleware": "^4.0.5", - "@smithy/util-utf8": "^4.0.0", - "fast-xml-parser": "5.2.5", + "@smithy/util-stream": "^4.2.4", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@aws-sdk/types": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.862.0.tgz", - "integrity": "sha512-Bei+RL0cDxxV+lW2UezLbCYYNeJm6Nzee0TpW0FfyTRBhH9C1XQh4+x+IClriXvgBnRquTMMYsmJfvx8iyLKrg==", + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.864.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.864.0.tgz", + "integrity": "sha512-PlxrijguR1gxyPd5EYam6OfWLarj2MJGf07DvCx9MAuQkw77HBnsu6+XbV8fQriFuoJVTBLn9ROhMr/ROAYfUg==", "license": "Apache-2.0", "dependencies": { + "@aws-sdk/core": "3.864.0", + "@aws-sdk/credential-provider-env": "3.864.0", + "@aws-sdk/credential-provider-http": "3.864.0", + "@aws-sdk/credential-provider-process": "3.864.0", + "@aws-sdk/credential-provider-sso": "3.864.0", + "@aws-sdk/credential-provider-web-identity": "3.864.0", + "@aws-sdk/nested-clients": "3.864.0", + "@aws-sdk/types": "3.862.0", + "@smithy/credential-provider-imds": "^4.0.7", + "@smithy/property-provider": "^4.0.5", + "@smithy/shared-ini-file-loader": "^4.0.5", "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, @@ -1703,12 +1045,22 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@aws-sdk/xml-builder": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.862.0.tgz", - "integrity": "sha512-6Ed0kmC1NMbuFTEgNmamAUU1h5gShgxL1hBVLbEzUa3trX5aJBz1vU4bXaBTvOYUAnOHtiy1Ml4AMStd6hJnFA==", + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.864.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.864.0.tgz", + "integrity": "sha512-2BEymFeXURS+4jE9tP3vahPwbYRl0/1MVaFZcijj6pq+nf5EPGvkFillbdBRdc98ZI2NedZgSKu3gfZXgYdUhQ==", "license": "Apache-2.0", "dependencies": { + "@aws-sdk/credential-provider-env": "3.864.0", + "@aws-sdk/credential-provider-http": "3.864.0", + "@aws-sdk/credential-provider-ini": "3.864.0", + "@aws-sdk/credential-provider-process": "3.864.0", + "@aws-sdk/credential-provider-sso": "3.864.0", + "@aws-sdk/credential-provider-web-identity": "3.864.0", + "@aws-sdk/types": "3.862.0", + "@smithy/credential-provider-imds": "^4.0.7", + "@smithy/property-provider": "^4.0.5", + "@smithy/shared-ini-file-loader": "^4.0.5", "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, @@ -1716,57 +1068,35 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/fast-xml-parser": { - "version": "5.2.5", - "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.2.5.tgz", - "integrity": "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "dependencies": { - "strnum": "^2.1.0" - }, - "bin": { - "fxparser": "src/cli/cli.js" - } - }, - "node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/strnum": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.1.1.tgz", - "integrity": "sha512-7ZvoFTiCnGxBtDqJ//Cu6fWtZtc7Y3x+QOirG15wztbdngGSkht27o2pyGWrVy0b4WAy3jbKmnoK6g5VlVNUUw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT" - }, - "node_modules/@aws-sdk/middleware-host-header": { - "version": "3.821.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.821.0.tgz", - "integrity": "sha512-xSMR+sopSeWGx5/4pAGhhfMvGBHioVBbqGvDs6pG64xfNwM5vq5s5v6D04e2i+uSTj4qGa71dLUs5I0UzAK3sw==", + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.864.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.864.0.tgz", + "integrity": "sha512-Zxnn1hxhq7EOqXhVYgkF4rI9MnaO3+6bSg/tErnBQ3F8kDpA7CFU24G1YxwaJXp2X4aX3LwthefmSJHwcVP/2g==", + "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.821.0", - "@smithy/protocol-http": "^5.1.2", - "@smithy/types": "^4.3.1", + "@aws-sdk/core": "3.864.0", + "@aws-sdk/types": "3.862.0", + "@smithy/property-provider": "^4.0.5", + "@smithy/shared-ini-file-loader": "^4.0.5", + "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-location-constraint": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-location-constraint/-/middleware-location-constraint-3.862.0.tgz", - "integrity": "sha512-MnwLxCw7Cc9OngEH3SHFhrLlDI9WVxaBkp3oTsdY9JE7v8OE38wQ9vtjaRsynjwu0WRtrctSHbpd7h/QVvtjyA==", + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.864.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.864.0.tgz", + "integrity": "sha512-UPyPNQbxDwHVGmgWdGg9/9yvzuedRQVF5jtMkmP565YX9pKZ8wYAcXhcYdNPWFvH0GYdB0crKOmvib+bmCuwkw==", "license": "Apache-2.0", "dependencies": { + "@aws-sdk/client-sso": "3.864.0", + "@aws-sdk/core": "3.864.0", + "@aws-sdk/token-providers": "3.864.0", "@aws-sdk/types": "3.862.0", + "@smithy/property-provider": "^4.0.5", + "@smithy/shared-ini-file-loader": "^4.0.5", "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, @@ -1774,12 +1104,16 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-location-constraint/node_modules/@aws-sdk/types": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.862.0.tgz", - "integrity": "sha512-Bei+RL0cDxxV+lW2UezLbCYYNeJm6Nzee0TpW0FfyTRBhH9C1XQh4+x+IClriXvgBnRquTMMYsmJfvx8iyLKrg==", + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.864.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.864.0.tgz", + "integrity": "sha512-nNcjPN4SYg8drLwqK0vgVeSvxeGQiD0FxOaT38mV2H8cu0C5NzpvA+14Xy+W6vT84dxgmJYKk71Cr5QL2Oz+rA==", "license": "Apache-2.0", "dependencies": { + "@aws-sdk/core": "3.864.0", + "@aws-sdk/nested-clients": "3.864.0", + "@aws-sdk/types": "3.862.0", + "@smithy/property-provider": "^4.0.5", "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, @@ -1787,49 +1121,54 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-logger": { - "version": "3.821.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.821.0.tgz", - "integrity": "sha512-0cvI0ipf2tGx7fXYEEN5fBeZDz2RnHyb9xftSgUsEq7NBxjV0yTZfLJw6Za5rjE6snC80dRN8+bTNR1tuG89zA==", + "node_modules/@aws-sdk/middleware-bucket-endpoint": { + "version": "3.862.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-bucket-endpoint/-/middleware-bucket-endpoint-3.862.0.tgz", + "integrity": "sha512-Wcsc7VPLjImQw+CP1/YkwyofMs9Ab6dVq96iS8p0zv0C6YTaMjvillkau4zFfrrrTshdzFWKptIFhKK8Zsei1g==", + "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.821.0", - "@smithy/types": "^4.3.1", + "@aws-sdk/types": "3.862.0", + "@aws-sdk/util-arn-parser": "3.804.0", + "@smithy/node-config-provider": "^4.1.4", + "@smithy/protocol-http": "^5.1.3", + "@smithy/types": "^4.3.2", + "@smithy/util-config-provider": "^4.0.0", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-recursion-detection": { - "version": "3.821.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.821.0.tgz", - "integrity": "sha512-efmaifbhBoqKG3bAoEfDdcM8hn1psF+4qa7ykWuYmfmah59JBeqHLfz5W9m9JoTwoKPkFcVLWZxnyZzAnVBOIg==", + "node_modules/@aws-sdk/middleware-expect-continue": { + "version": "3.862.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-expect-continue/-/middleware-expect-continue-3.862.0.tgz", + "integrity": "sha512-oG3AaVUJ+26p0ESU4INFn6MmqqiBFZGrebST66Or+YBhteed2rbbFl7mCfjtPWUFgquQlvT1UP19P3LjQKeKpw==", + "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.821.0", - "@smithy/protocol-http": "^5.1.2", - "@smithy/types": "^4.3.1", + "@aws-sdk/types": "3.862.0", + "@smithy/protocol-http": "^5.1.3", + "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-sdk-s3": { + "node_modules/@aws-sdk/middleware-flexible-checksums": { "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.864.0.tgz", - "integrity": "sha512-GjYPZ6Xnqo17NnC8NIQyvvdzzO7dm+Ks7gpxD/HsbXPmV2aEfuFveJXneGW9e1BheSKFff6FPDWu8Gaj2Iu1yg==", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-flexible-checksums/-/middleware-flexible-checksums-3.864.0.tgz", + "integrity": "sha512-MvakvzPZi9uyP3YADuIqtk/FAcPFkyYFWVVMf5iFs/rCdk0CUzn02Qf4CSuyhbkS6Y0KrAsMgKR4MgklPU79Wg==", "license": "Apache-2.0", "dependencies": { + "@aws-crypto/crc32": "5.2.0", + "@aws-crypto/crc32c": "5.2.0", + "@aws-crypto/util": "5.2.0", "@aws-sdk/core": "3.864.0", "@aws-sdk/types": "3.862.0", - "@aws-sdk/util-arn-parser": "3.804.0", - "@smithy/core": "^3.8.0", + "@smithy/is-array-buffer": "^4.0.0", "@smithy/node-config-provider": "^4.1.4", "@smithy/protocol-http": "^5.1.3", - "@smithy/signature-v4": "^5.1.3", - "@smithy/smithy-client": "^4.4.10", "@smithy/types": "^4.3.2", - "@smithy/util-config-provider": "^4.0.0", "@smithy/util-middleware": "^4.0.5", "@smithy/util-stream": "^4.2.4", "@smithy/util-utf8": "^4.0.0", @@ -1839,38 +1178,28 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@aws-sdk/core": { - "version": "3.864.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.864.0.tgz", - "integrity": "sha512-LFUREbobleHEln+Zf7IG83lAZwvHZG0stI7UU0CtwyuhQy5Yx0rKksHNOCmlM7MpTEbSCfntEhYi3jUaY5e5lg==", + "node_modules/@aws-sdk/middleware-host-header": { + "version": "3.862.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.862.0.tgz", + "integrity": "sha512-jDje8dCFeFHfuCAxMDXBs8hy8q9NCTlyK4ThyyfAj3U4Pixly2mmzY2u7b7AyGhWsjJNx8uhTjlYq5zkQPQCYw==", "license": "Apache-2.0", "dependencies": { "@aws-sdk/types": "3.862.0", - "@aws-sdk/xml-builder": "3.862.0", - "@smithy/core": "^3.8.0", - "@smithy/node-config-provider": "^4.1.4", - "@smithy/property-provider": "^4.0.5", "@smithy/protocol-http": "^5.1.3", - "@smithy/signature-v4": "^5.1.3", - "@smithy/smithy-client": "^4.4.10", "@smithy/types": "^4.3.2", - "@smithy/util-base64": "^4.0.0", - "@smithy/util-body-length-browser": "^4.0.0", - "@smithy/util-middleware": "^4.0.5", - "@smithy/util-utf8": "^4.0.0", - "fast-xml-parser": "5.2.5", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@aws-sdk/types": { + "node_modules/@aws-sdk/middleware-location-constraint": { "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.862.0.tgz", - "integrity": "sha512-Bei+RL0cDxxV+lW2UezLbCYYNeJm6Nzee0TpW0FfyTRBhH9C1XQh4+x+IClriXvgBnRquTMMYsmJfvx8iyLKrg==", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-location-constraint/-/middleware-location-constraint-3.862.0.tgz", + "integrity": "sha512-MnwLxCw7Cc9OngEH3SHFhrLlDI9WVxaBkp3oTsdY9JE7v8OE38wQ9vtjaRsynjwu0WRtrctSHbpd7h/QVvtjyA==", "license": "Apache-2.0", "dependencies": { + "@aws-sdk/types": "3.862.0", "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, @@ -1878,12 +1207,13 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@aws-sdk/xml-builder": { + "node_modules/@aws-sdk/middleware-logger": { "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.862.0.tgz", - "integrity": "sha512-6Ed0kmC1NMbuFTEgNmamAUU1h5gShgxL1hBVLbEzUa3trX5aJBz1vU4bXaBTvOYUAnOHtiy1Ml4AMStd6hJnFA==", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.862.0.tgz", + "integrity": "sha512-N/bXSJznNBR/i7Ofmf9+gM6dx/SPBK09ZWLKsW5iQjqKxAKn/2DozlnE54uiEs1saHZWoNDRg69Ww4XYYSlG1Q==", "license": "Apache-2.0", "dependencies": { + "@aws-sdk/types": "3.862.0", "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, @@ -1891,56 +1221,53 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-sdk-s3/node_modules/fast-xml-parser": { - "version": "5.2.5", - "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.2.5.tgz", - "integrity": "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", + "node_modules/@aws-sdk/middleware-recursion-detection": { + "version": "3.862.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.862.0.tgz", + "integrity": "sha512-KVoo3IOzEkTq97YKM4uxZcYFSNnMkhW/qj22csofLegZi5fk90ztUnnaeKfaEJHfHp/tm1Y3uSoOXH45s++kKQ==", + "license": "Apache-2.0", "dependencies": { - "strnum": "^2.1.0" + "@aws-sdk/types": "3.862.0", + "@smithy/protocol-http": "^5.1.3", + "@smithy/types": "^4.3.2", + "tslib": "^2.6.2" }, - "bin": { - "fxparser": "src/cli/cli.js" + "engines": { + "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-sdk-s3/node_modules/strnum": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.1.1.tgz", - "integrity": "sha512-7ZvoFTiCnGxBtDqJ//Cu6fWtZtc7Y3x+QOirG15wztbdngGSkht27o2pyGWrVy0b4WAy3jbKmnoK6g5VlVNUUw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT" - }, - "node_modules/@aws-sdk/middleware-ssec": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-ssec/-/middleware-ssec-3.862.0.tgz", - "integrity": "sha512-72VtP7DZC8lYTE2L3Efx2BrD98oe9WTK8X6hmd3WTLkbIjvgWQWIdjgaFXBs8WevsXkewIctfyA3KEezvL5ggw==", + "node_modules/@aws-sdk/middleware-sdk-s3": { + "version": "3.864.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.864.0.tgz", + "integrity": "sha512-GjYPZ6Xnqo17NnC8NIQyvvdzzO7dm+Ks7gpxD/HsbXPmV2aEfuFveJXneGW9e1BheSKFff6FPDWu8Gaj2Iu1yg==", "license": "Apache-2.0", "dependencies": { + "@aws-sdk/core": "3.864.0", "@aws-sdk/types": "3.862.0", + "@aws-sdk/util-arn-parser": "3.804.0", + "@smithy/core": "^3.8.0", + "@smithy/node-config-provider": "^4.1.4", + "@smithy/protocol-http": "^5.1.3", + "@smithy/signature-v4": "^5.1.3", + "@smithy/smithy-client": "^4.4.10", "@smithy/types": "^4.3.2", + "@smithy/util-config-provider": "^4.0.0", + "@smithy/util-middleware": "^4.0.5", + "@smithy/util-stream": "^4.2.4", + "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, "engines": { "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/middleware-ssec/node_modules/@aws-sdk/types": { + "node_modules/@aws-sdk/middleware-ssec": { "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.862.0.tgz", - "integrity": "sha512-Bei+RL0cDxxV+lW2UezLbCYYNeJm6Nzee0TpW0FfyTRBhH9C1XQh4+x+IClriXvgBnRquTMMYsmJfvx8iyLKrg==", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-ssec/-/middleware-ssec-3.862.0.tgz", + "integrity": "sha512-72VtP7DZC8lYTE2L3Efx2BrD98oe9WTK8X6hmd3WTLkbIjvgWQWIdjgaFXBs8WevsXkewIctfyA3KEezvL5ggw==", "license": "Apache-2.0", "dependencies": { + "@aws-sdk/types": "3.862.0", "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, @@ -1949,16 +1276,17 @@ } }, "node_modules/@aws-sdk/middleware-user-agent": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.826.0.tgz", - "integrity": "sha512-j404+EcfBbtTlAhyObjXbdKwwDXO1pCxHvR5Fw8FXNvp/H330j6YnXgs3SJ6d3bZUwUJ/ztPx2S5AlBbLVLDFw==", - "dependencies": { - "@aws-sdk/core": "3.826.0", - "@aws-sdk/types": "3.821.0", - "@aws-sdk/util-endpoints": "3.821.0", - "@smithy/core": "^3.5.3", - "@smithy/protocol-http": "^5.1.2", - "@smithy/types": "^4.3.1", + "version": "3.864.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.864.0.tgz", + "integrity": "sha512-wrddonw4EyLNSNBrApzEhpSrDwJiNfjxDm5E+bn8n32BbAojXASH8W8jNpxz/jMgNkkJNxCfyqybGKzBX0OhbQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.864.0", + "@aws-sdk/types": "3.862.0", + "@aws-sdk/util-endpoints": "3.862.0", + "@smithy/core": "^3.8.0", + "@smithy/protocol-http": "^5.1.3", + "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, "engines": { @@ -1966,46 +1294,47 @@ } }, "node_modules/@aws-sdk/nested-clients": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.826.0.tgz", - "integrity": "sha512-p7olPq0uTtHqGuXI1GSc/gzKDvV55PMbLtnmupEDfnY9SoRu+QatbWQ6da9sI1lhOcNmRMgiNQBXFzaUFrG+SQ==", + "version": "3.864.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.864.0.tgz", + "integrity": "sha512-H1C+NjSmz2y8Tbgh7Yy89J20yD/hVyk15hNoZDbCYkXg0M358KS7KVIEYs8E2aPOCr1sK3HBE819D/yvdMgokA==", + "license": "Apache-2.0", "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "3.826.0", - "@aws-sdk/middleware-host-header": "3.821.0", - "@aws-sdk/middleware-logger": "3.821.0", - "@aws-sdk/middleware-recursion-detection": "3.821.0", - "@aws-sdk/middleware-user-agent": "3.826.0", - "@aws-sdk/region-config-resolver": "3.821.0", - "@aws-sdk/types": "3.821.0", - "@aws-sdk/util-endpoints": "3.821.0", - "@aws-sdk/util-user-agent-browser": "3.821.0", - "@aws-sdk/util-user-agent-node": "3.826.0", - "@smithy/config-resolver": "^4.1.4", - "@smithy/core": "^3.5.3", - "@smithy/fetch-http-handler": "^5.0.4", - "@smithy/hash-node": "^4.0.4", - "@smithy/invalid-dependency": "^4.0.4", - "@smithy/middleware-content-length": "^4.0.4", - "@smithy/middleware-endpoint": "^4.1.11", - "@smithy/middleware-retry": "^4.1.12", - "@smithy/middleware-serde": "^4.0.8", - "@smithy/middleware-stack": "^4.0.4", - "@smithy/node-config-provider": "^4.1.3", - "@smithy/node-http-handler": "^4.0.6", - "@smithy/protocol-http": "^5.1.2", - "@smithy/smithy-client": "^4.4.3", - "@smithy/types": "^4.3.1", - "@smithy/url-parser": "^4.0.4", + "@aws-sdk/core": "3.864.0", + "@aws-sdk/middleware-host-header": "3.862.0", + "@aws-sdk/middleware-logger": "3.862.0", + "@aws-sdk/middleware-recursion-detection": "3.862.0", + "@aws-sdk/middleware-user-agent": "3.864.0", + "@aws-sdk/region-config-resolver": "3.862.0", + "@aws-sdk/types": "3.862.0", + "@aws-sdk/util-endpoints": "3.862.0", + "@aws-sdk/util-user-agent-browser": "3.862.0", + "@aws-sdk/util-user-agent-node": "3.864.0", + "@smithy/config-resolver": "^4.1.5", + "@smithy/core": "^3.8.0", + "@smithy/fetch-http-handler": "^5.1.1", + "@smithy/hash-node": "^4.0.5", + "@smithy/invalid-dependency": "^4.0.5", + "@smithy/middleware-content-length": "^4.0.5", + "@smithy/middleware-endpoint": "^4.1.18", + "@smithy/middleware-retry": "^4.1.19", + "@smithy/middleware-serde": "^4.0.9", + "@smithy/middleware-stack": "^4.0.5", + "@smithy/node-config-provider": "^4.1.4", + "@smithy/node-http-handler": "^4.1.1", + "@smithy/protocol-http": "^5.1.3", + "@smithy/smithy-client": "^4.4.10", + "@smithy/types": "^4.3.2", + "@smithy/url-parser": "^4.0.5", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", - "@smithy/util-defaults-mode-browser": "^4.0.19", - "@smithy/util-defaults-mode-node": "^4.0.19", - "@smithy/util-endpoints": "^3.0.6", - "@smithy/util-middleware": "^4.0.4", - "@smithy/util-retry": "^4.0.5", + "@smithy/util-defaults-mode-browser": "^4.0.26", + "@smithy/util-defaults-mode-node": "^4.0.26", + "@smithy/util-endpoints": "^3.0.7", + "@smithy/util-middleware": "^4.0.5", + "@smithy/util-retry": "^4.0.7", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" }, @@ -2014,15 +1343,16 @@ } }, "node_modules/@aws-sdk/region-config-resolver": { - "version": "3.821.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.821.0.tgz", - "integrity": "sha512-t8og+lRCIIy5nlId0bScNpCkif8sc0LhmtaKsbm0ZPm3sCa/WhCbSZibjbZ28FNjVCV+p0D9RYZx0VDDbtWyjw==", + "version": "3.862.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.862.0.tgz", + "integrity": "sha512-VisR+/HuVFICrBPY+q9novEiE4b3mvDofWqyvmxHcWM7HumTz9ZQSuEtnlB/92GVM3KDUrR9EmBHNRrfXYZkcQ==", + "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.821.0", - "@smithy/node-config-provider": "^4.1.3", - "@smithy/types": "^4.3.1", + "@aws-sdk/types": "3.862.0", + "@smithy/node-config-provider": "^4.1.4", + "@smithy/types": "^4.3.2", "@smithy/util-config-provider": "^4.0.0", - "@smithy/util-middleware": "^4.0.4", + "@smithy/util-middleware": "^4.0.5", "tslib": "^2.6.2" }, "engines": { @@ -2055,12 +1385,17 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/signature-v4-multi-region/node_modules/@aws-sdk/types": { - "version": "3.862.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.862.0.tgz", - "integrity": "sha512-Bei+RL0cDxxV+lW2UezLbCYYNeJm6Nzee0TpW0FfyTRBhH9C1XQh4+x+IClriXvgBnRquTMMYsmJfvx8iyLKrg==", + "node_modules/@aws-sdk/token-providers": { + "version": "3.864.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.864.0.tgz", + "integrity": "sha512-gTc2QHOBo05SCwVA65dUtnJC6QERvFaPiuppGDSxoF7O5AQNK0UR/kMSenwLqN8b5E1oLYvQTv3C1idJLRX0cg==", "license": "Apache-2.0", "dependencies": { + "@aws-sdk/core": "3.864.0", + "@aws-sdk/nested-clients": "3.864.0", + "@aws-sdk/types": "3.862.0", + "@smithy/property-provider": "^4.0.5", + "@smithy/shared-ini-file-loader": "^4.0.5", "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, @@ -2068,30 +1403,13 @@ "node": ">=18.0.0" } }, - "node_modules/@aws-sdk/token-providers": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.826.0.tgz", - "integrity": "sha512-iCOcVAqGPSHtQL8ZBXifZMEcHyUl9wJ8HvLZ5l1ohA/3ZNP+dqEPGi7jfhR5jZKs+xyp2jxByFqfil9PjI9c5A==", - "dependencies": { - "@aws-sdk/core": "3.826.0", - "@aws-sdk/nested-clients": "3.826.0", - "@aws-sdk/types": "3.821.0", - "@smithy/property-provider": "^4.0.4", - "@smithy/shared-ini-file-loader": "^4.0.4", - "@smithy/types": "^4.3.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, "node_modules/@aws-sdk/types": { - "version": "3.821.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.821.0.tgz", - "integrity": "sha512-Znroqdai1a90TlxGaJ+FK1lwC0fHpo97Xjsp5UKGR5JODYm7f9+/fF17ebO1KdoBr/Rm0UIFiF5VmI8ts9F1eA==", + "version": "3.862.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.862.0.tgz", + "integrity": "sha512-Bei+RL0cDxxV+lW2UezLbCYYNeJm6Nzee0TpW0FfyTRBhH9C1XQh4+x+IClriXvgBnRquTMMYsmJfvx8iyLKrg==", "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.3.1", + "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, "engines": { @@ -2111,13 +1429,15 @@ } }, "node_modules/@aws-sdk/util-endpoints": { - "version": "3.821.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.821.0.tgz", - "integrity": "sha512-Uknt/zUZnLE76zaAAPEayOeF5/4IZ2puTFXvcSCWHsi9m3tqbb9UozlnlVqvCZLCRWfQryZQoG2W4XSS3qgk5A==", + "version": "3.862.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.862.0.tgz", + "integrity": "sha512-eCZuScdE9MWWkHGM2BJxm726MCmWk/dlHjOKvkM0sN1zxBellBMw5JohNss1Z8/TUmnW2gb9XHTOiHuGjOdksA==", + "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.821.0", - "@smithy/types": "^4.3.1", - "@smithy/util-endpoints": "^3.0.6", + "@aws-sdk/types": "3.862.0", + "@smithy/types": "^4.3.2", + "@smithy/url-parser": "^4.0.5", + "@smithy/util-endpoints": "^3.0.7", "tslib": "^2.6.2" }, "engines": { @@ -2149,25 +1469,27 @@ } }, "node_modules/@aws-sdk/util-user-agent-browser": { - "version": "3.821.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.821.0.tgz", - "integrity": "sha512-irWZHyM0Jr1xhC+38OuZ7JB6OXMLPZlj48thElpsO1ZSLRkLZx5+I7VV6k3sp2yZ7BYbKz/G2ojSv4wdm7XTLw==", + "version": "3.862.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.862.0.tgz", + "integrity": "sha512-BmPTlm0r9/10MMr5ND9E92r8KMZbq5ltYXYpVcUbAsnB1RJ8ASJuRoLne5F7mB3YMx0FJoOTuSq7LdQM3LgW3Q==", + "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "3.821.0", - "@smithy/types": "^4.3.1", + "@aws-sdk/types": "3.862.0", + "@smithy/types": "^4.3.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "node_modules/@aws-sdk/util-user-agent-node": { - "version": "3.826.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.826.0.tgz", - "integrity": "sha512-wHw6bZQWIMcFF/8r03aY9Itp6JLBYY4absGGhCDK1dc3tPEfi8NVSdb05a/Oz+g4TVaDdxLo0OQ/OKMS1DFRHQ==", + "version": "3.864.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.864.0.tgz", + "integrity": "sha512-d+FjUm2eJEpP+FRpVR3z6KzMdx1qwxEYDz8jzNKwxYLBBquaBaP/wfoMtMQKAcbrR7aT9FZVZF7zDgzNxUvQlQ==", + "license": "Apache-2.0", "dependencies": { - "@aws-sdk/middleware-user-agent": "3.826.0", - "@aws-sdk/types": "3.821.0", - "@smithy/node-config-provider": "^4.1.3", - "@smithy/types": "^4.3.1", + "@aws-sdk/middleware-user-agent": "3.864.0", + "@aws-sdk/types": "3.862.0", + "@smithy/node-config-provider": "^4.1.4", + "@smithy/types": "^4.3.2", "tslib": "^2.6.2" }, "engines": { @@ -5599,21 +4921,18 @@ "dev": true }, "node_modules/fast-xml-parser": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.4.1.tgz", - "integrity": "sha512-xkjOecfnKGkSsOwtZ5Pz7Us/T6mrbPQrq0nh+aCO5V9nk5NLWmasAHumTKjiPJPWANe+kAZ84Jc8ooJkzZ88Sw==", + "version": "5.2.5", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.2.5.tgz", + "integrity": "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==", "funding": [ { "type": "github", "url": "https://github.com/sponsors/NaturalIntelligence" - }, - { - "type": "paypal", - "url": "https://paypal.me/naturalintelligence" } ], + "license": "MIT", "dependencies": { - "strnum": "^1.0.5" + "strnum": "^2.1.0" }, "bin": { "fxparser": "src/cli/cli.js" @@ -7832,15 +7151,16 @@ } }, "node_modules/strnum": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz", - "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.1.1.tgz", + "integrity": "sha512-7ZvoFTiCnGxBtDqJ//Cu6fWtZtc7Y3x+QOirG15wztbdngGSkht27o2pyGWrVy0b4WAy3jbKmnoK6g5VlVNUUw==", "funding": [ { "type": "github", "url": "https://github.com/sponsors/NaturalIntelligence" } - ] + ], + "license": "MIT" }, "node_modules/supports-color": { "version": "7.2.0", diff --git a/package.json b/package.json index c674b46..36defbe 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "dependencies": { "@actions/core": "^1.10.0", "@actions/github": "^6.0.1", - "@aws-sdk/client-lambda": "^3.826.0", + "@aws-sdk/client-lambda": "^3.865.0", "@aws-sdk/client-s3": "^3.864.0", "@aws-sdk/util-retry": "^3.370.0", "@smithy/node-http-handler": "^4.0.6",