Add extracted source directory and README navigation

This commit is contained in:
Shawn Bot
2026-03-31 14:56:06 +00:00
parent 6252bb6eb5
commit 91e01d755b
4757 changed files with 984951 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,51 @@
'use strict';
const state = {
warningEmitted: false,
};
const emitWarningIfUnsupportedVersion = (version) => {
if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) {
state.warningEmitted = true;
process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will
no longer support Node.js 16.x on January 6, 2025.
To continue receiving updates to AWS services, bug fixes, and security
updates please upgrade to a supported Node.js LTS version.
More information can be found at: https://a.co/74kJMmI`);
}
};
function setCredentialFeature(credentials, feature, value) {
if (!credentials.$source) {
credentials.$source = {};
}
credentials.$source[feature] = value;
return credentials;
}
function setFeature(context, feature, value) {
if (!context.__aws_sdk_context) {
context.__aws_sdk_context = {
features: {},
};
}
else if (!context.__aws_sdk_context.features) {
context.__aws_sdk_context.features = {};
}
context.__aws_sdk_context.features[feature] = value;
}
function setTokenFeature(token, feature, value) {
if (!token.$source) {
token.$source = {};
}
token.$source[feature] = value;
return token;
}
exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion;
exports.setCredentialFeature = setCredentialFeature;
exports.setFeature = setFeature;
exports.setTokenFeature = setTokenFeature;
exports.state = state;

View File

