openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
10,914 lines • 444 kB
JavaScript
import { a as __toCommonJS, i as __require, n as __esmMin, o as __toESM, r as __exportAll, t as __commonJSMin } from "./chunk-DORXReHP.js";
import { t as require_dist_cjs$33 } from "./dist-cjs-WSNQnW7p.js";
import { t as require_dist_cjs$34 } from "./dist-cjs-g8U_euY0.js";
import { a as setCredentialFeature, i as setFeature$2, n as init_client, o as emitWarningIfUnsupportedVersion, r as setTokenFeature, s as state } from "./client-Cta4m6Io.js";
import { C as require_dist_cjs$40, S as require_dist_cjs$37, d as endpoints_exports, f as init_endpoints, h as require_dist_cjs$36, i as requestBuilder$1, m as require_dist_cjs$39, n as init_protocols$3, t as require_dist_cjs$41, v as require_dist_cjs$35, y as require_dist_cjs$38 } from "./dist-cjs-Bw_je4qJ.js";
import { n as require_dist_cjs$43, t as require_dist_cjs$42 } from "./dist-cjs-DPPy6JFe.js";
import { t as require_dist_cjs$44 } from "./dist-cjs-C-v0A3hP.js";
import { n as require_dist_cjs$45, r as require_dist_cjs$47, t as require_dist_cjs$46 } from "./dist-cjs-Cpxgp4nL.js";
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js
var import_dist_cjs$49, getDateHeader;
var init_getDateHeader = __esmMin((() => {
import_dist_cjs$49 = require_dist_cjs$34();
getDateHeader = (response) => import_dist_cjs$49.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0;
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js
var getSkewCorrectedDate;
var init_getSkewCorrectedDate = __esmMin((() => {
getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset);
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js
var isClockSkewed;
var init_isClockSkewed = __esmMin((() => {
init_getSkewCorrectedDate();
isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5;
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js
var getUpdatedSystemClockOffset;
var init_getUpdatedSystemClockOffset = __esmMin((() => {
init_isClockSkewed();
getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => {
const clockTimeInMs = Date.parse(clockTime);
if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) return clockTimeInMs - Date.now();
return currentSystemClockOffset;
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js
var init_utils = __esmMin((() => {
init_getDateHeader();
init_getSkewCorrectedDate();
init_getUpdatedSystemClockOffset();
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js
var import_dist_cjs$48, throwSigningPropertyError, validateSigningProperties, AwsSdkSigV4Signer, AWSSDKSigV4Signer;
var init_AwsSdkSigV4Signer = __esmMin((() => {
import_dist_cjs$48 = require_dist_cjs$34();
init_utils();
throwSigningPropertyError = (name, property) => {
if (!property) throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`);
return property;
};
validateSigningProperties = async (signingProperties) => {
const context = throwSigningPropertyError("context", signingProperties.context);
const config = throwSigningPropertyError("config", signingProperties.config);
const authScheme = context.endpointV2?.properties?.authSchemes?.[0];
return {
config,
signer: await throwSigningPropertyError("signer", config.signer)(authScheme),
signingRegion: signingProperties?.signingRegion,
signingRegionSet: signingProperties?.signingRegionSet,
signingName: signingProperties?.signingName
};
};
AwsSdkSigV4Signer = class {
async sign(httpRequest, identity, signingProperties) {
if (!import_dist_cjs$48.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 ?? false) {
const [first, second] = handlerExecutionContext.authSchemes;
if (first?.name === "sigv4a" && second?.name === "sigv4") {
signingRegion = second?.signingRegion ?? signingRegion;
signingName = second?.signingName ?? signingName;
}
}
return await signer.sign(httpRequest, {
signingDate: getSkewCorrectedDate(config.systemClockOffset),
signingRegion,
signingService: signingName
});
}
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);
if (config.systemClockOffset !== initialSystemClockOffset && 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);
}
}
};
AWSSDKSigV4Signer = AwsSdkSigV4Signer;
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.js
var import_dist_cjs$47, AwsSdkSigV4ASigner;
var init_AwsSdkSigV4ASigner = __esmMin((() => {
import_dist_cjs$47 = require_dist_cjs$34();
init_utils();
init_AwsSdkSigV4Signer();
AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer {
async sign(httpRequest, identity, signingProperties) {
if (!import_dist_cjs$47.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 multiRegionOverride = (await config.sigv4aSigningRegionSet?.() ?? signingRegionSet ?? [signingRegion]).join(",");
return await signer.sign(httpRequest, {
signingDate: getSkewCorrectedDate(config.systemClockOffset),
signingRegion: multiRegionOverride,
signingService: signingName
});
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js
var getArrayForCommaSeparatedString;
var init_getArrayForCommaSeparatedString = __esmMin((() => {
getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [];
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js
var getBearerTokenEnvKey;
var init_getBearerTokenEnvKey = __esmMin((() => {
getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`;
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js
var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY, NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS;
var init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = __esmMin((() => {
init_getArrayForCommaSeparatedString();
init_getBearerTokenEnvKey();
NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE";
NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference";
NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = {
environmentVariableSelector: (env, options) => {
if (options?.signingName) {
if (getBearerTokenEnvKey(options.signingName) 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]);
},
configFileSelector: (profile) => {
if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) return void 0;
return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]);
},
default: []
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/getSmithyContext.js
var init_getSmithyContext$2 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js
var init_httpAuthSchemeMiddleware$2 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js
var init_getHttpAuthSchemeEndpointRuleSetPlugin$2 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js
var init_getHttpAuthSchemePlugin$2 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js
var init_middleware_http_auth_scheme$2 = __esmMin((() => {
init_httpAuthSchemeMiddleware$2();
init_getHttpAuthSchemeEndpointRuleSetPlugin$2();
init_getHttpAuthSchemePlugin$2();
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js
var init_httpSigningMiddleware$2 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js
var init_getHttpSigningMiddleware$2 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js
var init_middleware_http_signing$2 = __esmMin((() => {
init_httpSigningMiddleware$2();
init_getHttpSigningMiddleware$2();
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/normalizeProvider.js
var normalizeProvider$2;
var init_normalizeProvider$2 = __esmMin((() => {
normalizeProvider$2 = (input) => {
if (typeof input === "function") return input;
const promisified = Promise.resolve(input);
return () => promisified;
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js
var import_dist_cjs$46, collectBody$1;
var init_collect_stream_body$1 = __esmMin((() => {
import_dist_cjs$46 = require_dist_cjs$35();
collectBody$1 = async (streamBody = new Uint8Array(), context) => {
if (streamBody instanceof Uint8Array) return import_dist_cjs$46.Uint8ArrayBlobAdapter.mutate(streamBody);
if (!streamBody) return import_dist_cjs$46.Uint8ArrayBlobAdapter.mutate(new Uint8Array());
const fromContext = context.streamCollector(streamBody);
return import_dist_cjs$46.Uint8ArrayBlobAdapter.mutate(await fromContext);
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js
function extendedEncodeURIComponent$1(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return "%" + c.charCodeAt(0).toString(16).toUpperCase();
});
}
var init_extended_encode_uri_component$1 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/schema/deref.js
var deref;
var init_deref = __esmMin((() => {
deref = (schemaRef) => {
if (typeof schemaRef === "function") return schemaRef();
return schemaRef;
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/schema/schemas/operation.js
var init_operation = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js
var init_getSchemaSerdePlugin = __esmMin((() => {}));
var init_Schema = __esmMin((() => {
Symbol.hasInstance;
}));
var init_ListSchema = __esmMin((() => {
init_Schema();
}));
var init_MapSchema = __esmMin((() => {
init_Schema();
}));
var init_OperationSchema = __esmMin((() => {
init_Schema();
}));
var init_StructureSchema = __esmMin((() => {
init_Schema();
}));
var init_ErrorSchema = __esmMin((() => {
init_StructureSchema();
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/schema/schemas/translateTraits.js
function translateTraits(indicator) {
if (typeof indicator === "object") return indicator;
indicator = indicator | 0;
if (traitsCache[indicator]) return traitsCache[indicator];
const traits = {};
let i = 0;
for (const trait of [
"httpLabel",
"idempotent",
"idempotencyToken",
"sensitive",
"httpPayload",
"httpResponseCode",
"httpQueryParams"
]) if ((indicator >> i++ & 1) === 1) traits[trait] = 1;
return traitsCache[indicator] = traits;
}
var traitsCache;
var init_translateTraits = __esmMin((() => {
traitsCache = [];
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js
function member(memberSchema, memberName) {
if (memberSchema instanceof NormalizedSchema) return Object.assign(memberSchema, {
memberName,
_isMemberSchema: true
});
return new NormalizedSchema(memberSchema, memberName);
}
var anno, simpleSchemaCacheN, simpleSchemaCacheS, NormalizedSchema, isMemberSchema, isStaticSchema;
var init_NormalizedSchema = __esmMin((() => {
init_deref();
init_translateTraits();
anno = {
it: Symbol.for("@smithy/nor-struct-it"),
ns: Symbol.for("@smithy/ns")
};
simpleSchemaCacheN = [];
simpleSchemaCacheS = {};
NormalizedSchema = class NormalizedSchema {
ref;
memberName;
static symbol = Symbol.for("@smithy/nor");
symbol = NormalizedSchema.symbol;
name;
schema;
_isMemberSchema;
traits;
memberTraits;
normalizedTraits;
constructor(ref, memberName) {
this.ref = ref;
this.memberName = memberName;
const traitStack = [];
let _ref = ref;
let schema = ref;
this._isMemberSchema = false;
while (isMemberSchema(_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, translateTraits(traitSet));
}
} else this.memberTraits = 0;
if (schema instanceof NormalizedSchema) {
const computedMemberTraits = this.memberTraits;
Object.assign(this, schema);
this.memberTraits = Object.assign({}, computedMemberTraits, schema.getMemberTraits(), this.getMemberTraits());
this.normalizedTraits = void 0;
this.memberName = memberName ?? schema.memberName;
return;
}
this.schema = deref(schema);
if (isStaticSchema(this.schema)) {
this.name = `${this.schema[1]}#${this.schema[2]}`;
this.traits = this.schema[3];
} else {
this.name = this.memberName ?? String(schema);
this.traits = 0;
}
if (this._isMemberSchema && !memberName) throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`);
}
static [Symbol.hasInstance](lhs) {
const isPrototype = this.prototype.isPrototypeOf(lhs);
if (!isPrototype && typeof lhs === "object" && lhs !== null) return lhs.symbol === this.symbol;
return isPrototype;
}
static of(ref) {
const keyAble = typeof ref === "function" || typeof ref === "object" && ref !== null;
if (typeof ref === "number") {
if (simpleSchemaCacheN[ref]) return simpleSchemaCacheN[ref];
} else if (typeof ref === "string") {
if (simpleSchemaCacheS[ref]) return simpleSchemaCacheS[ref];
} else if (keyAble) {
if (ref[anno.ns]) return ref[anno.ns];
}
const sc = deref(ref);
if (sc instanceof NormalizedSchema) return sc;
if (isMemberSchema(sc)) {
const [ns, traits] = sc;
if (ns instanceof NormalizedSchema) {
Object.assign(ns.getMergedTraits(), translateTraits(traits));
return ns;
}
throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`);
}
const ns = new NormalizedSchema(sc);
if (keyAble) return ref[anno.ns] = ns;
if (typeof sc === "string") return simpleSchemaCacheS[sc] = ns;
if (typeof sc === "number") return simpleSchemaCacheN[sc] = ns;
return ns;
}
getSchema() {
const sc = this.schema;
if (Array.isArray(sc) && sc[0] === 0) return sc[4];
return sc;
}
getName(withNamespace = false) {
const { name } = this;
return !withNamespace && name && name.includes("#") ? name.split("#")[1] : name || void 0;
}
getMemberName() {
return this.memberName;
}
isMemberSchema() {
return this._isMemberSchema;
}
isListSchema() {
const sc = this.getSchema();
return typeof sc === "number" ? sc >= 64 && sc < 128 : sc[0] === 1;
}
isMapSchema() {
const sc = this.getSchema();
return typeof sc === "number" ? sc >= 128 && sc <= 255 : sc[0] === 2;
}
isStructSchema() {
const sc = this.getSchema();
if (typeof sc !== "object") return false;
const id = sc[0];
return id === 3 || id === -3 || id === 4;
}
isUnionSchema() {
const sc = this.getSchema();
if (typeof sc !== "object") return false;
return sc[0] === 4;
}
isBlobSchema() {
const sc = this.getSchema();
return sc === 21 || sc === 42;
}
isTimestampSchema() {
const sc = this.getSchema();
return typeof sc === "number" && sc >= 4 && sc <= 7;
}
isUnitSchema() {
return this.getSchema() === "unit";
}
isDocumentSchema() {
return this.getSchema() === 15;
}
isStringSchema() {
return this.getSchema() === 0;
}
isBooleanSchema() {
return this.getSchema() === 2;
}
isNumericSchema() {
return this.getSchema() === 1;
}
isBigIntegerSchema() {
return this.getSchema() === 17;
}
isBigDecimalSchema() {
return this.getSchema() === 19;
}
isStreaming() {
const { streaming } = this.getMergedTraits();
return !!streaming || this.getSchema() === 42;
}
isIdempotencyToken() {
return !!this.getMergedTraits().idempotencyToken;
}
getMergedTraits() {
return this.normalizedTraits ?? (this.normalizedTraits = {
...this.getOwnTraits(),
...this.getMemberTraits()
});
}
getMemberTraits() {
return translateTraits(this.memberTraits);
}
getOwnTraits() {
return translateTraits(this.traits);
}
getKeySchema() {
const [isDoc, isMap] = [this.isDocumentSchema(), this.isMapSchema()];
if (!isDoc && !isMap) throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`);
const schema = this.getSchema();
return member([isDoc ? 15 : schema[4] ?? 0, 0], "key");
}
getValueSchema() {
const sc = this.getSchema();
const [isDoc, isMap, isList] = [
this.isDocumentSchema(),
this.isMapSchema(),
this.isListSchema()
];
const memberSchema = typeof sc === "number" ? 63 & sc : sc && typeof sc === "object" && (isMap || isList) ? sc[3 + sc[0]] : isDoc ? 15 : void 0;
if (memberSchema != null) return member([memberSchema, 0], isMap ? "value" : "member");
throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`);
}
getMemberSchema(memberName) {
const struct = this.getSchema();
if (this.isStructSchema() && struct[4].includes(memberName)) {
const i = struct[4].indexOf(memberName);
const memberSchema = struct[5][i];
return member(isMemberSchema(memberSchema) ? memberSchema : [memberSchema, 0], memberName);
}
if (this.isDocumentSchema()) return member([15, 0], memberName);
throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${memberName}.`);
}
getMemberSchemas() {
const buffer = {};
try {
for (const [k, v] of this.structIterator()) buffer[k] = v;
} catch (ignored) {}
return buffer;
}
getEventStreamMember() {
if (this.isStructSchema()) {
for (const [memberName, memberSchema] of this.structIterator()) if (memberSchema.isStreaming() && memberSchema.isStructSchema()) return memberName;
}
return "";
}
*structIterator() {
if (this.isUnitSchema()) return;
if (!this.isStructSchema()) throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");
const struct = this.getSchema();
const z = struct[4].length;
let it = struct[anno.it];
if (it && z === it.length) {
yield* it;
return;
}
it = Array(z);
for (let i = 0; i < z; ++i) {
const k = struct[4][i];
const v = member([struct[5][i], 0], k);
yield it[i] = [k, v];
}
struct[anno.it] = it;
}
};
isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2;
isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5;
}));
var init_SimpleSchema = __esmMin((() => {
init_Schema();
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js
var init_sentinels = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js
var TypeRegistry;
var init_TypeRegistry = __esmMin((() => {
TypeRegistry = class TypeRegistry {
namespace;
schemas;
exceptions;
static registries = /* @__PURE__ */ new Map();
constructor(namespace, schemas = /* @__PURE__ */ new Map(), exceptions = /* @__PURE__ */ new Map()) {
this.namespace = namespace;
this.schemas = schemas;
this.exceptions = exceptions;
}
static for(namespace) {
if (!TypeRegistry.registries.has(namespace)) TypeRegistry.registries.set(namespace, new TypeRegistry(namespace));
return TypeRegistry.registries.get(namespace);
}
copyFrom(other) {
const { schemas, exceptions } = this;
for (const [k, v] of other.schemas) if (!schemas.has(k)) schemas.set(k, v);
for (const [k, v] of other.exceptions) if (!exceptions.has(k)) exceptions.set(k, v);
}
register(shapeId, schema) {
const qualifiedName = this.normalizeShapeId(shapeId);
for (const r of [this, TypeRegistry.for(qualifiedName.split("#")[0])]) r.schemas.set(qualifiedName, 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);
}
registerError(es, ctor) {
const $error = es;
const ns = $error[1];
for (const r of [this, TypeRegistry.for(ns)]) {
r.schemas.set(ns + "#" + $error[2], $error);
r.exceptions.set($error, ctor);
}
}
getErrorCtor(es) {
const $error = es;
if (this.exceptions.has($error)) return this.exceptions.get($error);
return TypeRegistry.for($error[1]).exceptions.get($error);
}
getBaseException() {
for (const exceptionKey of this.exceptions.keys()) if (Array.isArray(exceptionKey)) {
const [, ns, name] = exceptionKey;
const id = ns + "#" + name;
if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) return exceptionKey;
}
}
find(predicate) {
return [...this.schemas.values()].find(predicate);
}
clear() {
this.schemas.clear();
this.exceptions.clear();
}
normalizeShapeId(shapeId) {
if (shapeId.includes("#")) return shapeId;
return this.namespace + "#" + shapeId;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/schema/index.js
var init_schema = __esmMin((() => {
init_deref();
init_getSchemaSerdePlugin();
init_ListSchema();
init_MapSchema();
init_OperationSchema();
init_operation();
init_ErrorSchema();
init_NormalizedSchema();
init_Schema();
init_SimpleSchema();
init_StructureSchema();
init_sentinels();
init_translateTraits();
init_TypeRegistry();
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js
var init_copyDocumentWithTransform = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js
var expectNumber, MAX_FLOAT, expectFloat32, expectLong, expectShort, expectByte, expectSizedInt, castInt, strictParseDouble, strictParseFloat32, NUMBER_REGEX, parseNumber, strictParseShort, strictParseByte, stackTraceWarning, logger;
var init_parse_utils = __esmMin((() => {
expectNumber = (value) => {
if (value === null || value === void 0) return;
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 (typeof value === "number") return value;
throw new TypeError(`Expected number, got ${typeof value}: ${value}`);
};
MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));
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 expected;
};
expectLong = (value) => {
if (value === null || value === void 0) return;
if (Number.isInteger(value) && !Number.isNaN(value)) return value;
throw new TypeError(`Expected integer, got ${typeof value}: ${value}`);
};
expectShort = (value) => expectSizedInt(value, 16);
expectByte = (value) => expectSizedInt(value, 8);
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;
};
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];
}
};
strictParseDouble = (value) => {
if (typeof value == "string") return expectNumber(parseNumber(value));
return expectNumber(value);
};
strictParseFloat32 = (value) => {
if (typeof value == "string") return expectFloat32(parseNumber(value));
return expectFloat32(value);
};
NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;
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);
};
strictParseShort = (value) => {
if (typeof value === "string") return expectShort(parseNumber(value));
return expectShort(value);
};
strictParseByte = (value) => {
if (typeof value === "string") return expectByte(parseNumber(value));
return expectByte(value);
};
stackTraceWarning = (message) => {
return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n");
};
logger = { warn: console.warn };
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js
function dateToUtcString$2(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 DAYS, MONTHS, RFC3339_WITH_OFFSET$1, parseRfc3339DateTimeWithOffset, IMF_FIXDATE$1, RFC_850_DATE$1, ASC_TIME$1, parseRfc7231DateTime, parseEpochTimestamp, buildDate, parseTwoDigitYear, FIFTY_YEARS_IN_MILLIS, adjustRfc850Year, parseMonthByShortName, DAYS_IN_MONTH, validateDayOfMonth, isLeapYear, parseDateValue, parseMilliseconds, parseOffsetToMilliseconds, stripLeadingZeroes;
var init_date_utils = __esmMin((() => {
init_parse_utils();
DAYS = [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
];
MONTHS = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
RFC3339_WITH_OFFSET$1 = /* @__PURE__ */ new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);
parseRfc3339DateTimeWithOffset = (value) => {
if (value === null || value === void 0) return;
if (typeof value !== "string") throw new TypeError("RFC-3339 date-times must be expressed as strings");
const match = RFC3339_WITH_OFFSET$1.exec(value);
if (!match) throw new TypeError("Invalid RFC-3339 date-time value");
const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match;
const date = buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseDateValue(monthStr, "month", 1, 12), parseDateValue(dayStr, "day", 1, 31), {
hours,
minutes,
seconds,
fractionalMilliseconds
});
if (offsetStr.toUpperCase() != "Z") date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr));
return date;
};
IMF_FIXDATE$1 = /* @__PURE__ */ 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$/);
RFC_850_DATE$1 = /* @__PURE__ */ 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$/);
ASC_TIME$1 = /* @__PURE__ */ 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})$/);
parseRfc7231DateTime = (value) => {
if (value === null || value === void 0) return;
if (typeof value !== "string") throw new TypeError("RFC-7231 date-times must be expressed as strings");
let match = IMF_FIXDATE$1.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$1.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$1.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");
};
parseEpochTimestamp = (value) => {
if (value === null || value === void 0) return;
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));
};
buildDate = (year, month, day, time) => {
const adjustedMonth = month - 1;
validateDayOfMonth(year, adjustedMonth, day);
return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds)));
};
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;
};
FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3;
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()));
return input;
};
parseMonthByShortName = (value) => {
const monthIdx = MONTHS.indexOf(value);
if (monthIdx < 0) throw new TypeError(`Invalid month: ${value}`);
return monthIdx + 1;
};
DAYS_IN_MONTH = [
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
];
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}`);
};
isLeapYear = (year) => {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
};
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 dateVal;
};
parseMilliseconds = (value) => {
if (value === null || value === void 0) return 0;
return strictParseFloat32("0." + value) * 1e3;
};
parseOffsetToMilliseconds = (value) => {
const directionStr = value[0];
let direction = 1;
if (directionStr == "+") direction = 1;
else if (directionStr == "-") direction = -1;
else throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`);
const hour = Number(value.substring(1, 3));
const minute = Number(value.substring(4, 6));
return direction * (hour * 60 + minute) * 60 * 1e3;
};
stripLeadingZeroes = (value) => {
let idx = 0;
while (idx < value.length - 1 && value.charAt(idx) === "0") idx++;
if (idx === 0) return value;
return value.slice(idx);
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/serde/generateIdempotencyToken.js
var import_dist_cjs$45;
var init_generateIdempotencyToken = __esmMin((() => {
import_dist_cjs$45 = require_dist_cjs$36();
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js
var LazyJsonString;
var init_lazy_json = __esmMin((() => {
LazyJsonString = function LazyJsonString(val) {
return Object.assign(new String(val), {
deserializeJSON() {
return JSON.parse(String(val));
},
toString() {
return String(val);
},
toJSON() {
return String(val);
}
});
};
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 LazyJsonString(JSON.stringify(object));
};
LazyJsonString.fromObject = LazyJsonString.from;
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js
function quoteHeader(part) {
if (part.includes(",") || part.includes("\"")) part = `"${part.replace(/"/g, "\\\"")}"`;
return part;
}
var init_quote_header = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/serde/schema-serde-lib/schema-date-utils.js
function range(v, min, max) {
const _v = Number(v);
if (_v < min || _v > max) throw new Error(`Value ${_v} out of range [${min}, ${max}]`);
}
var ddd, mmm, time, date, year, RFC3339_WITH_OFFSET, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, months, _parseEpochTimestamp, _parseRfc3339DateTimeWithOffset, _parseRfc7231DateTime;
var init_schema_date_utils = __esmMin((() => {
ddd = `(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?`;
mmm = `(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)`;
time = `(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?`;
date = `(\\d?\\d)`;
year = `(\\d{4})`;
RFC3339_WITH_OFFSET = /* @__PURE__ */ new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/);
IMF_FIXDATE = new RegExp(`^${ddd}, ${date} ${mmm} ${year} ${time} GMT$`);
RFC_850_DATE = new RegExp(`^${ddd}, ${date}-${mmm}-(\\d\\d) ${time} GMT$`);
ASC_TIME = new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time} ${year}$`);
months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
_parseEpochTimestamp = (value) => {
if (value == null) return;
let num = NaN;
if (typeof value === "number") num = value;
else if (typeof value === "string") {
if (!/^-?\d*\.?\d+$/.test(value)) throw new TypeError(`parseEpochTimestamp - numeric string invalid.`);
num = Number.parseFloat(value);
} else if (typeof value === "object" && value.tag === 1) num = value.value;
if (isNaN(num) || Math.abs(num) === Infinity) throw new TypeError("Epoch timestamps must be valid finite numbers.");
return new Date(Math.round(num * 1e3));
};
_parseRfc3339DateTimeWithOffset = (value) => {
if (value == null) return;
if (typeof value !== "string") throw new TypeError("RFC3339 timestamps must be strings");
const matches = RFC3339_WITH_OFFSET.exec(value);
if (!matches) throw new TypeError(`Invalid RFC3339 timestamp format ${value}`);
const [, yearStr, monthStr, dayStr, hours, minutes, seconds, , ms, offsetStr] = matches;
range(monthStr, 1, 12);
range(dayStr, 1, 31);
range(hours, 0, 23);
range(minutes, 0, 59);
range(seconds, 0, 60);
const date = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1e3) : 0));
date.setUTCFullYear(Number(yearStr));
if (offsetStr.toUpperCase() != "Z") {
const [, sign, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [
void 0,
"+",
0,
0
];
const scalar = sign === "-" ? 1 : -1;
date.setTime(date.getTime() + scalar * (Number(offsetH) * 60 * 60 * 1e3 + Number(offsetM) * 60 * 1e3));
}
return date;
};
_parseRfc7231DateTime = (value) => {
if (value == null) return;
if (typeof value !== "string") throw new TypeError("RFC7231 timestamps must be strings.");
let day;
let month;
let year;
let hour;
let minute;
let second;
let fraction;
let matches;
if (matches = IMF_FIXDATE.exec(value)) [, day, month, year, hour, minute, second, fraction] = matches;
else if (matches = RFC_850_DATE.exec(value)) {
[, day, month, year, hour, minute, second, fraction] = matches;
year = (Number(year) + 1900).toString();
} else if (matches = ASC_TIME.exec(value)) [, month, day, hour, minute, second, fraction, year] = matches;
if (year && second) {
const timestamp = Date.UTC(Number(year), months.indexOf(month), Number(day), Number(hour), Number(minute), Number(second), fraction ? Math.round(parseFloat(`0.${fraction}`) * 1e3) : 0);
range(day, 1, 31);
range(hour, 0, 23);
range(minute, 0, 59);
range(second, 0, 60);
const date = new Date(timestamp);
date.setUTCFullYear(Number(year));
return date;
}
throw new TypeError(`Invalid RFC7231 date-time value ${value}.`);
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js
function splitEvery(value, delimiter, numDelimiters) {
if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery.");
const segments = value.split(delimiter);
if (numDelimiters === 1) return segments;
const compoundSegments = [];
let currentSegment = "";
for (let i = 0; i < segments.length; i++) {
if (currentSegment === "") currentSegment = segments[i];
else currentSegment += delimiter + segments[i];
if ((i + 1) % numDelimiters === 0) {
compoundSegments.push(currentSegment);
currentSegment = "";
}
}
if (currentSegment !== "") compoundSegments.push(currentSegment);
return compoundSegments;
}
var init_split_every = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js
var splitHeader;
var init_split_header = __esmMin((() => {
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;
}
values.push(value.slice(anchor));
return values.map((v) => {
v = v.trim();
const z = v.length;
if (z < 2) return v;
if (v[0] === `"` && v[z - 1] === `"`) v = v.slice(1, z - 1);
return v.replace(/\\"/g, "\"");
});
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js
function nv(input) {
return new NumericValue(String(input), "bigDecimal");
}
var format, NumericValue;
var init_NumericValue = __esmMin((() => {
format = /^-?\d*(\.\d+)?$/;
NumericValue = class NumericValue {
string;
type;
constructor(string, type) {
this.string = string;
this.type = type;
if (!format.test(string)) throw new Error(`@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".`);
}
toString() {
return this.string;
}
static [Symbol.hasInstance](object) {
if (!object || typeof object !== "object") return false;
const _nv = object;
return NumericValue.prototype.isPrototypeOf(object) || _nv.type === "bigDecimal" && format.test(_nv.string);
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/serde/index.js
var init_serde = __esmMin((() => {
init_copyDocumentWithTransform();
init_date_utils();
init_generateIdempotencyToken();
init_lazy_json();
init_parse_utils();
init_quote_header();
init_schema_date_utils();
init_split_every();
init_split_header();
init_NumericValue();
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/SerdeContext.js
var SerdeContext;
var init_SerdeContext$1 = __esmMin((() => {
SerdeContext = class {
serdeContext;
setSerdeContext(serdeContext) {
this.serdeContext = serdeContext;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js
var import_dist_cjs$44, HttpProtocol;
var init_HttpProtocol$1 = __esmMin((() => {
init_schema();
import_dist_cjs$44 = require_dist_cjs$34();
init_SerdeContext$1();
HttpProtocol = class extends SerdeContext {
options;
compositeErrorRegistry;
constructor(options) {
super();
this.options = options;
this.compositeErrorRegistry = TypeRegistry.for(options.defaultNamespace);
for (const etr of options.errorTypeRegistries ?? []) this.compositeErrorRegistry.copyFrom(etr);
}
getRequestType() {
return import_dist_cjs$44.HttpRequest;
}
getResponseType() {
return import_dist_cjs$44.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;
if (!request.query) request.query = {};
for (const [k, v] of endpoint.url.searchParams.entries()) request.query[k] = v;
if (endpoint.headers) for (const [name, values] of Object.entries(endpoint.headers)) request.headers[name] = values.join(", ");
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 };
if (endpoint.headers) for (const [name, value] of Object.entries(endpoint.headers)) request.headers[name] = value;
return request;
}
}
setHostPrefix(request, operationSchema, input) {
if (this.serdeContext?.disableHostPrefix) return;
const inputNs = NormalizedSchema.of(operationSchema.input);
const opTraits = translateTraits(operationSchema.traits ?? {});
if (opTraits.endpoint) {
let hostPrefix = opTraits.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 serializeEventStream({ eventStream, requestSchema, initialRequest }) {
return (await this.loadEventStreamCapability()).serializeEventStream({
eventStream,
requestSchema,
initialRequest
});
}
async deserializeEventStream({ response, responseSchema, initialResponseContainer }) {
return (await this.loadEventStreamCapability()).deserializeEventStream({
response,
responseSchema,
initialResponseContainer
});
}
async loadEventStreamCapability() {
const { EventStreamSerde } = await import("./event-streams-x9F3Kuz5.js");
return new EventStreamSerde({
marshaller: this.getEventStreamMarshaller(),
serializer: this.serializer,
deserializer: this.deserializer,
serdeContext: this.serdeContext,
defaultContentType: this.getDefaultContentType()
});
}
getDefaultContentType() {
throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`);
}
async deserializeHttpMessage(schema, context, response, arg4, arg5) {
return [];
}
getEventStreamMarshaller() {
const context = this.serdeContext;
if (!context.eventStreamMarshaller) throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");
return context.eventStreamMarshaller;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js
var import_dist_cjs$42, import_dist_cjs$43, HttpBindingProtocol;
var init_HttpBindingProtocol$1 = __esmMin((() => {
init_schema();
init_serde();
import_dist_cjs$42 = require_dist_cjs$34();
import_dist_cjs$43 = require_dist_cjs$35();
init_collect_stream_body$1();
init_extended_encode_uri_component$1();
init_HttpProtocol$1();
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 = NormalizedSchema.of(operationSchema?.input);
const payloadMemberNames = [];
const payloadMemberSchemas = [];
let hasNonHttpBindingMember = false;
let payload;
const request = new import_dist_cjs$42.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 = 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 && !memberNs.isIdempotencyToken()) {
if (memberTraits.httpLabel) {
if (request.path.includes(`{${memberName}+}`) || request.path.includes(`{${memberName}}`)) throw new Error(`No value provided for input HTTP label: ${memberName}.`);
}
continue;
}
if (memberTraits.httpPayload) {
if (memberNs.isStreaming()) if (memberNs.isStructSchema()) {
if (input[memberName]) payload = await this.serializeEventStream({
eventStream: input[memberName],
requestSchema: ns
});
} 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$1).join("/"));
else if (request.path.includes(`{${memberName}}`)) request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent$1(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;
payloadMemberNames.push(memberName);
payloadMemberSchemas.push(memberNs);
}
}
if (hasNonHttpBindingMember && input) {
const [namespace, name] = (ns.getName(true) ?? "#Unknown").split("#");
const requiredMembers = ns.getSchema()[6];
const payloadSchema = [
3,
namespace,
name,
ns.getMergedTraits(),
payloadMemberNames,
payloadMemberSchemas,
void 0
];
if (requiredMembers) payloadSchema[6] = requiredMembers;
else payloadSchema.pop();
serializer.write(payloadSchema, 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)) {
const valueSchema = ns.getValueSchema();
Object.assign(valueSchema.getMergedTraits(), {
...traits,
httpQuery: key,
httpQueryParams: void 0
});
this.serializeQuery(valueSchema, 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 = NormalizedSchema.of(operationSchema.output);
const dataObject = {};
if (response.statusCode >= 300) {
const bytes = await collectBody$1(response.body, context);
if (bytes.byteLength > 0) Object.assign(dataObject, await deserializer.read(15, 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$1(response.body, context);
if (bytes.byteLength > 0) {
const dataFromBody = await deserializer.read(ns, bytes);
for (const member of nonHttpBindingMembers) if (dataFromBody[member] != null) dataObject[member] = dataFromBody[member];
}
} else if (nonHttpBindingMembers.discardResponseBody) await collectBody$1(response.body, context);
dataObject.$metadata = this.deserializeMetadata(response);
return dataObject;
}
async deserializeHttpMessage(schema, context, response, arg4, arg5) {
let dataObject;
if (arg4 instanceof Set) dataObject = arg5;
else dataObject = arg4;
let discardResponseBody = true;
const deserializer = this.deserializer;
const ns = NormalizedSchema.of(schema);
const nonHttpBindingMembers = [];
for (const [memberName, memberSchema] of ns.structIterator()) {
const memberTraits = memberSchema.getMemberTraits();
if (memberTraits.httpPayload) {
discardResponseBody = false;
if (memberSchema.isStreaming()) if (memberSchema.isStructSchema()) dataObject[memberName] = await this.deserializeEventStream({
response,
responseSchema: ns
});
else dataObject[memberName] = (0, import_dist_cjs$43.sdkStreamMixin)(response.body);
else if (response.body) {
const bytes = await collectBody$1(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();
headerListValueSchema.getMergedTraits().httpHeader = key;
let sections;
if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === 4) sections = splitEvery(value, ",", 2);
else sections = splitHeader(value);
const list = [];
for (const section of sections) list.push(await deserializer.read(headerListValueSchema, 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)) {
const valueSchema = memberSchema.getValueSchema();
valueSchema.getMergedTraits().httpHeader = header;
dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read(valueSchema, value);
}
} else if (memberTraits.httpResponseCode) dataObject[memberName] = response.statusCode;
else nonHttpBindingMembers.push(memberName);
}
nonHttpBindingMembers.discardResponseBody = discardResponseBody;
return nonHttpBindingMembers;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js
var import_dist_cjs$41, RpcProtocol;
var init_RpcProtocol$1 = __esmMin((() => {
init_schema();
import_dist_cjs$41 = require_dist_cjs$34();
init_collect_stream_body$1();
init_HttpProtocol$1();
RpcProtocol = class extends HttpProtocol {
async serializeRequest(operationSchema, input, context) {
const serializer = this.serializer;
const query = {};
const headers = {};
const endpoint = await context.endpoint();
const ns = NormalizedSchema.of(operationSchema?.input);
const schema = ns.getSchema();
let payload;
const request = new import_dist_cjs$41.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) {
const eventStreamMember = ns.getEventStreamMember();
if (eventStreamMember) {
if (_input[eventStreamMember]) {
const initialRequest = {};
for (const [memberName, memberSchema] of ns.structIterator()) if (memberName !== eventStreamMember && _input[memberName]) {
serializer.write(memberSchema, _input[memberName]);
initialRequest[memberName] = serializer.flush();
}
payload = await this.serializeEventStream({
eventStream: _input[eventStreamMember],
requestSchema: ns,
initialRequest
});
}
} else {
serializer.write(schema, _input);
payload = serializer.flush();
}
}
request.headers = Object.assign(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 = NormalizedSchema.of(operationSchema.output);
const dataObject = {};
if (response.statusCode >= 300) {
const bytes = await collectBody$1(response.body, context);
if (bytes.byteLength > 0) Object.assign(dataObject, await deserializer.read(15, bytes));
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 eventStreamMember = ns.getEventStreamMember();
if (eventStreamMember) dataObject[eventStreamMember] = await this.deserializeEventStream({
response,
responseSchema: ns,
initialResponseContainer: dataObject
});
else {
const bytes = await collectBody$1(response.body, context);
if (bytes.byteLength > 0) Object.assign(dataObject, await deserializer.read(ns, bytes));
}
dataObject.$metadata = this.deserializeMetadata(response);
return dataObject;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js
var init_resolve_path$1 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js
var init_requestBuilder$4 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js
function determineTimestampFormat(ns, settings) {
if (settings.timestampFormat.useTrait) {
if (ns.isTimestampSchema() && (ns.getSchema() === 5 || ns.getSchema() === 6 || ns.getSchema() === 7)) return ns.getSchema();
}
const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits();
return (settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? 6 : Boolean(httpQuery) || Boolean(httpLabel) ? 5 : void 0 : void 0) ?? settings.timestampFormat.default;
}
var init_determineTimestampFormat$1 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js
var import_dist_cjs$39, import_dist_cjs$40, FromStringShapeDeserializer;
var init_FromStringShapeDeserializer$1 = __esmMin((() => {
init_schema();
init_serde();
import_dist_cjs$39 = require_dist_cjs$37();
import_dist_cjs$40 = require_dist_cjs$42();
init_SerdeContext$1();
init_determineTimestampFormat$1();
FromStringShapeDeserializer = class extends SerdeContext {
settings;
constructor(settings) {
super();
this.settings = settings;
}
read(_schema, data) {
const ns = NormalizedSchema.of(_schema);
if (ns.isListSchema()) return splitHeader(data).map((item) => this.read(ns.getValueSchema(), item));
if (ns.isBlobSchema()) return (this.serdeContext?.base64Decoder ?? import_dist_cjs$39.fromBase64)(data);
if (ns.isTimestampSchema()) switch (determineTimestampFormat(ns, this.settings)) {
case 5: return _parseRfc3339DateTimeWithOffset(data);
case 6: return _parseRfc7231DateTime(data);
case 7: return _parseEpochTimestamp(data);
default:
console.warn("Missing timestamp format, parsing value with Date constructor:", data);
return new Date(data);
}
if (ns.isStringSchema()) {
const mediaType = ns.getMergedTraits().mediaType;
let intermediateValue = data;
if (mediaType) {
if (ns.getMergedTraits().httpHeader) intermediateValue = this.base64ToUtf8(intermediateValue);
if (mediaType === "application/json" || mediaType.endsWith("+json")) intermediateValue = LazyJsonString.from(intermediateValue);
return intermediateValue;
}
}
if (ns.isNumericSchema()) return Number(data);
if (ns.isBigIntegerSchema()) return BigInt(data);
if (ns.isBigDecimalSchema()) return new NumericValue(data, "bigDecimal");
if (ns.isBooleanSchema()) return String(data).toLowerCase() === "true";
return data;
}
base64ToUtf8(base64String) {
return (this.serdeContext?.utf8Encoder ?? import_dist_cjs$40.toUtf8)((this.serdeContext?.base64Decoder ?? import_dist_cjs$39.fromBase64)(base64String));
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js
var import_dist_cjs$38, HttpInterceptingShapeDeserializer;
var init_HttpInterceptingShapeDeserializer$1 = __esmMin((() => {
init_schema();
import_dist_cjs$38 = require_dist_cjs$42();
init_SerdeContext$1();
init_FromStringShapeDeserializer$1();
HttpInterceptingShapeDeserializer = class extends SerdeContext {
codecDeserializer;
stringDeserializer;
constructor(codecDeserializer, codecSettings) {
super();
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 = NormalizedSchema.of(schema);
const traits = ns.getMergedTraits();
const toString = this.serdeContext?.utf8Encoder ?? import_dist_cjs$38.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_dist_cjs$38.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);
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js
var import_dist_cjs$37, ToStringShapeSerializer;
var init_ToStringShapeSerializer$1 = __esmMin((() => {
init_schema();
init_serde();
import_dist_cjs$37 = require_dist_cjs$37();
init_SerdeContext$1();
init_determineTimestampFormat$1();
ToStringShapeSerializer = class extends SerdeContext {
settings;
stringBuffer = "";
constructor(settings) {
super();
this.settings = settings;
}
write(schema, value) {
const ns = 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)}`);
switch (determineTimestampFormat(ns, this.settings)) {
case 5:
this.stringBuffer = value.toISOString().replace(".000Z", "Z");
break;
case 6:
this.stringBuffer = dateToUtcString$2(value);
break;
case 7:
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_dist_cjs$37.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 : 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) {
if (mediaType === "application/json" || mediaType.endsWith("+json")) intermediateValue = LazyJsonString.from(intermediateValue);
if (ns.getMergedTraits().httpHeader) {
this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_dist_cjs$37.toBase64)(intermediateValue.toString());
return;
}
}
this.stringBuffer = value;
break;
default: if (ns.isIdempotencyToken()) this.stringBuffer = (0, import_dist_cjs$45.v4)();
else this.stringBuffer = String(value);
}
}
flush() {
const buffer = this.stringBuffer;
this.stringBuffer = "";
return buffer;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js
var HttpInterceptingShapeSerializer;
var init_HttpInterceptingShapeSerializer$1 = __esmMin((() => {
init_schema();
init_ToStringShapeSerializer$1();
HttpInterceptingShapeSerializer = class {
codecSerializer;
stringSerializer;
buffer;
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 = 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);
}
flush() {
if (this.buffer !== void 0) {
const buffer = this.buffer;
this.buffer = void 0;
return buffer;
}
return this.codecSerializer.flush();
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/protocols/index.js
var init_protocols$2 = __esmMin((() => {
init_collect_stream_body$1();
init_extended_encode_uri_component$1();
init_HttpBindingProtocol$1();
init_HttpProtocol$1();
init_RpcProtocol$1();
init_requestBuilder$4();
init_resolve_path$1();
init_FromStringShapeDeserializer$1();
init_HttpInterceptingShapeDeserializer$1();
init_HttpInterceptingShapeSerializer$1();
init_ToStringShapeSerializer$1();
init_determineTimestampFormat$1();
init_SerdeContext$1();
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/request-builder/requestBuilder.js
var init_requestBuilder$3 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/setFeature.js
var init_setFeature$2 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js
var init_DefaultIdentityProviderConfig$2 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js
var init_httpApiKeyAuth$2 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js
var init_httpBearerAuth$2 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js
var init_noAuth$2 = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js
var init_httpAuthSchemes$3 = __esmMin((() => {
init_httpApiKeyAuth$2();
init_httpBearerAuth$2();
init_noAuth$2();
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js
var createIsIdentityExpiredFunction$2, EXPIRATION_MS$2, isIdentityExpired$2, doesIdentityRequireRefresh$2, memoizeIdentityProvider$2;
var init_memoizeIdentityProvider$2 = __esmMin((() => {
createIsIdentityExpiredFunction$2 = (expirationMs) => function isIdentityExpired(identity) {
return doesIdentityRequireRefresh$2(identity) && identity.expiration.getTime() - Date.now() < expirationMs;
};
EXPIRATION_MS$2 = 3e5;
isIdentityExpired$2 = createIsIdentityExpiredFunction$2(EXPIRATION_MS$2);
doesIdentityRequireRefresh$2 = (identity) => identity.expiration !== void 0;
memoizeIdentityProvider$2 = (provider, isExpired, requiresRefresh) => {
if (provider === void 0) return;
const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider;
let resolved;
let pending;
let hasResult;
let isConstant = false;
const coalesceProvider = async (options) => {
if (!pending) pending = normalizedProvider(options);
try {
resolved = await pending;
hasResult = true;
isConstant = false;
} finally {
pending = void 0;
}
return resolved;
};
if (isExpired === void 0) return async (options) => {
if (!hasResult || options?.forceRefresh) resolved = await coalesceProvider(options);
return resolved;
};
return async (options) => {
if (!hasResult || options?.forceRefresh) resolved = await coalesceProvider(options);
if (isConstant) return resolved;
if (!requiresRefresh(resolved)) {
isConstant = true;
return resolved;
}
if (isExpired(resolved)) {
await coalesceProvider(options);
return resolved;
}
return resolved;
};
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js
var init_util_identity_and_auth$2 = __esmMin((() => {
init_DefaultIdentityProviderConfig$2();
init_httpAuthSchemes$3();
init_memoizeIdentityProvider$2();
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/index.js
var init_dist_es$3 = __esmMin((() => {
init_getSmithyContext$2();
init_middleware_http_auth_scheme$2();
init_middleware_http_signing$2();
init_normalizeProvider$2();
init_requestBuilder$3();
init_setFeature$2();
init_util_identity_and_auth$2();
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/property-provider/dist-cjs/index.js
var require_dist_cjs$32 = /* @__PURE__ */ __commonJSMin(((exports) => {
exports.ProviderError = class ProviderError extends Error {
name = "ProviderError";
tryNextLink;
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.tryNextLink = tryNextLink;
Object.setPrototypeOf(this, ProviderError.prototype);
logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`);
}
static from(error, options = true) {
return Object.assign(new this(error.message, options), error);
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js
var import_dist_cjs$36, resolveAwsSdkSigV4AConfig, NODE_SIGV4A_CONFIG_OPTIONS;
var init_resolveAwsSdkSigV4AConfig = __esmMin((() => {
init_dist_es$3();
import_dist_cjs$36 = require_dist_cjs$32();
resolveAwsSdkSigV4AConfig = (config) => {
config.sigv4aSigningRegionSet = normalizeProvider$2(config.sigv4aSigningRegionSet);
return config;
};
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_dist_cjs$36.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_dist_cjs$36.ProviderError("sigv4a_signing_region_set not set in profile.", { tryNextLink: true });
},
default: void 0
};
}));
//#endregion
//#region node_modules/@smithy/signature-v4/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
var require_dist_cjs$31 = /* @__PURE__ */ __commonJSMin(((exports) => {
const isArrayBuffer = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
exports.isArrayBuffer = isArrayBuffer;
}));
//#endregion
//#region node_modules/@smithy/signature-v4/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
var require_dist_cjs$30 = /* @__PURE__ */ __commonJSMin(((exports) => {
var isArrayBuffer = require_dist_cjs$31();
var buffer$1 = __require("buffer");
const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
if (!isArrayBuffer.isArrayBuffer(input)) throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
return buffer$1.Buffer.from(input, offset, length);
};
const fromString = (input, encoding) => {
if (typeof input !== "string") throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
return encoding ? buffer$1.Buffer.from(input, encoding) : buffer$1.Buffer.from(input);
};
exports.fromArrayBuffer = fromArrayBuffer;
exports.fromString = fromString;
}));
//#endregion
//#region node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/index.js
var require_dist_cjs$29 = /* @__PURE__ */ __commonJSMin(((exports) => {
var utilBufferFrom = require_dist_cjs$30();
const fromUtf8 = (input) => {
const buf = utilBufferFrom.fromString(input, "utf8");
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
};
const toUint8Array = (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);
};
const toUtf8 = (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 utilBufferFrom.fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
};
exports.fromUtf8 = fromUtf8;
exports.toUint8Array = toUint8Array;
exports.toUtf8 = toUtf8;
}));
//#endregion
//#region node_modules/@smithy/signature-v4/node_modules/@smithy/util-middleware/dist-cjs/index.js
var require_dist_cjs$28 = /* @__PURE__ */ __commonJSMin(((exports) => {
var types = require_dist_cjs$33();
const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {});
const normalizeProvider = (input) => {
if (typeof input === "function") return input;
const promisified = Promise.resolve(input);
return () => promisified;
};
exports.getSmithyContext = getSmithyContext;
exports.normalizeProvider = normalizeProvider;
}));
//#endregion
//#region node_modules/@smithy/signature-v4/dist-cjs/index.js
var require_dist_cjs$27 = /* @__PURE__ */ __commonJSMin(((exports) => {
var utilHexEncoding = require_dist_cjs$38();
var utilUtf8 = require_dist_cjs$29();
var isArrayBuffer = require_dist_cjs$31();
var protocolHttp = require_dist_cjs$34();
var utilMiddleware = require_dist_cjs$28();
var utilUriEscape = require_dist_cjs$39();
const ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm";
const CREDENTIAL_QUERY_PARAM = "X-Amz-Credential";
const AMZ_DATE_QUERY_PARAM = "X-Amz-Date";
const SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders";
const EXPIRES_QUERY_PARAM = "X-Amz-Expires";
const SIGNATURE_QUERY_PARAM = "X-Amz-Signature";
const TOKEN_QUERY_PARAM = "X-Amz-Security-Token";
const REGION_SET_PARAM = "X-Amz-Region-Set";
const AUTH_HEADER = "authorization";
const AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();
const DATE_HEADER = "date";
const GENERATED_HEADERS = [
AUTH_HEADER,
AMZ_DATE_HEADER,
DATE_HEADER
];
const SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase();
const SHA256_HEADER = "x-amz-content-sha256";
const TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();
const HOST_HEADER = "host";
const 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
};
const PROXY_HEADER_PATTERN = /^proxy-/;
const SEC_HEADER_PATTERN = /^sec-/;
const UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i];
const ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256";
const ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256";
const EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD";
const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
const MAX_CACHE_SIZE = 50;
const KEY_TYPE_IDENTIFIER = "aws4_request";
const MAX_PRESIGNED_TTL = 3600 * 24 * 7;
const signingKeyCache = {};
const cacheQueue = [];
const createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`;
const getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => {
const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId);
const cacheKey = `${shortDate}:${region}:${service}:${utilHexEncoding.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;
};
const clearCredentialCache = () => {
cacheQueue.length = 0;
Object.keys(signingKeyCache).forEach((cacheKey) => {
delete signingKeyCache[cacheKey];
});
};
const hmac = (ctor, secret, data) => {
const hash = new ctor(secret);
hash.update(utilUtf8.toUint8Array(data));
return hash.digest();
};
const getCanonicalHeaders = ({ 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;
}
canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " ");
}
return canonical;
};
const getPayloadHash = 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) || isArrayBuffer.isArrayBuffer(body)) {
const hashCtor = new hashConstructor();
hashCtor.update(utilUtf8.toUint8Array(body));
return utilHexEncoding.toHex(await hashCtor.digest());
}
return UNSIGNED_PAYLOAD;
};
var HeaderFormatter = class {
format(headers) {
const chunks = [];
for (const headerName of Object.keys(headers)) {
const bytes = utilUtf8.fromUtf8(headerName);
chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
}
const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
let position = 0;
for (const chunk of chunks) {
out.set(chunk, position);
position += chunk.byteLength;
}
return out;
}
formatHeaderValue(header) {
switch (header.type) {
case "boolean": return Uint8Array.from([header.value ? 0 : 1]);
case "byte": return Uint8Array.from([2, header.value]);
case "short":
const shortView = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(3));
shortView.setUint8(0, 3);
shortView.setInt16(1, header.value, false);
return new Uint8Array(shortView.buffer);
case "integer":
const intView = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(5));
intView.setUint8(0, 4);
intView.setInt32(1, header.value, false);
return new Uint8Array(intView.buffer);
case "long":
const longBytes = new Uint8Array(9);
longBytes[0] = 5;
longBytes.set(header.value.bytes, 1);
return longBytes;
case "binary":
const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
binView.setUint8(0, 6);
binView.setUint16(1, header.value.byteLength, false);
const binBytes = new Uint8Array(binView.buffer);
binBytes.set(header.value, 3);
return binBytes;
case "string":
const utf8Bytes = utilUtf8.fromUtf8(header.value);
const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
strView.setUint8(0, 7);
strView.setUint16(1, utf8Bytes.byteLength, false);
const strBytes = new Uint8Array(strView.buffer);
strBytes.set(utf8Bytes, 3);
return strBytes;
case "timestamp":
const tsBytes = new Uint8Array(9);
tsBytes[0] = 8;
tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1);
return tsBytes;
case "uuid":
if (!UUID_PATTERN.test(header.value)) throw new Error(`Invalid UUID received: ${header.value}`);
const uuidBytes = new Uint8Array(17);
uuidBytes[0] = 9;
uuidBytes.set(utilHexEncoding.fromHex(header.value.replace(/\-/g, "")), 1);
return uuidBytes;
}
}
};
const 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 {
bytes;
constructor(bytes) {
this.bytes = bytes;
if (bytes.byteLength !== 8) throw new Error("Int64 buffers must be exactly 8 bytes");
}
static fromNumber(number) {
if (number > 0x8000000000000000 || number < -0x8000000000000000) throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);
const bytes = new Uint8Array(8);
for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) bytes[i] = remaining;
if (number < 0) negate(bytes);
return new Int64(bytes);
}
valueOf() {
const bytes = this.bytes.slice(0);
const negative = bytes[0] & 128;
if (negative) negate(bytes);
return parseInt(utilHexEncoding.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;
}
}
const hasHeader = (soughtHeader, headers) => {
soughtHeader = soughtHeader.toLowerCase();
for (const headerName of Object.keys(headers)) if (soughtHeader === headerName.toLowerCase()) return true;
return false;
};
const moveHeadersToQuery = (request, options = {}) => {
const { headers, query = {} } = protocolHttp.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
};
};
const prepareRequest = (request) => {
request = protocolHttp.HttpRequest.clone(request);
for (const headerName of Object.keys(request.headers)) if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) delete request.headers[headerName];
return request;
};
const getCanonicalQuery = ({ query = {} }) => {
const keys = [];
const serialized = {};
for (const key of Object.keys(query)) {
if (key.toLowerCase() === SIGNATURE_HEADER) continue;
const encodedKey = utilUriEscape.escapeUri(key);
keys.push(encodedKey);
const value = query[key];
if (typeof value === "string") serialized[encodedKey] = `${encodedKey}=${utilUriEscape.escapeUri(value)}`;
else if (Array.isArray(value)) serialized[encodedKey] = value.slice(0).reduce((encoded, value) => encoded.concat([`${encodedKey}=${utilUriEscape.escapeUri(value)}`]), []).sort().join("&");
}
return keys.sort().map((key) => serialized[key]).filter((serialized) => serialized).join("&");
};
const iso8601 = (time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z");
const toDate = (time) => {
if (typeof time === "number") return /* @__PURE__ */ new Date(time * 1e3);
if (typeof time === "string") {
if (Number(time)) return /* @__PURE__ */ new Date(Number(time) * 1e3);
return new Date(time);
}
return time;
};
var SignatureV4Base = class {
service;
regionProvider;
credentialProvider;
sha256;
uriEscapePath;
applyChecksum;
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 = utilMiddleware.normalizeProvider(region);
this.credentialProvider = utilMiddleware.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")}
${sortedHeaders.join(";")}
${payloadHash}`;
}
async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) {
const hash = new this.sha256();
hash.update(utilUtf8.toUint8Array(canonicalRequest));
const hashedRequest = await hash.digest();
return `${algorithmIdentifier}
${longDate}
${credentialScope}
${utilHexEncoding.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("/") ? "/" : ""}`;
return utilUriEscape.escapeUri(normalizedPath).replace(/%2F/g, "/");
}
return path;
}
validateResolvedCredentials(credentials) {
if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || 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(";");
}
};
var SignatureV4 = class extends SignatureV4Base {
headerFormatter = new HeaderFormatter();
constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true }) {
super({
applyChecksum,
credentials,
region,
service,
sha256,
uriEscapePath
});
}
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;
}
async sign(toSign, options) {
if (typeof toSign === "string") return this.signString(toSign, options);
else if (toSign.headers && toSign.payload) return this.signEvent(toSign, options);
else if (toSign.message) return this.signMessage(toSign, options);
else return this.signRequest(toSign, options);
}
async signEvent({ headers, payload }, { signingDate = /* @__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 stringToSign = [
EVENT_ALGORITHM_IDENTIFIER,
longDate,
scope,
priorSignature,
utilHexEncoding.toHex(await hash.digest()),
hashedPayload
].join("\n");
return this.signString(stringToSign, {
signingDate,
signingRegion: region,
signingService
});
}
async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) {
return this.signEvent({
headers: this.headerFormatter.format(signableMessage.message.headers),
payload: signableMessage.message.body
}, {
signingDate,
signingRegion,
signingService,
priorSignature: signableMessage.priorSignature
}).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(utilUtf8.toUint8Array(stringToSign));
return utilHexEncoding.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;
}
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(utilUtf8.toUint8Array(stringToSign));
return utilHexEncoding.toHex(await hash.digest());
}
getSigningKey(credentials, region, shortDate, service) {
return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service);
}
};
const signatureV4aContainer = { SignatureV4a: null };
exports.ALGORITHM_IDENTIFIER = ALGORITHM_IDENTIFIER;
exports.ALGORITHM_IDENTIFIER_V4A = ALGORITHM_IDENTIFIER_V4A;
exports.ALGORITHM_QUERY_PARAM = ALGORITHM_QUERY_PARAM;
exports.ALWAYS_UNSIGNABLE_HEADERS = ALWAYS_UNSIGNABLE_HEADERS;
exports.AMZ_DATE_HEADER = AMZ_DATE_HEADER;
exports.AMZ_DATE_QUERY_PARAM = AMZ_DATE_QUERY_PARAM;
exports.AUTH_HEADER = AUTH_HEADER;
exports.CREDENTIAL_QUERY_PARAM = CREDENTIAL_QUERY_PARAM;
exports.DATE_HEADER = DATE_HEADER;
exports.EVENT_ALGORITHM_IDENTIFIER = EVENT_ALGORITHM_IDENTIFIER;
exports.EXPIRES_QUERY_PARAM = EXPIRES_QUERY_PARAM;
exports.GENERATED_HEADERS = GENERATED_HEADERS;
exports.HOST_HEADER = HOST_HEADER;
exports.KEY_TYPE_IDENTIFIER = KEY_TYPE_IDENTIFIER;
exports.MAX_CACHE_SIZE = MAX_CACHE_SIZE;
exports.MAX_PRESIGNED_TTL = MAX_PRESIGNED_TTL;
exports.PROXY_HEADER_PATTERN = PROXY_HEADER_PATTERN;
exports.REGION_SET_PARAM = REGION_SET_PARAM;
exports.SEC_HEADER_PATTERN = SEC_HEADER_PATTERN;
exports.SHA256_HEADER = SHA256_HEADER;
exports.SIGNATURE_HEADER = SIGNATURE_HEADER;
exports.SIGNATURE_QUERY_PARAM = SIGNATURE_QUERY_PARAM;
exports.SIGNED_HEADERS_QUERY_PARAM = SIGNED_HEADERS_QUERY_PARAM;
exports.SignatureV4 = SignatureV4;
exports.SignatureV4Base = SignatureV4Base;
exports.TOKEN_HEADER = TOKEN_HEADER;
exports.TOKEN_QUERY_PARAM = TOKEN_QUERY_PARAM;
exports.UNSIGNABLE_PATTERNS = UNSIGNABLE_PATTERNS;
exports.UNSIGNED_PAYLOAD = UNSIGNED_PAYLOAD;
exports.clearCredentialCache = clearCredentialCache;
exports.createScope = createScope;
exports.getCanonicalHeaders = getCanonicalHeaders;
exports.getCanonicalQuery = getCanonicalQuery;
exports.getPayloadHash = getPayloadHash;
exports.getSigningKey = getSigningKey;
exports.hasHeader = hasHeader;
exports.moveHeadersToQuery = moveHeadersToQuery;
exports.prepareRequest = prepareRequest;
exports.signatureV4aContainer = signatureV4aContainer;
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js
function normalizeCredentialProvider(config, { credentials, credentialDefaultProvider }) {
let credentialsProvider;
if (credentials) if (!credentials?.memoized) credentialsProvider = memoizeIdentityProvider$2(credentials, isIdentityExpired$2, doesIdentityRequireRefresh$2);
else credentialsProvider = credentials;
else if (credentialDefaultProvider) credentialsProvider = normalizeProvider$2(credentialDefaultProvider(Object.assign({}, config, { parentClientConfig: config })));
else credentialsProvider = async () => {
throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.");
};
credentialsProvider.memoized = true;
return credentialsProvider;
}
function bindCallerConfig(config, credentialsProvider) {
if (credentialsProvider.configBound) return credentialsProvider;
const fn = async (options) => credentialsProvider({
...options,
callerClientConfig: config
});
fn.memoized = credentialsProvider.memoized;
fn.configBound = true;
return fn;
}
var import_dist_cjs$35, resolveAwsSdkSigV4Config, resolveAWSSDKSigV4Config;
var init_resolveAwsSdkSigV4Config = __esmMin((() => {
init_client();
init_dist_es$3();
import_dist_cjs$35 = require_dist_cjs$27();
resolveAwsSdkSigV4Config = (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 boundProvider = bindCallerConfig(config, normalizeCredentialProvider(config, {
credentials: inputCredentials,
credentialDefaultProvider: config.credentialDefaultProvider
}));
if (isUserSupplied && !boundProvider.attributed) {
const isCredentialObject = typeof inputCredentials === "object" && inputCredentials !== null;
resolvedCredentials = async (options) => {
const attributedCreds = await boundProvider(options);
if (isCredentialObject && (!attributedCreds.$source || Object.keys(attributedCreds.$source).length === 0)) return setCredentialFeature(attributedCreds, "CREDENTIALS_CODE", "e");
return attributedCreds;
};
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 { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256 } = config;
let signer;
if (config.signer) signer = normalizeProvider$2(config.signer);
else if (config.regionInfoProvider) signer = () => normalizeProvider$2(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
};
return new (config.signerConstructor || import_dist_cjs$35.SignatureV4)(params);
});
else signer = async (authScheme) => {
authScheme = Object.assign({}, {
name: "sigv4",
signingName: config.signingName || config.defaultSigningName,
signingRegion: await normalizeProvider$2(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
};
return new (config.signerConstructor || import_dist_cjs$35.SignatureV4)(params);
};
return Object.assign(config, {
systemClockOffset,
signingEscapePath,
signer
});
};
resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config;
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js
var init_aws_sdk = __esmMin((() => {
init_AwsSdkSigV4Signer();
init_AwsSdkSigV4ASigner();
init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS();
init_resolveAwsSdkSigV4AConfig();
init_resolveAwsSdkSigV4Config();
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js
var httpAuthSchemes_exports = /* @__PURE__ */ __exportAll({
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
});
var init_httpAuthSchemes$2 = __esmMin((() => {
init_aws_sdk();
init_getBearerTokenEnvKey();
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-types.js
function alloc(size) {
return typeof Buffer !== "undefined" ? Buffer.alloc(size) : new Uint8Array(size);
}
function tag(data) {
data[tagSymbol] = true;
return data;
}
var tagSymbol;
var init_cbor_types = __esmMin((() => {
tagSymbol = Symbol("@smithy/core/cbor::tagSymbol");
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-decode.js
function setPayload(bytes) {
payload = bytes;
dataView$1 = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
}
function decode(at, to) {
if (at >= to) throw new Error("unexpected end of (decode) payload.");
const major = (payload[at] & 224) >> 5;
const minor = payload[at] & 31;
switch (major) {
case 0:
case 1:
case 6:
let unsignedInt;
let offset;
if (minor < 24) {
unsignedInt = minor;
offset = 1;
} else switch (minor) {
case 24:
case 25:
case 26:
case 27:
const countLength = minorValueToArgumentLength[minor];
const countOffset = countLength + 1;
offset = countOffset;
if (to - at < countOffset) throw new Error(`countLength ${countLength} greater than remaining buf len.`);
const countIndex = at + 1;
if (countLength === 1) unsignedInt = payload[countIndex];
else if (countLength === 2) unsignedInt = dataView$1.getUint16(countIndex);
else if (countLength === 4) unsignedInt = dataView$1.getUint32(countIndex);
else unsignedInt = dataView$1.getBigUint64(countIndex);
break;
default: throw new Error(`unexpected minor value ${minor}.`);
}
if (major === 0) {
_offset = offset;
return castBigInt(unsignedInt);
} else if (major === 1) {
let negativeInt;
if (typeof unsignedInt === "bigint") negativeInt = BigInt(-1) - unsignedInt;
else negativeInt = -1 - unsignedInt;
_offset = offset;
return castBigInt(negativeInt);
} else if (minor === 2 || minor === 3) {
const length = decodeCount(at + offset, to);
let b = BigInt(0);
const start = at + offset + _offset;
for (let i = start; i < start + length; ++i) b = b << BigInt(8) | BigInt(payload[i]);
_offset = offset + _offset + length;
return minor === 3 ? -b - BigInt(1) : b;
} else if (minor === 4) {
const [exponent, mantissa] = decode(at + offset, to);
const normalizer = mantissa < 0 ? -1 : 1;
const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + String(BigInt(normalizer) * BigInt(mantissa));
let numericString;
const sign = mantissa < 0 ? "-" : "";
numericString = exponent === 0 ? mantissaStr : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent);
numericString = numericString.replace(/^0+/g, "");
if (numericString === "") numericString = "0";
if (numericString[0] === ".") numericString = "0" + numericString;
numericString = sign + numericString;
_offset = offset + _offset;
return nv(numericString);
} else {
const value = decode(at + offset, to);
_offset = offset + _offset;
return tag({
tag: castBigInt(unsignedInt),
value
});
}
case 3:
case 5:
case 4:
case 2: if (minor === 31) switch (major) {
case 3: return decodeUtf8StringIndefinite(at, to);
case 5: return decodeMapIndefinite(at, to);
case 4: return decodeListIndefinite(at, to);
case 2: return decodeUnstructuredByteStringIndefinite(at, to);
}
else switch (major) {
case 3: return decodeUtf8String(at, to);
case 5: return decodeMap(at, to);
case 4: return decodeList(at, to);
case 2: return decodeUnstructuredByteString(at, to);
}
default: return decodeSpecial(at, to);
}
}
function bytesToUtf8(bytes, at, to) {
if (USE_BUFFER$1 && bytes.constructor?.name === "Buffer") return bytes.toString("utf-8", at, to);
if (textDecoder) return textDecoder.decode(bytes.subarray(at, to));
return (0, import_dist_cjs$34.toUtf8)(bytes.subarray(at, to));
}
function demote(bigInteger) {
const num = Number(bigInteger);
if (num < Number.MIN_SAFE_INTEGER || Number.MAX_SAFE_INTEGER < num) console.warn(/* @__PURE__ */ new Error(`@smithy/core/cbor - truncating BigInt(${bigInteger}) to ${num} with loss of precision.`));
return num;
}
function bytesToFloat16(a, b) {
const sign = a >> 7;
const exponent = (a & 124) >> 2;
const fraction = (a & 3) << 8 | b;
const scalar = sign === 0 ? 1 : -1;
let exponentComponent;
let summation;
if (exponent === 0) if (fraction === 0) return 0;
else {
exponentComponent = Math.pow(2, -14);
summation = 0;
}
else if (exponent === 31) if (fraction === 0) return scalar * Infinity;
else return NaN;
else {
exponentComponent = Math.pow(2, exponent - 15);
summation = 1;
}
summation += fraction / 1024;
return scalar * (exponentComponent * summation);
}
function decodeCount(at, to) {
const minor = payload[at] & 31;
if (minor < 24) {
_offset = 1;
return minor;
}
if (minor === 24 || minor === 25 || minor === 26 || minor === 27) {
const countLength = minorValueToArgumentLength[minor];
_offset = countLength + 1;
if (to - at < _offset) throw new Error(`countLength ${countLength} greater than remaining buf len.`);
const countIndex = at + 1;
if (countLength === 1) return payload[countIndex];
else if (countLength === 2) return dataView$1.getUint16(countIndex);
else if (countLength === 4) return dataView$1.getUint32(countIndex);
return demote(dataView$1.getBigUint64(countIndex));
}
throw new Error(`unexpected minor value ${minor}.`);
}
function decodeUtf8String(at, to) {
const length = decodeCount(at, to);
const offset = _offset;
at += offset;
if (to - at < length) throw new Error(`string len ${length} greater than remaining buf len.`);
const value = bytesToUtf8(payload, at, at + length);
_offset = offset + length;
return value;
}
function decodeUtf8StringIndefinite(at, to) {
at += 1;
const vector = [];
for (const base = at; at < to;) {
if (payload[at] === 255) {
const data = alloc(vector.length);
data.set(vector, 0);
_offset = at - base + 2;
return bytesToUtf8(data, 0, data.length);
}
const major = (payload[at] & 224) >> 5;
const minor = payload[at] & 31;
if (major !== 3) throw new Error(`unexpected major type ${major} in indefinite string.`);
if (minor === 31) throw new Error("nested indefinite string.");
const bytes = decodeUnstructuredByteString(at, to);
at += _offset;
for (let i = 0; i < bytes.length; ++i) vector.push(bytes[i]);
}
throw new Error("expected break marker.");
}
function decodeUnstructuredByteString(at, to) {
const length = decodeCount(at, to);
const offset = _offset;
at += offset;
if (to - at < length) throw new Error(`unstructured byte string len ${length} greater than remaining buf len.`);
const value = payload.subarray(at, at + length);
_offset = offset + length;
return value;
}
function decodeUnstructuredByteStringIndefinite(at, to) {
at += 1;
const vector = [];
for (const base = at; at < to;) {
if (payload[at] === 255) {
const data = alloc(vector.length);
data.set(vector, 0);
_offset = at - base + 2;
return data;
}
const major = (payload[at] & 224) >> 5;
const minor = payload[at] & 31;
if (major !== 2) throw new Error(`unexpected major type ${major} in indefinite string.`);
if (minor === 31) throw new Error("nested indefinite string.");
const bytes = decodeUnstructuredByteString(at, to);
at += _offset;
for (let i = 0; i < bytes.length; ++i) vector.push(bytes[i]);
}
throw new Error("expected break marker.");
}
function decodeList(at, to) {
const listDataLength = decodeCount(at, to);
const offset = _offset;
at += offset;
const base = at;
const list = Array(listDataLength);
for (let i = 0; i < listDataLength; ++i) {
const item = decode(at, to);
const itemOffset = _offset;
list[i] = item;
at += itemOffset;
}
_offset = offset + (at - base);
return list;
}
function decodeListIndefinite(at, to) {
at += 1;
const list = [];
for (const base = at; at < to;) {
if (payload[at] === 255) {
_offset = at - base + 2;
return list;
}
const item = decode(at, to);
at += _offset;
list.push(item);
}
throw new Error("expected break marker.");
}
function decodeMap(at, to) {
const mapDataLength = decodeCount(at, to);
const offset = _offset;
at += offset;
const base = at;
const map = {};
for (let i = 0; i < mapDataLength; ++i) {
if (at >= to) throw new Error("unexpected end of map payload.");
const major = (payload[at] & 224) >> 5;
if (major !== 3) throw new Error(`unexpected major type ${major} for map key at index ${at}.`);
const key = decode(at, to);
at += _offset;
const value = decode(at, to);
at += _offset;
map[key] = value;
}
_offset = offset + (at - base);
return map;
}
function decodeMapIndefinite(at, to) {
at += 1;
const base = at;
const map = {};
for (; at < to;) {
if (at >= to) throw new Error("unexpected end of map payload.");
if (payload[at] === 255) {
_offset = at - base + 2;
return map;
}
const major = (payload[at] & 224) >> 5;
if (major !== 3) throw new Error(`unexpected major type ${major} for map key.`);
const key = decode(at, to);
at += _offset;
const value = decode(at, to);
at += _offset;
map[key] = value;
}
throw new Error("expected break marker.");
}
function decodeSpecial(at, to) {
const minor = payload[at] & 31;
switch (minor) {
case 21:
case 20:
_offset = 1;
return minor === 21;
case 22:
_offset = 1;
return null;
case 23:
_offset = 1;
return null;
case 25:
if (to - at < 3) throw new Error("incomplete float16 at end of buf.");
_offset = 3;
return bytesToFloat16(payload[at + 1], payload[at + 2]);
case 26:
if (to - at < 5) throw new Error("incomplete float32 at end of buf.");
_offset = 5;
return dataView$1.getFloat32(at + 1);
case 27:
if (to - at < 9) throw new Error("incomplete float64 at end of buf.");
_offset = 9;
return dataView$1.getFloat64(at + 1);
default: throw new Error(`unexpected minor value ${minor}.`);
}
}
function castBigInt(bigInt) {
if (typeof bigInt === "number") return bigInt;
const num = Number(bigInt);
if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) return num;
return bigInt;
}
var import_dist_cjs$34, USE_TEXT_DECODER, USE_BUFFER$1, payload, dataView$1, textDecoder, _offset, minorValueToArgumentLength;
var init_cbor_decode = __esmMin((() => {
init_serde();
import_dist_cjs$34 = require_dist_cjs$42();
init_cbor_types();
USE_TEXT_DECODER = typeof TextDecoder !== "undefined";
USE_BUFFER$1 = typeof Buffer !== "undefined";
payload = alloc(0);
dataView$1 = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
textDecoder = USE_TEXT_DECODER ? new TextDecoder() : null;
_offset = 0;
minorValueToArgumentLength = {
[24]: 1,
[25]: 2,
[26]: 4,
[27]: 8
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-encode.js
function ensureSpace(bytes) {
if (data.byteLength - cursor < bytes) if (cursor < 16e6) resize(Math.max(data.byteLength * 4, data.byteLength + bytes));
else resize(data.byteLength + bytes + 16e6);
}
function toUint8Array() {
const out = alloc(cursor);
out.set(data.subarray(0, cursor), 0);
cursor = 0;
return out;
}
function resize(size) {
const old = data;
data = alloc(size);
if (old) if (old.copy) old.copy(data, 0, 0, old.byteLength);
else data.set(old, 0);
dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
}
function encodeHeader(major, value) {
if (value < 24) data[cursor++] = major << 5 | value;
else if (value < 256) {
data[cursor++] = major << 5 | 24;
data[cursor++] = value;
} else if (value < 65536) {
data[cursor++] = major << 5 | 25;
dataView.setUint16(cursor, value);
cursor += 2;
} else if (value < 2 ** 32) {
data[cursor++] = major << 5 | 26;
dataView.setUint32(cursor, value);
cursor += 4;
} else {
data[cursor++] = major << 5 | 27;
dataView.setBigUint64(cursor, typeof value === "bigint" ? value : BigInt(value));
cursor += 8;
}
}
function encode(_input) {
const encodeStack = [_input];
while (encodeStack.length) {
const input = encodeStack.pop();
ensureSpace(typeof input === "string" ? input.length * 4 : 64);
if (typeof input === "string") {
if (USE_BUFFER) {
encodeHeader(3, Buffer.byteLength(input));
cursor += data.write(input, cursor);
} else {
const bytes = (0, import_dist_cjs$33.fromUtf8)(input);
encodeHeader(3, bytes.byteLength);
data.set(bytes, cursor);
cursor += bytes.byteLength;
}
continue;
} else if (typeof input === "number") {
if (Number.isInteger(input)) {
const nonNegative = input >= 0;
const major = nonNegative ? 0 : 1;
const value = nonNegative ? input : -input - 1;
if (value < 24) data[cursor++] = major << 5 | value;
else if (value < 256) {
data[cursor++] = major << 5 | 24;
data[cursor++] = value;
} else if (value < 65536) {
data[cursor++] = major << 5 | 25;
data[cursor++] = value >> 8;
data[cursor++] = value;
} else if (value < 4294967296) {
data[cursor++] = major << 5 | 26;
dataView.setUint32(cursor, value);
cursor += 4;
} else {
data[cursor++] = major << 5 | 27;
dataView.setBigUint64(cursor, BigInt(value));
cursor += 8;
}
continue;
}
data[cursor++] = 251;
dataView.setFloat64(cursor, input);
cursor += 8;
continue;
} else if (typeof input === "bigint") {
const nonNegative = input >= 0;
const major = nonNegative ? 0 : 1;
const value = nonNegative ? input : -input - BigInt(1);
const n = Number(value);
if (n < 24) data[cursor++] = major << 5 | n;
else if (n < 256) {
data[cursor++] = major << 5 | 24;
data[cursor++] = n;
} else if (n < 65536) {
data[cursor++] = major << 5 | 25;
data[cursor++] = n >> 8;
data[cursor++] = n & 255;
} else if (n < 4294967296) {
data[cursor++] = major << 5 | 26;
dataView.setUint32(cursor, n);
cursor += 4;
} else if (value < BigInt("18446744073709551616")) {
data[cursor++] = major << 5 | 27;
dataView.setBigUint64(cursor, value);
cursor += 8;
} else {
const binaryBigInt = value.toString(2);
const bigIntBytes = new Uint8Array(Math.ceil(binaryBigInt.length / 8));
let b = value;
let i = 0;
while (bigIntBytes.byteLength - ++i >= 0) {
bigIntBytes[bigIntBytes.byteLength - i] = Number(b & BigInt(255));
b >>= BigInt(8);
}
ensureSpace(bigIntBytes.byteLength * 2);
data[cursor++] = nonNegative ? 194 : 195;
if (USE_BUFFER) encodeHeader(2, Buffer.byteLength(bigIntBytes));
else encodeHeader(2, bigIntBytes.byteLength);
data.set(bigIntBytes, cursor);
cursor += bigIntBytes.byteLength;
}
continue;
} else if (input === null) {
data[cursor++] = 246;
continue;
} else if (typeof input === "boolean") {
data[cursor++] = 224 | (input ? 21 : 20);
continue;
} else if (typeof input === "undefined") throw new Error("@smithy/core/cbor: client may not serialize undefined value.");
else if (Array.isArray(input)) {
for (let i = input.length - 1; i >= 0; --i) encodeStack.push(input[i]);
encodeHeader(4, input.length);
continue;
} else if (typeof input.byteLength === "number") {
ensureSpace(input.length * 2);
encodeHeader(2, input.length);
data.set(input, cursor);
cursor += input.byteLength;
continue;
} else if (typeof input === "object") {
if (input instanceof NumericValue) {
const decimalIndex = input.string.indexOf(".");
const exponent = decimalIndex === -1 ? 0 : decimalIndex - input.string.length + 1;
const mantissa = BigInt(input.string.replace(".", ""));
data[cursor++] = 196;
encodeStack.push(mantissa);
encodeStack.push(exponent);
encodeHeader(4, 2);
continue;
}
if (input[tagSymbol]) if ("tag" in input && "value" in input) {
encodeStack.push(input.value);
encodeHeader(6, input.tag);
continue;
} else throw new Error("tag encountered with missing fields, need 'tag' and 'value', found: " + JSON.stringify(input));
const keys = Object.keys(input);
for (let i = keys.length - 1; i >= 0; --i) {
const key = keys[i];
encodeStack.push(input[key]);
encodeStack.push(key);
}
encodeHeader(5, keys.length);
continue;
}
throw new Error(`data type ${input?.constructor?.name ?? typeof input} not compatible for encoding.`);
}
}
var import_dist_cjs$33, USE_BUFFER, data, dataView, cursor;
var init_cbor_encode = __esmMin((() => {
init_serde();
import_dist_cjs$33 = require_dist_cjs$42();
init_cbor_types();
USE_BUFFER = typeof Buffer !== "undefined";
data = alloc(2048);
dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
cursor = 0;
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/cbor/cbor.js
var cbor;
var init_cbor$1 = __esmMin((() => {
init_cbor_decode();
init_cbor_encode();
cbor = {
deserialize(payload) {
setPayload(payload);
return decode(0, payload.length);
},
serialize(input) {
try {
encode(input);
return toUint8Array();
} catch (e) {
toUint8Array();
throw e;
}
},
resizeEncodingBuffer(size) {
resize(size);
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/cbor/parseCborBody.js
var dateToTag, loadSmithyRpcV2CborErrorCode;
var init_parseCborBody = __esmMin((() => {
init_cbor_types();
dateToTag = (date) => {
return tag({
tag: 1,
value: date.getTime() / 1e3
});
};
loadSmithyRpcV2CborErrorCode = (output, data) => {
const sanitizeErrorCode = (rawValue) => {
let cleanValue = rawValue;
if (typeof cleanValue === "number") cleanValue = cleanValue.toString();
if (cleanValue.indexOf(",") >= 0) cleanValue = cleanValue.split(",")[0];
if (cleanValue.indexOf(":") >= 0) cleanValue = cleanValue.split(":")[0];
if (cleanValue.indexOf("#") >= 0) cleanValue = cleanValue.split("#")[1];
return cleanValue;
};
if (data["__type"] !== void 0) return sanitizeErrorCode(data["__type"]);
const codeKey = Object.keys(data).find((key) => key.toLowerCase() === "code");
if (codeKey && data[codeKey] !== void 0) return sanitizeErrorCode(data[codeKey]);
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/cbor/CborCodec.js
var import_dist_cjs$32, CborCodec, CborShapeSerializer, CborShapeDeserializer;
var init_CborCodec = __esmMin((() => {
init_protocols$2();
init_schema();
init_serde();
import_dist_cjs$32 = require_dist_cjs$37();
init_cbor$1();
init_parseCborBody();
CborCodec = class extends SerdeContext {
createSerializer() {
const serializer = new CborShapeSerializer();
serializer.setSerdeContext(this.serdeContext);
return serializer;
}
createDeserializer() {
const deserializer = new CborShapeDeserializer();
deserializer.setSerdeContext(this.serdeContext);
return deserializer;
}
};
CborShapeSerializer = class extends SerdeContext {
value;
write(schema, value) {
this.value = this.serialize(schema, value);
}
serialize(schema, source) {
const ns = NormalizedSchema.of(schema);
if (source == null) {
if (ns.isIdempotencyToken()) return (0, import_dist_cjs$45.v4)();
return source;
}
if (ns.isBlobSchema()) {
if (typeof source === "string") return (this.serdeContext?.base64Decoder ?? import_dist_cjs$32.fromBase64)(source);
return source;
}
if (ns.isTimestampSchema()) {
if (typeof source === "number" || typeof source === "bigint") return dateToTag(/* @__PURE__ */ new Date(Number(source) / 1e3 | 0));
return dateToTag(source);
}
if (typeof source === "function" || typeof source === "object") {
const sourceObject = source;
if (ns.isListSchema() && Array.isArray(sourceObject)) {
const sparse = !!ns.getMergedTraits().sparse;
const newArray = [];
let i = 0;
for (const item of sourceObject) {
const value = this.serialize(ns.getValueSchema(), item);
if (value != null || sparse) newArray[i++] = value;
}
return newArray;
}
if (sourceObject instanceof Date) return dateToTag(sourceObject);
const newObject = {};
if (ns.isMapSchema()) {
const sparse = !!ns.getMergedTraits().sparse;
for (const key of Object.keys(sourceObject)) {
const value = this.serialize(ns.getValueSchema(), sourceObject[key]);
if (value != null || sparse) newObject[key] = value;
}
} else if (ns.isStructSchema()) {
for (const [key, memberSchema] of ns.structIterator()) {
const value = this.serialize(memberSchema, sourceObject[key]);
if (value != null) newObject[key] = value;
}
if (ns.isUnionSchema() && Array.isArray(sourceObject.$unknown)) {
const [k, v] = sourceObject.$unknown;
newObject[k] = v;
} else if (typeof sourceObject.__type === "string") {
for (const [k, v] of Object.entries(sourceObject)) if (!(k in newObject)) newObject[k] = this.serialize(15, v);
}
} else if (ns.isDocumentSchema()) for (const key of Object.keys(sourceObject)) newObject[key] = this.serialize(ns.getValueSchema(), sourceObject[key]);
else if (ns.isBigDecimalSchema()) return sourceObject;
return newObject;
}
return source;
}
flush() {
const buffer = cbor.serialize(this.value);
this.value = void 0;
return buffer;
}
};
CborShapeDeserializer = class extends SerdeContext {
read(schema, bytes) {
const data = cbor.deserialize(bytes);
return this.readValue(schema, data);
}
readValue(_schema, value) {
const ns = NormalizedSchema.of(_schema);
if (ns.isTimestampSchema()) {
if (typeof value === "number") return _parseEpochTimestamp(value);
if (typeof value === "object") {
if (value.tag === 1 && "value" in value) return _parseEpochTimestamp(value.value);
}
}
if (ns.isBlobSchema()) {
if (typeof value === "string") return (this.serdeContext?.base64Decoder ?? import_dist_cjs$32.fromBase64)(value);
return value;
}
if (typeof value === "undefined" || typeof value === "boolean" || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || typeof value === "symbol") return value;
else if (typeof value === "object") {
if (value === null) return null;
if ("byteLength" in value) return value;
if (value instanceof Date) return value;
if (ns.isDocumentSchema()) return value;
if (ns.isListSchema()) {
const newArray = [];
const memberSchema = ns.getValueSchema();
for (const item of value) {
const itemValue = this.readValue(memberSchema, item);
newArray.push(itemValue);
}
return newArray;
}
const newObject = {};
if (ns.isMapSchema()) {
const targetSchema = ns.getValueSchema();
for (const key of Object.keys(value)) newObject[key] = this.readValue(targetSchema, value[key]);
} else if (ns.isStructSchema()) {
const isUnion = ns.isUnionSchema();
let keys;
if (isUnion) keys = new Set(Object.keys(value).filter((k) => k !== "__type"));
for (const [key, memberSchema] of ns.structIterator()) {
if (isUnion) keys.delete(key);
if (value[key] != null) newObject[key] = this.readValue(memberSchema, value[key]);
}
if (isUnion && keys?.size === 1 && Object.keys(newObject).length === 0) {
const k = keys.values().next().value;
newObject.$unknown = [k, value[k]];
} else if (typeof value.__type === "string") {
for (const [k, v] of Object.entries(value)) if (!(k in newObject)) newObject[k] = v;
}
} else if (value instanceof NumericValue) return value;
return newObject;
} else return value;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/cbor/SmithyRpcV2CborProtocol.js
var import_dist_cjs$31, SmithyRpcV2CborProtocol;
var init_SmithyRpcV2CborProtocol = __esmMin((() => {
init_protocols$2();
init_schema();
import_dist_cjs$31 = require_dist_cjs$40();
init_CborCodec();
init_parseCborBody();
SmithyRpcV2CborProtocol = class extends RpcProtocol {
codec = new CborCodec();
serializer = this.codec.createSerializer();
deserializer = this.codec.createDeserializer();
constructor({ defaultNamespace, errorTypeRegistries }) {
super({
defaultNamespace,
errorTypeRegistries
});
}
getShapeId() {
return "smithy.protocols#rpcv2Cbor";
}
getPayloadCodec() {
return this.codec;
}
async serializeRequest(operationSchema, input, context) {
const request = await super.serializeRequest(operationSchema, input, context);
Object.assign(request.headers, {
"content-type": this.getDefaultContentType(),
"smithy-protocol": "rpc-v2-cbor",
accept: this.getDefaultContentType()
});
if (deref(operationSchema.input) === "unit") {
delete request.body;
delete request.headers["content-type"];
} else {
if (!request.body) {
this.serializer.write(15, {});
request.body = this.serializer.flush();
}
try {
request.headers["content-length"] = String(request.body.byteLength);
} catch (e) {}
}
const { service, operation } = (0, import_dist_cjs$31.getSmithyContext)(context);
const path = `/service/${service}/operation/${operation}`;
if (request.path.endsWith("/")) request.path += path.slice(1);
else request.path += path;
return request;
}
async deserializeResponse(operationSchema, context, response) {
return super.deserializeResponse(operationSchema, context, response);
}
async handleError(operationSchema, context, response, dataObject, metadata) {
const errorName = loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown";
const errorMetadata = {
$metadata: metadata,
$fault: response.statusCode <= 500 ? "client" : "server"
};
let namespace = this.options.defaultNamespace;
if (errorName.includes("#")) [namespace] = errorName.split("#");
const registry = this.compositeErrorRegistry;
const nsRegistry = TypeRegistry.for(namespace);
registry.copyFrom(nsRegistry);
let errorSchema;
try {
errorSchema = registry.getSchema(errorName);
} catch (e) {
if (dataObject.Message) dataObject.message = dataObject.Message;
const syntheticRegistry = TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace);
registry.copyFrom(syntheticRegistry);
const baseExceptionSchema = registry.getBaseException();
if (baseExceptionSchema) {
const ErrorCtor = registry.getErrorCtor(baseExceptionSchema);
throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject);
}
throw Object.assign(new Error(errorName), errorMetadata, dataObject);
}
const ns = NormalizedSchema.of(errorSchema);
const ErrorCtor = registry.getErrorCtor(errorSchema);
const message = dataObject.message ?? dataObject.Message ?? "Unknown";
const exception = new ErrorCtor(message);
const output = {};
for (const [name, member] of ns.structIterator()) output[name] = this.deserializer.readValue(member, dataObject[name]);
throw Object.assign(exception, errorMetadata, {
$fault: ns.getMergedTraits().error,
message
}, output);
}
getDefaultContentType() {
return "application/cbor";
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/node_modules/@smithy/core/dist-es/submodules/cbor/index.js
var init_cbor = __esmMin((() => {
init_parseCborBody();
init_SmithyRpcV2CborProtocol();
init_CborCodec();
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/ProtocolLib.js
var import_dist_cjs$30, ProtocolLib;
var init_ProtocolLib = __esmMin((() => {
init_schema();
import_dist_cjs$30 = require_dist_cjs$41();
ProtocolLib = class {
queryCompat;
constructor(queryCompat = false) {
this.queryCompat = queryCompat;
}
resolveRestContentType(defaultContentType, inputSchema) {
const members = inputSchema.getMemberSchemas();
const httpPayloadMember = Object.values(members).find((m) => {
return !!m.getMergedTraits().httpPayload;
});
if (httpPayloadMember) {
const mediaType = httpPayloadMember.getMergedTraits().mediaType;
if (mediaType) return mediaType;
else if (httpPayloadMember.isStringSchema()) return "text/plain";
else if (httpPayloadMember.isBlobSchema()) return "application/octet-stream";
else return defaultContentType;
} else if (!inputSchema.isUnitSchema()) {
if (Object.values(members).find((m) => {
const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits();
return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && httpPrefixHeaders === void 0;
})) return defaultContentType;
}
}
async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) {
let namespace = defaultNamespace;
let errorName = errorIdentifier;
if (errorIdentifier.includes("#")) [namespace, errorName] = errorIdentifier.split("#");
const errorMetadata = {
$metadata: metadata,
$fault: response.statusCode < 500 ? "client" : "server"
};
const registry = TypeRegistry.for(namespace);
try {
return {
errorSchema: getErrorSchema?.(registry, errorName) ?? registry.getSchema(errorIdentifier),
errorMetadata
};
} catch (e) {
dataObject.message = dataObject.message ?? dataObject.Message ?? "UnknownError";
const synthetic = TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace);
const baseExceptionSchema = synthetic.getBaseException();
if (baseExceptionSchema) {
const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema) ?? Error;
throw this.decorateServiceException(Object.assign(new ErrorCtor({ name: errorName }), errorMetadata), dataObject);
}
throw this.decorateServiceException(Object.assign(new Error(errorName), errorMetadata), dataObject);
}
}
decorateServiceException(exception, additions = {}) {
if (this.queryCompat) {
const msg = exception.Message ?? additions.Message;
const error = (0, import_dist_cjs$30.decorateServiceException)(exception, additions);
if (msg) error.message = msg;
error.Error = {
...error.Error,
Type: error.Error?.Type,
Code: error.Error?.Code,
Message: error.Error?.message ?? error.Error?.Message ?? msg
};
const reqId = error.$metadata.requestId;
if (reqId) error.RequestId = reqId;
return error;
}
return (0, import_dist_cjs$30.decorateServiceException)(exception, additions);
}
setQueryCompatError(output, response) {
const queryErrorHeader = response.headers?.["x-amzn-query-error"];
if (output !== void 0 && queryErrorHeader != null) {
const [Code, Type] = queryErrorHeader.split(";");
const entries = Object.entries(output);
const Error = {
Code,
Type
};
Object.assign(output, Error);
for (const [k, v] of entries) Error[k === "message" ? "Message" : k] = v;
delete Error.__type;
output.Error = Error;
}
}
queryCompatOutput(queryCompatErrorData, errorData) {
if (queryCompatErrorData.Error) errorData.Error = queryCompatErrorData.Error;
if (queryCompatErrorData.Type) errorData.Type = queryCompatErrorData.Type;
if (queryCompatErrorData.Code) errorData.Code = queryCompatErrorData.Code;
}
findQueryCompatibleError(registry, errorName) {
try {
return registry.getSchema(errorName);
} catch (e) {
return registry.find((schema) => NormalizedSchema.of(schema).getMergedTraits().awsQueryError?.[0] === errorName);
}
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.js
var AwsSmithyRpcV2CborProtocol;
var init_AwsSmithyRpcV2CborProtocol = __esmMin((() => {
init_cbor();
init_schema();
init_ProtocolLib();
AwsSmithyRpcV2CborProtocol = class extends SmithyRpcV2CborProtocol {
awsQueryCompatible;
mixin;
constructor({ defaultNamespace, awsQueryCompatible }) {
super({ defaultNamespace });
this.awsQueryCompatible = !!awsQueryCompatible;
this.mixin = new ProtocolLib(this.awsQueryCompatible);
}
async serializeRequest(operationSchema, input, context) {
const request = await super.serializeRequest(operationSchema, input, context);
if (this.awsQueryCompatible) request.headers["x-amzn-query-mode"] = "true";
return request;
}
async handleError(operationSchema, context, response, dataObject, metadata) {
if (this.awsQueryCompatible) this.mixin.setQueryCompatError(dataObject, response);
const errorName = (() => {
const compatHeader = response.headers["x-amzn-query-error"];
if (compatHeader && this.awsQueryCompatible) return compatHeader.split(";")[0];
return loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown";
})();
const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorName, this.options.defaultNamespace, response, dataObject, metadata, this.awsQueryCompatible ? this.mixin.findQueryCompatibleError : void 0);
const ns = NormalizedSchema.of(errorSchema);
const message = dataObject.message ?? dataObject.Message ?? "Unknown";
const exception = new ((TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema)) ?? Error)(message);
const output = {};
for (const [name, member] of ns.structIterator()) if (dataObject[name] != null) output[name] = this.deserializer.readValue(member, dataObject[name]);
if (this.awsQueryCompatible) this.mixin.queryCompatOutput(dataObject, output);
throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {
$fault: ns.getMergedTraits().error,
message
}, output), dataObject);
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js
var _toStr, _toBool, _toNum;
var init_coercing_serializers = __esmMin((() => {
_toStr = (val) => {
if (val == null) return val;
if (typeof val === "number" || typeof val === "bigint") {
const warning = /* @__PURE__ */ 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 = /* @__PURE__ */ new Error(`Received boolean ${val} where a string was expected.`);
warning.name = "Warning";
console.warn(warning);
return String(val);
}
return val;
};
_toBool = (val) => {
if (val == null) return val;
if (typeof val === "number") {}
if (typeof val === "string") {
const lowercase = val.toLowerCase();
if (val !== "" && lowercase !== "false" && lowercase !== "true") {
const warning = /* @__PURE__ */ new Error(`Received string "${val}" where a boolean was expected.`);
warning.name = "Warning";
console.warn(warning);
}
return val !== "" && lowercase !== "false";
}
return val;
};
_toNum = (val) => {
if (val == null) return val;
if (typeof val === "boolean") {}
if (typeof val === "string") {
const num = Number(val);
if (num.toString() !== val) {
const warning = /* @__PURE__ */ new Error(`Received string "${val}" where a number was expected.`);
warning.name = "Warning";
console.warn(warning);
return val;
}
return num;
}
return val;
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/ConfigurableSerdeContext.js
var SerdeContextConfig;
var init_ConfigurableSerdeContext = __esmMin((() => {
SerdeContextConfig = class {
serdeContext;
setSerdeContext(serdeContext) {
this.serdeContext = serdeContext;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/UnionSerde.js
var UnionSerde;
var init_UnionSerde = __esmMin((() => {
UnionSerde = class {
from;
to;
keys;
constructor(from, to) {
this.from = from;
this.to = to;
this.keys = new Set(Object.keys(this.from).filter((k) => k !== "__type"));
}
mark(key) {
this.keys.delete(key);
}
hasUnknown() {
return this.keys.size === 1 && Object.keys(this.to).length === 0;
}
writeUnknown() {
if (this.hasUnknown()) {
const k = this.keys.values().next().value;
const v = this.from[k];
this.to.$unknown = [k, v];
}
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReviver.js
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)) if (numericString.includes(".")) return new NumericValue(numericString, "bigDecimal");
else return BigInt(numericString);
}
}
return value;
}
var init_jsonReviver = __esmMin((() => {
init_serde();
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js
var import_dist_cjs$28, import_dist_cjs$29, collectBodyString;
var init_common = __esmMin((() => {
import_dist_cjs$28 = require_dist_cjs$41();
import_dist_cjs$29 = require_dist_cjs$42();
collectBodyString = (streamBody, context) => (0, import_dist_cjs$28.collectBody)(streamBody, context).then((body) => (context?.utf8Encoder ?? import_dist_cjs$29.toUtf8)(body));
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js
var parseJsonBody, parseJsonErrorBody, loadRestJsonErrorCode;
var init_parseJsonBody = __esmMin((() => {
init_common();
parseJsonBody = (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 {};
});
parseJsonErrorBody = async (errorBody, context) => {
const value = await parseJsonBody(errorBody, context);
value.message = value.message ?? value.Message;
return value;
};
loadRestJsonErrorCode = (output, data) => {
const findKey = (object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase());
const sanitizeErrorCode = (rawValue) => {
let cleanValue = rawValue;
if (typeof cleanValue === "number") cleanValue = cleanValue.toString();
if (cleanValue.indexOf(",") >= 0) cleanValue = cleanValue.split(",")[0];
if (cleanValue.indexOf(":") >= 0) cleanValue = cleanValue.split(":")[0];
if (cleanValue.indexOf("#") >= 0) cleanValue = cleanValue.split("#")[1];
return cleanValue;
};
const headerKey = findKey(output.headers, "x-amzn-errortype");
if (headerKey !== 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"]);
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeDeserializer.js
var import_dist_cjs$27, JsonShapeDeserializer;
var init_JsonShapeDeserializer = __esmMin((() => {
init_protocols$2();
init_schema();
init_serde();
import_dist_cjs$27 = require_dist_cjs$37();
init_ConfigurableSerdeContext();
init_UnionSerde();
init_jsonReviver();
init_parseJsonBody();
JsonShapeDeserializer = class extends SerdeContextConfig {
settings;
constructor(settings) {
super();
this.settings = settings;
}
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 = NormalizedSchema.of(schema);
if (isObject) {
if (ns.isStructSchema()) {
const record = value;
const union = ns.isUnionSchema();
const out = {};
let nameMap = void 0;
const { jsonName } = this.settings;
if (jsonName) nameMap = {};
let unionSerde;
if (union) unionSerde = new UnionSerde(record, out);
for (const [memberName, memberSchema] of ns.structIterator()) {
let fromKey = memberName;
if (jsonName) {
fromKey = memberSchema.getMergedTraits().jsonName ?? fromKey;
nameMap[fromKey] = memberName;
}
if (union) unionSerde.mark(fromKey);
if (record[fromKey] != null) out[memberName] = this._read(memberSchema, record[fromKey]);
}
if (union) unionSerde.writeUnknown();
else if (typeof record.__type === "string") for (const [k, v] of Object.entries(record)) {
const t = jsonName ? nameMap[k] ?? k : k;
if (!(t in out)) out[t] = v;
}
return out;
}
if (Array.isArray(value) && ns.isListSchema()) {
const listMember = ns.getValueSchema();
const out = [];
for (const item of value) out.push(this._read(listMember, item));
return out;
}
if (ns.isMapSchema()) {
const mapMember = ns.getValueSchema();
const out = {};
for (const [_k, _v] of Object.entries(value)) out[_k] = this._read(mapMember, _v);
return out;
}
}
if (ns.isBlobSchema() && typeof value === "string") return (0, import_dist_cjs$27.fromBase64)(value);
const mediaType = ns.getMergedTraits().mediaType;
if (ns.isStringSchema() && typeof value === "string" && mediaType) {
if (mediaType === "application/json" || mediaType.endsWith("+json")) return LazyJsonString.from(value);
return value;
}
if (ns.isTimestampSchema() && value != null) switch (determineTimestampFormat(ns, this.settings)) {
case 5: return parseRfc3339DateTimeWithOffset(value);
case 6: return parseRfc7231DateTime(value);
case 7: return 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 NumericValue) return value;
const untyped = value;
if (untyped.type === "bigDecimal" && "string" in untyped) return new NumericValue(untyped.string, untyped.type);
return new 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 (ns.isDocumentSchema()) if (isObject) {
const out = Array.isArray(value) ? [] : {};
for (const [k, v] of Object.entries(value)) if (v instanceof NumericValue) out[k] = v;
else out[k] = this._read(ns, v);
return out;
} else return structuredClone(value);
return value;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReplacer.js
var NUMERIC_CONTROL_CHAR, JsonReplacer;
var init_jsonReplacer = __esmMin((() => {
init_serde();
NUMERIC_CONTROL_CHAR = String.fromCharCode(925);
JsonReplacer = class {
values = /* @__PURE__ */ new Map();
counter = 0;
stage = 0;
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 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;
};
}
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;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeSerializer.js
var import_dist_cjs$26, JsonShapeSerializer;
var init_JsonShapeSerializer = __esmMin((() => {
init_protocols$2();
init_schema();
init_serde();
import_dist_cjs$26 = require_dist_cjs$37();
init_ConfigurableSerdeContext();
init_jsonReplacer();
JsonShapeSerializer = class extends SerdeContextConfig {
settings;
buffer;
useReplacer = false;
rootSchema;
constructor(settings) {
super();
this.settings = settings;
}
write(schema, value) {
this.rootSchema = NormalizedSchema.of(schema);
this.buffer = this._write(this.rootSchema, value);
}
writeDiscriminatedDocument(schema, value) {
this.write(schema, value);
if (typeof this.buffer === "object") this.buffer.__type = NormalizedSchema.of(schema).getName(true);
}
flush() {
const { rootSchema, useReplacer } = this;
this.rootSchema = void 0;
this.useReplacer = false;
if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) {
if (!useReplacer) return JSON.stringify(this.buffer);
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 = NormalizedSchema.of(schema);
if (isObject) {
if (ns.isStructSchema()) {
const record = value;
const out = {};
const { jsonName } = this.settings;
let nameMap = void 0;
if (jsonName) nameMap = {};
for (const [memberName, memberSchema] of ns.structIterator()) {
const serializableValue = this._write(memberSchema, record[memberName], ns);
if (serializableValue !== void 0) {
let targetKey = memberName;
if (jsonName) {
targetKey = memberSchema.getMergedTraits().jsonName ?? memberName;
nameMap[memberName] = targetKey;
}
out[targetKey] = serializableValue;
}
}
if (ns.isUnionSchema() && Object.keys(out).length === 0) {
const { $unknown } = record;
if (Array.isArray($unknown)) {
const [k, v] = $unknown;
out[k] = this._write(15, v);
}
} else if (typeof record.__type === "string") for (const [k, v] of Object.entries(record)) {
const targetKey = jsonName ? nameMap[k] ?? k : k;
if (!(targetKey in out)) out[targetKey] = this._write(15, v);
}
return out;
}
if (Array.isArray(value) && ns.isListSchema()) {
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;
}
if (ns.isMapSchema()) {
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;
}
if (value instanceof Uint8Array && (ns.isBlobSchema() || ns.isDocumentSchema())) {
if (ns === this.rootSchema) return value;
return (this.serdeContext?.base64Encoder ?? import_dist_cjs$26.toBase64)(value);
}
if (value instanceof Date && (ns.isTimestampSchema() || ns.isDocumentSchema())) switch (determineTimestampFormat(ns, this.settings)) {
case 5: return value.toISOString().replace(".000Z", "Z");
case 6: return dateToUtcString$2(value);
case 7: return value.getTime() / 1e3;
default:
console.warn("Missing timestamp format, using epoch seconds", value);
return value.getTime() / 1e3;
}
if (value instanceof NumericValue) this.useReplacer = true;
}
if (value === null && container?.isStructSchema()) return;
if (ns.isStringSchema()) {
if (typeof value === "undefined" && ns.isIdempotencyToken()) return (0, import_dist_cjs$45.v4)();
const mediaType = ns.getMergedTraits().mediaType;
if (value != null && mediaType) {
if (mediaType === "application/json" || mediaType.endsWith("+json")) return LazyJsonString.from(value);
}
return value;
}
if (typeof value === "number" && ns.isNumericSchema()) {
if (Math.abs(value) === Infinity || isNaN(value)) return String(value);
return value;
}
if (typeof value === "string" && ns.isBlobSchema()) {
if (ns === this.rootSchema) return value;
return (this.serdeContext?.base64Encoder ?? import_dist_cjs$26.toBase64)(value);
}
if (typeof value === "bigint") this.useReplacer = true;
if (ns.isDocumentSchema()) if (isObject) {
const out = Array.isArray(value) ? [] : {};
for (const [k, v] of Object.entries(value)) if (v instanceof NumericValue) {
this.useReplacer = true;
out[k] = v;
} else out[k] = this._write(ns, v);
return out;
} else return structuredClone(value);
return value;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonCodec.js
var JsonCodec;
var init_JsonCodec = __esmMin((() => {
init_ConfigurableSerdeContext();
init_JsonShapeDeserializer();
init_JsonShapeSerializer();
JsonCodec = class extends SerdeContextConfig {
settings;
constructor(settings) {
super();
this.settings = settings;
}
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;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJsonRpcProtocol.js
var AwsJsonRpcProtocol;
var init_AwsJsonRpcProtocol = __esmMin((() => {
init_protocols$2();
init_schema();
init_ProtocolLib();
init_JsonCodec();
init_parseJsonBody();
AwsJsonRpcProtocol = class extends RpcProtocol {
serializer;
deserializer;
serviceTarget;
codec;
mixin;
awsQueryCompatible;
constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, jsonCodec }) {
super({ defaultNamespace });
this.serviceTarget = serviceTarget;
this.codec = jsonCodec ?? new JsonCodec({
timestampFormat: {
useTrait: true,
default: 7
},
jsonName: false
});
this.serializer = this.codec.createSerializer();
this.deserializer = this.codec.createDeserializer();
this.awsQueryCompatible = !!awsQueryCompatible;
this.mixin = new ProtocolLib(this.awsQueryCompatible);
}
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}.${operationSchema.name}`
});
if (this.awsQueryCompatible) request.headers["x-amzn-query-mode"] = "true";
if (deref(operationSchema.input) === "unit" || !request.body) request.body = "{}";
return request;
}
getPayloadCodec() {
return this.codec;
}
async handleError(operationSchema, context, response, dataObject, metadata) {
if (this.awsQueryCompatible) this.mixin.setQueryCompatError(dataObject, response);
const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown";
const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata, this.awsQueryCompatible ? this.mixin.findQueryCompatibleError : void 0);
const ns = NormalizedSchema.of(errorSchema);
const message = dataObject.message ?? dataObject.Message ?? "Unknown";
const exception = new ((TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema)) ?? Error)(message);
const output = {};
for (const [name, member] of ns.structIterator()) if (dataObject[name] != null) output[name] = this.codec.createDeserializer().readObject(member, dataObject[name]);
if (this.awsQueryCompatible) this.mixin.queryCompatOutput(dataObject, output);
throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {
$fault: ns.getMergedTraits().error,
message
}, output), dataObject);
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_0Protocol.js
var AwsJson1_0Protocol;
var init_AwsJson1_0Protocol = __esmMin((() => {
init_AwsJsonRpcProtocol();
AwsJson1_0Protocol = class extends AwsJsonRpcProtocol {
constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, jsonCodec }) {
super({
defaultNamespace,
serviceTarget,
awsQueryCompatible,
jsonCodec
});
}
getShapeId() {
return "aws.protocols#awsJson1_0";
}
getJsonRpcVersion() {
return "1.0";
}
getDefaultContentType() {
return "application/x-amz-json-1.0";
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_1Protocol.js
var AwsJson1_1Protocol;
var init_AwsJson1_1Protocol = __esmMin((() => {
init_AwsJsonRpcProtocol();
AwsJson1_1Protocol = class extends AwsJsonRpcProtocol {
constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, jsonCodec }) {
super({
defaultNamespace,
serviceTarget,
awsQueryCompatible,
jsonCodec
});
}
getShapeId() {
return "aws.protocols#awsJson1_1";
}
getJsonRpcVersion() {
return "1.1";
}
getDefaultContentType() {
return "application/x-amz-json-1.1";
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsRestJsonProtocol.js
var AwsRestJsonProtocol;
var init_AwsRestJsonProtocol = __esmMin((() => {
init_protocols$2();
init_schema();
init_ProtocolLib();
init_JsonCodec();
init_parseJsonBody();
AwsRestJsonProtocol = class extends HttpBindingProtocol {
serializer;
deserializer;
codec;
mixin = new ProtocolLib();
constructor({ defaultNamespace }) {
super({ defaultNamespace });
const settings = {
timestampFormat: {
useTrait: true,
default: 7
},
httpBindings: true,
jsonName: true
};
this.codec = new JsonCodec(settings);
this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings);
this.deserializer = new 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 = NormalizedSchema.of(operationSchema.input);
if (!request.headers["content-type"]) {
const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema);
if (contentType) request.headers["content-type"] = contentType;
}
if (request.body == null && request.headers["content-type"] === this.getDefaultContentType()) request.body = "{}";
return request;
}
async deserializeResponse(operationSchema, context, response) {
const output = await super.deserializeResponse(operationSchema, context, response);
const outputSchema = NormalizedSchema.of(operationSchema.output);
for (const [name, member] of outputSchema.structIterator()) if (member.getMemberTraits().httpPayload && !(name in output)) output[name] = null;
return output;
}
async handleError(operationSchema, context, response, dataObject, metadata) {
const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown";
const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata);
const ns = NormalizedSchema.of(errorSchema);
const message = dataObject.message ?? dataObject.Message ?? "Unknown";
const exception = new ((TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema)) ?? Error)(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]);
}
throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {
$fault: ns.getMergedTraits().error,
message
}, output), dataObject);
}
getDefaultContentType() {
return "application/json";
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js
var import_dist_cjs$25, awsExpectUnion;
var init_awsExpectUnion = __esmMin((() => {
import_dist_cjs$25 = require_dist_cjs$41();
awsExpectUnion = (value) => {
if (value == null) return;
if (typeof value === "object" && "__type" in value) delete value.__type;
return (0, import_dist_cjs$25.expectUnion)(value);
};
}));
//#endregion
//#region node_modules/fast-xml-parser/lib/fxp.cjs
var require_fxp = /* @__PURE__ */ __commonJSMin(((exports, module) => {
(() => {
"use strict";
var t = {
d: (e, i) => {
for (var n in i) t.o(i, n) && !t.o(e, n) && Object.defineProperty(e, n, {
enumerable: !0,
get: i[n]
});
},
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: () => Ot,
XMLParser: () => ft,
XMLValidator: () => $t
});
const n = /* @__PURE__ */ new RegExp("^[: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][: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\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");
function s(t, e) {
const i = [];
let n = e.exec(t);
for (; n;) {
const s = [];
s.startIndex = e.lastIndex - n[0].length;
const r = n.length;
for (let t = 0; t < r; t++) s.push(n[t]);
i.push(s), n = e.exec(t);
}
return i;
}
const r = function(t) {
return !(null == n.exec(t));
}, o = [
"hasOwnProperty",
"toString",
"valueOf",
"__defineGetter__",
"__defineSetter__",
"__lookupGetter__",
"__lookupSetter__"
], a = [
"__proto__",
"constructor",
"prototype"
], h = {
allowBooleanAttributes: !1,
unpairedTags: []
};
function l(t, e) {
e = Object.assign({}, h, e);
const i = [];
let n = !1, s = !1;
"" === t[0] && (t = t.substr(1));
for (let r = 0; r < t.length; r++) if ("<" === t[r] && "?" === t[r + 1]) {
if (r += 2, r = u(t, r), r.err) return r;
} else {
if ("<" !== t[r]) {
if (p(t[r])) continue;
return b("InvalidChar", "char '" + t[r] + "' is not expected.", w(t, r));
}
{
let o = r;
if (r++, "!" === t[r]) {
r = c(t, r);
continue;
}
{
let a = !1;
"/" === t[r] && (a = !0, r++);
let h = "";
for (; r < t.length && ">" !== t[r] && " " !== t[r] && " " !== t[r] && "\n" !== t[r] && "\r" !== t[r]; r++) h += t[r];
if (h = h.trim(), "/" === h[h.length - 1] && (h = h.substring(0, h.length - 1), r--), !y(h)) {
let e;
return e = 0 === h.trim().length ? "Invalid space after '<'." : "Tag '" + h + "' is an invalid name.", b("InvalidTag", e, w(t, r));
}
const l = g(t, r);
if (!1 === l) return b("InvalidAttr", "Attributes for '" + h + "' have open quote.", w(t, r));
let d = l.value;
if (r = l.index, "/" === d[d.length - 1]) {
const i = r - d.length;
d = d.substring(0, d.length - 1);
const s = x(d, e);
if (!0 !== s) return b(s.err.code, s.err.msg, w(t, i + s.err.line));
n = !0;
} else if (a) {
if (!l.tagClosed) return b("InvalidTag", "Closing tag '" + h + "' doesn't have proper closing.", w(t, r));
if (d.trim().length > 0) return b("InvalidTag", "Closing tag '" + h + "' can't have attributes or invalid starting.", w(t, o));
if (0 === i.length) return b("InvalidTag", "Closing tag '" + h + "' has not been opened.", w(t, o));
{
const e = i.pop();
if (h !== e.tagName) {
let i = w(t, e.tagStartPos);
return b("InvalidTag", "Expected closing tag '" + e.tagName + "' (opened in line " + i.line + ", col " + i.col + ") instead of closing tag '" + h + "'.", w(t, o));
}
0 == i.length && (s = !0);
}
} else {
const a = x(d, e);
if (!0 !== a) return b(a.err.code, a.err.msg, w(t, r - d.length + a.err.line));
if (!0 === s) return b("InvalidXml", "Multiple possible root nodes found.", w(t, r));
-1 !== e.unpairedTags.indexOf(h) || i.push({
tagName: h,
tagStartPos: o
}), n = !0;
}
for (r++; r < t.length; r++) if ("<" === t[r]) {
if ("!" === t[r + 1]) {
r++, r = c(t, r);
continue;
}
if ("?" !== t[r + 1]) break;
if (r = u(t, ++r), r.err) return r;
} else if ("&" === t[r]) {
const e = N(t, r);
if (-1 == e) return b("InvalidChar", "char '&' is not expected.", w(t, r));
r = e;
} else if (!0 === s && !p(t[r])) return b("InvalidXml", "Extra text at the end", w(t, r));
"<" === t[r] && r--;
}
}
}
return n ? 1 == i.length ? b("InvalidTag", "Unclosed tag '" + i[0].tagName + "'.", w(t, i[0].tagStartPos)) : !(i.length > 0) || b("InvalidXml", "Invalid '" + JSON.stringify(i.map((t) => t.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", {
line: 1,
col: 1
}) : b("InvalidXml", "Start tag expected.", 1);
}
function p(t) {
return " " === t || " " === t || "\n" === t || "\r" === t;
}
function u(t, e) {
const i = e;
for (; e < t.length; e++) if ("?" == t[e] || " " == t[e]) {
const n = t.substr(i, e - i);
if (e > 5 && "xml" === n) return b("InvalidXml", "XML declaration allowed only at the start of the document.", w(t, e));
if ("?" == t[e] && ">" == t[e + 1]) {
e++;
break;
}
continue;
}
return e;
}
function c(t, e) {
if (t.length > e + 5 && "-" === t[e + 1] && "-" === t[e + 2]) {
for (e += 3; e < t.length; e++) if ("-" === t[e] && "-" === t[e + 1] && ">" === 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 i = 1;
for (e += 8; e < t.length; e++) if ("<" === t[e]) i++;
else if (">" === t[e] && (i--, 0 === i)) 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.length; e++) if ("]" === t[e] && "]" === t[e + 1] && ">" === t[e + 2]) {
e += 2;
break;
}
}
return e;
}
const d = "\"", f = "'";
function g(t, e) {
let i = "", n = "", s = !1;
for (; e < t.length; e++) {
if (t[e] === d || t[e] === f) "" === n ? n = t[e] : n !== t[e] || (n = "");
else if (">" === t[e] && "" === n) {
s = !0;
break;
}
i += t[e];
}
return "" === n && {
value: i,
index: e,
tagClosed: s
};
}
const m = /* @__PURE__ */ new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?", "g");
function x(t, e) {
const i = s(t, m), n = {};
for (let t = 0; t < i.length; t++) {
if (0 === i[t][1].length) return b("InvalidAttr", "Attribute '" + i[t][2] + "' has no space in starting.", v(i[t]));
if (void 0 !== i[t][3] && void 0 === i[t][4]) return b("InvalidAttr", "Attribute '" + i[t][2] + "' is without value.", v(i[t]));
if (void 0 === i[t][3] && !e.allowBooleanAttributes) return b("InvalidAttr", "boolean attribute '" + i[t][2] + "' is not allowed.", v(i[t]));
const s = i[t][2];
if (!E(s)) return b("InvalidAttr", "Attribute '" + s + "' is an invalid name.", v(i[t]));
if (Object.prototype.hasOwnProperty.call(n, s)) return b("InvalidAttr", "Attribute '" + s + "' is repeated.", v(i[t]));
n[s] = 1;
}
return !0;
}
function N(t, e) {
if (";" === t[++e]) return -1;
if ("#" === t[e]) return function(t, e) {
let i = /\d/;
for ("x" === t[e] && (e++, i = /[\da-fA-F]/); e < t.length; e++) {
if (";" === t[e]) return e;
if (!t[e].match(i)) break;
}
return -1;
}(t, ++e);
let i = 0;
for (; e < t.length; e++, i++) if (!(t[e].match(/\w/) && i < 20)) {
if (";" === t[e]) break;
return -1;
}
return e;
}
function b(t, e, i) {
return { err: {
code: t,
msg: e,
line: i.line || i,
col: i.col
} };
}
function E(t) {
return r(t);
}
function y(t) {
return r(t);
}
function w(t, e) {
const i = t.substring(0, e).split(/\r?\n/);
return {
line: i.length,
col: i[i.length - 1].length + 1
};
}
function v(t) {
return t.startIndex + t[1].length;
}
const T = (t) => o.includes(t) ? "__" + t : t, P = {
preserveOrder: !1,
attributeNamePrefix: "@_",
attributesGroupName: !1,
textNodeName: "#text",
ignoreAttributes: !0,
removeNSPrefix: !1,
allowBooleanAttributes: !1,
parseTagValue: !0,
parseAttributeValue: !1,
trimValues: !0,
cdataPropName: !1,
numberParseOptions: {
hex: !0,
leadingZeros: !0,
eNotation: !0
},
tagValueProcessor: function(t, e) {
return e;
},
attributeValueProcessor: function(t, e) {
return e;
},
stopNodes: [],
alwaysCreateTextNode: !1,
isArray: () => !1,
commentPropName: !1,
unpairedTags: [],
processEntities: !0,
htmlEntities: !1,
ignoreDeclaration: !1,
ignorePiTags: !1,
transformTagName: !1,
transformAttributeName: !1,
updateTag: function(t, e, i) {
return t;
},
captureMetaData: !1,
maxNestedTags: 100,
strictReservedNames: !0,
jPath: !0,
onDangerousProperty: T
};
function S(t, e) {
if ("string" != typeof t) return;
const i = t.toLowerCase();
if (o.some((t) => i === t.toLowerCase())) throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);
if (a.some((t) => i === t.toLowerCase())) throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);
}
function A(t) {
return "boolean" == typeof t ? {
enabled: t,
maxEntitySize: 1e4,
maxExpansionDepth: 10,
maxTotalExpansions: 1e3,
maxExpandedLength: 1e5,
maxEntityCount: 100,
allowedTags: null,
tagFilter: null
} : "object" == typeof t && null !== t ? {
enabled: !1 !== t.enabled,
maxEntitySize: Math.max(1, t.maxEntitySize ?? 1e4),
maxExpansionDepth: Math.max(1, t.maxExpansionDepth ?? 10),
maxTotalExpansions: Math.max(1, t.maxTotalExpansions ?? 1e3),
maxExpandedLength: Math.max(1, t.maxExpandedLength ?? 1e5),
maxEntityCount: Math.max(1, t.maxEntityCount ?? 100),
allowedTags: t.allowedTags ?? null,
tagFilter: t.tagFilter ?? null
} : A(!0);
}
const C = function(t) {
const e = Object.assign({}, P, t), i = [
{
value: e.attributeNamePrefix,
name: "attributeNamePrefix"
},
{
value: e.attributesGroupName,
name: "attributesGroupName"
},
{
value: e.textNodeName,
name: "textNodeName"
},
{
value: e.cdataPropName,
name: "cdataPropName"
},
{
value: e.commentPropName,
name: "commentPropName"
}
];
for (const { value: t, name: e } of i) t && S(t, e);
return null === e.onDangerousProperty && (e.onDangerousProperty = T), e.processEntities = A(e.processEntities), e.stopNodes && Array.isArray(e.stopNodes) && (e.stopNodes = e.stopNodes.map((t) => "string" == typeof t && t.startsWith("*.") ? ".." + t.substring(2) : t)), e;
};
let O;
O = "function" != typeof Symbol ? "@@xmlMetadata" : Symbol("XML Node Metadata");
class $ {
constructor(t) {
this.tagname = t, this.child = [], this[":@"] = Object.create(null);
}
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][O] = { startIndex: e });
}
static getMetaDataSymbol() {
return O;
}
}
class I {
constructor(t) {
this.suppressValidationErr = !t, this.options = t;
}
readDocType(t, e) {
const i = Object.create(null);
let n = 0;
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 s = 1, r = !1, o = !1, a = "";
for (; e < t.length; e++) if ("<" !== t[e] || o) if (">" === t[e]) {
if (o ? "-" === t[e - 1] && "-" === t[e - 2] && (o = !1, s--) : s--, 0 === s) break;
} else "[" === t[e] ? r = !0 : a += t[e];
else {
if (r && _(t, "!ENTITY", e)) {
let s, r;
if (e += 7, [s, r, e] = this.readEntityExp(t, e + 1, this.suppressValidationErr), -1 === r.indexOf("&")) {
if (!1 !== this.options.enabled && null != this.options.maxEntityCount && n >= this.options.maxEntityCount) throw new Error(`Entity count (${n + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`);
const t = s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
i[s] = {
regx: RegExp(`&${t};`, "g"),
val: r
}, n++;
}
} else if (r && _(t, "!ELEMENT", e)) {
e += 8;
const { index: i } = this.readElementExp(t, e + 1);
e = i;
} else if (r && _(t, "!ATTLIST", e)) e += 8;
else if (r && _(t, "!NOTATION", e)) {
e += 9;
const { index: i } = this.readNotationExp(t, e + 1, this.suppressValidationErr);
e = i;
} else {
if (!_(t, "!--", e)) throw new Error("Invalid DOCTYPE");
o = !0;
}
s++, a = "";
}
if (0 !== s) throw new Error("Unclosed DOCTYPE");
}
return {
entities: i,
i: e
};
}
readEntityExp(t, e) {
const i = e = j(t, e);
for (; e < t.length && !/\s/.test(t[e]) && "\"" !== t[e] && "'" !== t[e];) e++;
let n = t.substring(i, e);
if (D(n), e = j(t, e), !this.suppressValidationErr) {
if ("SYSTEM" === t.substring(e, e + 6).toUpperCase()) throw new Error("External entities are not supported");
if ("%" === t[e]) throw new Error("Parameter entities are not supported");
}
let s = "";
if ([e, s] = this.readIdentifierVal(t, e, "entity"), !1 !== this.options.enabled && null != this.options.maxEntitySize && s.length > this.options.maxEntitySize) throw new Error(`Entity "${n}" size (${s.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);
return [
n,
s,
--e
];
}
readNotationExp(t, e) {
const i = e = j(t, e);
for (; e < t.length && !/\s/.test(t[e]);) e++;
let n = t.substring(i, e);
!this.suppressValidationErr && D(n), e = j(t, e);
const s = t.substring(e, e + 6).toUpperCase();
if (!this.suppressValidationErr && "SYSTEM" !== s && "PUBLIC" !== s) throw new Error(`Expected SYSTEM or PUBLIC, found "${s}"`);
e += s.length, e = j(t, e);
let r = null, o = null;
if ("PUBLIC" === s) [e, r] = this.readIdentifierVal(t, e, "publicIdentifier"), "\"" !== t[e = j(t, e)] && "'" !== t[e] || ([e, o] = this.readIdentifierVal(t, e, "systemIdentifier"));
else if ("SYSTEM" === s && ([e, o] = this.readIdentifierVal(t, e, "systemIdentifier"), !this.suppressValidationErr && !o)) throw new Error("Missing mandatory system identifier for SYSTEM notation");
return {
notationName: n,
publicIdentifier: r,
systemIdentifier: o,
index: --e
};
}
readIdentifierVal(t, e, i) {
let n = "";
const s = t[e];
if ("\"" !== s && "'" !== s) throw new Error(`Expected quoted string, found "${s}"`);
const r = ++e;
for (; e < t.length && t[e] !== s;) e++;
if (n = t.substring(r, e), t[e] !== s) throw new Error(`Unterminated ${i} value`);
return [++e, n];
}
readElementExp(t, e) {
const i = e = j(t, e);
for (; e < t.length && !/\s/.test(t[e]);) e++;
let n = t.substring(i, e);
if (!this.suppressValidationErr && !r(n)) throw new Error(`Invalid element name: "${n}"`);
let s = "";
if ("E" === t[e = j(t, e)] && _(t, "MPTY", e)) e += 4;
else if ("A" === t[e] && _(t, "NY", e)) e += 2;
else if ("(" === t[e]) {
const i = ++e;
for (; e < t.length && ")" !== t[e];) e++;
if (s = t.substring(i, e), ")" !== t[e]) throw new Error("Unterminated content model");
} else if (!this.suppressValidationErr) throw new Error(`Invalid Element Expression, found "${t[e]}"`);
return {
elementName: n,
contentModel: s.trim(),
index: e
};
}
readAttlistExp(t, e) {
let i = e = j(t, e);
for (; e < t.length && !/\s/.test(t[e]);) e++;
let n = t.substring(i, e);
for (D(n), i = e = j(t, e); e < t.length && !/\s/.test(t[e]);) e++;
let s = t.substring(i, e);
if (!D(s)) throw new Error(`Invalid attribute name: "${s}"`);
e = j(t, e);
let r = "";
if ("NOTATION" === t.substring(e, e + 8).toUpperCase()) {
if (r = "NOTATION", "(" !== t[e = j(t, e += 8)]) throw new Error(`Expected '(', found "${t[e]}"`);
e++;
let i = [];
for (; e < t.length && ")" !== t[e];) {
const n = e;
for (; e < t.length && "|" !== t[e] && ")" !== t[e];) e++;
let s = t.substring(n, e);
if (s = s.trim(), !D(s)) throw new Error(`Invalid notation name: "${s}"`);
i.push(s), "|" === t[e] && (e++, e = j(t, e));
}
if (")" !== t[e]) throw new Error("Unterminated list of notations");
e++, r += " (" + i.join("|") + ")";
} else {
const i = e;
for (; e < t.length && !/\s/.test(t[e]);) e++;
r += t.substring(i, e);
if (!this.suppressValidationErr && ![
"CDATA",
"ID",
"IDREF",
"IDREFS",
"ENTITY",
"ENTITIES",
"NMTOKEN",
"NMTOKENS"
].includes(r.toUpperCase())) throw new Error(`Invalid attribute type: "${r}"`);
}
e = j(t, e);
let o = "";
return "#REQUIRED" === t.substring(e, e + 8).toUpperCase() ? (o = "#REQUIRED", e += 8) : "#IMPLIED" === t.substring(e, e + 7).toUpperCase() ? (o = "#IMPLIED", e += 7) : [e, o] = this.readIdentifierVal(t, e, "ATTLIST"), {
elementName: n,
attributeName: s,
attributeType: r,
defaultValue: o,
index: e
};
}
}
const j = (t, e) => {
for (; e < t.length && /\s/.test(t[e]);) e++;
return e;
};
function _(t, e, i) {
for (let n = 0; n < e.length; n++) if (e[n] !== t[i + n + 1]) return !1;
return !0;
}
function D(t) {
if (r(t)) return t;
throw new Error(`Invalid entity name ${t}`);
}
const V = /^[-+]?0x[a-fA-F0-9]+$/, k = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/, M = {
hex: !0,
leadingZeros: !0,
decimalPoint: ".",
eNotation: !0,
infinity: "original"
};
const F = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;
class L {
constructor(t = {}) {
this.separator = t.separator || ".", this.path = [], this.siblingStacks = [];
}
push(t, e = null, i = null) {
this.path.length > 0 && (this.path[this.path.length - 1].values = void 0);
const n = this.path.length;
this.siblingStacks[n] || (this.siblingStacks[n] = /* @__PURE__ */ new Map());
const s = this.siblingStacks[n], r = i ? `${i}:${t}` : t, o = s.get(r) || 0;
let a = 0;
for (const t of s.values()) a += t;
s.set(r, o + 1);
const h = {
tag: t,
position: a,
counter: o
};
null != i && (h.namespace = i), null != e && (h.values = e), this.path.push(h);
}
pop() {
if (0 === this.path.length) return;
const t = this.path.pop();
return this.siblingStacks.length > this.path.length + 1 && (this.siblingStacks.length = this.path.length + 1), t;
}
updateCurrent(t) {
if (this.path.length > 0) {
const e = this.path[this.path.length - 1];
null != t && (e.values = t);
}
}
getCurrentTag() {
return this.path.length > 0 ? this.path[this.path.length - 1].tag : void 0;
}
getCurrentNamespace() {
return this.path.length > 0 ? this.path[this.path.length - 1].namespace : void 0;
}
getAttrValue(t) {
if (0 === this.path.length) return;
return this.path[this.path.length - 1].values?.[t];
}
hasAttr(t) {
if (0 === this.path.length) return !1;
const e = this.path[this.path.length - 1];
return void 0 !== e.values && t in e.values;
}
getPosition() {
return 0 === this.path.length ? -1 : this.path[this.path.length - 1].position ?? 0;
}
getCounter() {
return 0 === this.path.length ? -1 : this.path[this.path.length - 1].counter ?? 0;
}
getIndex() {
return this.getPosition();
}
getDepth() {
return this.path.length;
}
toString(t, e = !0) {
const i = t || this.separator;
return this.path.map((t) => e && t.namespace ? `${t.namespace}:${t.tag}` : t.tag).join(i);
}
toArray() {
return this.path.map((t) => t.tag);
}
reset() {
this.path = [], this.siblingStacks = [];
}
matches(t) {
const e = t.segments;
return 0 !== e.length && (t.hasDeepWildcard() ? this._matchWithDeepWildcard(e) : this._matchSimple(e));
}
_matchSimple(t) {
if (this.path.length !== t.length) return !1;
for (let e = 0; e < t.length; e++) {
const i = t[e], n = this.path[e], s = e === this.path.length - 1;
if (!this._matchSegment(i, n, s)) return !1;
}
return !0;
}
_matchWithDeepWildcard(t) {
let e = this.path.length - 1, i = t.length - 1;
for (; i >= 0 && e >= 0;) {
const n = t[i];
if ("deep-wildcard" === n.type) {
if (i--, i < 0) return !0;
const n = t[i];
let s = !1;
for (let t = e; t >= 0; t--) {
const r = t === this.path.length - 1;
if (this._matchSegment(n, this.path[t], r)) {
e = t - 1, i--, s = !0;
break;
}
}
if (!s) return !1;
} else {
const t = e === this.path.length - 1;
if (!this._matchSegment(n, this.path[e], t)) return !1;
e--, i--;
}
}
return i < 0;
}
_matchSegment(t, e, i) {
if ("*" !== t.tag && t.tag !== e.tag) return !1;
if (void 0 !== t.namespace && "*" !== t.namespace && t.namespace !== e.namespace) return !1;
if (void 0 !== t.attrName) {
if (!i) return !1;
if (!e.values || !(t.attrName in e.values)) return !1;
if (void 0 !== t.attrValue) {
const i = e.values[t.attrName];
if (String(i) !== String(t.attrValue)) return !1;
}
}
if (void 0 !== t.position) {
if (!i) return !1;
const n = e.counter ?? 0;
if ("first" === t.position && 0 !== n) return !1;
if ("odd" === t.position && n % 2 != 1) return !1;
if ("even" === t.position && n % 2 != 0) return !1;
if ("nth" === t.position && n !== t.positionValue) return !1;
}
return !0;
}
snapshot() {
return {
path: this.path.map((t) => ({ ...t })),
siblingStacks: this.siblingStacks.map((t) => new Map(t))
};
}
restore(t) {
this.path = t.path.map((t) => ({ ...t })), this.siblingStacks = t.siblingStacks.map((t) => new Map(t));
}
}
class G {
constructor(t, e = {}) {
this.pattern = t, this.separator = e.separator || ".", this.segments = this._parse(t), this._hasDeepWildcard = this.segments.some((t) => "deep-wildcard" === t.type), this._hasAttributeCondition = this.segments.some((t) => void 0 !== t.attrName), this._hasPositionSelector = this.segments.some((t) => void 0 !== t.position);
}
_parse(t) {
const e = [];
let i = 0, n = "";
for (; i < t.length;) t[i] === this.separator ? i + 1 < t.length && t[i + 1] === this.separator ? (n.trim() && (e.push(this._parseSegment(n.trim())), n = ""), e.push({ type: "deep-wildcard" }), i += 2) : (n.trim() && e.push(this._parseSegment(n.trim())), n = "", i++) : (n += t[i], i++);
return n.trim() && e.push(this._parseSegment(n.trim())), e;
}
_parseSegment(t) {
const e = { type: "tag" };
let i = null, n = t;
const s = t.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);
if (s && (n = s[1] + s[3], s[2])) {
const t = s[2].slice(1, -1);
t && (i = t);
}
let r, o, a = n;
if (n.includes("::")) {
const e = n.indexOf("::");
if (r = n.substring(0, e).trim(), a = n.substring(e + 2).trim(), !r) throw new Error(`Invalid namespace in pattern: ${t}`);
}
let h = null;
if (a.includes(":")) {
const t = a.lastIndexOf(":"), e = a.substring(0, t).trim(), i = a.substring(t + 1).trim();
[
"first",
"last",
"odd",
"even"
].includes(i) || /^nth\(\d+\)$/.test(i) ? (o = e, h = i) : o = a;
} else o = a;
if (!o) throw new Error(`Invalid segment pattern: ${t}`);
if (e.tag = o, r && (e.namespace = r), i) if (i.includes("=")) {
const t = i.indexOf("=");
e.attrName = i.substring(0, t).trim(), e.attrValue = i.substring(t + 1).trim();
} else e.attrName = i.trim();
if (h) {
const t = h.match(/^nth\((\d+)\)$/);
t ? (e.position = "nth", e.positionValue = parseInt(t[1], 10)) : e.position = h;
}
return e;
}
get length() {
return this.segments.length;
}
hasDeepWildcard() {
return this._hasDeepWildcard;
}
hasAttributeCondition() {
return this._hasAttributeCondition;
}
hasPositionSelector() {
return this._hasPositionSelector;
}
toString() {
return this.pattern;
}
}
function R(t, e) {
if (!t) return {};
const i = e.attributesGroupName ? t[e.attributesGroupName] : t;
if (!i) return {};
const n = {};
for (const t in i) t.startsWith(e.attributeNamePrefix) ? n[t.substring(e.attributeNamePrefix.length)] = i[t] : n[t] = i[t];
return n;
}
function U(t) {
if (!t || "string" != typeof t) return;
const e = t.indexOf(":");
if (-1 !== e && e > 0) {
const i = t.substring(0, e);
if ("xmlns" !== i) return i;
}
}
class B {
constructor(t) {
var e;
if (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) => st(e, 10, "&#")
},
num_hex: {
regex: /&#x([0-9a-fA-F]{1,6});/g,
val: (t, e) => st(e, 16, "&#x")
}
}, this.addExternalEntities = W, this.parseXml = Z, this.parseTextData = Y, this.resolveNameSpace = X, this.buildAttributesMap = q, this.isItStopNode = H, this.replaceEntitiesValue = K, this.readStopNodeData = it, this.saveTextToParentTag = Q, this.addChild = J, this.ignoreAttributesFn = "function" == typeof (e = this.options.ignoreAttributes) ? e : Array.isArray(e) ? (t) => {
for (const i of e) {
if ("string" == typeof i && t === i) return !0;
if (i instanceof RegExp && i.test(t)) return !0;
}
} : () => !1, this.entityExpansionCount = 0, this.currentExpandedLength = 0, this.matcher = new L(), this.isCurrentNodeStopNode = !1, this.options.stopNodes && this.options.stopNodes.length > 0) {
this.stopNodeExpressions = [];
for (let t = 0; t < this.options.stopNodes.length; t++) {
const e = this.options.stopNodes[t];
"string" == typeof e ? this.stopNodeExpressions.push(new G(e)) : e instanceof G && this.stopNodeExpressions.push(e);
}
}
}
}
function W(t) {
const e = Object.keys(t);
for (let i = 0; i < e.length; i++) {
const n = e[i], s = n.replace(/[.\-+*:]/g, "\\.");
this.lastEntities[n] = {
regex: new RegExp("&" + s + ";", "g"),
val: t[n]
};
}
}
function Y(t, e, i, n, s, r, o) {
if (void 0 !== t && (this.options.trimValues && !n && (t = t.trim()), t.length > 0)) {
o || (t = this.replaceEntitiesValue(t, e, i));
const n = this.options.jPath ? i.toString() : i, a = this.options.tagValueProcessor(e, t, n, s, r);
return null == a ? t : typeof a != typeof t || a !== t ? a : this.options.trimValues || t.trim() === t ? nt(t, this.options.parseTagValue, this.options.numberParseOptions) : t;
}
}
function X(t) {
if (this.options.removeNSPrefix) {
const e = t.split(":"), i = "/" === t.charAt(0) ? "/" : "";
if ("xmlns" === e[0]) return "";
2 === e.length && (t = i + e[1]);
}
return t;
}
const z = /* @__PURE__ */ new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?", "gm");
function q(t, e, i) {
if (!0 !== this.options.ignoreAttributes && "string" == typeof t) {
const n = s(t, z), r = n.length, o = {}, a = {};
for (let t = 0; t < r; t++) {
const s = this.resolveNameSpace(n[t][1]), r = n[t][4];
if (s.length && void 0 !== r) {
let t = r;
this.options.trimValues && (t = t.trim()), t = this.replaceEntitiesValue(t, i, e), a[s] = t;
}
}
Object.keys(a).length > 0 && "object" == typeof e && e.updateCurrent && e.updateCurrent(a);
for (let t = 0; t < r; t++) {
const s = this.resolveNameSpace(n[t][1]), r = this.options.jPath ? e.toString() : e;
if (this.ignoreAttributesFn(s, r)) continue;
let a = n[t][4], h = this.options.attributeNamePrefix + s;
if (s.length) if (this.options.transformAttributeName && (h = this.options.transformAttributeName(h)), h = ot(h, this.options), void 0 !== a) {
this.options.trimValues && (a = a.trim()), a = this.replaceEntitiesValue(a, i, e);
const t = this.options.jPath ? e.toString() : e, n = this.options.attributeValueProcessor(s, a, t);
o[h] = null == n ? a : typeof n != typeof a || n !== a ? n : nt(a, this.options.parseAttributeValue, this.options.numberParseOptions);
} else this.options.allowBooleanAttributes && (o[h] = !0);
}
if (!Object.keys(o).length) return;
if (this.options.attributesGroupName) {
const t = {};
return t[this.options.attributesGroupName] = o, t;
}
return o;
}
}
const Z = function(t) {
t = t.replace(/\r\n?/g, "\n");
const e = new $("!xml");
let i = e, n = "";
this.matcher.reset(), this.entityExpansionCount = 0, this.currentExpandedLength = 0;
const s = new I(this.options.processEntities);
for (let r = 0; r < t.length; r++) if ("<" === t[r]) if ("/" === t[r + 1]) {
const e = tt(t, ">", r, "Closing Tag is not closed.");
let s = t.substring(r + 2, e).trim();
if (this.options.removeNSPrefix) {
const t = s.indexOf(":");
-1 !== t && (s = s.substr(t + 1));
}
s = rt(this.options.transformTagName, s, "", this.options).tagName, i && (n = this.saveTextToParentTag(n, i, this.matcher));
const o = this.matcher.getCurrentTag();
if (s && -1 !== this.options.unpairedTags.indexOf(s)) throw new Error(`Unpaired tag can not be used as closing tag: </${s}>`);
o && -1 !== this.options.unpairedTags.indexOf(o) && (this.matcher.pop(), this.tagsNodeStack.pop()), this.matcher.pop(), this.isCurrentNodeStopNode = !1, i = this.tagsNodeStack.pop(), n = "", r = e;
} else if ("?" === t[r + 1]) {
let e = et(t, r, !1, "?>");
if (!e) throw new Error("Pi Tag is not closed.");
if (n = this.saveTextToParentTag(n, i, this.matcher), this.options.ignoreDeclaration && "?xml" === e.tagName || this.options.ignorePiTags);
else {
const t = new $(e.tagName);
t.add(this.options.textNodeName, ""), e.tagName !== e.tagExp && e.attrExpPresent && (t[":@"] = this.buildAttributesMap(e.tagExp, this.matcher, e.tagName)), this.addChild(i, t, this.matcher, r);
}
r = e.closeIndex + 1;
} else if ("!--" === t.substr(r + 1, 3)) {
const e = tt(t, "-->", r + 4, "Comment is not closed.");
if (this.options.commentPropName) {
const s = t.substring(r + 4, e - 2);
n = this.saveTextToParentTag(n, i, this.matcher), i.add(this.options.commentPropName, [{ [this.options.textNodeName]: s }]);
}
r = e;
} else if ("!D" === t.substr(r + 1, 2)) {
const e = s.readDocType(t, r);
this.docTypeEntities = e.entities, r = e.i;
} else if ("![" === t.substr(r + 1, 2)) {
const e = tt(t, "]]>", r, "CDATA is not closed.") - 2, s = t.substring(r + 9, e);
n = this.saveTextToParentTag(n, i, this.matcher);
let o = this.parseTextData(s, i.tagname, this.matcher, !0, !1, !0, !0);
o ??= "", this.options.cdataPropName ? i.add(this.options.cdataPropName, [{ [this.options.textNodeName]: s }]) : i.add(this.options.textNodeName, o), r = e + 2;
} else {
let s = et(t, r, this.options.removeNSPrefix);
if (!s) {
const e = t.substring(Math.max(0, r - 50), Math.min(t.length, r + 50));
throw new Error(`readTagExp returned undefined at position ${r}. Context: "${e}"`);
}
let o = s.tagName;
const a = s.rawTagName;
let h = s.tagExp, l = s.attrExpPresent, p = s.closeIndex;
if ({tagName: o, tagExp: h} = rt(this.options.transformTagName, o, h, this.options), this.options.strictReservedNames && (o === this.options.commentPropName || o === this.options.cdataPropName || o === this.options.textNodeName || o === this.options.attributesGroupName)) throw new Error(`Invalid tag name: ${o}`);
i && n && "!xml" !== i.tagname && (n = this.saveTextToParentTag(n, i, this.matcher, !1));
const u = i;
u && -1 !== this.options.unpairedTags.indexOf(u.tagname) && (i = this.tagsNodeStack.pop(), this.matcher.pop());
let c = !1;
h.length > 0 && h.lastIndexOf("/") === h.length - 1 && (c = !0, "/" === o[o.length - 1] ? (o = o.substr(0, o.length - 1), h = o) : h = h.substr(0, h.length - 1), l = o !== h);
let d, f = null;
d = U(a), o !== e.tagname && this.matcher.push(o, {}, d), o !== h && l && (f = this.buildAttributesMap(h, this.matcher, o), f && R(f, this.options)), o !== e.tagname && (this.isCurrentNodeStopNode = this.isItStopNode(this.stopNodeExpressions, this.matcher));
const m = r;
if (this.isCurrentNodeStopNode) {
let e = "";
if (c) r = s.closeIndex;
else if (-1 !== this.options.unpairedTags.indexOf(o)) r = s.closeIndex;
else {
const i = this.readStopNodeData(t, a, p + 1);
if (!i) throw new Error(`Unexpected end of ${a}`);
r = i.i, e = i.tagContent;
}
const n = new $(o);
f && (n[":@"] = f), n.add(this.options.textNodeName, e), this.matcher.pop(), this.isCurrentNodeStopNode = !1, this.addChild(i, n, this.matcher, m);
} else {
if (c) {
({tagName: o, tagExp: h} = rt(this.options.transformTagName, o, h, this.options));
const t = new $(o);
f && (t[":@"] = f), this.addChild(i, t, this.matcher, m), this.matcher.pop(), this.isCurrentNodeStopNode = !1;
} else {
if (-1 !== this.options.unpairedTags.indexOf(o)) {
const t = new $(o);
f && (t[":@"] = f), this.addChild(i, t, this.matcher, m), this.matcher.pop(), this.isCurrentNodeStopNode = !1, r = s.closeIndex;
continue;
}
{
const t = new $(o);
if (this.tagsNodeStack.length > this.options.maxNestedTags) throw new Error("Maximum nested tags exceeded");
this.tagsNodeStack.push(i), f && (t[":@"] = f), this.addChild(i, t, this.matcher, m), i = t;
}
}
n = "", r = p;
}
}
else n += t[r];
return e.child;
};
function J(t, e, i, n) {
this.options.captureMetaData || (n = void 0);
const s = this.options.jPath ? i.toString() : i, r = this.options.updateTag(e.tagname, s, e[":@"]);
!1 === r || ("string" == typeof r ? (e.tagname = r, t.addChild(e, n)) : t.addChild(e, n));
}
function K(t, e, i) {
const n = this.options.processEntities;
if (!n || !n.enabled) return t;
if (n.allowedTags) {
const s = this.options.jPath ? i.toString() : i;
if (!(Array.isArray(n.allowedTags) ? n.allowedTags.includes(e) : n.allowedTags(e, s))) return t;
}
if (n.tagFilter) {
const s = this.options.jPath ? i.toString() : i;
if (!n.tagFilter(e, s)) return t;
}
for (const e of Object.keys(this.docTypeEntities)) {
const i = this.docTypeEntities[e], s = t.match(i.regx);
if (s) {
if (this.entityExpansionCount += s.length, n.maxTotalExpansions && this.entityExpansionCount > n.maxTotalExpansions) throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n.maxTotalExpansions}`);
const e = t.length;
if (t = t.replace(i.regx, i.val), n.maxExpandedLength && (this.currentExpandedLength += t.length - e, this.currentExpandedLength > n.maxExpandedLength)) throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${n.maxExpandedLength}`);
}
}
for (const e of Object.keys(this.lastEntities)) {
const i = this.lastEntities[e], s = t.match(i.regex);
if (s && (this.entityExpansionCount += s.length, n.maxTotalExpansions && this.entityExpansionCount > n.maxTotalExpansions)) throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n.maxTotalExpansions}`);
t = t.replace(i.regex, i.val);
}
if (-1 === t.indexOf("&")) return t;
if (this.options.htmlEntities) for (const e of Object.keys(this.htmlEntities)) {
const i = this.htmlEntities[e], s = t.match(i.regex);
if (s && (this.entityExpansionCount += s.length, n.maxTotalExpansions && this.entityExpansionCount > n.maxTotalExpansions)) throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n.maxTotalExpansions}`);
t = t.replace(i.regex, i.val);
}
return t.replace(this.ampEntity.regex, this.ampEntity.val);
}
function Q(t, e, i, n) {
return t && (void 0 === n && (n = 0 === e.child.length), void 0 !== (t = this.parseTextData(t, e.tagname, i, !1, !!e[":@"] && 0 !== Object.keys(e[":@"]).length, n)) && "" !== t && e.add(this.options.textNodeName, t), t = ""), t;
}
function H(t, e) {
if (!t || 0 === t.length) return !1;
for (let i = 0; i < t.length; i++) if (e.matches(t[i])) return !0;
return !1;
}
function tt(t, e, i, n) {
const s = t.indexOf(e, i);
if (-1 === s) throw new Error(n);
return s + e.length - 1;
}
function et(t, e, i, n = ">") {
const s = function(t, e, i = ">") {
let n, s = "";
for (let r = e; r < t.length; r++) {
let e = t[r];
if (n) e === n && (n = "");
else if ("\"" === e || "'" === e) n = e;
else if (e === i[0]) {
if (!i[1]) return {
data: s,
index: r
};
if (t[r + 1] === i[1]) return {
data: s,
index: r
};
} else " " === e && (e = " ");
s += e;
}
}(t, e + 1, n);
if (!s) return;
let r = s.data;
const o = s.index, a = r.search(/\s/);
let h = r, l = !0;
-1 !== a && (h = r.substring(0, a), r = r.substring(a + 1).trimStart());
const p = h;
if (i) {
const t = h.indexOf(":");
-1 !== t && (h = h.substr(t + 1), l = h !== s.data.substr(t + 1));
}
return {
tagName: h,
tagExp: r,
closeIndex: o,
attrExpPresent: l,
rawTagName: p
};
}
function it(t, e, i) {
const n = i;
let s = 1;
for (; i < t.length; i++) if ("<" === t[i]) if ("/" === t[i + 1]) {
const r = tt(t, ">", i, `${e} is not closed`);
if (t.substring(i + 2, r).trim() === e && (s--, 0 === s)) return {
tagContent: t.substring(n, i),
i: r
};
i = r;
} else if ("?" === t[i + 1]) i = tt(t, "?>", i + 1, "StopNode is not closed.");
else if ("!--" === t.substr(i + 1, 3)) i = tt(t, "-->", i + 3, "StopNode is not closed.");
else if ("![" === t.substr(i + 1, 2)) i = tt(t, "]]>", i, "StopNode is not closed.") - 2;
else {
const n = et(t, i, ">");
n && ((n && n.tagName) === e && "/" !== n.tagExp[n.tagExp.length - 1] && s++, i = n.closeIndex);
}
}
function nt(t, e, i) {
if (e && "string" == typeof t) {
const e = t.trim();
return "true" === e || "false" !== e && function(t, e = {}) {
if (e = Object.assign({}, M, e), !t || "string" != typeof t) return t;
let i = t.trim();
if (void 0 !== e.skipLike && e.skipLike.test(i)) return t;
if ("0" === t) return 0;
if (e.hex && V.test(i)) 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");
}(i);
if (isFinite(i)) {
if (i.includes("e") || i.includes("E")) return function(t, e, i) {
if (!i.eNotation) return t;
const n = e.match(F);
if (n) {
let s = n[1] || "";
const r = -1 === n[3].indexOf("e") ? "E" : "e", o = n[2], a = s ? t[o.length + 1] === r : t[o.length] === r;
return o.length > 1 && a ? t : (1 !== o.length || !n[3].startsWith(`.${r}`) && n[3][0] !== r) && o.length > 0 ? i.leadingZeros && !a ? (e = (n[1] || "") + n[3], Number(e)) : t : Number(e);
}
return t;
}(t, i, e);
{
const s = k.exec(i);
if (s) {
const r = s[1] || "", o = s[2];
let a = (n = s[3]) && -1 !== n.indexOf(".") ? ("." === (n = n.replace(/0+$/, "")) ? n = "0" : "." === n[0] ? n = "0" + n : "." === n[n.length - 1] && (n = n.substring(0, n.length - 1)), n) : n;
const h = r ? "." === t[o.length + 1] : "." === t[o.length];
if (!e.leadingZeros && (o.length > 1 || 1 === o.length && !h)) return t;
{
const n = Number(i), s = String(n);
if (0 === n) return n;
if (-1 !== s.search(/[eE]/)) return e.eNotation ? n : t;
if (-1 !== i.indexOf(".")) return "0" === s || s === a || s === `${r}${a}` ? n : t;
let h = o ? a : i;
return o ? h === s || r + h === s ? n : t : h === s || h === r + s ? n : t;
}
}
return t;
}
}
var n;
return function(t, e, i) {
const n = e === Infinity;
switch (i.infinity.toLowerCase()) {
case "null": return null;
case "infinity": return e;
case "string": return n ? "Infinity" : "-Infinity";
default: return t;
}
}(t, Number(i), e);
}(t, i);
}
return void 0 !== t ? t : "";
}
function st(t, e, i) {
const n = Number.parseInt(t, e);
return n >= 0 && n <= 1114111 ? String.fromCodePoint(n) : i + t + ";";
}
function rt(t, e, i, n) {
if (t) {
const n = t(e);
i === e && (i = n), e = n;
}
return {
tagName: e = ot(e, n),
tagExp: i
};
}
function ot(t, e) {
if (a.includes(t)) throw new Error(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);
return o.includes(t) ? e.onDangerousProperty(t) : t;
}
const at = $.getMetaDataSymbol();
function ht(t, e) {
if (!t || "object" != typeof t) return {};
if (!e) return t;
const i = {};
for (const n in t) n.startsWith(e) ? i[n.substring(e.length)] = t[n] : i[n] = t[n];
return i;
}
function lt(t, e, i) {
return pt(t, e, i);
}
function pt(t, e, i) {
let n;
const s = {};
for (let r = 0; r < t.length; r++) {
const o = t[r], a = ut(o);
if (void 0 !== a && a !== e.textNodeName) {
const t = ht(o[":@"] || {}, e.attributeNamePrefix);
i.push(a, t);
}
if (a === e.textNodeName) void 0 === n ? n = o[a] : n += "" + o[a];
else {
if (void 0 === a) continue;
if (o[a]) {
let t = pt(o[a], e, i);
const n = dt(t, e);
if (o[":@"] ? ct(t, o[":@"], i, e) : 1 !== Object.keys(t).length || void 0 === t[e.textNodeName] || e.alwaysCreateTextNode ? 0 === Object.keys(t).length && (e.alwaysCreateTextNode ? t[e.textNodeName] = "" : t = "") : t = t[e.textNodeName], void 0 !== o[at] && "object" == typeof t && null !== t && (t[at] = o[at]), void 0 !== s[a] && Object.prototype.hasOwnProperty.call(s, a)) Array.isArray(s[a]) || (s[a] = [s[a]]), s[a].push(t);
else {
const r = e.jPath ? i.toString() : i;
e.isArray(a, r, n) ? s[a] = [t] : s[a] = t;
}
void 0 !== a && a !== e.textNodeName && i.pop();
}
}
}
return "string" == typeof n ? n.length > 0 && (s[e.textNodeName] = n) : void 0 !== n && (s[e.textNodeName] = n), s;
}
function ut(t) {
const e = Object.keys(t);
for (let t = 0; t < e.length; t++) {
const i = e[t];
if (":@" !== i) return i;
}
}
function ct(t, e, i, n) {
if (e) {
const s = Object.keys(e), r = s.length;
for (let o = 0; o < r; o++) {
const r = s[o], a = r.startsWith(n.attributeNamePrefix) ? r.substring(n.attributeNamePrefix.length) : r, h = n.jPath ? i.toString() + "." + a : i;
n.isArray(r, h, !0, !0) ? t[r] = [e[r]] : t[r] = e[r];
}
}
}
function dt(t, e) {
const { textNodeName: i } = e, n = Object.keys(t).length;
return 0 === n || !(1 !== n || !t[i] && "boolean" != typeof t[i] && 0 !== t[i]);
}
class ft {
constructor(t) {
this.externalEntities = {}, this.options = C(t);
}
parse(t, e) {
if ("string" != typeof t && t.toString) t = t.toString();
else if ("string" != typeof t) throw new Error("XML data is accepted in String or Bytes[] form.");
if (e) {
!0 === e && (e = {});
const i = l(t, e);
if (!0 !== i) throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`);
}
const i = new B(this.options);
i.addExternalEntities(this.externalEntities);
const n = i.parseXml(t);
return this.options.preserveOrder || void 0 === n ? n : lt(n, this.options, i.matcher);
}
addEntity(t, e) {
if (-1 !== e.indexOf("&")) throw new Error("Entity value can't have '&'");
if (-1 !== t.indexOf("&") || -1 !== t.indexOf(";")) throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");
if ("&" === e) throw new Error("An entity with value '&' is not permitted");
this.externalEntities[t] = e;
}
static getMetaDataSymbol() {
return $.getMetaDataSymbol();
}
}
function gt(t, e) {
let i = "";
e.format && e.indentBy.length > 0 && (i = "\n");
const n = [];
if (e.stopNodes && Array.isArray(e.stopNodes)) for (let t = 0; t < e.stopNodes.length; t++) {
const i = e.stopNodes[t];
"string" == typeof i ? n.push(new G(i)) : i instanceof G && n.push(i);
}
return mt(t, e, i, new L(), n);
}
function mt(t, e, i, n, s) {
let r = "", o = !1;
if (e.maxNestedTags && n.getDepth() > e.maxNestedTags) throw new Error("Maximum nested tags exceeded");
if (!Array.isArray(t)) {
if (null != t) {
let i = t.toString();
return i = vt(i, e), i;
}
return "";
}
for (let a = 0; a < t.length; a++) {
const h = t[a], l = Et(h);
if (void 0 === l) continue;
const p = xt(h[":@"], e);
n.push(l, p);
const u = wt(n, s);
if (l === e.textNodeName) {
let t = h[l];
u || (t = e.tagValueProcessor(l, t), t = vt(t, e)), o && (r += i), r += t, o = !1, n.pop();
continue;
}
if (l === e.cdataPropName) {
o && (r += i), r += `<![CDATA[${h[l][0][e.textNodeName]}]]>`, o = !1, n.pop();
continue;
}
if (l === e.commentPropName) {
r += i + `\x3c!--${h[l][0][e.textNodeName]}--\x3e`, o = !0, n.pop();
continue;
}
if ("?" === l[0]) {
const t = yt(h[":@"], e, u), s = "?xml" === l ? "" : i;
let a = h[l][0][e.textNodeName];
a = 0 !== a.length ? " " + a : "", r += s + `<${l}${a}${t}?>`, o = !0, n.pop();
continue;
}
let c = i;
"" !== c && (c += e.indentBy);
const d = i + `<${l}${yt(h[":@"], e, u)}`;
let f;
f = u ? Nt(h[l], e) : mt(h[l], e, c, n, s), -1 !== e.unpairedTags.indexOf(l) ? e.suppressUnpairedNode ? r += d + ">" : r += d + "/>" : f && 0 !== f.length || !e.suppressEmptyNode ? f && f.endsWith(">") ? r += d + `>${f}${i}</${l}>` : (r += d + ">", f && "" !== i && (f.includes("/>") || f.includes("</")) ? r += i + e.indentBy + f + i : r += f, r += `</${l}>`) : r += d + "/>", o = !0, n.pop();
}
return r;
}
function xt(t, e) {
if (!t || e.ignoreAttributes) return null;
const i = {};
let n = !1;
for (let s in t) Object.prototype.hasOwnProperty.call(t, s) && (i[s.startsWith(e.attributeNamePrefix) ? s.substr(e.attributeNamePrefix.length) : s] = t[s], n = !0);
return n ? i : null;
}
function Nt(t, e) {
if (!Array.isArray(t)) return null != t ? t.toString() : "";
let i = "";
for (let n = 0; n < t.length; n++) {
const s = t[n], r = Et(s);
if (r === e.textNodeName) i += s[r];
else if (r === e.cdataPropName) i += s[r][0][e.textNodeName];
else if (r === e.commentPropName) i += s[r][0][e.textNodeName];
else {
if (r && "?" === r[0]) continue;
if (r) {
const t = bt(s[":@"], e), n = Nt(s[r], e);
n && 0 !== n.length ? i += `<${r}${t}>${n}</${r}>` : i += `<${r}${t}/>`;
}
}
}
return i;
}
function bt(t, e) {
let i = "";
if (t && !e.ignoreAttributes) for (let n in t) {
if (!Object.prototype.hasOwnProperty.call(t, n)) continue;
let s = t[n];
!0 === s && e.suppressBooleanAttributes ? i += ` ${n.substr(e.attributeNamePrefix.length)}` : i += ` ${n.substr(e.attributeNamePrefix.length)}="${s}"`;
}
return i;
}
function Et(t) {
const e = Object.keys(t);
for (let i = 0; i < e.length; i++) {
const n = e[i];
if (Object.prototype.hasOwnProperty.call(t, n) && ":@" !== n) return n;
}
}
function yt(t, e, i) {
let n = "";
if (t && !e.ignoreAttributes) for (let s in t) {
if (!Object.prototype.hasOwnProperty.call(t, s)) continue;
let r;
i ? r = t[s] : (r = e.attributeValueProcessor(s, t[s]), r = vt(r, e)), !0 === r && e.suppressBooleanAttributes ? n += ` ${s.substr(e.attributeNamePrefix.length)}` : n += ` ${s.substr(e.attributeNamePrefix.length)}="${r}"`;
}
return n;
}
function wt(t, e) {
if (!e || 0 === e.length) return !1;
for (let i = 0; i < e.length; i++) if (t.matches(e[i])) return !0;
return !1;
}
function vt(t, e) {
if (t && t.length > 0 && e.processEntities) for (let i = 0; i < e.entities.length; i++) {
const n = e.entities[i];
t = t.replace(n.regex, n.val);
}
return t;
}
const Tt = {
attributeNamePrefix: "@_",
attributesGroupName: !1,
textNodeName: "#text",
ignoreAttributes: !0,
cdataPropName: !1,
format: !1,
indentBy: " ",
suppressEmptyNode: !1,
suppressUnpairedNode: !0,
suppressBooleanAttributes: !0,
tagValueProcessor: function(t, e) {
return e;
},
attributeValueProcessor: function(t, e) {
return e;
},
preserveOrder: !1,
commentPropName: !1,
unpairedTags: [],
entities: [
{
regex: /* @__PURE__ */ new RegExp("&", "g"),
val: "&"
},
{
regex: /* @__PURE__ */ new RegExp(">", "g"),
val: ">"
},
{
regex: /* @__PURE__ */ new RegExp("<", "g"),
val: "<"
},
{
regex: /* @__PURE__ */ new RegExp("'", "g"),
val: "'"
},
{
regex: /* @__PURE__ */ new RegExp("\"", "g"),
val: """
}
],
processEntities: !0,
stopNodes: [],
oneListGroup: !1,
maxNestedTags: 100,
jPath: !0
};
function Pt(t) {
if (this.options = Object.assign({}, Tt, t), this.options.stopNodes && Array.isArray(this.options.stopNodes) && (this.options.stopNodes = this.options.stopNodes.map((t) => "string" == typeof t && t.startsWith("*.") ? ".." + t.substring(2) : t)), this.stopNodeExpressions = [], this.options.stopNodes && Array.isArray(this.options.stopNodes)) for (let t = 0; t < this.options.stopNodes.length; t++) {
const e = this.options.stopNodes[t];
"string" == typeof e ? this.stopNodeExpressions.push(new G(e)) : e instanceof G && this.stopNodeExpressions.push(e);
}
var e;
!0 === this.options.ignoreAttributes || this.options.attributesGroupName ? this.isAttribute = function() {
return !1;
} : (this.ignoreAttributesFn = "function" == typeof (e = this.options.ignoreAttributes) ? e : Array.isArray(e) ? (t) => {
for (const i of e) {
if ("string" == typeof i && t === i) return !0;
if (i instanceof RegExp && i.test(t)) return !0;
}
} : () => !1, this.attrPrefixLen = this.options.attributeNamePrefix.length, this.isAttribute = Ct), this.processTextOrObjNode = St, this.options.format ? (this.indentate = At, this.tagEndChar = ">\n", this.newLine = "\n") : (this.indentate = function() {
return "";
}, this.tagEndChar = ">", this.newLine = "");
}
function St(t, e, i, n) {
const s = this.extractAttributes(t);
if (n.push(e, s), this.checkStopNode(n)) {
const s = this.buildRawContent(t), r = this.buildAttributesForStopNode(t);
return n.pop(), this.buildObjectNode(s, e, r, i);
}
const r = this.j2x(t, i + 1, n);
return n.pop(), void 0 !== t[this.options.textNodeName] && 1 === Object.keys(t).length ? this.buildTextValNode(t[this.options.textNodeName], e, r.attrStr, i, n) : this.buildObjectNode(r.val, e, r.attrStr, i);
}
function At(t) {
return this.options.indentBy.repeat(t);
}
function Ct(t) {
return !(!t.startsWith(this.options.attributeNamePrefix) || t === this.options.textNodeName) && t.substr(this.attrPrefixLen);
}
Pt.prototype.build = function(t) {
if (this.options.preserveOrder) return gt(t, this.options);
{
Array.isArray(t) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1 && (t = { [this.options.arrayNodeName]: t });
const e = new L();
return this.j2x(t, 0, e).val;
}
}, Pt.prototype.j2x = function(t, e, i) {
let n = "", s = "";
if (this.options.maxNestedTags && i.getDepth() >= this.options.maxNestedTags) throw new Error("Maximum nested tags exceeded");
const r = this.options.jPath ? i.toString() : i, o = this.checkStopNode(i);
for (let a in t) if (Object.prototype.hasOwnProperty.call(t, a)) if (void 0 === t[a]) this.isAttribute(a) && (s += "");
else if (null === t[a]) this.isAttribute(a) || a === this.options.cdataPropName ? s += "" : "?" === a[0] ? s += this.indentate(e) + "<" + a + "?" + this.tagEndChar : s += this.indentate(e) + "<" + a + "/" + this.tagEndChar;
else if (t[a] instanceof Date) s += this.buildTextValNode(t[a], a, "", e, i);
else if ("object" != typeof t[a]) {
const h = this.isAttribute(a);
if (h && !this.ignoreAttributesFn(h, r)) n += this.buildAttrPairStr(h, "" + t[a], o);
else if (!h) if (a === this.options.textNodeName) {
let e = this.options.tagValueProcessor(a, "" + t[a]);
s += this.replaceEntitiesValue(e);
} else {
i.push(a);
const n = this.checkStopNode(i);
if (i.pop(), n) {
const i = "" + t[a];
s += "" === i ? this.indentate(e) + "<" + a + this.closeTag(a) + this.tagEndChar : this.indentate(e) + "<" + a + ">" + i + "</" + a + this.tagEndChar;
} else s += this.buildTextValNode(t[a], a, "", e, i);
}
} else if (Array.isArray(t[a])) {
const n = t[a].length;
let r = "", o = "";
for (let h = 0; h < n; h++) {
const n = t[a][h];
if (void 0 === n);
else if (null === n) "?" === a[0] ? s += this.indentate(e) + "<" + a + "?" + this.tagEndChar : s += this.indentate(e) + "<" + a + "/" + this.tagEndChar;
else if ("object" == typeof n) if (this.options.oneListGroup) {
i.push(a);
const t = this.j2x(n, e + 1, i);
i.pop(), r += t.val, this.options.attributesGroupName && n.hasOwnProperty(this.options.attributesGroupName) && (o += t.attrStr);
} else r += this.processTextOrObjNode(n, a, e, i);
else if (this.options.oneListGroup) {
let t = this.options.tagValueProcessor(a, n);
t = this.replaceEntitiesValue(t), r += t;
} else {
i.push(a);
const t = this.checkStopNode(i);
if (i.pop(), t) {
const t = "" + n;
r += "" === t ? this.indentate(e) + "<" + a + this.closeTag(a) + this.tagEndChar : this.indentate(e) + "<" + a + ">" + t + "</" + a + this.tagEndChar;
} else r += this.buildTextValNode(n, a, "", e, i);
}
}
this.options.oneListGroup && (r = this.buildObjectNode(r, a, o, e)), s += r;
} else if (this.options.attributesGroupName && a === this.options.attributesGroupName) {
const e = Object.keys(t[a]), i = e.length;
for (let s = 0; s < i; s++) n += this.buildAttrPairStr(e[s], "" + t[a][e[s]], o);
} else s += this.processTextOrObjNode(t[a], a, e, i);
return {
attrStr: n,
val: s
};
}, Pt.prototype.buildAttrPairStr = function(t, e, i) {
return i || (e = this.options.attributeValueProcessor(t, "" + e), e = this.replaceEntitiesValue(e)), this.options.suppressBooleanAttributes && "true" === e ? " " + t : " " + t + "=\"" + e + "\"";
}, Pt.prototype.extractAttributes = function(t) {
if (!t || "object" != typeof t) return null;
const e = {};
let i = !1;
if (this.options.attributesGroupName && t[this.options.attributesGroupName]) {
const n = t[this.options.attributesGroupName];
for (let t in n) Object.prototype.hasOwnProperty.call(n, t) && (e[t.startsWith(this.options.attributeNamePrefix) ? t.substring(this.options.attributeNamePrefix.length) : t] = n[t], i = !0);
} else for (let n in t) {
if (!Object.prototype.hasOwnProperty.call(t, n)) continue;
const s = this.isAttribute(n);
s && (e[s] = t[n], i = !0);
}
return i ? e : null;
}, Pt.prototype.buildRawContent = function(t) {
if ("string" == typeof t) return t;
if ("object" != typeof t || null === t) return String(t);
if (void 0 !== t[this.options.textNodeName]) return t[this.options.textNodeName];
let e = "";
for (let i in t) {
if (!Object.prototype.hasOwnProperty.call(t, i)) continue;
if (this.isAttribute(i)) continue;
if (this.options.attributesGroupName && i === this.options.attributesGroupName) continue;
const n = t[i];
if (i === this.options.textNodeName) e += n;
else if (Array.isArray(n)) {
for (let t of n) if ("string" == typeof t || "number" == typeof t) e += `<${i}>${t}</${i}>`;
else if ("object" == typeof t && null !== t) {
const n = this.buildRawContent(t), s = this.buildAttributesForStopNode(t);
e += "" === n ? `<${i}${s}/>` : `<${i}${s}>${n}</${i}>`;
}
} else if ("object" == typeof n && null !== n) {
const t = this.buildRawContent(n), s = this.buildAttributesForStopNode(n);
e += "" === t ? `<${i}${s}/>` : `<${i}${s}>${t}</${i}>`;
} else e += `<${i}>${n}</${i}>`;
}
return e;
}, Pt.prototype.buildAttributesForStopNode = function(t) {
if (!t || "object" != typeof t) return "";
let e = "";
if (this.options.attributesGroupName && t[this.options.attributesGroupName]) {
const i = t[this.options.attributesGroupName];
for (let t in i) {
if (!Object.prototype.hasOwnProperty.call(i, t)) continue;
const n = t.startsWith(this.options.attributeNamePrefix) ? t.substring(this.options.attributeNamePrefix.length) : t, s = i[t];
!0 === s && this.options.suppressBooleanAttributes ? e += " " + n : e += " " + n + "=\"" + s + "\"";
}
} else for (let i in t) {
if (!Object.prototype.hasOwnProperty.call(t, i)) continue;
const n = this.isAttribute(i);
if (n) {
const s = t[i];
!0 === s && this.options.suppressBooleanAttributes ? e += " " + n : e += " " + n + "=\"" + s + "\"";
}
}
return e;
}, Pt.prototype.buildObjectNode = function(t, e, i, n) {
if ("" === t) return "?" === e[0] ? this.indentate(n) + "<" + e + i + "?" + this.tagEndChar : this.indentate(n) + "<" + e + i + this.closeTag(e) + this.tagEndChar;
{
let s = "</" + e + this.tagEndChar, r = "";
return "?" === e[0] && (r = "?", s = ""), !i && "" !== i || -1 !== t.indexOf("<") ? !1 !== this.options.commentPropName && e === this.options.commentPropName && 0 === r.length ? this.indentate(n) + `\x3c!--${t}--\x3e` + this.newLine : this.indentate(n) + "<" + e + i + r + this.tagEndChar + t + this.indentate(n) + s : this.indentate(n) + "<" + e + i + r + ">" + t + s;
}
}, Pt.prototype.closeTag = function(t) {
let e = "";
return -1 !== this.options.unpairedTags.indexOf(t) ? this.options.suppressUnpairedNode || (e = "/") : e = this.options.suppressEmptyNode ? "/" : `></${t}`, e;
}, Pt.prototype.checkStopNode = function(t) {
if (!this.stopNodeExpressions || 0 === this.stopNodeExpressions.length) return !1;
for (let e = 0; e < this.stopNodeExpressions.length; e++) if (t.matches(this.stopNodeExpressions[e])) return !0;
return !1;
}, Pt.prototype.buildTextValNode = function(t, e, i, n, s) {
if (!1 !== this.options.cdataPropName && e === this.options.cdataPropName) return this.indentate(n) + `<![CDATA[${t}]]>` + this.newLine;
if (!1 !== this.options.commentPropName && e === this.options.commentPropName) return this.indentate(n) + `\x3c!--${t}--\x3e` + this.newLine;
if ("?" === e[0]) return this.indentate(n) + "<" + e + i + "?" + this.tagEndChar;
{
let s = this.options.tagValueProcessor(e, t);
return s = this.replaceEntitiesValue(s), "" === s ? this.indentate(n) + "<" + e + i + this.closeTag(e) + this.tagEndChar : this.indentate(n) + "<" + e + i + ">" + s + "</" + e + this.tagEndChar;
}
}, Pt.prototype.replaceEntitiesValue = function(t) {
if (t && t.length > 0 && this.options.processEntities) for (let e = 0; e < this.options.entities.length; e++) {
const i = this.options.entities[e];
t = t.replace(i.regex, i.val);
}
return t;
};
const Ot = Pt, $t = { validate: l };
module.exports = e;
})();
}));
//#endregion
//#region node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js
var require_xml_parser = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseXML = parseXML;
const parser = new (require_fxp()).XMLParser({
attributeNamePrefix: "",
processEntities: {
enabled: true,
maxTotalExpansions: Infinity
},
htmlEntities: true,
ignoreAttributes: false,
ignoreDeclaration: true,
parseTagValue: false,
trimValues: false,
tagValueProcessor: (_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0,
maxNestedTags: Infinity
});
parser.addEntity("#xD", "\r");
parser.addEntity("#10", "\n");
function parseXML(xmlString) {
return parser.parse(xmlString, true);
}
}));
//#endregion
//#region node_modules/@aws-sdk/xml-builder/dist-cjs/index.js
var require_dist_cjs$26 = /* @__PURE__ */ __commonJSMin(((exports) => {
var xmlParser = require_xml_parser();
const ATTR_ESCAPE_RE = /[&<>"]/g;
const ATTR_ESCAPE_MAP = {
"&": "&",
"<": "<",
">": ">",
"\"": """
};
function escapeAttribute(value) {
return value.replace(ATTR_ESCAPE_RE, (ch) => ATTR_ESCAPE_MAP[ch]);
}
const ELEMENT_ESCAPE_RE = /[&"'<>\r\n\u0085\u2028]/g;
const ELEMENT_ESCAPE_MAP = {
"&": "&",
"\"": """,
"'": "'",
"<": "<",
">": ">",
"\r": "
",
"\n": "
",
"
": "…",
"\u2028": "
"
};
function escapeElement(value) {
return value.replace(ELEMENT_ESCAPE_RE, (ch) => ELEMENT_ESCAPE_MAP[ch]);
}
var XmlText = class {
value;
constructor(value) {
this.value = value;
}
toString() {
return escapeElement("" + this.value);
}
};
var XmlNode = class XmlNode {
name;
children;
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;
}
constructor(name, children = []) {
this.name = name;
this.children = children;
}
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;
}
n(name) {
this.name = name;
return this;
}
c(child) {
this.children.push(child);
return this;
}
a(name, value) {
if (value != null) this.attributes[name] = value;
return this;
}
cc(input, field, withName = field) {
if (input[field] != null) {
const node = XmlNode.of(field, input[field]).withName(withName);
this.c(node);
}
}
l(input, listName, memberName, valueProvider) {
if (input[listName] != null) valueProvider().map((node) => {
node.withName(memberName);
this.c(node);
});
}
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("")}</${this.name}>`;
}
};
exports.parseXML = xmlParser.parseXML;
exports.XmlNode = XmlNode;
exports.XmlText = XmlText;
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeDeserializer.js
var import_dist_cjs$22, import_dist_cjs$23, import_dist_cjs$24, XmlShapeDeserializer;
var init_XmlShapeDeserializer = __esmMin((() => {
import_dist_cjs$22 = require_dist_cjs$26();
init_protocols$2();
init_schema();
import_dist_cjs$23 = require_dist_cjs$41();
import_dist_cjs$24 = require_dist_cjs$42();
init_ConfigurableSerdeContext();
init_UnionSerde();
XmlShapeDeserializer = class extends SerdeContextConfig {
settings;
stringDeserializer;
constructor(settings) {
super();
this.settings = settings;
this.stringDeserializer = new FromStringShapeDeserializer(settings);
}
setSerdeContext(serdeContext) {
this.serdeContext = serdeContext;
this.stringDeserializer.setSerdeContext(serdeContext);
}
read(schema, bytes, key) {
const ns = NormalizedSchema.of(schema);
const memberSchemas = ns.getMemberSchemas();
if (ns.isStructSchema() && ns.isMemberSchema() && !!Object.values(memberSchemas).find((memberNs) => {
return !!memberNs.getMemberTraits().eventPayload;
})) {
const output = {};
const memberName = Object.keys(memberSchemas)[0];
if (memberSchemas[memberName].isBlobSchema()) output[memberName] = bytes;
else output[memberName] = this.read(memberSchemas[memberName], bytes);
return output;
}
const xmlString = (this.serdeContext?.utf8Encoder ?? import_dist_cjs$24.toUtf8)(bytes);
const parsedObject = this.parseXml(xmlString);
return this.readSchema(schema, key ? parsedObject[key] : parsedObject);
}
readSchema(_schema, value) {
const ns = NormalizedSchema.of(_schema);
if (ns.isUnitSchema()) return;
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 flat = !!traits.xmlFlattened;
if (ns.isListSchema()) {
const listValue = ns.getValueSchema();
const buffer = [];
const sourceKey = listValue.getMergedTraits().xmlName ?? "member";
const source = flat ? value : (value[0] ?? value)[sourceKey];
if (source == null) return buffer;
const sourceArray = Array.isArray(source) ? source : [source];
for (const v of sourceArray) buffer.push(this.readSchema(listValue, v));
return buffer;
}
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 value = entry[valueProperty];
buffer[key] = this.readSchema(memberNs, value);
}
return buffer;
}
if (ns.isStructSchema()) {
const union = ns.isUnionSchema();
let unionSerde;
if (union) unionSerde = new UnionSerde(value, buffer);
for (const [memberName, memberSchema] of ns.structIterator()) {
const memberTraits = memberSchema.getMergedTraits();
const xmlObjectKey = !memberTraits.httpPayload ? memberSchema.getMemberTraits().xmlName ?? memberName : memberTraits.xmlName ?? memberSchema.getName();
if (union) unionSerde.mark(xmlObjectKey);
if (value[xmlObjectKey] != null) buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]);
}
if (union) unionSerde.writeUnknown();
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) {
let parsedObj;
try {
parsedObj = (0, import_dist_cjs$22.parseXML)(xml);
} 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_dist_cjs$23.getValueFromTextNode)(parsedObjToReturn);
}
return {};
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/QueryShapeSerializer.js
var import_dist_cjs$20, import_dist_cjs$21, QueryShapeSerializer;
var init_QueryShapeSerializer = __esmMin((() => {
init_protocols$2();
init_schema();
init_serde();
import_dist_cjs$20 = require_dist_cjs$41();
import_dist_cjs$21 = require_dist_cjs$37();
init_ConfigurableSerdeContext();
QueryShapeSerializer = class extends SerdeContextConfig {
settings;
buffer;
constructor(settings) {
super();
this.settings = settings;
}
write(schema, value, prefix = "") {
if (this.buffer === void 0) this.buffer = "";
const ns = 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_dist_cjs$21.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_dist_cjs$45.v4)());
}
} 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 NumericValue ? value.string : String(value));
}
} else if (ns.isTimestampSchema()) {
if (value instanceof Date) {
this.writeKey(prefix);
switch (determineTimestampFormat(ns, this.settings)) {
case 5:
this.writeValue(value.toISOString().replace(".000Z", "Z"));
break;
case 6:
this.writeValue((0, import_dist_cjs$20.dateToUtcString)(value));
break;
case 7:
this.writeValue(String(value.getTime() / 1e3));
break;
}
}
} else if (ns.isDocumentSchema()) if (Array.isArray(value)) this.write(79, value, prefix);
else if (value instanceof Date) this.write(4, value, prefix);
else if (value instanceof Uint8Array) this.write(21, value, prefix);
else if (value && typeof value === "object") this.write(143, value, prefix);
else {
this.writeKey(prefix);
this.writeValue(String(value));
}
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 traits = member.getMergedTraits();
const suffix = this.getKey("member", traits.xmlName, traits.ec2QueryName);
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 keyTraits = keySchema.getMergedTraits();
const keySuffix = this.getKey("key", keyTraits.xmlName, keyTraits.ec2QueryName);
const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`;
const valTraits = memberSchema.getMergedTraits();
const valueSuffix = this.getKey("value", valTraits.xmlName, valTraits.ec2QueryName);
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") {
let didWriteMember = false;
for (const [memberName, member] of ns.structIterator()) {
if (value[memberName] == null && !member.isIdempotencyToken()) continue;
const traits = member.getMergedTraits();
const suffix = this.getKey(memberName, traits.xmlName, traits.ec2QueryName, "struct");
const key = `${prefix}${suffix}`;
this.write(member, value[memberName], key);
didWriteMember = true;
}
if (!didWriteMember && ns.isUnionSchema()) {
const { $unknown } = value;
if (Array.isArray($unknown)) {
const [k, v] = $unknown;
const key = `${prefix}${k}`;
this.write(15, v, 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, ec2QueryName, keySource) {
const { ec2, capitalizeKeys } = this.settings;
if (ec2 && ec2QueryName) return ec2QueryName;
const key = xmlName ?? memberName;
if (capitalizeKeys && keySource === "struct") return key[0].toUpperCase() + key.slice(1);
return key;
}
writeKey(key) {
if (key.endsWith(".")) key = key.slice(0, key.length - 1);
this.buffer += `&${extendedEncodeURIComponent$1(key)}=`;
}
writeValue(value) {
this.buffer += extendedEncodeURIComponent$1(value);
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsQueryProtocol.js
var AwsQueryProtocol;
var init_AwsQueryProtocol = __esmMin((() => {
init_protocols$2();
init_schema();
init_ProtocolLib();
init_XmlShapeDeserializer();
init_QueryShapeSerializer();
AwsQueryProtocol = class extends RpcProtocol {
options;
serializer;
deserializer;
mixin = new ProtocolLib();
constructor(options) {
super({ defaultNamespace: options.defaultNamespace });
this.options = options;
const settings = {
timestampFormat: {
useTrait: true,
default: 5
},
httpBindings: false,
xmlNamespace: options.xmlNamespace,
serviceNamespace: options.defaultNamespace,
serializeEmptyLists: true
};
this.serializer = new QueryShapeSerializer(settings);
this.deserializer = new XmlShapeDeserializer(settings);
}
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 (deref(operationSchema.input) === "unit" || !request.body) request.body = "";
request.body = `Action=${operationSchema.name.split("#")[1] ?? operationSchema.name}&Version=${this.options.version}` + request.body;
if (request.body.endsWith("&")) request.body = request.body.slice(-1);
return request;
}
async deserializeResponse(operationSchema, context, response) {
const deserializer = this.deserializer;
const ns = NormalizedSchema.of(operationSchema.output);
const dataObject = {};
if (response.statusCode >= 300) {
const bytes = await collectBody$1(response.body, context);
if (bytes.byteLength > 0) Object.assign(dataObject, await deserializer.read(15, bytes));
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 shortName = operationSchema.name.split("#")[1] ?? operationSchema.name;
const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : void 0;
const bytes = await collectBody$1(response.body, context);
if (bytes.byteLength > 0) Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey));
return {
$metadata: this.deserializeMetadata(response),
...dataObject
};
}
useNestedResult() {
return true;
}
async handleError(operationSchema, context, response, dataObject, metadata) {
const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown";
const errorData = this.loadQueryError(dataObject) ?? {};
const message = this.loadQueryErrorMessage(dataObject);
errorData.message = message;
errorData.Error = {
Type: errorData.Type,
Code: errorData.Code,
Message: message
};
const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, errorData, metadata, this.mixin.findQueryCompatibleError);
const ns = NormalizedSchema.of(errorSchema);
const exception = new ((TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema)) ?? Error)(message);
const output = {
Type: errorData.Error.Type,
Code: errorData.Error.Code,
Error: errorData.Error
};
for (const [name, member] of ns.structIterator()) {
const target = member.getMergedTraits().xmlName ?? name;
const value = errorData[target] ?? dataObject[target];
output[name] = this.deserializer.readSchema(member, value);
}
throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {
$fault: ns.getMergedTraits().error,
message
}, output), dataObject);
}
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";
}
getDefaultContentType() {
return "application/x-www-form-urlencoded";
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsEc2QueryProtocol.js
var AwsEc2QueryProtocol;
var init_AwsEc2QueryProtocol = __esmMin((() => {
init_AwsQueryProtocol();
AwsEc2QueryProtocol = class extends AwsQueryProtocol {
options;
constructor(options) {
super(options);
this.options = options;
Object.assign(this.serializer.settings, {
capitalizeKeys: true,
flattenLists: true,
serializeEmptyLists: false,
ec2: true
});
}
getShapeId() {
return "aws.protocols#ec2Query";
}
useNestedResult() {
return false;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/QuerySerializerSettings.js
var init_QuerySerializerSettings = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js
var import_dist_cjs$18, import_dist_cjs$19, parseXmlBody, parseXmlErrorBody, loadRestXmlErrorCode;
var init_parseXmlBody = __esmMin((() => {
import_dist_cjs$18 = require_dist_cjs$26();
import_dist_cjs$19 = require_dist_cjs$41();
init_common();
parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
if (encoded.length) {
let parsedObj;
try {
parsedObj = (0, import_dist_cjs$18.parseXML)(encoded);
} 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_dist_cjs$19.getValueFromTextNode)(parsedObjToReturn);
}
return {};
});
parseXmlErrorBody = async (errorBody, context) => {
const value = await parseXmlBody(errorBody, context);
if (value.Error) value.Error.message = value.Error.message ?? value.Error.Message;
return value;
};
loadRestXmlErrorCode = (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";
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeSerializer.js
var import_dist_cjs$15, import_dist_cjs$16, import_dist_cjs$17, XmlShapeSerializer;
var init_XmlShapeSerializer = __esmMin((() => {
import_dist_cjs$15 = require_dist_cjs$26();
init_protocols$2();
init_schema();
init_serde();
import_dist_cjs$16 = require_dist_cjs$41();
import_dist_cjs$17 = require_dist_cjs$37();
init_ConfigurableSerdeContext();
XmlShapeSerializer = class extends SerdeContextConfig {
settings;
stringBuffer;
byteBuffer;
buffer;
constructor(settings) {
super();
this.settings = settings;
}
write(schema, value) {
const ns = 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_dist_cjs$17.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_dist_cjs$15.XmlNode.of(name);
const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns);
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_dist_cjs$15.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName());
this.writeSimpleInto(memberSchema, val, memberNode, xmlns);
structXmlNode.addChildNode(memberNode);
}
}
}
const { $unknown } = value;
if ($unknown && ns.isUnionSchema() && Array.isArray($unknown) && Object.keys(value).length === 1) {
const [k, v] = $unknown;
const node = import_dist_cjs$15.XmlNode.of(k);
if (typeof v !== "string") if (value instanceof import_dist_cjs$15.XmlNode || value instanceof import_dist_cjs$15.XmlText) structXmlNode.addChildNode(value);
else throw new Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");
this.writeSimpleInto(0, v, node, xmlns);
structXmlNode.addChildNode(node);
}
if (xmlns) structXmlNode.addAttribute(xmlnsAttr, xmlns);
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 = (container, value) => {
if (listValueSchema.isListSchema()) this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container, xmlns);
else if (listValueSchema.isMapSchema()) this.writeMap(listValueSchema, value, container, xmlns);
else if (listValueSchema.isStructSchema()) {
const struct = this.writeStruct(listValueSchema, value, xmlns);
container.addChildNode(struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member"));
} else {
const listItemNode = import_dist_cjs$15.XmlNode.of(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member");
this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns);
container.addChildNode(listItemNode);
}
};
if (flat) {
for (const value of array) if (sparse || value != null) writeItem(container, value);
} else {
const listNode = import_dist_cjs$15.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 keyTag = mapKeySchema.getMergedTraits().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 = (entry, key, val) => {
const keyNode = import_dist_cjs$15.XmlNode.of(keyTag, key);
const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns);
if (keyXmlns) keyNode.addAttribute(keyXmlnsAttr, keyXmlns);
entry.addChildNode(keyNode);
let valueNode = import_dist_cjs$15.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);
};
if (flat) {
for (const [key, val] of Object.entries(map)) if (sparse || val != null) {
const entry = import_dist_cjs$15.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName());
addKeyValue(entry, key, val);
container.addChildNode(entry);
}
} else {
let mapNode;
if (!containerIsMap) {
mapNode = import_dist_cjs$15.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_dist_cjs$15.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 = NormalizedSchema.of(_schema);
let nodeContents = null;
if (value && typeof value === "object") if (ns.isBlobSchema()) nodeContents = (this.serdeContext?.base64Encoder ?? import_dist_cjs$17.toBase64)(value);
else if (ns.isTimestampSchema() && value instanceof Date) switch (determineTimestampFormat(ns, this.settings)) {
case 5:
nodeContents = value.toISOString().replace(".000Z", "Z");
break;
case 6:
nodeContents = (0, import_dist_cjs$16.dateToUtcString)(value);
break;
case 7:
nodeContents = String(value.getTime() / 1e3);
break;
default:
console.warn("Missing timestamp format, using http date", value);
nodeContents = (0, import_dist_cjs$16.dateToUtcString)(value);
break;
}
else if (ns.isBigDecimalSchema() && value) {
if (value instanceof 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_dist_cjs$45.v4)();
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 = NormalizedSchema.of(_schema);
const content = new import_dist_cjs$15.XmlText(nodeContents);
const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns);
if (xmlns) into.addAttribute(xmlnsAttr, xmlns);
into.addChildNode(content);
}
getXmlnsAttribute(ns, parentXmlns) {
const [prefix, xmlns] = ns.getMergedTraits().xmlNamespace ?? [];
if (xmlns && xmlns !== parentXmlns) return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns];
return [void 0, void 0];
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlCodec.js
var XmlCodec;
var init_XmlCodec = __esmMin((() => {
init_ConfigurableSerdeContext();
init_XmlShapeDeserializer();
init_XmlShapeSerializer();
XmlCodec = class extends SerdeContextConfig {
settings;
constructor(settings) {
super();
this.settings = settings;
}
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;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/AwsRestXmlProtocol.js
var AwsRestXmlProtocol;
var init_AwsRestXmlProtocol = __esmMin((() => {
init_protocols$2();
init_schema();
init_ProtocolLib();
init_parseXmlBody();
init_XmlCodec();
AwsRestXmlProtocol = class extends HttpBindingProtocol {
codec;
serializer;
deserializer;
mixin = new ProtocolLib();
constructor(options) {
super(options);
const settings = {
timestampFormat: {
useTrait: true,
default: 5
},
httpBindings: true,
xmlNamespace: options.xmlNamespace,
serviceNamespace: options.defaultNamespace
};
this.codec = new XmlCodec(settings);
this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings);
this.deserializer = new 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 inputSchema = NormalizedSchema.of(operationSchema.input);
if (!request.headers["content-type"]) {
const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema);
if (contentType) request.headers["content-type"] = contentType;
}
if (typeof request.body === "string" && request.headers["content-type"] === this.getDefaultContentType() && !request.body.startsWith("<?xml ") && !this.hasUnstructuredPayloadBinding(inputSchema)) request.body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + request.body;
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";
if (dataObject.Error && typeof dataObject.Error === "object") for (const key of Object.keys(dataObject.Error)) {
dataObject[key] = dataObject.Error[key];
if (key.toLowerCase() === "message") dataObject.message = dataObject.Error[key];
}
if (dataObject.RequestId && !metadata.requestId) metadata.requestId = dataObject.RequestId;
const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata);
const ns = NormalizedSchema.of(errorSchema);
const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown";
const exception = new ((TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema)) ?? Error)(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);
}
throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {
$fault: ns.getMergedTraits().error,
message
}, output), dataObject);
}
getDefaultContentType() {
return "application/xml";
}
hasUnstructuredPayloadBinding(ns) {
for (const [, member] of ns.structIterator()) if (member.getMergedTraits().httpPayload) return !(member.isStructSchema() || member.isMapSchema() || member.isListSchema());
return false;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js
var protocols_exports = /* @__PURE__ */ __exportAll({
AwsEc2QueryProtocol: () => AwsEc2QueryProtocol,
AwsJson1_0Protocol: () => AwsJson1_0Protocol,
AwsJson1_1Protocol: () => AwsJson1_1Protocol,
AwsJsonRpcProtocol: () => AwsJsonRpcProtocol,
AwsQueryProtocol: () => AwsQueryProtocol,
AwsRestJsonProtocol: () => AwsRestJsonProtocol,
AwsRestXmlProtocol: () => AwsRestXmlProtocol,
AwsSmithyRpcV2CborProtocol: () => AwsSmithyRpcV2CborProtocol,
JsonCodec: () => JsonCodec,
JsonShapeDeserializer: () => JsonShapeDeserializer,
JsonShapeSerializer: () => JsonShapeSerializer,
QueryShapeSerializer: () => QueryShapeSerializer,
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
});
var init_protocols$1 = __esmMin((() => {
init_AwsSmithyRpcV2CborProtocol();
init_coercing_serializers();
init_AwsJson1_0Protocol();
init_AwsJson1_1Protocol();
init_AwsJsonRpcProtocol();
init_AwsRestJsonProtocol();
init_JsonCodec();
init_JsonShapeDeserializer();
init_JsonShapeSerializer();
init_awsExpectUnion();
init_parseJsonBody();
init_AwsEc2QueryProtocol();
init_AwsQueryProtocol();
init_QuerySerializerSettings();
init_QueryShapeSerializer();
init_AwsRestXmlProtocol();
init_XmlCodec();
init_XmlShapeDeserializer();
init_XmlShapeSerializer();
init_parseXmlBody();
}));
//#endregion
//#region node_modules/@aws-sdk/core/dist-es/index.js
var dist_es_exports$2 = /* @__PURE__ */ __exportAll({
AWSSDKSigV4Signer: () => AWSSDKSigV4Signer,
AwsEc2QueryProtocol: () => AwsEc2QueryProtocol,
AwsJson1_0Protocol: () => AwsJson1_0Protocol,
AwsJson1_1Protocol: () => AwsJson1_1Protocol,
AwsJsonRpcProtocol: () => AwsJsonRpcProtocol,
AwsQueryProtocol: () => AwsQueryProtocol,
AwsRestJsonProtocol: () => AwsRestJsonProtocol,
AwsRestXmlProtocol: () => AwsRestXmlProtocol,
AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner,
AwsSdkSigV4Signer: () => AwsSdkSigV4Signer,
AwsSmithyRpcV2CborProtocol: () => AwsSmithyRpcV2CborProtocol,
JsonCodec: () => JsonCodec,
JsonShapeDeserializer: () => JsonShapeDeserializer,
JsonShapeSerializer: () => JsonShapeSerializer,
NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,
NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS,
QueryShapeSerializer: () => QueryShapeSerializer,
XmlCodec: () => XmlCodec,
XmlShapeDeserializer: () => XmlShapeDeserializer,
XmlShapeSerializer: () => XmlShapeSerializer,
_toBool: () => _toBool,
_toNum: () => _toNum,
_toStr: () => _toStr,
awsExpectUnion: () => awsExpectUnion,
emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion,
getBearerTokenEnvKey: () => getBearerTokenEnvKey,
loadRestJsonErrorCode: () => loadRestJsonErrorCode,
loadRestXmlErrorCode: () => loadRestXmlErrorCode,
parseJsonBody: () => parseJsonBody,
parseJsonErrorBody: () => parseJsonErrorBody,
parseXmlBody: () => parseXmlBody,
parseXmlErrorBody: () => parseXmlErrorBody,
resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config,
resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig,
resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config,
setCredentialFeature: () => setCredentialFeature,
setFeature: () => setFeature$2,
setTokenFeature: () => setTokenFeature,
state: () => state,
validateSigningProperties: () => validateSigningProperties
});
var init_dist_es$2 = __esmMin((() => {
init_client();
init_httpAuthSchemes$2();
init_protocols$1();
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js
var require_dist_cjs$25 = /* @__PURE__ */ __commonJSMin(((exports) => {
var protocolHttp = require_dist_cjs$34();
function resolveHostHeaderConfig(input) {
return input;
}
const hostHeaderMiddleware = (options) => (next) => async (args) => {
if (!protocolHttp.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);
};
const hostHeaderMiddlewareOptions = {
name: "hostHeaderMiddleware",
step: "build",
priority: "low",
tags: ["HOST"],
override: true
};
const getHostHeaderPlugin = (options) => ({ applyToStack: (clientStack) => {
clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions);
} });
exports.getHostHeaderPlugin = getHostHeaderPlugin;
exports.hostHeaderMiddleware = hostHeaderMiddleware;
exports.hostHeaderMiddlewareOptions = hostHeaderMiddlewareOptions;
exports.resolveHostHeaderConfig = resolveHostHeaderConfig;
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js
var require_dist_cjs$24 = /* @__PURE__ */ __commonJSMin(((exports) => {
const loggerMiddleware = () => (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;
}
};
const loggerMiddlewareOptions = {
name: "loggerMiddleware",
tags: ["LOGGER"],
step: "initialize",
override: true
};
const getLoggerPlugin = (options) => ({ applyToStack: (clientStack) => {
clientStack.add(loggerMiddleware(), loggerMiddlewareOptions);
} });
exports.getLoggerPlugin = getLoggerPlugin;
exports.loggerMiddleware = loggerMiddleware;
exports.loggerMiddlewareOptions = loggerMiddlewareOptions;
}));
//#endregion
//#region node_modules/@aws/lambda-invoke-store/dist-es/invoke-store.js
var invoke_store_exports = /* @__PURE__ */ __exportAll({
InvokeStore: () => InvokeStore,
InvokeStoreBase: () => InvokeStoreBase
});
var PROTECTED_KEYS, NO_GLOBAL_AWS_LAMBDA, InvokeStoreBase, InvokeStoreSingle, InvokeStoreMulti, InvokeStore;
var init_invoke_store = __esmMin((() => {
PROTECTED_KEYS = {
REQUEST_ID: Symbol.for("_AWS_LAMBDA_REQUEST_ID"),
X_RAY_TRACE_ID: Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),
TENANT_ID: Symbol.for("_AWS_LAMBDA_TENANT_ID")
};
NO_GLOBAL_AWS_LAMBDA = ["true", "1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA ?? "");
if (!NO_GLOBAL_AWS_LAMBDA) globalThis.awslambda = globalThis.awslambda || {};
InvokeStoreBase = class {
static PROTECTED_KEYS = PROTECTED_KEYS;
isProtectedKey(key) {
return Object.values(PROTECTED_KEYS).includes(key);
}
getRequestId() {
return this.get(PROTECTED_KEYS.REQUEST_ID) ?? "-";
}
getXRayTraceId() {
return this.get(PROTECTED_KEYS.X_RAY_TRACE_ID);
}
getTenantId() {
return this.get(PROTECTED_KEYS.TENANT_ID);
}
};
InvokeStoreSingle = class extends InvokeStoreBase {
currentContext;
getContext() {
return this.currentContext;
}
hasContext() {
return this.currentContext !== void 0;
}
get(key) {
return this.currentContext?.[key];
}
set(key, value) {
if (this.isProtectedKey(key)) throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);
this.currentContext = this.currentContext || {};
this.currentContext[key] = value;
}
run(context, fn) {
this.currentContext = context;
return fn();
}
};
InvokeStoreMulti = class InvokeStoreMulti extends InvokeStoreBase {
als;
static async create() {
const instance = new InvokeStoreMulti();
instance.als = new (await (import("node:async_hooks"))).AsyncLocalStorage();
return instance;
}
getContext() {
return this.als.getStore();
}
hasContext() {
return this.als.getStore() !== void 0;
}
get(key) {
return this.als.getStore()?.[key];
}
set(key, value) {
if (this.isProtectedKey(key)) throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);
const store = this.als.getStore();
if (!store) throw new Error("No context available");
store[key] = value;
}
run(context, fn) {
return this.als.run(context, fn);
}
};
(function(InvokeStore) {
let instance = null;
async function getInstanceAsync(forceInvokeStoreMulti) {
if (!instance) instance = (async () => {
const newInstance = forceInvokeStoreMulti === true || "AWS_LAMBDA_MAX_CONCURRENCY" in process.env ? await InvokeStoreMulti.create() : new InvokeStoreSingle();
if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda?.InvokeStore) return globalThis.awslambda.InvokeStore;
else if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda) {
globalThis.awslambda.InvokeStore = newInstance;
return newInstance;
} else return newInstance;
})();
return instance;
}
InvokeStore.getInstanceAsync = getInstanceAsync;
InvokeStore._testing = process.env.AWS_LAMBDA_BENCHMARK_MODE === "1" ? { reset: () => {
instance = null;
if (globalThis.awslambda?.InvokeStore) delete globalThis.awslambda.InvokeStore;
globalThis.awslambda = { InvokeStore: void 0 };
} } : void 0;
})(InvokeStore || (InvokeStore = {}));
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js
var require_recursionDetectionMiddleware = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.recursionDetectionMiddleware = void 0;
const lambda_invoke_store_1 = (init_invoke_store(), __toCommonJS(invoke_store_exports));
const protocol_http_1 = require_dist_cjs$34();
const TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id";
const ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME";
const ENV_TRACE_ID = "_X_AMZN_TRACE_ID";
const recursionDetectionMiddleware = () => (next) => async (args) => {
const { request } = args;
if (!protocol_http_1.HttpRequest.isInstance(request)) 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 traceIdFromEnv = process.env[ENV_TRACE_ID];
const traceId = (await lambda_invoke_store_1.InvokeStore.getInstanceAsync())?.getXRayTraceId() ?? traceIdFromEnv;
const nonEmptyString = (str) => typeof str === "string" && str.length > 0;
if (nonEmptyString(functionName) && nonEmptyString(traceId)) request.headers[TRACE_ID_HEADER_NAME] = traceId;
return next({
...args,
request
});
};
exports.recursionDetectionMiddleware = recursionDetectionMiddleware;
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js
var require_dist_cjs$23 = /* @__PURE__ */ __commonJSMin(((exports) => {
var recursionDetectionMiddleware = require_recursionDetectionMiddleware();
const recursionDetectionMiddlewareOptions = {
step: "build",
tags: ["RECURSION_DETECTION"],
name: "recursionDetectionMiddleware",
override: true,
priority: "low"
};
const getRecursionDetectionPlugin = (options) => ({ applyToStack: (clientStack) => {
clientStack.add(recursionDetectionMiddleware.recursionDetectionMiddleware(), recursionDetectionMiddlewareOptions);
} });
exports.getRecursionDetectionPlugin = getRecursionDetectionPlugin;
Object.prototype.hasOwnProperty.call(recursionDetectionMiddleware, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
enumerable: true,
value: recursionDetectionMiddleware["__proto__"]
});
Object.keys(recursionDetectionMiddleware).forEach(function(k) {
if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = recursionDetectionMiddleware[k];
});
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/getSmithyContext.js
var import_dist_cjs$14, getSmithyContext$5;
var init_getSmithyContext$1 = __esmMin((() => {
import_dist_cjs$14 = require_dist_cjs$33();
getSmithyContext$5 = (context) => context[import_dist_cjs$14.SMITHY_CONTEXT_KEY] || (context[import_dist_cjs$14.SMITHY_CONTEXT_KEY] = {});
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js
var resolveAuthOptions$1;
var init_resolveAuthOptions$1 = __esmMin((() => {
resolveAuthOptions$1 = (candidateAuthOptions, authSchemePreference) => {
if (!authSchemePreference || authSchemePreference.length === 0) return candidateAuthOptions;
const preferredAuthOptions = [];
for (const preferredSchemeName of authSchemePreference) for (const candidateAuthOption of candidateAuthOptions) if (candidateAuthOption.schemeId.split("#")[1] === preferredSchemeName) preferredAuthOptions.push(candidateAuthOption);
for (const candidateAuthOption of candidateAuthOptions) if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) preferredAuthOptions.push(candidateAuthOption);
return preferredAuthOptions;
};
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js
function convertHttpAuthSchemesToMap$1(httpAuthSchemes) {
const map = /* @__PURE__ */ new Map();
for (const scheme of httpAuthSchemes) map.set(scheme.schemeId, scheme);
return map;
}
var import_dist_cjs$13, httpAuthSchemeMiddleware$1;
var init_httpAuthSchemeMiddleware$1 = __esmMin((() => {
import_dist_cjs$13 = require_dist_cjs$40();
init_resolveAuthOptions$1();
httpAuthSchemeMiddleware$1 = (config, mwOptions) => (next, context) => async (args) => {
const resolvedOptions = resolveAuthOptions$1(config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input)), config.authSchemePreference ? await config.authSchemePreference() : []);
const authSchemes = convertHttpAuthSchemesToMap$1(config.httpAuthSchemes);
const smithyContext = (0, import_dist_cjs$13.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;
}
if (!smithyContext.selectedHttpAuthScheme) throw new Error(failureReasons.join("\n"));
return next(args);
};
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js
var httpAuthSchemeEndpointRuleSetMiddlewareOptions$1, getHttpAuthSchemeEndpointRuleSetPlugin$1;
var init_getHttpAuthSchemeEndpointRuleSetPlugin$1 = __esmMin((() => {
init_httpAuthSchemeMiddleware$1();
httpAuthSchemeEndpointRuleSetMiddlewareOptions$1 = {
step: "serialize",
tags: ["HTTP_AUTH_SCHEME"],
name: "httpAuthSchemeMiddleware",
override: true,
relation: "before",
toMiddleware: "endpointV2Middleware"
};
getHttpAuthSchemeEndpointRuleSetPlugin$1 = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ applyToStack: (clientStack) => {
clientStack.addRelativeTo(httpAuthSchemeMiddleware$1(config, {
httpAuthSchemeParametersProvider,
identityProviderConfigProvider
}), httpAuthSchemeEndpointRuleSetMiddlewareOptions$1);
} });
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js
var httpAuthSchemeMiddlewareOptions$1, getHttpAuthSchemePlugin$1;
var init_getHttpAuthSchemePlugin$1 = __esmMin((() => {
init_httpAuthSchemeMiddleware$1();
httpAuthSchemeMiddlewareOptions$1 = {
step: "serialize",
tags: ["HTTP_AUTH_SCHEME"],
name: "httpAuthSchemeMiddleware",
override: true,
relation: "before",
toMiddleware: "serializerMiddleware"
};
getHttpAuthSchemePlugin$1 = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ applyToStack: (clientStack) => {
clientStack.addRelativeTo(httpAuthSchemeMiddleware$1(config, {
httpAuthSchemeParametersProvider,
identityProviderConfigProvider
}), httpAuthSchemeMiddlewareOptions$1);
} });
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js
var init_middleware_http_auth_scheme$1 = __esmMin((() => {
init_httpAuthSchemeMiddleware$1();
init_getHttpAuthSchemeEndpointRuleSetPlugin$1();
init_getHttpAuthSchemePlugin$1();
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js
var import_dist_cjs$11, import_dist_cjs$12, defaultErrorHandler$1, defaultSuccessHandler$1, httpSigningMiddleware$1;
var init_httpSigningMiddleware$1 = __esmMin((() => {
import_dist_cjs$11 = require_dist_cjs$34();
import_dist_cjs$12 = require_dist_cjs$40();
defaultErrorHandler$1 = (signingProperties) => (error) => {
throw error;
};
defaultSuccessHandler$1 = (httpResponse, signingProperties) => {};
httpSigningMiddleware$1 = (config) => (next, context) => async (args) => {
if (!import_dist_cjs$11.HttpRequest.isInstance(args.request)) return next(args);
const scheme = (0, import_dist_cjs$12.getSmithyContext)(context).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$1)(signingProperties));
(signer.successHandler || defaultSuccessHandler$1)(output.response, signingProperties);
return output;
};
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js
var httpSigningMiddlewareOptions$1, getHttpSigningPlugin$1;
var init_getHttpSigningMiddleware$1 = __esmMin((() => {
init_httpSigningMiddleware$1();
httpSigningMiddlewareOptions$1 = {
step: "finalizeRequest",
tags: ["HTTP_SIGNING"],
name: "httpSigningMiddleware",
aliases: [
"apiKeyMiddleware",
"tokenMiddleware",
"awsAuthMiddleware"
],
override: true,
relation: "after",
toMiddleware: "retryMiddleware"
};
getHttpSigningPlugin$1 = (config) => ({ applyToStack: (clientStack) => {
clientStack.addRelativeTo(httpSigningMiddleware$1(config), httpSigningMiddlewareOptions$1);
} });
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/middleware-http-signing/index.js
var init_middleware_http_signing$1 = __esmMin((() => {
init_httpSigningMiddleware$1();
init_getHttpSigningMiddleware$1();
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/normalizeProvider.js
var normalizeProvider$1;
var init_normalizeProvider$1 = __esmMin((() => {
normalizeProvider$1 = (input) => {
if (typeof input === "function") return input;
const promisified = Promise.resolve(input);
return () => promisified;
};
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/pagination/createPaginator.js
function createPaginator$1(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) {
return 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$1(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$1(page, outputTokenName);
hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken));
}
return void 0;
};
}
var makePagedClientRequest$1, get$1;
var init_createPaginator$1 = __esmMin((() => {
makePagedClientRequest$1 = async (CommandCtor, client, input, withCommand = (_) => _, ...args) => {
let command = new CommandCtor(input);
command = withCommand(command) ?? command;
return await client.send(command, ...args);
};
get$1 = (fromObject, path) => {
let cursor = fromObject;
const pathComponents = path.split(".");
for (const step of pathComponents) {
if (!cursor || typeof cursor !== "object") return;
cursor = cursor[step];
}
return cursor;
};
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/request-builder/requestBuilder.js
var init_requestBuilder$2 = __esmMin((() => {
init_protocols$3();
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/setFeature.js
function setFeature$1(context, feature, value) {
if (!context.__smithy_context) context.__smithy_context = { features: {} };
else if (!context.__smithy_context.features) context.__smithy_context.features = {};
context.__smithy_context.features[feature] = value;
}
var init_setFeature$1 = __esmMin((() => {}));
//#endregion
//#region node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js
var DefaultIdentityProviderConfig$1;
var init_DefaultIdentityProviderConfig$1 = __esmMin((() => {
DefaultIdentityProviderConfig$1 = class {
authSchemes = /* @__PURE__ */ new Map();
constructor(config) {
for (const [key, value] of Object.entries(config)) if (value !== void 0) this.authSchemes.set(key, value);
}
getIdentityProvider(schemeId) {
return this.authSchemes.get(schemeId);
}
};
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js
var import_dist_cjs$9, import_dist_cjs$10, HttpApiKeyAuthSigner$1;
var init_httpApiKeyAuth$1 = __esmMin((() => {
import_dist_cjs$9 = require_dist_cjs$34();
import_dist_cjs$10 = require_dist_cjs$33();
HttpApiKeyAuthSigner$1 = class {
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_dist_cjs$9.HttpRequest.clone(httpRequest);
if (signingProperties.in === import_dist_cjs$10.HttpApiKeyAuthLocation.QUERY) clonedRequest.query[signingProperties.name] = identity.apiKey;
else if (signingProperties.in === import_dist_cjs$10.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;
}
};
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js
var import_dist_cjs$8, HttpBearerAuthSigner$1;
var init_httpBearerAuth$1 = __esmMin((() => {
import_dist_cjs$8 = require_dist_cjs$34();
HttpBearerAuthSigner$1 = class {
async sign(httpRequest, identity, signingProperties) {
const clonedRequest = import_dist_cjs$8.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;
}
};
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js
var NoAuthSigner$1;
var init_noAuth$1 = __esmMin((() => {
NoAuthSigner$1 = class {
async sign(httpRequest, identity, signingProperties) {
return httpRequest;
}
};
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js
var init_httpAuthSchemes$1 = __esmMin((() => {
init_httpApiKeyAuth$1();
init_httpBearerAuth$1();
init_noAuth$1();
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js
var createIsIdentityExpiredFunction$1, EXPIRATION_MS$1, isIdentityExpired$1, doesIdentityRequireRefresh$1, memoizeIdentityProvider$1;
var init_memoizeIdentityProvider$1 = __esmMin((() => {
createIsIdentityExpiredFunction$1 = (expirationMs) => function isIdentityExpired(identity) {
return doesIdentityRequireRefresh$1(identity) && identity.expiration.getTime() - Date.now() < expirationMs;
};
EXPIRATION_MS$1 = 3e5;
isIdentityExpired$1 = createIsIdentityExpiredFunction$1(EXPIRATION_MS$1);
doesIdentityRequireRefresh$1 = (identity) => identity.expiration !== void 0;
memoizeIdentityProvider$1 = (provider, isExpired, requiresRefresh) => {
if (provider === void 0) return;
const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider;
let resolved;
let pending;
let hasResult;
let isConstant = false;
const coalesceProvider = async (options) => {
if (!pending) pending = normalizedProvider(options);
try {
resolved = await pending;
hasResult = true;
isConstant = false;
} finally {
pending = void 0;
}
return resolved;
};
if (isExpired === void 0) return async (options) => {
if (!hasResult || options?.forceRefresh) resolved = await coalesceProvider(options);
return resolved;
};
return async (options) => {
if (!hasResult || options?.forceRefresh) resolved = await coalesceProvider(options);
if (isConstant) return resolved;
if (!requiresRefresh(resolved)) {
isConstant = true;
return resolved;
}
if (isExpired(resolved)) {
await coalesceProvider(options);
return resolved;
}
return resolved;
};
};
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js
var init_util_identity_and_auth$1 = __esmMin((() => {
init_DefaultIdentityProviderConfig$1();
init_httpAuthSchemes$1();
init_memoizeIdentityProvider$1();
}));
//#endregion
//#region node_modules/@smithy/core/dist-es/index.js
var dist_es_exports$1 = /* @__PURE__ */ __exportAll({
DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig$1,
EXPIRATION_MS: () => EXPIRATION_MS$1,
HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner$1,
HttpBearerAuthSigner: () => HttpBearerAuthSigner$1,
NoAuthSigner: () => NoAuthSigner$1,
createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction$1,
createPaginator: () => createPaginator$1,
doesIdentityRequireRefresh: () => doesIdentityRequireRefresh$1,
getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin$1,
getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin$1,
getHttpSigningPlugin: () => getHttpSigningPlugin$1,
getSmithyContext: () => getSmithyContext$5,
httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions$1,
httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware$1,
httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions$1,
httpSigningMiddleware: () => httpSigningMiddleware$1,
httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions$1,
isIdentityExpired: () => isIdentityExpired$1,
memoizeIdentityProvider: () => memoizeIdentityProvider$1,
normalizeProvider: () => normalizeProvider$1,
requestBuilder: () => requestBuilder$1,
setFeature: () => setFeature$1
});
var init_dist_es$1 = __esmMin((() => {
init_getSmithyContext$1();
init_middleware_http_auth_scheme$1();
init_middleware_http_signing$1();
init_normalizeProvider$1();
init_createPaginator$1();
init_requestBuilder$2();
init_setFeature$1();
init_util_identity_and_auth$1();
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/getSmithyContext.js
var import_dist_cjs$7, getSmithyContext$2;
var init_getSmithyContext = __esmMin((() => {
import_dist_cjs$7 = require_dist_cjs$33();
getSmithyContext$2 = (context) => context[import_dist_cjs$7.SMITHY_CONTEXT_KEY] || (context[import_dist_cjs$7.SMITHY_CONTEXT_KEY] = {});
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/util-middleware/dist-cjs/index.js
var require_dist_cjs$22 = /* @__PURE__ */ __commonJSMin(((exports) => {
var types = require_dist_cjs$33();
const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {});
exports.getSmithyContext = getSmithyContext;
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js
var resolveAuthOptions;
var init_resolveAuthOptions = __esmMin((() => {
resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => {
if (!authSchemePreference || authSchemePreference.length === 0) return candidateAuthOptions;
const preferredAuthOptions = [];
for (const preferredSchemeName of authSchemePreference) for (const candidateAuthOption of candidateAuthOptions) if (candidateAuthOption.schemeId.split("#")[1] === preferredSchemeName) preferredAuthOptions.push(candidateAuthOption);
for (const candidateAuthOption of candidateAuthOptions) if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) preferredAuthOptions.push(candidateAuthOption);
return preferredAuthOptions;
};
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js
function convertHttpAuthSchemesToMap(httpAuthSchemes) {
const map = /* @__PURE__ */ new Map();
for (const scheme of httpAuthSchemes) map.set(scheme.schemeId, scheme);
return map;
}
var import_dist_cjs$6, httpAuthSchemeMiddleware;
var init_httpAuthSchemeMiddleware = __esmMin((() => {
import_dist_cjs$6 = require_dist_cjs$22();
init_resolveAuthOptions();
httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => {
const resolvedOptions = resolveAuthOptions(config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input)), config.authSchemePreference ? await config.authSchemePreference() : []);
const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes);
const smithyContext = (0, import_dist_cjs$6.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;
}
if (!smithyContext.selectedHttpAuthScheme) throw new Error(failureReasons.join("\n"));
return next(args);
};
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js
var httpAuthSchemeEndpointRuleSetMiddlewareOptions, getHttpAuthSchemeEndpointRuleSetPlugin;
var init_getHttpAuthSchemeEndpointRuleSetPlugin = __esmMin((() => {
init_httpAuthSchemeMiddleware();
httpAuthSchemeEndpointRuleSetMiddlewareOptions = {
step: "serialize",
tags: ["HTTP_AUTH_SCHEME"],
name: "httpAuthSchemeMiddleware",
override: true,
relation: "before",
toMiddleware: "endpointV2Middleware"
};
getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ applyToStack: (clientStack) => {
clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {
httpAuthSchemeParametersProvider,
identityProviderConfigProvider
}), httpAuthSchemeEndpointRuleSetMiddlewareOptions);
} });
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js
var httpAuthSchemeMiddlewareOptions, getHttpAuthSchemePlugin;
var init_getHttpAuthSchemePlugin = __esmMin((() => {
init_httpAuthSchemeMiddleware();
httpAuthSchemeMiddlewareOptions = {
step: "serialize",
tags: ["HTTP_AUTH_SCHEME"],
name: "httpAuthSchemeMiddleware",
override: true,
relation: "before",
toMiddleware: "serializerMiddleware"
};
getHttpAuthSchemePlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ applyToStack: (clientStack) => {
clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {
httpAuthSchemeParametersProvider,
identityProviderConfigProvider
}), httpAuthSchemeMiddlewareOptions);
} });
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js
var init_middleware_http_auth_scheme = __esmMin((() => {
init_httpAuthSchemeMiddleware();
init_getHttpAuthSchemeEndpointRuleSetPlugin();
init_getHttpAuthSchemePlugin();
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js
var import_dist_cjs$4, import_dist_cjs$5, defaultErrorHandler, defaultSuccessHandler, httpSigningMiddleware;
var init_httpSigningMiddleware = __esmMin((() => {
import_dist_cjs$4 = require_dist_cjs$34();
import_dist_cjs$5 = require_dist_cjs$22();
defaultErrorHandler = (signingProperties) => (error) => {
throw error;
};
defaultSuccessHandler = (httpResponse, signingProperties) => {};
httpSigningMiddleware = (config) => (next, context) => async (args) => {
if (!import_dist_cjs$4.HttpRequest.isInstance(args.request)) return next(args);
const scheme = (0, import_dist_cjs$5.getSmithyContext)(context).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;
};
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js
var httpSigningMiddlewareOptions, getHttpSigningPlugin;
var init_getHttpSigningMiddleware = __esmMin((() => {
init_httpSigningMiddleware();
httpSigningMiddlewareOptions = {
step: "finalizeRequest",
tags: ["HTTP_SIGNING"],
name: "httpSigningMiddleware",
aliases: [
"apiKeyMiddleware",
"tokenMiddleware",
"awsAuthMiddleware"
],
override: true,
relation: "after",
toMiddleware: "retryMiddleware"
};
getHttpSigningPlugin = (config) => ({ applyToStack: (clientStack) => {
clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions);
} });
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js
var init_middleware_http_signing = __esmMin((() => {
init_httpSigningMiddleware();
init_getHttpSigningMiddleware();
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/normalizeProvider.js
var normalizeProvider;
var init_normalizeProvider = __esmMin((() => {
normalizeProvider = (input) => {
if (typeof input === "function") return input;
const promisified = Promise.resolve(input);
return () => promisified;
};
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/pagination/createPaginator.js
function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) {
return 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;
};
}
var makePagedClientRequest, get;
var init_createPaginator = __esmMin((() => {
makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_) => _, ...args) => {
let command = new CommandCtor(input);
command = withCommand(command) ?? command;
return await client.send(command, ...args);
};
get = (fromObject, path) => {
let cursor = fromObject;
const pathComponents = path.split(".");
for (const step of pathComponents) {
if (!cursor || typeof cursor !== "object") return;
cursor = cursor[step];
}
return cursor;
};
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js
var init_collect_stream_body = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js
function extendedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return "%" + c.charCodeAt(0).toString(16).toUpperCase();
});
}
var init_extended_encode_uri_component = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/SerdeContext.js
var init_SerdeContext = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js
var init_HttpProtocol = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js
var init_HttpBindingProtocol = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js
var init_RpcProtocol = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js
var resolvedPath;
var init_resolve_path = __esmMin((() => {
init_extended_encode_uri_component();
resolvedPath = (resolvedPath, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => {
if (input != null && input[memberName] !== void 0) {
const labelValue = labelValueProvider();
if (labelValue == null || labelValue.length <= 0) throw new Error("Empty value provided for input HTTP label: " + memberName + ".");
resolvedPath = resolvedPath.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 resolvedPath;
};
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js
function requestBuilder(input, context) {
return new RequestBuilder(input, context);
}
var import_dist_cjs$3, RequestBuilder;
var init_requestBuilder$1 = __esmMin((() => {
import_dist_cjs$3 = require_dist_cjs$34();
init_resolve_path();
RequestBuilder = class {
input;
context;
query = {};
method = "";
headers = {};
path = "";
body = null;
hostname = "";
resolvePathStack = [];
constructor(input, context) {
this.input = input;
this.context = context;
}
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_dist_cjs$3.HttpRequest({
protocol,
hostname: this.hostname || hostname,
port,
method: this.method,
path: this.path,
query: this.query,
body: this.body,
headers: this.headers
});
}
hn(hostname) {
this.hostname = hostname;
return this;
}
bp(uriLabel) {
this.resolvePathStack.push((basePath) => {
this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel;
});
return this;
}
p(memberName, labelValueProvider, uriLabel, isGreedyLabel) {
this.resolvePathStack.push((path) => {
this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel);
});
return this;
}
h(headers) {
this.headers = headers;
return this;
}
q(query) {
this.query = query;
return this;
}
b(body) {
this.body = body;
return this;
}
m(method) {
this.method = method;
return this;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js
var init_determineTimestampFormat = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js
var init_FromStringShapeDeserializer = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js
var init_HttpInterceptingShapeDeserializer = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js
var init_ToStringShapeSerializer = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js
var init_HttpInterceptingShapeSerializer = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/submodules/protocols/index.js
var init_protocols = __esmMin((() => {
init_collect_stream_body();
init_extended_encode_uri_component();
init_HttpBindingProtocol();
init_HttpProtocol();
init_RpcProtocol();
init_requestBuilder$1();
init_resolve_path();
init_FromStringShapeDeserializer();
init_HttpInterceptingShapeDeserializer();
init_HttpInterceptingShapeSerializer();
init_ToStringShapeSerializer();
init_determineTimestampFormat();
init_SerdeContext();
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/request-builder/requestBuilder.js
var init_requestBuilder = __esmMin((() => {
init_protocols();
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/setFeature.js
function setFeature(context, feature, value) {
if (!context.__smithy_context) context.__smithy_context = { features: {} };
else if (!context.__smithy_context.features) context.__smithy_context.features = {};
context.__smithy_context.features[feature] = value;
}
var init_setFeature = __esmMin((() => {}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js
var DefaultIdentityProviderConfig;
var init_DefaultIdentityProviderConfig = __esmMin((() => {
DefaultIdentityProviderConfig = class {
authSchemes = /* @__PURE__ */ new Map();
constructor(config) {
for (const [key, value] of Object.entries(config)) if (value !== void 0) this.authSchemes.set(key, value);
}
getIdentityProvider(schemeId) {
return this.authSchemes.get(schemeId);
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js
var import_dist_cjs$1, import_dist_cjs$2, HttpApiKeyAuthSigner;
var init_httpApiKeyAuth = __esmMin((() => {
import_dist_cjs$1 = require_dist_cjs$34();
import_dist_cjs$2 = require_dist_cjs$33();
HttpApiKeyAuthSigner = class {
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_dist_cjs$1.HttpRequest.clone(httpRequest);
if (signingProperties.in === import_dist_cjs$2.HttpApiKeyAuthLocation.QUERY) clonedRequest.query[signingProperties.name] = identity.apiKey;
else if (signingProperties.in === import_dist_cjs$2.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;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js
var import_dist_cjs, HttpBearerAuthSigner;
var init_httpBearerAuth = __esmMin((() => {
import_dist_cjs = require_dist_cjs$34();
HttpBearerAuthSigner = class {
async sign(httpRequest, identity, signingProperties) {
const clonedRequest = import_dist_cjs.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;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js
var NoAuthSigner;
var init_noAuth = __esmMin((() => {
NoAuthSigner = class {
async sign(httpRequest, identity, signingProperties) {
return httpRequest;
}
};
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js
var init_httpAuthSchemes = __esmMin((() => {
init_httpApiKeyAuth();
init_httpBearerAuth();
init_noAuth();
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js
var createIsIdentityExpiredFunction, EXPIRATION_MS, isIdentityExpired, doesIdentityRequireRefresh, memoizeIdentityProvider;
var init_memoizeIdentityProvider = __esmMin((() => {
createIsIdentityExpiredFunction = (expirationMs) => function isIdentityExpired(identity) {
return doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs;
};
EXPIRATION_MS = 3e5;
isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS);
doesIdentityRequireRefresh = (identity) => identity.expiration !== void 0;
memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => {
if (provider === void 0) return;
const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider;
let resolved;
let pending;
let hasResult;
let isConstant = false;
const coalesceProvider = async (options) => {
if (!pending) pending = normalizedProvider(options);
try {
resolved = await pending;
hasResult = true;
isConstant = false;
} finally {
pending = void 0;
}
return resolved;
};
if (isExpired === void 0) return async (options) => {
if (!hasResult || options?.forceRefresh) resolved = await coalesceProvider(options);
return resolved;
};
return async (options) => {
if (!hasResult || options?.forceRefresh) resolved = await coalesceProvider(options);
if (isConstant) return resolved;
if (!requiresRefresh(resolved)) {
isConstant = true;
return resolved;
}
if (isExpired(resolved)) {
await coalesceProvider(options);
return resolved;
}
return resolved;
};
};
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js
var init_util_identity_and_auth = __esmMin((() => {
init_DefaultIdentityProviderConfig();
init_httpAuthSchemes();
init_memoizeIdentityProvider();
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/core/dist-es/index.js
var dist_es_exports = /* @__PURE__ */ __exportAll({
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$2,
httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions,
httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware,
httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions,
httpSigningMiddleware: () => httpSigningMiddleware,
httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions,
isIdentityExpired: () => isIdentityExpired,
memoizeIdentityProvider: () => memoizeIdentityProvider,
normalizeProvider: () => normalizeProvider,
requestBuilder: () => requestBuilder,
setFeature: () => setFeature
});
var init_dist_es = __esmMin((() => {
init_getSmithyContext();
init_middleware_http_auth_scheme();
init_middleware_http_signing();
init_normalizeProvider();
init_createPaginator();
init_requestBuilder();
init_setFeature();
init_util_identity_and_auth();
}));
//#endregion
//#region node_modules/@aws-sdk/util-endpoints/node_modules/@smithy/util-endpoints/dist-cjs/index.js
var require_dist_cjs$21 = /* @__PURE__ */ __commonJSMin(((exports) => {
var types = require_dist_cjs$33();
var EndpointCache = class {
capacity;
data = /* @__PURE__ */ new Map();
parameters = [];
constructor({ size, params }) {
this.capacity = size ?? 50;
if (params) this.parameters = params;
}
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);
}
size() {
return this.data.size;
}
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;
}
};
const IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`);
const isIpAddress = (value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]");
const VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);
const isValidHostLabel = (value, allowSubDomains = false) => {
if (!allowSubDomains) return VALID_HOST_LABEL_REGEX.test(value);
const labels = value.split(".");
for (const label of labels) if (!isValidHostLabel(label)) return false;
return true;
};
const customEndpointFunctions = {};
const debugId = "endpoints";
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);
}
var EndpointError = class extends Error {
constructor(message) {
super(message);
this.name = "EndpointError";
}
};
const booleanEquals = (value1, value2) => value1 === value2;
const getAttrPathList = (path) => {
const parts = path.split(".");
const pathList = [];
for (const part of parts) {
const squareBracketIndex = part.indexOf("[");
if (squareBracketIndex !== -1) {
if (part.indexOf("]") !== part.length - 1) throw new 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);
}
return pathList;
};
const getAttr = (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);
const isSet = (value) => value != null;
const not = (value) => !value;
const DEFAULT_PORTS = {
[types.EndpointURLScheme.HTTP]: 80,
[types.EndpointURLScheme.HTTPS]: 443
};
const parseURL = (value) => {
const whatwgURL = (() => {
try {
if (value instanceof URL) return value;
if (typeof value === "object" && "hostname" in value) {
const { hostname, port, protocol = "", path = "", query = {} } = value;
const url = new URL(`${protocol}//${hostname}${port ? `:${port}` : ""}${path}`);
url.search = Object.entries(query).map(([k, v]) => `${k}=${v}`).join("&");
return url;
}
return new URL(value);
} catch (error) {
return null;
}
})();
if (!whatwgURL) {
console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);
return null;
}
const urlString = whatwgURL.href;
const { host, hostname, pathname, protocol, search } = whatwgURL;
if (search) return null;
const scheme = protocol.slice(0, -1);
if (!Object.values(types.EndpointURLScheme).includes(scheme)) return null;
const isIp = isIpAddress(hostname);
return {
scheme,
authority: `${host}${urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`) ? `:${DEFAULT_PORTS[scheme]}` : ``}`,
path: pathname,
normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`,
isIp
};
};
const stringEquals = (value1, value2) => value1 === value2;
const substring = (input, start, stop, reverse) => {
if (start >= stop || input.length < stop || /[^\u0000-\u007f]/.test(input)) return null;
if (!reverse) return input.substring(start, stop);
return input.substring(input.length - stop, input.length - start);
};
const uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
const endpointFunctions = {
booleanEquals,
getAttr,
isSet,
isValidHostLabel,
not,
parseURL,
stringEquals,
substring,
uriEncode
};
const evaluateTemplate = (template, options) => {
const evaluatedTemplateArr = [];
const templateContext = {
...options.endpointParams,
...options.referenceRecord
};
let currentIndex = 0;
while (currentIndex < template.length) {
const openingBraceIndex = template.indexOf("{", currentIndex);
if (openingBraceIndex === -1) {
evaluatedTemplateArr.push(template.slice(currentIndex));
break;
}
evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex));
const closingBraceIndex = template.indexOf("}", openingBraceIndex);
if (closingBraceIndex === -1) {
evaluatedTemplateArr.push(template.slice(openingBraceIndex));
break;
}
if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") {
evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex));
currentIndex = closingBraceIndex + 2;
}
const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex);
if (parameterName.includes("#")) {
const [refName, attrName] = parameterName.split("#");
evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName));
} else evaluatedTemplateArr.push(templateContext[parameterName]);
currentIndex = closingBraceIndex + 1;
}
return evaluatedTemplateArr.join("");
};
const getReferenceValue = ({ ref }, options) => {
return {
...options.endpointParams,
...options.referenceRecord
}[ref];
};
const evaluateExpression = (obj, keyName, options) => {
if (typeof obj === "string") return evaluateTemplate(obj, options);
else if (obj["fn"]) return group$2.callFunction(obj, options);
else if (obj["ref"]) return getReferenceValue(obj, options);
throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`);
};
const callFunction = ({ fn, argv }, options) => {
const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : group$2.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);
};
const group$2 = {
evaluateExpression,
callFunction
};
const evaluateCondition = ({ 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
} }
};
};
const evaluateConditions = (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
};
};
const getEndpointHeaders = (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;
})
}), {});
const getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({
...acc,
[propertyKey]: group$1.getEndpointProperty(propertyVal, options)
}), {});
const getEndpointProperty = (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 group$1.getEndpointProperties(property, options);
case "boolean": return property;
default: throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`);
}
};
const group$1 = {
getEndpointProperty,
getEndpointProperties
};
const getEndpointUrl = (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;
}
throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`);
};
const evaluateEndpointRule = (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)
};
};
const evaluateErrorRule = (errorRule, options) => {
const { conditions, error } = errorRule;
const { result, referenceRecord } = evaluateConditions(conditions, options);
if (!result) return;
throw new EndpointError(evaluateExpression(error, "Error", {
...options,
referenceRecord: {
...options.referenceRecord,
...referenceRecord
}
}));
};
const evaluateRules = (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 = group.evaluateTreeRule(rule, options);
if (endpointOrUndefined) return endpointOrUndefined;
} else throw new EndpointError(`Unknown endpoint rule: ${rule}`);
throw new EndpointError(`Rules evaluation failed`);
};
const evaluateTreeRule = (treeRule, options) => {
const { conditions, rules } = treeRule;
const { result, referenceRecord } = evaluateConditions(conditions, options);
if (!result) return;
return group.evaluateRules(rules, {
...options,
referenceRecord: {
...options.referenceRecord,
...referenceRecord
}
});
};
const group = {
evaluateRules,
evaluateTreeRule
};
const resolveEndpoint = (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;
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}'`);
const endpoint = evaluateRules(rules, {
endpointParams,
logger,
referenceRecord: {}
});
options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);
return endpoint;
};
exports.EndpointCache = EndpointCache;
exports.EndpointError = EndpointError;
exports.customEndpointFunctions = customEndpointFunctions;
exports.isIpAddress = isIpAddress;
exports.isValidHostLabel = isValidHostLabel;
exports.resolveEndpoint = resolveEndpoint;
}));
//#endregion
//#region node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js
var require_dist_cjs$20 = /* @__PURE__ */ __commonJSMin(((exports) => {
var utilEndpoints = require_dist_cjs$21();
var urlParser = require_dist_cjs$44();
const isVirtualHostableS3Bucket = (value, allowSubDomains = false) => {
if (allowSubDomains) {
for (const label of value.split(".")) if (!isVirtualHostableS3Bucket(label)) return false;
return true;
}
if (!utilEndpoints.isValidHostLabel(value)) return false;
if (value.length < 3 || value.length > 63) return false;
if (value !== value.toLowerCase()) return false;
if (utilEndpoints.isIpAddress(value)) return false;
return true;
};
const ARN_DELIMITER = ":";
const RESOURCE_DELIMITER = "/";
const parseArn = (value) => {
const segments = value.split(ARN_DELIMITER);
if (segments.length < 6) return null;
const [arn, partition, service, region, accountId, ...resourcePath] = segments;
if (arn !== "arn" || partition === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null;
return {
partition,
service,
region,
accountId,
resourceId: resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat()
};
};
var partitionsInfo = {
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-6": { description: "Asia Pacific (New Zealand)" },
"ap-southeast-7": { description: "Asia Pacific (Thailand)" },
"aws-global": { description: "aws 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-cn global region" },
"cn-north-1": { description: "China (Beijing)" },
"cn-northwest-1": { description: "China (Ningxia)" }
}
},
{
id: "aws-eusc",
outputs: {
dnsSuffix: "amazonaws.eu",
dualStackDnsSuffix: "api.amazonwebservices.eu",
implicitGlobalRegion: "eusc-de-east-1",
name: "aws-eusc",
supportsDualStack: true,
supportsFIPS: true
},
regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$",
regions: { "eusc-de-east-1": { description: "AWS European Sovereign Cloud (Germany)" } }
},
{
id: "aws-iso",
outputs: {
dnsSuffix: "c2s.ic.gov",
dualStackDnsSuffix: "api.aws.ic.gov",
implicitGlobalRegion: "us-iso-east-1",
name: "aws-iso",
supportsDualStack: true,
supportsFIPS: true
},
regionRegex: "^us\\-iso\\-\\w+\\-\\d+$",
regions: {
"aws-iso-global": { description: "aws-iso 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: "api.aws.scloud",
implicitGlobalRegion: "us-isob-east-1",
name: "aws-iso-b",
supportsDualStack: true,
supportsFIPS: true
},
regionRegex: "^us\\-isob\\-\\w+\\-\\d+$",
regions: {
"aws-iso-b-global": { description: "aws-iso-b global region" },
"us-isob-east-1": { description: "US ISOB East (Ohio)" },
"us-isob-west-1": { description: "US ISOB West" }
}
},
{
id: "aws-iso-e",
outputs: {
dnsSuffix: "cloud.adc-e.uk",
dualStackDnsSuffix: "api.cloud-aws.adc-e.uk",
implicitGlobalRegion: "eu-isoe-west-1",
name: "aws-iso-e",
supportsDualStack: true,
supportsFIPS: true
},
regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$",
regions: {
"aws-iso-e-global": { description: "aws-iso-e global region" },
"eu-isoe-west-1": { description: "EU ISOE West" }
}
},
{
id: "aws-iso-f",
outputs: {
dnsSuffix: "csp.hci.ic.gov",
dualStackDnsSuffix: "api.aws.hci.ic.gov",
implicitGlobalRegion: "us-isof-south-1",
name: "aws-iso-f",
supportsDualStack: true,
supportsFIPS: true
},
regionRegex: "^us\\-isof\\-\\w+\\-\\d+$",
regions: {
"aws-iso-f-global": { description: "aws-iso-f global region" },
"us-isof-east-1": { description: "US ISOF EAST" },
"us-isof-south-1": { description: "US ISOF SOUTH" }
}
},
{
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-us-gov global region" },
"us-gov-east-1": { description: "AWS GovCloud (US-East)" },
"us-gov-west-1": { description: "AWS GovCloud (US-West)" }
}
}
],
version: "1.1"
};
let selectedPartitionsInfo = partitionsInfo;
let selectedUserAgentPrefix = "";
const partition = (value) => {
const { partitions } = selectedPartitionsInfo;
for (const partition of partitions) {
const { regions, outputs } = partition;
for (const [region, regionData] of Object.entries(regions)) if (region === value) return {
...outputs,
...regionData
};
}
for (const partition of partitions) {
const { regionRegex, outputs } = partition;
if (new RegExp(regionRegex).test(value)) return { ...outputs };
}
const DEFAULT_PARTITION = partitions.find((partition) => partition.id === "aws");
if (!DEFAULT_PARTITION) throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");
return { ...DEFAULT_PARTITION.outputs };
};
const setPartitionInfo = (partitionsInfo, userAgentPrefix = "") => {
selectedPartitionsInfo = partitionsInfo;
selectedUserAgentPrefix = userAgentPrefix;
};
const useDefaultPartitionInfo = () => {
setPartitionInfo(partitionsInfo, "");
};
const getUserAgentPrefix = () => selectedUserAgentPrefix;
const awsEndpointFunctions = {
isVirtualHostableS3Bucket,
parseArn,
partition
};
utilEndpoints.customEndpointFunctions.aws = awsEndpointFunctions;
const resolveDefaultAwsRegionalEndpointsConfig = (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;
};
const toEndpointV1 = (endpoint) => urlParser.parseUrl(endpoint.url);
exports.EndpointError = utilEndpoints.EndpointError;
exports.isIpAddress = utilEndpoints.isIpAddress;
exports.resolveEndpoint = utilEndpoints.resolveEndpoint;
exports.awsEndpointFunctions = awsEndpointFunctions;
exports.getUserAgentPrefix = getUserAgentPrefix;
exports.partition = partition;
exports.resolveDefaultAwsRegionalEndpointsConfig = resolveDefaultAwsRegionalEndpointsConfig;
exports.setPartitionInfo = setPartitionInfo;
exports.toEndpointV1 = toEndpointV1;
exports.useDefaultPartitionInfo = useDefaultPartitionInfo;
}));
//#endregion
//#region node_modules/@smithy/service-error-classification/dist-cjs/index.js
var require_dist_cjs$19 = /* @__PURE__ */ __commonJSMin(((exports) => {
const CLOCK_SKEW_ERROR_CODES = [
"AuthFailure",
"InvalidSignatureException",
"RequestExpired",
"RequestInTheFuture",
"RequestTimeTooSkewed",
"SignatureDoesNotMatch"
];
const THROTTLING_ERROR_CODES = [
"BandwidthLimitExceeded",
"EC2ThrottledException",
"LimitExceededException",
"PriorRequestNotComplete",
"ProvisionedThroughputExceededException",
"RequestLimitExceeded",
"RequestThrottled",
"RequestThrottledException",
"SlowDown",
"ThrottledException",
"Throttling",
"ThrottlingException",
"TooManyRequestsException",
"TransactionInProgressException"
];
const TRANSIENT_ERROR_CODES = [
"TimeoutError",
"RequestTimeout",
"RequestTimeoutException"
];
const TRANSIENT_ERROR_STATUS_CODES = [
500,
502,
503,
504
];
const NODEJS_TIMEOUT_ERROR_CODES = [
"ECONNRESET",
"ECONNREFUSED",
"EPIPE",
"ETIMEDOUT"
];
const NODEJS_NETWORK_ERROR_CODES = [
"EHOSTUNREACH",
"ENETUNREACH",
"ENOTFOUND"
];
const isRetryableByTrait = (error) => error?.$retryable !== void 0;
const isClockSkewError = (error) => CLOCK_SKEW_ERROR_CODES.includes(error.name);
const isClockSkewCorrectedError = (error) => error.$metadata?.clockSkewCorrected;
const isBrowserNetworkError = (error) => {
const errorMessages = new Set([
"Failed to fetch",
"NetworkError when attempting to fetch resource",
"The Internet connection appears to be offline",
"Load failed",
"Network request failed"
]);
if (!(error && error instanceof TypeError)) return false;
return errorMessages.has(error.message);
};
const isThrottlingError = (error) => error.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error.name) || error.$retryable?.throttling == true;
const isTransientError = (error, depth = 0) => isRetryableByTrait(error) || 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);
const isServerError = (error) => {
if (error.$metadata?.httpStatusCode !== void 0) {
const statusCode = error.$metadata.httpStatusCode;
if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) return true;
return false;
}
return false;
};
exports.isBrowserNetworkError = isBrowserNetworkError;
exports.isClockSkewCorrectedError = isClockSkewCorrectedError;
exports.isClockSkewError = isClockSkewError;
exports.isRetryableByTrait = isRetryableByTrait;
exports.isServerError = isServerError;
exports.isThrottlingError = isThrottlingError;
exports.isTransientError = isTransientError;
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/util-retry/dist-cjs/index.js
var require_dist_cjs$18 = /* @__PURE__ */ __commonJSMin(((exports) => {
var serviceErrorClassification = require_dist_cjs$19();
exports.RETRY_MODES = void 0;
(function(RETRY_MODES) {
RETRY_MODES["STANDARD"] = "standard";
RETRY_MODES["ADAPTIVE"] = "adaptive";
})(exports.RETRY_MODES || (exports.RETRY_MODES = {}));
const DEFAULT_MAX_ATTEMPTS = 3;
const DEFAULT_RETRY_MODE = exports.RETRY_MODES.STANDARD;
var DefaultRateLimiter = class DefaultRateLimiter {
static setTimeoutFn = setTimeout;
beta;
minCapacity;
minFillRate;
scaleConstant;
smooth;
currentCapacity = 0;
enabled = false;
lastMaxRate = 0;
measuredTxRate = 0;
requestCount = 0;
fillRate;
lastThrottleTime;
lastTimestamp = 0;
lastTxRateBucket;
maxCapacity;
timeWindow = 0;
constructor(options) {
this.beta = options?.beta ?? .7;
this.minCapacity = options?.minCapacity ?? 1;
this.minFillRate = options?.minFillRate ?? .5;
this.scaleConstant = options?.scaleConstant ?? .4;
this.smooth = options?.smooth ?? .8;
this.lastThrottleTime = this.getCurrentTimeInSeconds();
this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds());
this.fillRate = this.minFillRate;
this.maxCapacity = this.minCapacity;
}
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 (serviceErrorClassification.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));
}
};
const DEFAULT_RETRY_DELAY_BASE = 100;
const MAXIMUM_RETRY_DELAY = 20 * 1e3;
const THROTTLING_RETRY_DELAY_BASE = 500;
const INITIAL_RETRY_TOKENS = 500;
const RETRY_COST = 5;
const TIMEOUT_RETRY_COST = 10;
const NO_RETRY_INCREMENT = 1;
const INVOCATION_ID_HEADER = "amz-sdk-invocation-id";
const REQUEST_HEADER = "amz-sdk-request";
const getDefaultRetryBackoffStrategy = () => {
let delayBase = DEFAULT_RETRY_DELAY_BASE;
const computeNextBackoffDelay = (attempts) => {
return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
};
const setDelayBase = (delay) => {
delayBase = delay;
};
return {
computeNextBackoffDelay,
setDelayBase
};
};
const createDefaultRetryToken = ({ retryDelay, retryCount, retryCost }) => {
const getRetryCount = () => retryCount;
const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay);
const getRetryCost = () => retryCost;
return {
getRetryCount,
getRetryDelay,
getRetryCost
};
};
var StandardRetryStrategy = class {
maxAttempts;
mode = exports.RETRY_MODES.STANDARD;
capacity = INITIAL_RETRY_TOKENS;
retryBackoffStrategy = getDefaultRetryBackoffStrategy();
maxAttemptsProvider;
constructor(maxAttempts) {
this.maxAttempts = maxAttempts;
this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts;
}
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));
}
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) {
return tokenToRenew.getRetryCount() + 1 < 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 AdaptiveRetryStrategy = class {
maxAttemptsProvider;
rateLimiter;
standardRetryStrategy;
mode = exports.RETRY_MODES.ADAPTIVE;
constructor(maxAttemptsProvider, options) {
this.maxAttemptsProvider = maxAttemptsProvider;
const { rateLimiter } = options ?? {};
this.rateLimiter = rateLimiter ?? new DefaultRateLimiter();
this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider);
}
async acquireInitialRetryToken(retryTokenScope) {
await this.rateLimiter.getSendToken();
return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope);
}
async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
this.rateLimiter.updateClientSendingRate(errorInfo);
return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
}
recordSuccess(token) {
this.rateLimiter.updateClientSendingRate({});
this.standardRetryStrategy.recordSuccess(token);
}
};
var ConfiguredRetryStrategy = class extends StandardRetryStrategy {
computeNextBackoffDelay;
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;
}
};
exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy;
exports.ConfiguredRetryStrategy = ConfiguredRetryStrategy;
exports.DEFAULT_MAX_ATTEMPTS = DEFAULT_MAX_ATTEMPTS;
exports.DEFAULT_RETRY_DELAY_BASE = DEFAULT_RETRY_DELAY_BASE;
exports.DEFAULT_RETRY_MODE = DEFAULT_RETRY_MODE;
exports.DefaultRateLimiter = DefaultRateLimiter;
exports.INITIAL_RETRY_TOKENS = INITIAL_RETRY_TOKENS;
exports.INVOCATION_ID_HEADER = INVOCATION_ID_HEADER;
exports.MAXIMUM_RETRY_DELAY = MAXIMUM_RETRY_DELAY;
exports.NO_RETRY_INCREMENT = NO_RETRY_INCREMENT;
exports.REQUEST_HEADER = REQUEST_HEADER;
exports.RETRY_COST = RETRY_COST;
exports.StandardRetryStrategy = StandardRetryStrategy;
exports.THROTTLING_RETRY_DELAY_BASE = THROTTLING_RETRY_DELAY_BASE;
exports.TIMEOUT_RETRY_COST = TIMEOUT_RETRY_COST;
}));
//#endregion
//#region node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js
var require_dist_cjs$17 = /* @__PURE__ */ __commonJSMin(((exports) => {
var core = (init_dist_es(), __toCommonJS(dist_es_exports));
var utilEndpoints = require_dist_cjs$20();
var protocolHttp = require_dist_cjs$34();
var core$1 = (init_dist_es$2(), __toCommonJS(dist_es_exports$2));
var utilRetry = require_dist_cjs$18();
const DEFAULT_UA_APP_ID = void 0;
function isValidUserAgentAppId(appId) {
if (appId === void 0) return true;
return typeof appId === "string" && appId.length <= 50;
}
function resolveUserAgentConfig(input) {
const normalizedAppIdProvider = core.normalizeProvider(input.userAgentAppId ?? DEFAULT_UA_APP_ID);
const { customUserAgent } = input;
return Object.assign(input, {
customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent,
userAgentAppId: 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;
}
});
}
const ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/;
async function checkFeatures(context, config, args) {
if (args.request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") core$1.setFeature(context, "PROTOCOL_RPC_V2_CBOR", "M");
if (typeof config.retryStrategy === "function") {
const retryStrategy = await config.retryStrategy();
if (typeof retryStrategy.mode === "string") switch (retryStrategy.mode) {
case utilRetry.RETRY_MODES.ADAPTIVE:
core$1.setFeature(context, "RETRY_MODE_ADAPTIVE", "F");
break;
case utilRetry.RETRY_MODES.STANDARD:
core$1.setFeature(context, "RETRY_MODE_STANDARD", "E");
break;
}
}
if (typeof config.accountIdEndpointMode === "function") {
const endpointV2 = context.endpointV2;
if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) core$1.setFeature(context, "ACCOUNT_ID_ENDPOINT", "O");
switch (await config.accountIdEndpointMode?.()) {
case "disabled":
core$1.setFeature(context, "ACCOUNT_ID_MODE_DISABLED", "Q");
break;
case "preferred":
core$1.setFeature(context, "ACCOUNT_ID_MODE_PREFERRED", "P");
break;
case "required":
core$1.setFeature(context, "ACCOUNT_ID_MODE_REQUIRED", "R");
break;
}
}
const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity;
if (identity?.$source) {
const credentials = identity;
if (credentials.accountId) core$1.setFeature(context, "RESOLVED_ACCOUNT_ID", "T");
for (const [key, value] of Object.entries(credentials.$source ?? {})) core$1.setFeature(context, key, value);
}
}
const USER_AGENT = "user-agent";
const X_AMZ_USER_AGENT = "x-amz-user-agent";
const SPACE = " ";
const UA_NAME_SEPARATOR = "/";
const UA_NAME_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w]/g;
const UA_VALUE_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w#]/g;
const UA_ESCAPE_CHAR = "-";
const 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;
}
const userAgentMiddleware = (options) => (next, context) => async (args) => {
const { request } = args;
if (!protocolHttp.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 = utilEndpoints.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
});
};
const escapeUserAgent = (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}`;
}
}, "");
};
const getUserAgentMiddlewareOptions = {
name: "getUserAgentMiddleware",
step: "build",
priority: "low",
tags: ["SET_USER_AGENT", "USER_AGENT"],
override: true
};
const getUserAgentPlugin = (config) => ({ applyToStack: (clientStack) => {
clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions);
} });
exports.DEFAULT_UA_APP_ID = DEFAULT_UA_APP_ID;
exports.getUserAgentMiddlewareOptions = getUserAgentMiddlewareOptions;
exports.getUserAgentPlugin = getUserAgentPlugin;
exports.resolveUserAgentConfig = resolveUserAgentConfig;
exports.userAgentMiddleware = userAgentMiddleware;
}));
//#endregion
//#region node_modules/@smithy/util-config-provider/dist-cjs/index.js
var require_dist_cjs$16 = /* @__PURE__ */ __commonJSMin(((exports) => {
const booleanSelector = (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]}.`);
};
const numberSelector = (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;
};
exports.SelectorType = void 0;
(function(SelectorType) {
SelectorType["ENV"] = "env";
SelectorType["CONFIG"] = "shared config entry";
})(exports.SelectorType || (exports.SelectorType = {}));
exports.booleanSelector = booleanSelector;
exports.numberSelector = numberSelector;
}));
//#endregion
//#region node_modules/@smithy/util-endpoints/dist-cjs/index.js
var require_dist_cjs$15 = /* @__PURE__ */ __commonJSMin(((exports) => {
var types = require_dist_cjs$33();
var EndpointCache = class {
capacity;
data = /* @__PURE__ */ new Map();
parameters = [];
constructor({ size, params }) {
this.capacity = size ?? 50;
if (params) this.parameters = params;
}
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);
}
size() {
return this.data.size;
}
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;
}
};
const IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`);
const isIpAddress = (value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]");
const VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);
const isValidHostLabel = (value, allowSubDomains = false) => {
if (!allowSubDomains) return VALID_HOST_LABEL_REGEX.test(value);
const labels = value.split(".");
for (const label of labels) if (!isValidHostLabel(label)) return false;
return true;
};
const customEndpointFunctions = {};
const debugId = "endpoints";
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);
}
var EndpointError = class extends Error {
constructor(message) {
super(message);
this.name = "EndpointError";
}
};
const booleanEquals = (value1, value2) => value1 === value2;
const getAttrPathList = (path) => {
const parts = path.split(".");
const pathList = [];
for (const part of parts) {
const squareBracketIndex = part.indexOf("[");
if (squareBracketIndex !== -1) {
if (part.indexOf("]") !== part.length - 1) throw new 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);
}
return pathList;
};
const getAttr = (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);
const isSet = (value) => value != null;
const not = (value) => !value;
const DEFAULT_PORTS = {
[types.EndpointURLScheme.HTTP]: 80,
[types.EndpointURLScheme.HTTPS]: 443
};
const parseURL = (value) => {
const whatwgURL = (() => {
try {
if (value instanceof URL) return value;
if (typeof value === "object" && "hostname" in value) {
const { hostname, port, protocol = "", path = "", query = {} } = value;
const url = new URL(`${protocol}//${hostname}${port ? `:${port}` : ""}${path}`);
url.search = Object.entries(query).map(([k, v]) => `${k}=${v}`).join("&");
return url;
}
return new URL(value);
} catch (error) {
return null;
}
})();
if (!whatwgURL) {
console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);
return null;
}
const urlString = whatwgURL.href;
const { host, hostname, pathname, protocol, search } = whatwgURL;
if (search) return null;
const scheme = protocol.slice(0, -1);
if (!Object.values(types.EndpointURLScheme).includes(scheme)) return null;
const isIp = isIpAddress(hostname);
return {
scheme,
authority: `${host}${urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`) ? `:${DEFAULT_PORTS[scheme]}` : ``}`,
path: pathname,
normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`,
isIp
};
};
const stringEquals = (value1, value2) => value1 === value2;
const substring = (input, start, stop, reverse) => {
if (start >= stop || input.length < stop || /[^\u0000-\u007f]/.test(input)) return null;
if (!reverse) return input.substring(start, stop);
return input.substring(input.length - stop, input.length - start);
};
const uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
const endpointFunctions = {
booleanEquals,
getAttr,
isSet,
isValidHostLabel,
not,
parseURL,
stringEquals,
substring,
uriEncode
};
const evaluateTemplate = (template, options) => {
const evaluatedTemplateArr = [];
const templateContext = {
...options.endpointParams,
...options.referenceRecord
};
let currentIndex = 0;
while (currentIndex < template.length) {
const openingBraceIndex = template.indexOf("{", currentIndex);
if (openingBraceIndex === -1) {
evaluatedTemplateArr.push(template.slice(currentIndex));
break;
}
evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex));
const closingBraceIndex = template.indexOf("}", openingBraceIndex);
if (closingBraceIndex === -1) {
evaluatedTemplateArr.push(template.slice(openingBraceIndex));
break;
}
if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") {
evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex));
currentIndex = closingBraceIndex + 2;
}
const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex);
if (parameterName.includes("#")) {
const [refName, attrName] = parameterName.split("#");
evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName));
} else evaluatedTemplateArr.push(templateContext[parameterName]);
currentIndex = closingBraceIndex + 1;
}
return evaluatedTemplateArr.join("");
};
const getReferenceValue = ({ ref }, options) => {
return {
...options.endpointParams,
...options.referenceRecord
}[ref];
};
const evaluateExpression = (obj, keyName, options) => {
if (typeof obj === "string") return evaluateTemplate(obj, options);
else if (obj["fn"]) return group$2.callFunction(obj, options);
else if (obj["ref"]) return getReferenceValue(obj, options);
throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`);
};
const callFunction = ({ fn, argv }, options) => {
const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : group$2.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);
};
const group$2 = {
evaluateExpression,
callFunction
};
const evaluateCondition = ({ 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
} }
};
};
const evaluateConditions = (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
};
};
const getEndpointHeaders = (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;
})
}), {});
const getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({
...acc,
[propertyKey]: group$1.getEndpointProperty(propertyVal, options)
}), {});
const getEndpointProperty = (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 group$1.getEndpointProperties(property, options);
case "boolean": return property;
default: throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`);
}
};
const group$1 = {
getEndpointProperty,
getEndpointProperties
};
const getEndpointUrl = (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;
}
throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`);
};
const evaluateEndpointRule = (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)
};
};
const evaluateErrorRule = (errorRule, options) => {
const { conditions, error } = errorRule;
const { result, referenceRecord } = evaluateConditions(conditions, options);
if (!result) return;
throw new EndpointError(evaluateExpression(error, "Error", {
...options,
referenceRecord: {
...options.referenceRecord,
...referenceRecord
}
}));
};
const evaluateRules = (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 = group.evaluateTreeRule(rule, options);
if (endpointOrUndefined) return endpointOrUndefined;
} else throw new EndpointError(`Unknown endpoint rule: ${rule}`);
throw new EndpointError(`Rules evaluation failed`);
};
const evaluateTreeRule = (treeRule, options) => {
const { conditions, rules } = treeRule;
const { result, referenceRecord } = evaluateConditions(conditions, options);
if (!result) return;
return group.evaluateRules(rules, {
...options,
referenceRecord: {
...options.referenceRecord,
...referenceRecord
}
});
};
const group = {
evaluateRules,
evaluateTreeRule
};
const resolveEndpoint = (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;
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}'`);
const endpoint = evaluateRules(rules, {
endpointParams,
logger,
referenceRecord: {}
});
options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);
return endpoint;
};
exports.EndpointCache = EndpointCache;
exports.EndpointError = EndpointError;
exports.customEndpointFunctions = customEndpointFunctions;
exports.isIpAddress = isIpAddress;
exports.isValidHostLabel = isValidHostLabel;
exports.resolveEndpoint = resolveEndpoint;
}));
//#endregion
//#region node_modules/@smithy/config-resolver/dist-cjs/index.js
var require_dist_cjs$14 = /* @__PURE__ */ __commonJSMin(((exports) => {
var utilConfigProvider = require_dist_cjs$16();
var utilMiddleware = require_dist_cjs$40();
var utilEndpoints = require_dist_cjs$15();
const ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT";
const CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
const DEFAULT_USE_DUALSTACK_ENDPOINT = false;
const NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = {
environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.ENV),
configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.CONFIG),
default: false
};
const nodeDualstackConfigSelectors = {
environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.ENV),
configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.CONFIG),
default: void 0
};
const ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT";
const CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint";
const DEFAULT_USE_FIPS_ENDPOINT = false;
const NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = {
environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, ENV_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.ENV),
configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.CONFIG),
default: false
};
const nodeFipsConfigSelectors = {
environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, ENV_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.ENV),
configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.CONFIG),
default: void 0
};
const resolveCustomEndpointsConfig = (input) => {
const { tls, endpoint, urlParser, useDualstackEndpoint } = input;
return Object.assign(input, {
tls: tls ?? true,
endpoint: utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint),
isCustomEndpoint: true,
useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false)
});
};
const getEndpointFromRegion = async (input) => {
const { tls = true } = input;
const region = await input.region();
if (!(/* @__PURE__ */ new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/)).test(region)) throw new Error("Invalid region in client config");
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");
return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`);
};
const resolveEndpointsConfig = (input) => {
const useDualstackEndpoint = utilMiddleware.normalizeProvider(input.useDualstackEndpoint ?? false);
const { endpoint, useFipsEndpoint, urlParser, tls } = input;
return Object.assign(input, {
tls: tls ?? true,
endpoint: endpoint ? utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) : () => getEndpointFromRegion({
...input,
useDualstackEndpoint,
useFipsEndpoint
}),
isCustomEndpoint: !!endpoint,
useDualstackEndpoint
});
};
const REGION_ENV_NAME = "AWS_REGION";
const REGION_INI_NAME = "region";
const NODE_REGION_CONFIG_OPTIONS = {
environmentVariableSelector: (env) => env[REGION_ENV_NAME],
configFileSelector: (profile) => profile[REGION_INI_NAME],
default: () => {
throw new Error("Region is missing");
}
};
const NODE_REGION_CONFIG_FILE_OPTIONS = { preferredFile: "credentials" };
const validRegions = /* @__PURE__ */ new Set();
const checkRegion = (region, check = utilEndpoints.isValidHostLabel) => {
if (!validRegions.has(region) && !check(region)) if (region === "*") console.warn(`@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.`);
else throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`);
else validRegions.add(region);
};
const isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips"));
const getRealRegion = (region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region;
const resolveRegionConfig = (input) => {
const { region, useFipsEndpoint } = input;
if (!region) throw new Error("Region is missing");
return Object.assign(input, {
region: async () => {
const realRegion = getRealRegion(typeof region === "function" ? await region() : region);
checkRegion(realRegion);
return realRegion;
},
useFipsEndpoint: async () => {
if (isFipsRegion(typeof region === "string" ? region : await region())) return true;
return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
}
});
};
const getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))?.hostname;
const getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : void 0;
const getResolvedPartition = (region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws";
const getResolvedSigningRegion = (hostname, { signingRegion, regionRegex, useFipsEndpoint }) => {
if (signingRegion) return signingRegion;
else if (useFipsEndpoint) {
const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\.");
const regionRegexmatchArray = hostname.match(regionRegexJs);
if (regionRegexmatchArray) return regionRegexmatchArray[0].slice(1, -1);
}
};
const getRegionInfo = (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 hostname = getResolvedHostname(resolvedRegion, {
regionHostname: getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions),
partitionHostname: getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions)
});
if (hostname === void 0) throw new Error(`Endpoint resolution failed for: [object Object]`);
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 }
};
};
exports.CONFIG_USE_DUALSTACK_ENDPOINT = CONFIG_USE_DUALSTACK_ENDPOINT;
exports.CONFIG_USE_FIPS_ENDPOINT = CONFIG_USE_FIPS_ENDPOINT;
exports.DEFAULT_USE_DUALSTACK_ENDPOINT = DEFAULT_USE_DUALSTACK_ENDPOINT;
exports.DEFAULT_USE_FIPS_ENDPOINT = DEFAULT_USE_FIPS_ENDPOINT;
exports.ENV_USE_DUALSTACK_ENDPOINT = ENV_USE_DUALSTACK_ENDPOINT;
exports.ENV_USE_FIPS_ENDPOINT = ENV_USE_FIPS_ENDPOINT;
exports.NODE_REGION_CONFIG_FILE_OPTIONS = NODE_REGION_CONFIG_FILE_OPTIONS;
exports.NODE_REGION_CONFIG_OPTIONS = NODE_REGION_CONFIG_OPTIONS;
exports.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS;
exports.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS;
exports.REGION_ENV_NAME = REGION_ENV_NAME;
exports.REGION_INI_NAME = REGION_INI_NAME;
exports.getRegionInfo = getRegionInfo;
exports.nodeDualstackConfigSelectors = nodeDualstackConfigSelectors;
exports.nodeFipsConfigSelectors = nodeFipsConfigSelectors;
exports.resolveCustomEndpointsConfig = resolveCustomEndpointsConfig;
exports.resolveEndpointsConfig = resolveEndpointsConfig;
exports.resolveRegionConfig = resolveRegionConfig;
}));
//#endregion
//#region node_modules/@smithy/middleware-content-length/dist-cjs/index.js
var require_dist_cjs$13 = /* @__PURE__ */ __commonJSMin(((exports) => {
var protocolHttp = require_dist_cjs$34();
const CONTENT_LENGTH_HEADER = "content-length";
function contentLengthMiddleware(bodyLengthChecker) {
return (next) => async (args) => {
const request = args.request;
if (protocolHttp.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
});
};
}
const contentLengthMiddlewareOptions = {
step: "build",
tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"],
name: "contentLengthMiddleware",
override: true
};
const getContentLengthPlugin = (options) => ({ applyToStack: (clientStack) => {
clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions);
} });
exports.contentLengthMiddleware = contentLengthMiddleware;
exports.contentLengthMiddlewareOptions = contentLengthMiddlewareOptions;
exports.getContentLengthPlugin = getContentLengthPlugin;
}));
//#endregion
//#region node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js
var require_getEndpointUrlConfig = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.getEndpointUrlConfig = void 0;
const shared_ini_file_loader_1 = require_dist_cjs$45();
const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL";
const CONFIG_ENDPOINT_URL = "endpoint_url";
const getEndpointUrlConfig = (serviceId) => ({
environmentVariableSelector: (env) => {
const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceId.split(" ").map((w) => w.toUpperCase())].join("_")];
if (serviceEndpointUrl) return serviceEndpointUrl;
const endpointUrl = env[ENV_ENDPOINT_URL];
if (endpointUrl) return endpointUrl;
},
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 endpointUrl = servicesSection[[serviceId.split(" ").map((w) => w.toLowerCase()).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;
},
default: void 0
});
exports.getEndpointUrlConfig = getEndpointUrlConfig;
}));
//#endregion
//#region node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js
var require_getEndpointFromConfig = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.getEndpointFromConfig = void 0;
const node_config_provider_1 = require_dist_cjs$46();
const getEndpointUrlConfig_1 = require_getEndpointUrlConfig();
const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId ?? ""))();
exports.getEndpointFromConfig = getEndpointFromConfig;
}));
//#endregion
//#region node_modules/@smithy/middleware-endpoint/node_modules/@smithy/querystring-parser/dist-cjs/index.js
var require_dist_cjs$12 = /* @__PURE__ */ __commonJSMin(((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];
}
return query;
}
exports.parseQueryString = parseQueryString;
}));
//#endregion
//#region node_modules/@smithy/middleware-endpoint/node_modules/@smithy/url-parser/dist-cjs/index.js
var require_dist_cjs$11 = /* @__PURE__ */ __commonJSMin(((exports) => {
var querystringParser = require_dist_cjs$12();
const parseUrl = (url) => {
if (typeof url === "string") return parseUrl(new URL(url));
const { hostname, pathname, port, protocol, search } = url;
let query;
if (search) query = querystringParser.parseQueryString(search);
return {
hostname,
port: port ? parseInt(port) : void 0,
protocol,
path: pathname,
query
};
};
exports.parseUrl = parseUrl;
}));
//#endregion
//#region node_modules/@smithy/middleware-serde/dist-cjs/index.js
var require_dist_cjs$10 = /* @__PURE__ */ __commonJSMin(((exports) => {
var protocolHttp = require_dist_cjs$34();
var endpoints = (init_endpoints(), __toCommonJS(endpoints_exports));
const deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => {
const { response } = await next(args);
try {
return {
response,
output: await deserializer(response, options)
};
} catch (error) {
Object.defineProperty(error, "$response", {
value: response,
enumerable: false,
writable: false,
configurable: false
});
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;
}
try {
if (protocolHttp.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;
}
};
const findHeader = (pattern, headers) => {
return (headers.find(([k]) => {
return k.match(pattern);
}) || [void 0, void 0])[1];
};
const serializerMiddleware = (options, serializer) => (next, context) => async (args) => {
const endpointConfig = options;
const endpoint = context.endpointV2 ? async () => endpoints.toEndpointV1(context.endpointV2) : endpointConfig.endpoint;
if (!endpoint) throw new Error("No valid endpoint provider available.");
const request = await serializer(args.input, {
...options,
endpoint
});
return next({
...args,
request
});
};
const deserializerMiddlewareOption = {
name: "deserializerMiddleware",
step: "deserialize",
tags: ["DESERIALIZER"],
override: true
};
const 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);
} };
}
exports.deserializerMiddleware = deserializerMiddleware;
exports.deserializerMiddlewareOption = deserializerMiddlewareOption;
exports.getSerdePlugin = getSerdePlugin;
exports.serializerMiddleware = serializerMiddleware;
exports.serializerMiddlewareOption = serializerMiddlewareOption;
}));
//#endregion
//#region node_modules/@smithy/middleware-endpoint/dist-cjs/index.js
var require_dist_cjs$9 = /* @__PURE__ */ __commonJSMin(((exports) => {
var getEndpointFromConfig = require_getEndpointFromConfig();
var urlParser = require_dist_cjs$11();
var core = (init_dist_es$1(), __toCommonJS(dist_es_exports$1));
var utilMiddleware = require_dist_cjs$40();
var middlewareSerde = require_dist_cjs$10();
const resolveParamsForS3 = 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;
};
const DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;
const IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/;
const DOTS_PATTERN = /\.\./;
const isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName);
const isArnBucketName = (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;
};
const createConfigValueProvider = (configKey, canonicalEndpointParamKey, config, isClientContextParam = false) => {
const configProvider = async () => {
let configValue;
if (isClientContextParam) configValue = config.clientContextParams?.[configKey] ?? config[configKey] ?? config[canonicalEndpointParamKey];
else configValue = config[configKey] ?? config[canonicalEndpointParamKey];
if (typeof configValue === "function") return configValue();
return configValue;
};
if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") return async () => {
const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
return credentials?.credentialScope ?? credentials?.CredentialScope;
};
if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") return async () => {
const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
return credentials?.accountId ?? credentials?.AccountId;
};
if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") return async () => {
if (config.isCustomEndpoint === false) return;
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;
};
const toEndpointV1 = (endpoint) => {
if (typeof endpoint === "object") {
if ("url" in endpoint) {
const v1Endpoint = urlParser.parseUrl(endpoint.url);
if (endpoint.headers) {
v1Endpoint.headers = {};
for (const [name, values] of Object.entries(endpoint.headers)) v1Endpoint.headers[name.toLowerCase()] = values.join(", ");
}
return v1Endpoint;
}
return endpoint;
}
return urlParser.parseUrl(endpoint);
};
const getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => {
if (!clientConfig.isCustomEndpoint) {
let endpointFromConfig;
if (clientConfig.serviceConfiguredEndpoint) endpointFromConfig = await clientConfig.serviceConfiguredEndpoint();
else endpointFromConfig = await getEndpointFromConfig.getEndpointFromConfig(clientConfig.serviceId);
if (endpointFromConfig) {
clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig));
clientConfig.isCustomEndpoint = true;
}
}
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);
if (clientConfig.isCustomEndpoint && clientConfig.endpoint) {
const customEndpoint = await clientConfig.endpoint();
if (customEndpoint?.headers) {
endpoint.headers ??= {};
for (const [name, value] of Object.entries(customEndpoint.headers)) endpoint.headers[name] = Array.isArray(value) ? value : [value];
}
}
return endpoint;
};
const resolveParams = 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, instruction.type !== "builtInParams")();
break;
case "operationContextParams":
endpointParams[name] = instruction.get(commandInput);
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;
};
const endpointMiddleware = ({ config, instructions }) => {
return (next, context) => async (args) => {
if (config.isCustomEndpoint) core.setFeature(context, "ENDPOINT_OVERRIDE", "N");
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 httpAuthOption = utilMiddleware.getSmithyContext(context)?.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);
}
return next({ ...args });
};
};
const endpointMiddlewareOptions = {
step: "serialize",
tags: [
"ENDPOINT_PARAMETERS",
"ENDPOINT_V2",
"ENDPOINT"
],
name: "endpointV2Middleware",
override: true,
relation: "before",
toMiddleware: middlewareSerde.serializerMiddlewareOption.name
};
const getEndpointPlugin = (config, instructions) => ({ applyToStack: (clientStack) => {
clientStack.addRelativeTo(endpointMiddleware({
config,
instructions
}), endpointMiddlewareOptions);
} });
const resolveEndpointConfig = (input) => {
const tls = input.tls ?? true;
const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input;
const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await utilMiddleware.normalizeProvider(endpoint)()) : void 0;
const isCustomEndpoint = !!endpoint;
const resolvedConfig = Object.assign(input, {
endpoint: customEndpointProvider,
tls,
isCustomEndpoint,
useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false),
useFipsEndpoint: utilMiddleware.normalizeProvider(useFipsEndpoint ?? false)
});
let configuredEndpointPromise = void 0;
resolvedConfig.serviceConfiguredEndpoint = async () => {
if (input.serviceId && !configuredEndpointPromise) configuredEndpointPromise = getEndpointFromConfig.getEndpointFromConfig(input.serviceId);
return configuredEndpointPromise;
};
return resolvedConfig;
};
const resolveEndpointRequiredConfig = (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;
};
exports.endpointMiddleware = endpointMiddleware;
exports.endpointMiddlewareOptions = endpointMiddlewareOptions;
exports.getEndpointFromInstructions = getEndpointFromInstructions;
exports.getEndpointPlugin = getEndpointPlugin;
exports.resolveEndpointConfig = resolveEndpointConfig;
exports.resolveEndpointRequiredConfig = resolveEndpointRequiredConfig;
exports.resolveParams = resolveParams;
exports.toEndpointV1 = toEndpointV1;
}));
//#endregion
//#region node_modules/@smithy/util-retry/node_modules/@smithy/service-error-classification/dist-cjs/index.js
var require_dist_cjs$8 = /* @__PURE__ */ __commonJSMin(((exports) => {
const CLOCK_SKEW_ERROR_CODES = [
"AuthFailure",
"InvalidSignatureException",
"RequestExpired",
"RequestInTheFuture",
"RequestTimeTooSkewed",
"SignatureDoesNotMatch"
];
const THROTTLING_ERROR_CODES = [
"BandwidthLimitExceeded",
"EC2ThrottledException",
"LimitExceededException",
"PriorRequestNotComplete",
"ProvisionedThroughputExceededException",
"RequestLimitExceeded",
"RequestThrottled",
"RequestThrottledException",
"SlowDown",
"ThrottledException",
"Throttling",
"ThrottlingException",
"TooManyRequestsException",
"TransactionInProgressException"
];
const TRANSIENT_ERROR_CODES = [
"TimeoutError",
"RequestTimeout",
"RequestTimeoutException"
];
const TRANSIENT_ERROR_STATUS_CODES = [
500,
502,
503,
504
];
const NODEJS_TIMEOUT_ERROR_CODES = [
"ECONNRESET",
"ECONNREFUSED",
"EPIPE",
"ETIMEDOUT"
];
const NODEJS_NETWORK_ERROR_CODES = [
"EHOSTUNREACH",
"ENETUNREACH",
"ENOTFOUND"
];
const isRetryableByTrait = (error) => error?.$retryable !== void 0;
const isClockSkewError = (error) => CLOCK_SKEW_ERROR_CODES.includes(error.name);
const isClockSkewCorrectedError = (error) => error.$metadata?.clockSkewCorrected;
const isBrowserNetworkError = (error) => {
const errorMessages = new Set([
"Failed to fetch",
"NetworkError when attempting to fetch resource",
"The Internet connection appears to be offline",
"Load failed",
"Network request failed"
]);
if (!(error && error instanceof TypeError)) return false;
return errorMessages.has(error.message);
};
const isThrottlingError = (error) => error.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error.name) || error.$retryable?.throttling == true;
const isTransientError = (error, depth = 0) => isRetryableByTrait(error) || 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);
const isServerError = (error) => {
if (error.$metadata?.httpStatusCode !== void 0) {
const statusCode = error.$metadata.httpStatusCode;
if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) return true;
return false;
}
return false;
};
exports.isBrowserNetworkError = isBrowserNetworkError;
exports.isClockSkewCorrectedError = isClockSkewCorrectedError;
exports.isClockSkewError = isClockSkewError;
exports.isRetryableByTrait = isRetryableByTrait;
exports.isServerError = isServerError;
exports.isThrottlingError = isThrottlingError;
exports.isTransientError = isTransientError;
}));
//#endregion
//#region node_modules/@smithy/util-retry/dist-cjs/index.js
var require_dist_cjs$7 = /* @__PURE__ */ __commonJSMin(((exports) => {
var serviceErrorClassification = require_dist_cjs$8();
exports.RETRY_MODES = void 0;
(function(RETRY_MODES) {
RETRY_MODES["STANDARD"] = "standard";
RETRY_MODES["ADAPTIVE"] = "adaptive";
})(exports.RETRY_MODES || (exports.RETRY_MODES = {}));
const DEFAULT_MAX_ATTEMPTS = 3;
const DEFAULT_RETRY_MODE = exports.RETRY_MODES.STANDARD;
var DefaultRateLimiter = class DefaultRateLimiter {
static setTimeoutFn = setTimeout;
beta;
minCapacity;
minFillRate;
scaleConstant;
smooth;
currentCapacity = 0;
enabled = false;
lastMaxRate = 0;
measuredTxRate = 0;
requestCount = 0;
fillRate;
lastThrottleTime;
lastTimestamp = 0;
lastTxRateBucket;
maxCapacity;
timeWindow = 0;
constructor(options) {
this.beta = options?.beta ?? .7;
this.minCapacity = options?.minCapacity ?? 1;
this.minFillRate = options?.minFillRate ?? .5;
this.scaleConstant = options?.scaleConstant ?? .4;
this.smooth = options?.smooth ?? .8;
this.lastThrottleTime = this.getCurrentTimeInSeconds();
this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds());
this.fillRate = this.minFillRate;
this.maxCapacity = this.minCapacity;
}
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 (serviceErrorClassification.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));
}
};
const DEFAULT_RETRY_DELAY_BASE = 100;
const MAXIMUM_RETRY_DELAY = 20 * 1e3;
const THROTTLING_RETRY_DELAY_BASE = 500;
const INITIAL_RETRY_TOKENS = 500;
const RETRY_COST = 5;
const TIMEOUT_RETRY_COST = 10;
const NO_RETRY_INCREMENT = 1;
const INVOCATION_ID_HEADER = "amz-sdk-invocation-id";
const REQUEST_HEADER = "amz-sdk-request";
const getDefaultRetryBackoffStrategy = () => {
let delayBase = DEFAULT_RETRY_DELAY_BASE;
const computeNextBackoffDelay = (attempts) => {
return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
};
const setDelayBase = (delay) => {
delayBase = delay;
};
return {
computeNextBackoffDelay,
setDelayBase
};
};
const createDefaultRetryToken = ({ retryDelay, retryCount, retryCost }) => {
const getRetryCount = () => retryCount;
const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay);
const getRetryCost = () => retryCost;
return {
getRetryCount,
getRetryDelay,
getRetryCost
};
};
var StandardRetryStrategy = class {
maxAttempts;
mode = exports.RETRY_MODES.STANDARD;
capacity = INITIAL_RETRY_TOKENS;
retryBackoffStrategy = getDefaultRetryBackoffStrategy();
maxAttemptsProvider;
constructor(maxAttempts) {
this.maxAttempts = maxAttempts;
this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts;
}
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));
}
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) {
return tokenToRenew.getRetryCount() + 1 < 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 AdaptiveRetryStrategy = class {
maxAttemptsProvider;
rateLimiter;
standardRetryStrategy;
mode = exports.RETRY_MODES.ADAPTIVE;
constructor(maxAttemptsProvider, options) {
this.maxAttemptsProvider = maxAttemptsProvider;
const { rateLimiter } = options ?? {};
this.rateLimiter = rateLimiter ?? new DefaultRateLimiter();
this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider);
}
async acquireInitialRetryToken(retryTokenScope) {
await this.rateLimiter.getSendToken();
return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope);
}
async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
this.rateLimiter.updateClientSendingRate(errorInfo);
return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
}
recordSuccess(token) {
this.rateLimiter.updateClientSendingRate({});
this.standardRetryStrategy.recordSuccess(token);
}
};
var ConfiguredRetryStrategy = class extends StandardRetryStrategy {
computeNextBackoffDelay;
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;
}
};
exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy;
exports.ConfiguredRetryStrategy = ConfiguredRetryStrategy;
exports.DEFAULT_MAX_ATTEMPTS = DEFAULT_MAX_ATTEMPTS;
exports.DEFAULT_RETRY_DELAY_BASE = DEFAULT_RETRY_DELAY_BASE;
exports.DEFAULT_RETRY_MODE = DEFAULT_RETRY_MODE;
exports.DefaultRateLimiter = DefaultRateLimiter;
exports.INITIAL_RETRY_TOKENS = INITIAL_RETRY_TOKENS;
exports.INVOCATION_ID_HEADER = INVOCATION_ID_HEADER;
exports.MAXIMUM_RETRY_DELAY = MAXIMUM_RETRY_DELAY;
exports.NO_RETRY_INCREMENT = NO_RETRY_INCREMENT;
exports.REQUEST_HEADER = REQUEST_HEADER;
exports.RETRY_COST = RETRY_COST;
exports.StandardRetryStrategy = StandardRetryStrategy;
exports.THROTTLING_RETRY_DELAY_BASE = THROTTLING_RETRY_DELAY_BASE;
exports.TIMEOUT_RETRY_COST = TIMEOUT_RETRY_COST;
}));
//#endregion
//#region node_modules/@smithy/middleware-retry/node_modules/@smithy/service-error-classification/dist-cjs/index.js
var require_dist_cjs$6 = /* @__PURE__ */ __commonJSMin(((exports) => {
const CLOCK_SKEW_ERROR_CODES = [
"AuthFailure",
"InvalidSignatureException",
"RequestExpired",
"RequestInTheFuture",
"RequestTimeTooSkewed",
"SignatureDoesNotMatch"
];
const THROTTLING_ERROR_CODES = [
"BandwidthLimitExceeded",
"EC2ThrottledException",
"LimitExceededException",
"PriorRequestNotComplete",
"ProvisionedThroughputExceededException",
"RequestLimitExceeded",
"RequestThrottled",
"RequestThrottledException",
"SlowDown",
"ThrottledException",
"Throttling",
"ThrottlingException",
"TooManyRequestsException",
"TransactionInProgressException"
];
const TRANSIENT_ERROR_CODES = [
"TimeoutError",
"RequestTimeout",
"RequestTimeoutException"
];
const TRANSIENT_ERROR_STATUS_CODES = [
500,
502,
503,
504
];
const NODEJS_TIMEOUT_ERROR_CODES = [
"ECONNRESET",
"ECONNREFUSED",
"EPIPE",
"ETIMEDOUT"
];
const NODEJS_NETWORK_ERROR_CODES = [
"EHOSTUNREACH",
"ENETUNREACH",
"ENOTFOUND"
];
const isRetryableByTrait = (error) => error?.$retryable !== void 0;
const isClockSkewError = (error) => CLOCK_SKEW_ERROR_CODES.includes(error.name);
const isClockSkewCorrectedError = (error) => error.$metadata?.clockSkewCorrected;
const isBrowserNetworkError = (error) => {
const errorMessages = new Set([
"Failed to fetch",
"NetworkError when attempting to fetch resource",
"The Internet connection appears to be offline",
"Load failed",
"Network request failed"
]);
if (!(error && error instanceof TypeError)) return false;
return errorMessages.has(error.message);
};
const isThrottlingError = (error) => error.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error.name) || error.$retryable?.throttling == true;
const isTransientError = (error, depth = 0) => isRetryableByTrait(error) || 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);
const isServerError = (error) => {
if (error.$metadata?.httpStatusCode !== void 0) {
const statusCode = error.$metadata.httpStatusCode;
if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) return true;
return false;
}
return false;
};
exports.isBrowserNetworkError = isBrowserNetworkError;
exports.isClockSkewCorrectedError = isClockSkewCorrectedError;
exports.isClockSkewError = isClockSkewError;
exports.isRetryableByTrait = isRetryableByTrait;
exports.isServerError = isServerError;
exports.isThrottlingError = isThrottlingError;
exports.isTransientError = isTransientError;
}));
//#endregion
//#region node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js
var require_isStreamingPayload = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isStreamingPayload = void 0;
const stream_1 = __require("stream");
const isStreamingPayload = (request) => request?.body instanceof stream_1.Readable || typeof ReadableStream !== "undefined" && request?.body instanceof ReadableStream;
exports.isStreamingPayload = isStreamingPayload;
}));
//#endregion
//#region node_modules/@smithy/middleware-retry/dist-cjs/index.js
var require_dist_cjs$5 = /* @__PURE__ */ __commonJSMin(((exports) => {
var utilRetry = require_dist_cjs$7();
var protocolHttp = require_dist_cjs$34();
var serviceErrorClassification = require_dist_cjs$6();
var uuid = require_dist_cjs$36();
var utilMiddleware = require_dist_cjs$40();
var smithyClient = require_dist_cjs$41();
var isStreamingPayload = require_isStreamingPayload();
const getDefaultRetryQuota = (initialRetryTokens, options) => {
const MAX_CAPACITY = initialRetryTokens;
const noRetryIncrement = utilRetry.NO_RETRY_INCREMENT;
const retryCost = utilRetry.RETRY_COST;
const timeoutRetryCost = utilRetry.TIMEOUT_RETRY_COST;
let availableCapacity = initialRetryTokens;
const getCapacityAmount = (error) => error.name === "TimeoutError" ? timeoutRetryCost : retryCost;
const hasRetryTokens = (error) => getCapacityAmount(error) <= availableCapacity;
const retrieveRetryTokens = (error) => {
if (!hasRetryTokens(error)) throw new Error("No retry token available");
const capacityAmount = getCapacityAmount(error);
availableCapacity -= capacityAmount;
return capacityAmount;
};
const releaseRetryTokens = (capacityReleaseAmount) => {
availableCapacity += capacityReleaseAmount ?? noRetryIncrement;
availableCapacity = Math.min(availableCapacity, MAX_CAPACITY);
};
return Object.freeze({
hasRetryTokens,
retrieveRetryTokens,
releaseRetryTokens
});
};
const defaultDelayDecider = (delayBase, attempts) => Math.floor(Math.min(utilRetry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
const defaultRetryDecider = (error) => {
if (!error) return false;
return serviceErrorClassification.isRetryableByTrait(error) || serviceErrorClassification.isClockSkewError(error) || serviceErrorClassification.isThrottlingError(error) || serviceErrorClassification.isTransientError(error);
};
const asSdkError = (error) => {
if (error instanceof Error) return error;
if (error instanceof Object) return Object.assign(/* @__PURE__ */ new Error(), error);
if (typeof error === "string") return new Error(error);
return /* @__PURE__ */ new Error(`AWS SDK error wrapper for ${error}`);
};
var StandardRetryStrategy = class {
maxAttemptsProvider;
retryDecider;
delayDecider;
retryQuota;
mode = utilRetry.RETRY_MODES.STANDARD;
constructor(maxAttemptsProvider, options) {
this.maxAttemptsProvider = maxAttemptsProvider;
this.retryDecider = options?.retryDecider ?? defaultRetryDecider;
this.delayDecider = options?.delayDecider ?? defaultDelayDecider;
this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(utilRetry.INITIAL_RETRY_TOKENS);
}
shouldRetry(error, attempts, maxAttempts) {
return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error);
}
async getMaxAttempts() {
let maxAttempts;
try {
maxAttempts = await this.maxAttemptsProvider();
} catch (error) {
maxAttempts = utilRetry.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 (protocolHttp.HttpRequest.isInstance(request)) request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid.v4();
while (true) try {
if (protocolHttp.HttpRequest.isInstance(request)) request.headers[utilRetry.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(serviceErrorClassification.isThrottlingError(err) ? utilRetry.THROTTLING_RETRY_DELAY_BASE : utilRetry.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;
}
}
};
const getDelayFromRetryAfterHeader = (response) => {
if (!protocolHttp.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;
return new Date(retryAfter).getTime() - Date.now();
};
var AdaptiveRetryStrategy = class extends StandardRetryStrategy {
rateLimiter;
constructor(maxAttemptsProvider, options) {
const { rateLimiter, ...superOptions } = options ?? {};
super(maxAttemptsProvider, superOptions);
this.rateLimiter = rateLimiter ?? new utilRetry.DefaultRateLimiter();
this.mode = utilRetry.RETRY_MODES.ADAPTIVE;
}
async retry(next, args) {
return super.retry(next, args, {
beforeRequest: async () => {
return this.rateLimiter.getSendToken();
},
afterRequest: (response) => {
this.rateLimiter.updateClientSendingRate(response);
}
});
}
};
const ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS";
const CONFIG_MAX_ATTEMPTS = "max_attempts";
const 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}"`);
return maxAttempt;
},
default: utilRetry.DEFAULT_MAX_ATTEMPTS
};
const resolveRetryConfig = (input) => {
const { retryStrategy, retryMode } = input;
const maxAttempts = utilMiddleware.normalizeProvider(input.maxAttempts ?? utilRetry.DEFAULT_MAX_ATTEMPTS);
let controller = retryStrategy ? Promise.resolve(retryStrategy) : void 0;
const getDefault = async () => await utilMiddleware.normalizeProvider(retryMode)() === utilRetry.RETRY_MODES.ADAPTIVE ? new utilRetry.AdaptiveRetryStrategy(maxAttempts) : new utilRetry.StandardRetryStrategy(maxAttempts);
return Object.assign(input, {
maxAttempts,
retryStrategy: () => controller ??= getDefault()
});
};
const ENV_RETRY_MODE = "AWS_RETRY_MODE";
const CONFIG_RETRY_MODE = "retry_mode";
const NODE_RETRY_MODE_CONFIG_OPTIONS = {
environmentVariableSelector: (env) => env[ENV_RETRY_MODE],
configFileSelector: (profile) => profile[CONFIG_RETRY_MODE],
default: utilRetry.DEFAULT_RETRY_MODE
};
const omitRetryHeadersMiddleware = () => (next) => async (args) => {
const { request } = args;
if (protocolHttp.HttpRequest.isInstance(request)) {
delete request.headers[utilRetry.INVOCATION_ID_HEADER];
delete request.headers[utilRetry.REQUEST_HEADER];
}
return next(args);
};
const omitRetryHeadersMiddlewareOptions = {
name: "omitRetryHeadersMiddleware",
tags: [
"RETRY",
"HEADERS",
"OMIT_RETRY_HEADERS"
],
relation: "before",
toMiddleware: "awsAuthMiddleware",
override: true
};
const getOmitRetryHeadersPlugin = (options) => ({ applyToStack: (clientStack) => {
clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions);
} });
const retryMiddleware = (options) => (next, context) => async (args) => {
let retryStrategy = await options.retryStrategy();
const maxAttempts = await options.maxAttempts();
if (isRetryStrategyV2(retryStrategy)) {
retryStrategy = retryStrategy;
let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]);
let lastError = /* @__PURE__ */ new Error();
let attempts = 0;
let totalRetryDelay = 0;
const { request } = args;
const isRequest = protocolHttp.HttpRequest.isInstance(request);
if (isRequest) request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid.v4();
while (true) try {
if (isRequest) request.headers[utilRetry.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 && isStreamingPayload.isStreamingPayload(request)) {
(context.logger instanceof smithyClient.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);
}
};
const isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined";
const getRetryErrorInfo = (error) => {
const errorInfo = {
error,
errorType: getRetryErrorType(error)
};
const retryAfterHint = getRetryAfterHint(error.$response);
if (retryAfterHint) errorInfo.retryAfterHint = retryAfterHint;
return errorInfo;
};
const getRetryErrorType = (error) => {
if (serviceErrorClassification.isThrottlingError(error)) return "THROTTLING";
if (serviceErrorClassification.isTransientError(error)) return "TRANSIENT";
if (serviceErrorClassification.isServerError(error)) return "SERVER_ERROR";
return "CLIENT_ERROR";
};
const retryMiddlewareOptions = {
name: "retryMiddleware",
tags: ["RETRY"],
step: "finalizeRequest",
priority: "high",
override: true
};
const getRetryPlugin = (options) => ({ applyToStack: (clientStack) => {
clientStack.add(retryMiddleware(options), retryMiddlewareOptions);
} });
const getRetryAfterHint = (response) => {
if (!protocolHttp.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 /* @__PURE__ */ new Date(retryAfterSeconds * 1e3);
return new Date(retryAfter);
};
exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy;
exports.CONFIG_MAX_ATTEMPTS = CONFIG_MAX_ATTEMPTS;
exports.CONFIG_RETRY_MODE = CONFIG_RETRY_MODE;
exports.ENV_MAX_ATTEMPTS = ENV_MAX_ATTEMPTS;
exports.ENV_RETRY_MODE = ENV_RETRY_MODE;
exports.NODE_MAX_ATTEMPT_CONFIG_OPTIONS = NODE_MAX_ATTEMPT_CONFIG_OPTIONS;
exports.NODE_RETRY_MODE_CONFIG_OPTIONS = NODE_RETRY_MODE_CONFIG_OPTIONS;
exports.StandardRetryStrategy = StandardRetryStrategy;
exports.defaultDelayDecider = defaultDelayDecider;
exports.defaultRetryDecider = defaultRetryDecider;
exports.getOmitRetryHeadersPlugin = getOmitRetryHeadersPlugin;
exports.getRetryAfterHint = getRetryAfterHint;
exports.getRetryPlugin = getRetryPlugin;
exports.omitRetryHeadersMiddleware = omitRetryHeadersMiddleware;
exports.omitRetryHeadersMiddlewareOptions = omitRetryHeadersMiddlewareOptions;
exports.resolveRetryConfig = resolveRetryConfig;
exports.retryMiddleware = retryMiddleware;
exports.retryMiddlewareOptions = retryMiddlewareOptions;
}));
//#endregion
//#region node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js
var require_dist_cjs$4 = /* @__PURE__ */ __commonJSMin(((exports) => {
var node_os = __require("node:os");
var node_process = __require("node:process");
var utilConfigProvider = require_dist_cjs$16();
var promises = __require("node:fs/promises");
var node_path = __require("node:path");
var middlewareUserAgent = require_dist_cjs$17();
const getRuntimeUserAgentPair = () => {
for (const runtime of [
"deno",
"bun",
"llrt"
]) if (node_process.versions[runtime]) return [`md/${runtime}`, node_process.versions[runtime]];
return ["md/nodejs", node_process.versions.node];
};
const getNodeModulesParentDirs = (dirname) => {
const cwd = process.cwd();
if (!dirname) return [cwd];
const normalizedPath = node_path.normalize(dirname);
const parts = normalizedPath.split(node_path.sep);
const nodeModulesIndex = parts.indexOf("node_modules");
const parentDir = nodeModulesIndex !== -1 ? parts.slice(0, nodeModulesIndex).join(node_path.sep) : normalizedPath;
if (cwd === parentDir) return [cwd];
return [parentDir, cwd];
};
const SEMVER_REGEX = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;
const getSanitizedTypeScriptVersion = (version = "") => {
const match = version.match(SEMVER_REGEX);
if (!match) return;
const [major, minor, patch, prerelease] = [
match[1],
match[2],
match[3],
match[4]
];
return prerelease ? `${major}.${minor}.${patch}-${prerelease}` : `${major}.${minor}.${patch}`;
};
const ALLOWED_PREFIXES = [
"^",
"~",
">=",
"<=",
">",
"<"
];
const ALLOWED_DIST_TAGS = [
"latest",
"beta",
"dev",
"rc",
"insiders",
"next"
];
const getSanitizedDevTypeScriptVersion = (version = "") => {
if (ALLOWED_DIST_TAGS.includes(version)) return version;
const prefix = ALLOWED_PREFIXES.find((p) => version.startsWith(p)) ?? "";
const sanitizedTypeScriptVersion = getSanitizedTypeScriptVersion(version.slice(prefix.length));
if (!sanitizedTypeScriptVersion) return;
return `${prefix}${sanitizedTypeScriptVersion}`;
};
let tscVersion;
const TS_PACKAGE_JSON = node_path.join("node_modules", "typescript", "package.json");
const getTypeScriptUserAgentPair = async () => {
if (tscVersion === null) return;
else if (typeof tscVersion === "string") return ["md/tsc", tscVersion];
let isTypeScriptDetectionDisabled = false;
try {
isTypeScriptDetectionDisabled = utilConfigProvider.booleanSelector(process.env, "AWS_SDK_JS_TYPESCRIPT_DETECTION_DISABLED", utilConfigProvider.SelectorType.ENV) || false;
} catch {}
if (isTypeScriptDetectionDisabled) {
tscVersion = null;
return;
}
const nodeModulesParentDirs = getNodeModulesParentDirs(typeof __dirname !== "undefined" ? __dirname : void 0);
let versionFromApp;
for (const nodeModulesParentDir of nodeModulesParentDirs) try {
const appPackageJsonPath = node_path.join(nodeModulesParentDir, "package.json");
const packageJson = await promises.readFile(appPackageJsonPath, "utf-8");
const { dependencies, devDependencies } = JSON.parse(packageJson);
const version = devDependencies?.typescript ?? dependencies?.typescript;
if (typeof version !== "string") continue;
versionFromApp = version;
break;
} catch {}
if (!versionFromApp) {
tscVersion = null;
return;
}
let versionFromNodeModules;
for (const nodeModulesParentDir of nodeModulesParentDirs) try {
const tsPackageJsonPath = node_path.join(nodeModulesParentDir, TS_PACKAGE_JSON);
const packageJson = await promises.readFile(tsPackageJsonPath, "utf-8");
const { version } = JSON.parse(packageJson);
const sanitizedVersion = getSanitizedTypeScriptVersion(version);
if (typeof sanitizedVersion !== "string") continue;
versionFromNodeModules = sanitizedVersion;
break;
} catch {}
if (versionFromNodeModules) {
tscVersion = versionFromNodeModules;
return ["md/tsc", tscVersion];
}
const sanitizedVersion = getSanitizedDevTypeScriptVersion(versionFromApp);
if (typeof sanitizedVersion !== "string") {
tscVersion = null;
return;
}
tscVersion = `dev_${sanitizedVersion}`;
return ["md/tsc", tscVersion];
};
const crtAvailability = { isCrtAvailable: false };
const isCrtAvailable = () => {
if (crtAvailability.isCrtAvailable) return ["md/crt-avail"];
return null;
};
const createDefaultUserAgentProvider = ({ serviceId, clientVersion }) => {
const runtimeUserAgentPair = getRuntimeUserAgentPair();
return async (config) => {
const sections = [
["aws-sdk-js", clientVersion],
["ua", "2.1"],
[`os/${node_os.platform()}`, node_os.release()],
["lang/js"],
runtimeUserAgentPair
];
const typescriptUserAgentPair = await getTypeScriptUserAgentPair();
if (typescriptUserAgentPair) sections.push(typescriptUserAgentPair);
const crtAvailable = isCrtAvailable();
if (crtAvailable) sections.push(crtAvailable);
if (serviceId) sections.push([`api/${serviceId}`, clientVersion]);
if (node_process.env.AWS_EXECUTION_ENV) sections.push([`exec-env/${node_process.env.AWS_EXECUTION_ENV}`]);
const appId = await config?.userAgentAppId?.();
return appId ? [...sections, [`app/${appId}`]] : [...sections];
};
};
const defaultUserAgent = createDefaultUserAgentProvider;
const UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID";
const UA_APP_ID_INI_NAME = "sdk_ua_app_id";
const UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id";
exports.NODE_APP_ID_CONFIG_OPTIONS = {
environmentVariableSelector: (env) => env[UA_APP_ID_ENV_NAME],
configFileSelector: (profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED],
default: middlewareUserAgent.DEFAULT_UA_APP_ID
};
exports.UA_APP_ID_ENV_NAME = UA_APP_ID_ENV_NAME;
exports.UA_APP_ID_INI_NAME = UA_APP_ID_INI_NAME;
exports.createDefaultUserAgentProvider = createDefaultUserAgentProvider;
exports.crtAvailability = crtAvailability;
exports.defaultUserAgent = defaultUserAgent;
}));
//#endregion
//#region node_modules/@smithy/hash-node/dist-cjs/index.js
var require_dist_cjs$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
var utilBufferFrom = require_dist_cjs$43();
var utilUtf8 = require_dist_cjs$42();
var buffer = __require("buffer");
var crypto = __require("crypto");
var Hash = class {
algorithmIdentifier;
secret;
hash;
constructor(algorithmIdentifier, secret) {
this.algorithmIdentifier = algorithmIdentifier;
this.secret = secret;
this.reset();
}
update(toHash, encoding) {
this.hash.update(utilUtf8.toUint8Array(castSourceData(toHash, encoding)));
}
digest() {
return Promise.resolve(this.hash.digest());
}
reset() {
this.hash = this.secret ? crypto.createHmac(this.algorithmIdentifier, castSourceData(this.secret)) : crypto.createHash(this.algorithmIdentifier);
}
};
function castSourceData(toCast, encoding) {
if (buffer.Buffer.isBuffer(toCast)) return toCast;
if (typeof toCast === "string") return utilBufferFrom.fromString(toCast, encoding);
if (ArrayBuffer.isView(toCast)) return utilBufferFrom.fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength);
return utilBufferFrom.fromArrayBuffer(toCast);
}
exports.Hash = Hash;
}));
//#endregion
//#region node_modules/@smithy/util-body-length-node/dist-cjs/index.js
var require_dist_cjs$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
var node_fs = __require("node:fs");
const calculateBodyLength = (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 (body instanceof node_fs.ReadStream) {
if (body.path != null) return node_fs.lstatSync(body.path).size;
else if (typeof body.fd === "number") return node_fs.fstatSync(body.fd).size;
}
throw new Error(`Body Length computation failed for ${body}`);
};
exports.calculateBodyLength = calculateBodyLength;
}));
//#endregion
//#region node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js
var require_dist_cjs$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
var configResolver = require_dist_cjs$14();
var nodeConfigProvider = require_dist_cjs$46();
var propertyProvider = require_dist_cjs$47();
const AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV";
const AWS_REGION_ENV = "AWS_REGION";
const AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION";
const ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";
const DEFAULTS_MODE_OPTIONS = [
"in-region",
"cross-region",
"mobile",
"standard",
"legacy"
];
const IMDS_REGION_PATH = "/latest/meta-data/placement/region";
const AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE";
const AWS_DEFAULTS_MODE_CONFIG = "defaults_mode";
const NODE_DEFAULTS_MODE_CONFIG_OPTIONS = {
environmentVariableSelector: (env) => {
return env[AWS_DEFAULTS_MODE_ENV];
},
configFileSelector: (profile) => {
return profile[AWS_DEFAULTS_MODE_CONFIG];
},
default: "legacy"
};
const resolveDefaultsModeConfig = ({ region = nodeConfigProvider.loadConfig(configResolver.NODE_REGION_CONFIG_OPTIONS), defaultsMode = nodeConfigProvider.loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) } = {}) => propertyProvider.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}`);
}
});
const resolveNodeDefaultsModeAuto = async (clientRegion) => {
if (clientRegion) {
const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion;
const inferredRegion = await inferPhysicalRegion();
if (!inferredRegion) return "standard";
if (resolvedRegion === inferredRegion) return "in-region";
else return "cross-region";
}
return "standard";
};
const inferPhysicalRegion = async () => {
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 import("./dist-cjs-DHGjYoGG.js").then((m) => /* @__PURE__ */ __toESM(m.default));
return (await httpRequest({
...await getInstanceMetadataEndpoint(),
path: IMDS_REGION_PATH
})).toString();
} catch (e) {}
};
exports.resolveDefaultsModeConfig = resolveDefaultsModeConfig;
}));
//#endregion
//#region node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js
var require_stsRegionDefaultResolver = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.warning = void 0;
exports.stsRegionDefaultResolver = stsRegionDefaultResolver;
const config_resolver_1 = require_dist_cjs$14();
const node_config_provider_1 = require_dist_cjs$46();
function stsRegionDefaultResolver(loaderConfig = {}) {
return (0, node_config_provider_1.loadConfig)({
...config_resolver_1.NODE_REGION_CONFIG_OPTIONS,
async default() {
if (!exports.warning.silence) console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly.");
return "us-east-1";
}
}, {
...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS,
...loaderConfig
});
}
exports.warning = { silence: false };
}));
//#endregion
//#region node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js
var require_dist_cjs = /* @__PURE__ */ __commonJSMin(((exports) => {
var stsRegionDefaultResolver = require_stsRegionDefaultResolver();
var configResolver = require_dist_cjs$14();
const getAwsRegionExtensionConfiguration = (runtimeConfig) => {
return {
setRegion(region) {
runtimeConfig.region = region;
},
region() {
return runtimeConfig.region;
}
};
};
const resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => {
return { region: awsRegionExtensionConfiguration.region() };
};
exports.NODE_REGION_CONFIG_FILE_OPTIONS = configResolver.NODE_REGION_CONFIG_FILE_OPTIONS;
exports.NODE_REGION_CONFIG_OPTIONS = configResolver.NODE_REGION_CONFIG_OPTIONS;
exports.REGION_ENV_NAME = configResolver.REGION_ENV_NAME;
exports.REGION_INI_NAME = configResolver.REGION_INI_NAME;
exports.resolveRegionConfig = configResolver.resolveRegionConfig;
exports.getAwsRegionExtensionConfiguration = getAwsRegionExtensionConfiguration;
exports.resolveAwsRegionExtensionConfiguration = resolveAwsRegionExtensionConfiguration;
Object.prototype.hasOwnProperty.call(stsRegionDefaultResolver, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", {
enumerable: true,
value: stsRegionDefaultResolver["__proto__"]
});
Object.keys(stsRegionDefaultResolver).forEach(function(k) {
if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = stsRegionDefaultResolver[k];
});
}));
//#endregion
export { init_httpAuthSchemes$2 as A, dist_es_exports$2 as C, AwsQueryProtocol as D, protocols_exports as E, require_dist_cjs$27 as M, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS as N, AwsRestJsonProtocol as O, AwsSdkSigV4Signer as P, require_dist_cjs$25 as S, init_protocols$1 as T, DefaultIdentityProviderConfig$1 as _, require_dist_cjs$4 as a, require_dist_cjs$23 as b, require_dist_cjs$9 as c, require_dist_cjs$15 as d, require_dist_cjs$17 as f, NoAuthSigner$1 as g, init_dist_es$1 as h, require_dist_cjs$3 as i, resolveAwsSdkSigV4Config as j, httpAuthSchemes_exports as k, require_dist_cjs$13 as l, dist_es_exports$1 as m, require_dist_cjs$1 as n, require_dist_cjs$5 as o, require_dist_cjs$20 as p, require_dist_cjs$2 as r, require_dist_cjs$7 as s, require_dist_cjs as t, require_dist_cjs$14 as u, getHttpSigningPlugin$1 as v, init_dist_es$2 as w, require_dist_cjs$24 as x, getHttpAuthSchemeEndpointRuleSetPlugin$1 as y };