@@ -0,0 +1,299 @@
'use strict';
var protocolHttp = require('@smithy/protocol-http');
var core = require('@smithy/core');
var propertyProvider = require('@smithy/property-provider');
var client = require('@aws-sdk/core/client');
var signatureV4 = require('@smithy/signature-v4');
const getDateHeader = (response) => protocolHttp.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : undefined;
const getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset);
const isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 300000;
const getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => {
const clockTimeInMs = Date.parse(clockTime);
if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) {
return clockTimeInMs - Date.now();
}
return currentSystemClockOffset;
};
const throwSigningPropertyError = (name, property) => {
if (!property) {
throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`);
}
return property;
};
const validateSigningProperties = async (signingProperties) => {
const context = throwSigningPropertyError("context", signingProperties.context);
const config = throwSigningPropertyError("config", signingProperties.config);
const authScheme = context.endpointV2?.properties?.authSchemes?.[0];
const signerFunction = throwSigningPropertyError("signer", config.signer);
const signer = await signerFunction(authScheme);
const signingRegion = signingProperties?.signingRegion;
const signingRegionSet = signingProperties?.signingRegionSet;
const signingName = signingProperties?.signingName;
return {
config,
signer,
signingRegion,
signingRegionSet,
signingName,
};
};
class AwsSdkSigV4Signer {
async sign(httpRequest, identity, signingProperties) {
if (!protocolHttp.HttpRequest.isInstance(httpRequest)) {
throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
}
const validatedProps = await validateSigningProperties(signingProperties);
const { config, signer } = validatedProps;
let { signingRegion, signingName } = validatedProps;
const handlerExecutionContext = signingProperties.context;
if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) {
const [first, second] = handlerExecutionContext.authSchemes;
if (first?.name === "sigv4a" && second?.name === "sigv4") {
signingRegion = second?.signingRegion ?? signingRegion;
signingName = second?.signingName ?? signingName;
}
}
const signedRequest = await signer.sign(httpRequest, {
signingDate: getSkewCorrectedDate(config.systemClockOffset),
signingRegion: signingRegion,
signingService: signingName,
});
return signedRequest;
}
errorHandler(signingProperties) {
return (error) => {
const serverTime = error.ServerTime ?? getDateHeader(error.$response);
if (serverTime) {
const config = throwSigningPropertyError("config", signingProperties.config);
const initialSystemClockOffset = config.systemClockOffset;
config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset);
const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset;
if (clockSkewCorrected && error.$metadata) {
error.$metadata.clockSkewCorrected = true;
}
}
throw error;
};
}
successHandler(httpResponse, signingProperties) {
const dateHeader = getDateHeader(httpResponse);
if (dateHeader) {
const config = throwSigningPropertyError("config", signingProperties.config);
config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset);
}
}
}
const AWSSDKSigV4Signer = AwsSdkSigV4Signer;
class AwsSdkSigV4ASigner extends AwsSdkSigV4Signer {
async sign(httpRequest, identity, signingProperties) {
if (!protocolHttp.HttpRequest.isInstance(httpRequest)) {
throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
}
const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties);
const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.();
const multiRegionOverride = (configResolvedSigningRegionSet ??
signingRegionSet ?? [signingRegion]).join(",");
const signedRequest = await signer.sign(httpRequest, {
signingDate: getSkewCorrectedDate(config.systemClockOffset),
signingRegion: multiRegionOverride,
signingService: signingName,
});
return signedRequest;
}
}
const getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [];
const getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`;
const NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE";
const NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference";
const NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = {
environmentVariableSelector: (env, options) => {
if (options?.signingName) {
const bearerTokenKey = getBearerTokenEnvKey(options.signingName);
if (bearerTokenKey in env)
return ["httpBearerAuth"];
}
if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env))
return undefined;
return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]);
},
configFileSelector: (profile) => {
if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile))
return undefined;
return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]);
},
default: [],
};
const resolveAwsSdkSigV4AConfig = (config) => {
config.sigv4aSigningRegionSet = core.normalizeProvider(config.sigv4aSigningRegionSet);
return config;
};
const 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 propertyProvider.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 propertyProvider.ProviderError("sigv4a_signing_region_set not set in profile.", {
tryNextLink: true,
});
},
default: undefined,
};
const resolveAwsSdkSigV4Config = (config) => {
let inputCredentials = config.credentials;
let isUserSupplied = !!config.credentials;
let resolvedCredentials = undefined;
Object.defineProperty(config, "credentials", {
set(credentials) {
if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) {
isUserSupplied = true;
}
inputCredentials = credentials;
const memoizedProvider = normalizeCredentialProvider(config, {
credentials: inputCredentials,
credentialDefaultProvider: config.credentialDefaultProvider,
});
const boundProvider = bindCallerConfig(config, memoizedProvider);
if (isUserSupplied && !boundProvider.attributed) {
resolvedCredentials = async (options) => boundProvider(options).then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_CODE", "e"));
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 = core.normalizeProvider(config.signer);
}
else if (config.regionInfoProvider) {
signer = () => core.normalizeProvider(config.region)()
.then(async (region) => [
(await config.regionInfoProvider(region, {
useFipsEndpoint: await config.useFipsEndpoint(),
useDualstackEndpoint: await config.useDualstackEndpoint(),
})) || {},
region,
])
.then(([regionInfo, region]) => {
const { signingRegion, signingService } = regionInfo;
config.signingRegion = config.signingRegion || signingRegion || region;
config.signingName = config.signingName || signingService || config.serviceId;
const params = {
...config,
credentials: config.credentials,
region: config.signingRegion,
service: config.signingName,
sha256,
uriEscapePath: signingEscapePath,
};
const SignerCtor = config.signerConstructor || signatureV4.SignatureV4;
return new SignerCtor(params);
});
}
else {
signer = async (authScheme) => {
authScheme = Object.assign({}, {
name: "sigv4",
signingName: config.signingName || config.defaultSigningName,
signingRegion: await core.normalizeProvider(config.region)(),
properties: {},
}, authScheme);
const signingRegion = authScheme.signingRegion;
const signingService = authScheme.signingName;
config.signingRegion = config.signingRegion || signingRegion;
config.signingName = config.signingName || signingService || config.serviceId;
const params = {
...config,
credentials: config.credentials,
region: config.signingRegion,
service: config.signingName,
sha256,
uriEscapePath: signingEscapePath,
};
const SignerCtor = config.signerConstructor || signatureV4.SignatureV4;
return new SignerCtor(params);
};
}
const resolvedConfig = Object.assign(config, {
systemClockOffset,
signingEscapePath,
signer,
});
return resolvedConfig;
};
const resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config;
function normalizeCredentialProvider(config, { credentials, credentialDefaultProvider, }) {
let credentialsProvider;
if (credentials) {
if (!credentials?.memoized) {
credentialsProvider = core.memoizeIdentityProvider(credentials, core.isIdentityExpired, core.doesIdentityRequireRefresh);
}
else {
credentialsProvider = credentials;
}
}
else {
if (credentialDefaultProvider) {
credentialsProvider = core.normalizeProvider(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;
}
exports.AWSSDKSigV4Signer = AWSSDKSigV4Signer;
exports.AwsSdkSigV4ASigner = AwsSdkSigV4ASigner;
exports.AwsSdkSigV4Signer = AwsSdkSigV4Signer;
exports.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = NODE_AUTH_SCHEME_PREFERENCE_OPTIONS;
exports.NODE_SIGV4A_CONFIG_OPTIONS = NODE_SIGV4A_CONFIG_OPTIONS;
exports.getBearerTokenEnvKey = getBearerTokenEnvKey;
exports.resolveAWSSDKSigV4Config = resolveAWSSDKSigV4Config;
exports.resolveAwsSdkSigV4AConfig = resolveAwsSdkSigV4AConfig;
exports.resolveAwsSdkSigV4Config = resolveAwsSdkSigV4Config;
exports.validateSigningProperties = validateSigningProperties;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,169 @@
'use strict';
var types = require('@smithy/types');
const getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
return {
setHttpHandler(handler) {
runtimeConfig.httpHandler = handler;
},
httpHandler() {
return runtimeConfig.httpHandler;
},
updateHttpClientConfig(key, value) {
runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
},
httpHandlerConfigs() {
return runtimeConfig.httpHandler.httpHandlerConfigs();
},
};
};
const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
return {
httpHandler: httpHandlerExtensionConfiguration.httpHandler(),
};
};
class Field {
name;
kind;
values;
constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) {
this.name = name;
this.kind = kind;
this.values = values;
}
add(value) {
this.values.push(value);
}
set(values) {
this.values = values;
}
remove(value) {
this.values = this.values.filter((v) => v !== value);
}
toString() {
return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", ");
}
get() {
return this.values;
}
}
class Fields {
entries = {};
encoding;
constructor({ fields = [], encoding = "utf-8" }) {
fields.forEach(this.setField.bind(this));
this.encoding = encoding;
}
setField(field) {
this.entries[field.name.toLowerCase()] = field;
}
getField(name) {
return this.entries[name.toLowerCase()];
}
removeField(name) {
delete this.entries[name.toLowerCase()];
}
getByType(kind) {
return Object.values(this.entries).filter((field) => field.kind === kind);
}
}
class HttpRequest {
method;
protocol;
hostname;
port;
path;
query;
headers;
username;
password;
fragment;
body;
constructor(options) {
this.method = options.method || "GET";
this.hostname = options.hostname || "localhost";
this.port = options.port;
this.query = options.query || {};
this.headers = options.headers || {};
this.body = options.body;
this.protocol = options.protocol
? options.protocol.slice(-1) !== ":"
? `${options.protocol}:`
: options.protocol
: "https:";
this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/";
this.username = options.username;
this.password = options.password;
this.fragment = options.fragment;
}
static clone(request) {
const cloned = new HttpRequest({
...request,
headers: { ...request.headers },
});
if (cloned.query) {
cloned.query = cloneQuery(cloned.query);
}
return cloned;
}
static isInstance(request) {
if (!request) {
return false;
}
const req = request;
return ("method" in req &&
"protocol" in req &&
"hostname" in req &&
"path" in req &&
typeof req["query"] === "object" &&
typeof req["headers"] === "object");
}
clone() {
return HttpRequest.clone(this);
}
}
function cloneQuery(query) {
return Object.keys(query).reduce((carry, paramName) => {
const param = query[paramName];
return {
...carry,
[paramName]: Array.isArray(param) ? [...param] : param,
};
}, {});
}
class HttpResponse {
statusCode;
reason;
headers;
body;
constructor(options) {
this.statusCode = options.statusCode;
this.reason = options.reason;
this.headers = options.headers || {};
this.body = options.body;
}
static isInstance(response) {
if (!response)
return false;
const resp = response;
return typeof resp.statusCode === "number" && typeof resp.headers === "object";
}
}
function isValidHostname(hostname) {
const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
return hostPattern.test(hostname);
}
exports.Field = Field;
exports.Fields = Fields;
exports.HttpRequest = HttpRequest;
exports.HttpResponse = HttpResponse;
exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
exports.isValidHostname = isValidHostname;
exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;

View File

@@ -0,0 +1,556 @@
'use strict';
var utilHexEncoding = require('@smithy/util-hex-encoding');
var utilUtf8 = require('@smithy/util-utf8');
var isArrayBuffer = require('@smithy/is-array-buffer');
var protocolHttp = require('@smithy/protocol-http');
var utilMiddleware = require('@smithy/util-middleware');
var utilUriEscape = require('@smithy/util-uri-escape');
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 = 60 * 60 * 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] == undefined) {
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 == undefined) {
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;
};
class HeaderFormatter {
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 = new DataView(new ArrayBuffer(3));
shortView.setUint8(0, 3);
shortView.setInt16(1, header.value, false);
return new Uint8Array(shortView.buffer);
case "integer":
const intView = new DataView(new ArrayBuffer(5));
intView.setUint8(0, 4);
intView.setInt32(1, header.value, false);
return new Uint8Array(intView.buffer);
case "long":
const longBytes = new Uint8Array(9);
longBytes[0] = 5;
longBytes.set(header.value.bytes, 1);
return longBytes;
case "binary":
const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
binView.setUint8(0, 6);
binView.setUint16(1, header.value.byteLength, false);
const binBytes = new Uint8Array(binView.buffer);
binBytes.set(header.value, 3);
return binBytes;
case "string":
const utf8Bytes = 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}$/;
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 > 9_223_372_036_854_775_807 || number < -9223372036854776e3) {
throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);
}
const bytes = new Uint8Array(8);
for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) {
bytes[i] = remaining;
}
if (number < 0) {
negate(bytes);
}
return new Int64(bytes);
}
valueOf() {
const bytes = this.bytes.slice(0);
const negative = bytes[0] & 0b10000000;
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] ^= 0xff;
}
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 new Date(time * 1000);
}
if (typeof time === "string") {
if (Number(time)) {
return new Date(Number(time) * 1000);
}
return new Date(time);
}
return time;
};
class SignatureV4Base {
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("/") ? "/" : ""}`;
const doubleEncoded = utilUriEscape.escapeUri(normalizedPath);
return doubleEncoded.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(";");
}
}
class SignatureV4 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 = 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 = new Date(), priorSignature, signingRegion, signingService }) {
const region = signingRegion ?? (await this.regionProvider());
const { shortDate, longDate } = this.formatDate(signingDate);
const scope = createScope(shortDate, region, signingService ?? this.service);
const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256);
const hash = new this.sha256();
hash.update(headers);
const hashedHeaders = utilHexEncoding.toHex(await hash.digest());
const stringToSign = [
EVENT_ALGORITHM_IDENTIFIER,
longDate,
scope,
priorSignature,
hashedHeaders,
hashedPayload,
].join("\n");
return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });
}
async signMessage(signableMessage, { signingDate = new Date(), signingRegion, signingService }) {
const promise = this.signEvent({
headers: this.headerFormatter.format(signableMessage.message.headers),
payload: signableMessage.message.body,
}, {
signingDate,
signingRegion,
signingService,
priorSignature: signableMessage.priorSignature,
});
return promise.then((signature) => {
return { message: signableMessage.message, signature };
});
}
async signString(stringToSign, { signingDate = new Date(), signingRegion, signingService } = {}) {
const credentials = await this.credentialProvider();
this.validateResolvedCredentials(credentials);
const region = signingRegion ?? (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 = 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;

View File

@@ -0,0 +1,6 @@
'use strict';
const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) ||
Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
exports.isArrayBuffer = isArrayBuffer;

View File

@@ -0,0 +1,38 @@
'use strict';
const SHORT_TO_HEX = {};
const HEX_TO_SHORT = {};
for (let i = 0; i < 256; i++) {
let encodedByte = i.toString(16).toLowerCase();
if (encodedByte.length === 1) {
encodedByte = `0${encodedByte}`;
}
SHORT_TO_HEX[i] = encodedByte;
HEX_TO_SHORT[encodedByte] = i;
}
function fromHex(encoded) {
if (encoded.length % 2 !== 0) {
throw new Error("Hex encoded strings must have an even number length");
}
const out = new Uint8Array(encoded.length / 2);
for (let i = 0; i < encoded.length; i += 2) {
const encodedByte = encoded.slice(i, i + 2).toLowerCase();
if (encodedByte in HEX_TO_SHORT) {
out[i / 2] = HEX_TO_SHORT[encodedByte];
}
else {
throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
}
}
return out;
}
function toHex(bytes) {
let out = "";
for (let i = 0; i < bytes.byteLength; i++) {
out += SHORT_TO_HEX[bytes[i]];
}
return out;
}
exports.fromHex = fromHex;
exports.toHex = toHex;

View File

@@ -0,0 +1,9 @@
'use strict';
const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode);
const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`;
const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/");
exports.escapeUri = escapeUri;
exports.escapeUriPath = escapeUriPath;

View File

@@ -0,0 +1,589 @@
'use strict';
var middlewareStack = require('@smithy/middleware-stack');
var protocols = require('@smithy/core/protocols');
var types = require('@smithy/types');
var schema = require('@smithy/core/schema');
var serde = require('@smithy/core/serde');
class Client {
config;
middlewareStack = middlewareStack.constructStack();
initConfig;
handlers;
constructor(config) {
this.config = config;
}
send(command, optionsOrCb, cb) {
const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined;
const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
const useHandlerCache = options === undefined && this.config.cacheMiddleware === true;
let handler;
if (useHandlerCache) {
if (!this.handlers) {
this.handlers = new WeakMap();
}
const handlers = this.handlers;
if (handlers.has(command.constructor)) {
handler = handlers.get(command.constructor);
}
else {
handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
handlers.set(command.constructor, handler);
}
}
else {
delete this.handlers;
handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
}
if (callback) {
handler(command)
.then((result) => callback(null, result.output), (err) => callback(err))
.catch(() => { });
}
else {
return handler(command).then((result) => result.output);
}
}
destroy() {
this.config?.requestHandler?.destroy?.();
delete this.handlers;
}
}
const SENSITIVE_STRING$1 = "***SensitiveInformation***";
function schemaLogFilter(schema$1, data) {
if (data == null) {
return data;
}
const ns = schema.NormalizedSchema.of(schema$1);
if (ns.getMergedTraits().sensitive) {
return SENSITIVE_STRING$1;
}
if (ns.isListSchema()) {
const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive;
if (isSensitive) {
return SENSITIVE_STRING$1;
}
}
else if (ns.isMapSchema()) {
const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive;
if (isSensitive) {
return SENSITIVE_STRING$1;
}
}
else if (ns.isStructSchema() && typeof data === "object") {
const object = data;
const newObject = {};
for (const [member, memberNs] of ns.structIterator()) {
if (object[member] != null) {
newObject[member] = schemaLogFilter(memberNs, object[member]);
}
}
return newObject;
}
return data;
}
class Command {
middlewareStack = middlewareStack.constructStack();
schema;
static classBuilder() {
return new ClassBuilder();
}
resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) {
for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) {
this.middlewareStack.use(mw);
}
const stack = clientStack.concat(this.middlewareStack);
const { logger } = configuration;
const handlerExecutionContext = {
logger,
clientName,
commandName,
inputFilterSensitiveLog,
outputFilterSensitiveLog,
[types.SMITHY_CONTEXT_KEY]: {
commandInstance: this,
...smithyContext,
},
...additionalContext,
};
const { requestHandler } = configuration;
return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext);
}
}
class ClassBuilder {
_init = () => { };
_ep = {};
_middlewareFn = () => [];
_commandName = "";
_clientName = "";
_additionalContext = {};
_smithyContext = {};
_inputFilterSensitiveLog = undefined;
_outputFilterSensitiveLog = undefined;
_serializer = null;
_deserializer = null;
_operationSchema;
init(cb) {
this._init = cb;
}
ep(endpointParameterInstructions) {
this._ep = endpointParameterInstructions;
return this;
}
m(middlewareSupplier) {
this._middlewareFn = middlewareSupplier;
return this;
}
s(service, operation, smithyContext = {}) {
this._smithyContext = {
service,
operation,
...smithyContext,
};
return this;
}
c(additionalContext = {}) {
this._additionalContext = additionalContext;
return this;
}
n(clientName, commandName) {
this._clientName = clientName;
this._commandName = commandName;
return this;
}
f(inputFilter = (_) => _, outputFilter = (_) => _) {
this._inputFilterSensitiveLog = inputFilter;
this._outputFilterSensitiveLog = outputFilter;
return this;
}
ser(serializer) {
this._serializer = serializer;
return this;
}
de(deserializer) {
this._deserializer = deserializer;
return this;
}
sc(operation) {
this._operationSchema = operation;
this._smithyContext.operationSchema = operation;
return this;
}
build() {
const closure = this;
let CommandRef;
return (CommandRef = class extends Command {
input;
static getEndpointParameterInstructions() {
return closure._ep;
}
constructor(...[input]) {
super();
this.input = input ?? {};
closure._init(this);
this.schema = closure._operationSchema;
}
resolveMiddleware(stack, configuration, options) {
const op = closure._operationSchema;
const input = op?.[4] ?? op?.input;
const output = op?.[5] ?? op?.output;
return this.resolveMiddlewareWithContext(stack, configuration, options, {
CommandCtor: CommandRef,
middlewareFn: closure._middlewareFn,
clientName: closure._clientName,
commandName: closure._commandName,
inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _),
outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _),
smithyContext: closure._smithyContext,
additionalContext: closure._additionalContext,
});
}
serialize = closure._serializer;
deserialize = closure._deserializer;
});
}
}
const SENSITIVE_STRING = "***SensitiveInformation***";
const createAggregatedClient = (commands, Client) => {
for (const command of Object.keys(commands)) {
const CommandCtor = commands[command];
const methodImpl = async function (args, optionsOrCb, cb) {
const command = new CommandCtor(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
}
else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object")
throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
}
else {
return this.send(command, optionsOrCb);
}
};
const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, "");
Client.prototype[methodName] = methodImpl;
}
};
class ServiceException extends Error {
$fault;
$response;
$retryable;
$metadata;
constructor(options) {
super(options.message);
Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
this.name = options.name;
this.$fault = options.$fault;
this.$metadata = options.$metadata;
}
static isInstance(value) {
if (!value)
return false;
const candidate = value;
return (ServiceException.prototype.isPrototypeOf(candidate) ||
(Boolean(candidate.$fault) &&
Boolean(candidate.$metadata) &&
(candidate.$fault === "client" || candidate.$fault === "server")));
}
static [Symbol.hasInstance](instance) {
if (!instance)
return false;
const candidate = instance;
if (this === ServiceException) {
return ServiceException.isInstance(instance);
}
if (ServiceException.isInstance(instance)) {
if (candidate.name && this.name) {
return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
}
return this.prototype.isPrototypeOf(instance);
}
return false;
}
}
const decorateServiceException = (exception, additions = {}) => {
Object.entries(additions)
.filter(([, v]) => v !== undefined)
.forEach(([k, v]) => {
if (exception[k] == undefined || exception[k] === "") {
exception[k] = v;
}
});
const message = exception.message || exception.Message || "UnknownError";
exception.message = message;
delete exception.Message;
return exception;
};
const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => {
const $metadata = deserializeMetadata(output);
const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined;
const response = new exceptionCtor({
name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
$fault: "client",
$metadata,
});
throw decorateServiceException(response, parsedBody);
};
const withBaseException = (ExceptionCtor) => {
return ({ output, parsedBody, errorCode }) => {
throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
};
};
const deserializeMetadata = (output) => ({
httpStatusCode: output.statusCode,
requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
extendedRequestId: output.headers["x-amz-id-2"],
cfId: output.headers["x-amz-cf-id"],
});
const loadConfigsForDefaultMode = (mode) => {
switch (mode) {
case "standard":
return {
retryMode: "standard",
connectionTimeout: 3100,
};
case "in-region":
return {
retryMode: "standard",
connectionTimeout: 1100,
};
case "cross-region":
return {
retryMode: "standard",
connectionTimeout: 3100,
};
case "mobile":
return {
retryMode: "standard",
connectionTimeout: 30000,
};
default:
return {};
}
};
let warningEmitted = false;
const emitWarningIfUnsupportedVersion = (version) => {
if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) {
warningEmitted = true;
}
};
const getChecksumConfiguration = (runtimeConfig) => {
const checksumAlgorithms = [];
for (const id in types.AlgorithmId) {
const algorithmId = types.AlgorithmId[id];
if (runtimeConfig[algorithmId] === undefined) {
continue;
}
checksumAlgorithms.push({
algorithmId: () => algorithmId,
checksumConstructor: () => runtimeConfig[algorithmId],
});
}
return {
addChecksumAlgorithm(algo) {
checksumAlgorithms.push(algo);
},
checksumAlgorithms() {
return checksumAlgorithms;
},
};
};
const resolveChecksumRuntimeConfig = (clientConfig) => {
const runtimeConfig = {};
clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
});
return runtimeConfig;
};
const getRetryConfiguration = (runtimeConfig) => {
return {
setRetryStrategy(retryStrategy) {
runtimeConfig.retryStrategy = retryStrategy;
},
retryStrategy() {
return runtimeConfig.retryStrategy;
},
};
};
const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => {
const runtimeConfig = {};
runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
return runtimeConfig;
};
const getDefaultExtensionConfiguration = (runtimeConfig) => {
return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig));
};
const getDefaultClientConfiguration = getDefaultExtensionConfiguration;
const resolveDefaultRuntimeConfig = (config) => {
return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config));
};
const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray];
const getValueFromTextNode = (obj) => {
const textNodeName = "#text";
for (const key in obj) {
if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) {
obj[key] = obj[key][textNodeName];
}
else if (typeof obj[key] === "object" && obj[key] !== null) {
obj[key] = getValueFromTextNode(obj[key]);
}
}
return obj;
};
const isSerializableHeaderValue = (value) => {
return value != null;
};
class NoOpLogger {
trace() { }
debug() { }
info() { }
warn() { }
error() { }
}
function map(arg0, arg1, arg2) {
let target;
let filter;
let instructions;
if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
target = {};
instructions = arg0;
}
else {
target = arg0;
if (typeof arg1 === "function") {
filter = arg1;
instructions = arg2;
return mapWithFilter(target, filter, instructions);
}
else {
instructions = arg1;
}
}
for (const key of Object.keys(instructions)) {
if (!Array.isArray(instructions[key])) {
target[key] = instructions[key];
continue;
}
applyInstruction(target, null, instructions, key);
}
return target;
}
const convertMap = (target) => {
const output = {};
for (const [k, v] of Object.entries(target || {})) {
output[k] = [, v];
}
return output;
};
const take = (source, instructions) => {
const out = {};
for (const key in instructions) {
applyInstruction(out, source, instructions, key);
}
return out;
};
const mapWithFilter = (target, filter, instructions) => {
return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
if (Array.isArray(value)) {
_instructions[key] = value;
}
else {
if (typeof value === "function") {
_instructions[key] = [filter, value()];
}
else {
_instructions[key] = [filter, value];
}
}
return _instructions;
}, {}));
};
const applyInstruction = (target, source, instructions, targetKey) => {
if (source !== null) {
let instruction = instructions[targetKey];
if (typeof instruction === "function") {
instruction = [, instruction];
}
const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction;
if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) {
target[targetKey] = valueFn(source[sourceKey]);
}
return;
}
let [filter, value] = instructions[targetKey];
if (typeof value === "function") {
let _value;
const defaultFilterPassed = filter === undefined && (_value = value()) != null;
const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter);
if (defaultFilterPassed) {
target[targetKey] = _value;
}
else if (customFilterPassed) {
target[targetKey] = value();
}
}
else {
const defaultFilterPassed = filter === undefined && value != null;
const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter);
if (defaultFilterPassed || customFilterPassed) {
target[targetKey] = value;
}
}
};
const nonNullish = (_) => _ != null;
const pass = (_) => _;
const serializeFloat = (value) => {
if (value !== value) {
return "NaN";
}
switch (value) {
case Infinity:
return "Infinity";
case -Infinity:
return "-Infinity";
default:
return value;
}
};
const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z");
const _json = (obj) => {
if (obj == null) {
return {};
}
if (Array.isArray(obj)) {
return obj.filter((_) => _ != null).map(_json);
}
if (typeof obj === "object") {
const target = {};
for (const key of Object.keys(obj)) {
if (obj[key] == null) {
continue;
}
target[key] = _json(obj[key]);
}
return target;
}
return obj;
};
Object.defineProperty(exports, "collectBody", {
enumerable: true,
get: function () { return protocols.collectBody; }
});
Object.defineProperty(exports, "extendedEncodeURIComponent", {
enumerable: true,
get: function () { return protocols.extendedEncodeURIComponent; }
});
Object.defineProperty(exports, "resolvedPath", {
enumerable: true,
get: function () { return protocols.resolvedPath; }
});
exports.Client = Client;
exports.Command = Command;
exports.NoOpLogger = NoOpLogger;
exports.SENSITIVE_STRING = SENSITIVE_STRING;
exports.ServiceException = ServiceException;
exports._json = _json;
exports.convertMap = convertMap;
exports.createAggregatedClient = createAggregatedClient;
exports.decorateServiceException = decorateServiceException;
exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion;
exports.getArrayIfSingleItem = getArrayIfSingleItem;
exports.getDefaultClientConfiguration = getDefaultClientConfiguration;
exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration;
exports.getValueFromTextNode = getValueFromTextNode;
exports.isSerializableHeaderValue = isSerializableHeaderValue;
exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode;
exports.map = map;
exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig;
exports.serializeDateTime = serializeDateTime;
exports.serializeFloat = serializeFloat;
exports.take = take;
exports.throwDefaultError = throwDefaultError;
exports.withBaseException = withBaseException;
Object.keys(serde).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return serde[k]; }
});
});

View File

@@ -0,0 +1,91 @@
'use strict';
exports.HttpAuthLocation = void 0;
(function (HttpAuthLocation) {
HttpAuthLocation["HEADER"] = "header";
HttpAuthLocation["QUERY"] = "query";
})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
exports.HttpApiKeyAuthLocation = void 0;
(function (HttpApiKeyAuthLocation) {
HttpApiKeyAuthLocation["HEADER"] = "header";
HttpApiKeyAuthLocation["QUERY"] = "query";
})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
exports.EndpointURLScheme = void 0;
(function (EndpointURLScheme) {
EndpointURLScheme["HTTP"] = "http";
EndpointURLScheme["HTTPS"] = "https";
})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
exports.AlgorithmId = void 0;
(function (AlgorithmId) {
AlgorithmId["MD5"] = "md5";
AlgorithmId["CRC32"] = "crc32";
AlgorithmId["CRC32C"] = "crc32c";
AlgorithmId["SHA1"] = "sha1";
AlgorithmId["SHA256"] = "sha256";
})(exports.AlgorithmId || (exports.AlgorithmId = {}));
const getChecksumConfiguration = (runtimeConfig) => {
const checksumAlgorithms = [];
if (runtimeConfig.sha256 !== undefined) {
checksumAlgorithms.push({
algorithmId: () => exports.AlgorithmId.SHA256,
checksumConstructor: () => runtimeConfig.sha256,
});
}
if (runtimeConfig.md5 != undefined) {
checksumAlgorithms.push({
algorithmId: () => exports.AlgorithmId.MD5,
checksumConstructor: () => runtimeConfig.md5,
});
}
return {
addChecksumAlgorithm(algo) {
checksumAlgorithms.push(algo);
},
checksumAlgorithms() {
return checksumAlgorithms;
},
};
};
const resolveChecksumRuntimeConfig = (clientConfig) => {
const runtimeConfig = {};
clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
});
return runtimeConfig;
};
const getDefaultClientConfiguration = (runtimeConfig) => {
return getChecksumConfiguration(runtimeConfig);
};
const resolveDefaultRuntimeConfig = (config) => {
return resolveChecksumRuntimeConfig(config);
};
exports.FieldPosition = void 0;
(function (FieldPosition) {
FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER";
FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER";
})(exports.FieldPosition || (exports.FieldPosition = {}));
const SMITHY_CONTEXT_KEY = "__smithy_context";
exports.IniSectionType = void 0;
(function (IniSectionType) {
IniSectionType["PROFILE"] = "profile";
IniSectionType["SSO_SESSION"] = "sso-session";
IniSectionType["SERVICES"] = "services";
})(exports.IniSectionType || (exports.IniSectionType = {}));
exports.RequestHandlerProtocol = void 0;
(function (RequestHandlerProtocol) {
RequestHandlerProtocol["HTTP_0_9"] = "http/0.9";
RequestHandlerProtocol["HTTP_1_0"] = "http/1.0";
RequestHandlerProtocol["TDS_8_0"] = "tds/8.0";
})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY;
exports.getDefaultClientConfiguration = getDefaultClientConfiguration;
exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig;

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromBase64 = void 0;
const util_buffer_from_1 = require("@smithy/util-buffer-from");
const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
const fromBase64 = (input) => {
if ((input.length * 3) % 4 !== 0) {
throw new TypeError(`Incorrect padding on base64 string.`);
}
if (!BASE64_REGEX.exec(input)) {
throw new TypeError(`Invalid base64 string.`);
}
const buffer = (0, util_buffer_from_1.fromString)(input, "base64");
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
};
exports.fromBase64 = fromBase64;

View File

@@ -0,0 +1,19 @@
'use strict';
var fromBase64 = require('./fromBase64');
var toBase64 = require('./toBase64');
Object.keys(fromBase64).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return fromBase64[k]; }
});
});
Object.keys(toBase64).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return toBase64[k]; }
});
});

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toBase64 = void 0;
const util_buffer_from_1 = require("@smithy/util-buffer-from");
const util_utf8_1 = require("@smithy/util-utf8");
const toBase64 = (_input) => {
let input;
if (typeof _input === "string") {
input = (0, util_utf8_1.fromUtf8)(_input);
}
else {
input = _input;
}
if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
}
return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64");
};
exports.toBase64 = toBase64;

View File

@@ -0,0 +1,20 @@
'use strict';
var isArrayBuffer = require('@smithy/is-array-buffer');
var buffer = 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.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.Buffer.from(input, encoding) : buffer.Buffer.from(input);
};
exports.fromArrayBuffer = fromArrayBuffer;
exports.fromString = fromString;

View File

@@ -0,0 +1,6 @@
'use strict';
const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) ||
Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
exports.isArrayBuffer = isArrayBuffer;