UNPKG

failure-lambda

Version:

Failure injection for AWS Lambda - chaos engineering made simple

854 lines (833 loc) 30.3 kB
#!/usr/bin/env node import { fromArrayBuffer, fromString, fromUtf8 } from "./chunk-VACN7GDP.js"; // node_modules/@smithy/protocol-http/dist-es/httpResponse.js var HttpResponse = class { 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"; } }; // node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js var escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); var hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; // node_modules/@smithy/querystring-builder/dist-es/index.js function buildQueryString(query) { const parts = []; for (let key of Object.keys(query).sort()) { const value = query[key]; key = escapeUri(key); if (Array.isArray(value)) { for (let i = 0, iLen = value.length; i < iLen; i++) { parts.push(`${key}=${escapeUri(value[i])}`); } } else { let qsEntry = key; if (value || typeof value === "string") { qsEntry += `=${escapeUri(value)}`; } parts.push(qsEntry); } } return parts.join("&"); } // node_modules/@smithy/node-http-handler/dist-es/node-http-handler.js import { Agent as hAgent, request as hRequest } from "http"; import { Agent as hsAgent, request as hsRequest } from "https"; // node_modules/@smithy/node-http-handler/dist-es/constants.js var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; // node_modules/@smithy/node-http-handler/dist-es/get-transformed-headers.js var getTransformedHeaders = (headers) => { const transformedHeaders = {}; for (const name of Object.keys(headers)) { const headerValues = headers[name]; transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; } return transformedHeaders; }; // node_modules/@smithy/node-http-handler/dist-es/timing.js var timing = { setTimeout: (cb, ms) => setTimeout(cb, ms), clearTimeout: (timeoutId) => clearTimeout(timeoutId) }; // node_modules/@smithy/node-http-handler/dist-es/set-connection-timeout.js var DEFER_EVENT_LISTENER_TIME = 1e3; var setConnectionTimeout = (request, reject, timeoutInMs = 0) => { if (!timeoutInMs) { return -1; } const registerTimeout = (offset) => { const timeoutId = timing.setTimeout(() => { request.destroy(); reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), { name: "TimeoutError" })); }, timeoutInMs - offset); const doWithSocket = (socket) => { if (socket?.connecting) { socket.on("connect", () => { timing.clearTimeout(timeoutId); }); } else { timing.clearTimeout(timeoutId); } }; if (request.socket) { doWithSocket(request.socket); } else { request.on("socket", doWithSocket); } }; if (timeoutInMs < 2e3) { registerTimeout(0); return 0; } return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); }; // node_modules/@smithy/node-http-handler/dist-es/set-request-timeout.js var setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger2) => { if (timeoutInMs) { return timing.setTimeout(() => { let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? "ERROR" : "WARN"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`; if (throwOnRequestTimeout) { const error = Object.assign(new Error(msg), { name: "TimeoutError", code: "ETIMEDOUT" }); req.destroy(error); reject(error); } else { msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`; logger2?.warn?.(msg); } }, timeoutInMs); } return -1; }; // node_modules/@smithy/node-http-handler/dist-es/set-socket-keep-alive.js var DEFER_EVENT_LISTENER_TIME2 = 3e3; var setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { if (keepAlive !== true) { return -1; } const registerListener = () => { if (request.socket) { request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); } else { request.on("socket", (socket) => { socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); }); } }; if (deferTimeMs === 0) { registerListener(); return 0; } return timing.setTimeout(registerListener, deferTimeMs); }; // node_modules/@smithy/node-http-handler/dist-es/set-socket-timeout.js var DEFER_EVENT_LISTENER_TIME3 = 3e3; var setSocketTimeout = (request, reject, timeoutInMs = 0) => { const registerTimeout = (offset) => { const timeout = timeoutInMs - offset; const onTimeout = () => { request.destroy(); reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: "TimeoutError" })); }; if (request.socket) { request.socket.setTimeout(timeout, onTimeout); request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); } else { request.setTimeout(timeout, onTimeout); } }; if (0 < timeoutInMs && timeoutInMs < 6e3) { registerTimeout(0); return 0; } return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), DEFER_EVENT_LISTENER_TIME3); }; // node_modules/@smithy/node-http-handler/dist-es/write-request-body.js import { Readable } from "stream"; var MIN_WAIT_TIME = 6e3; async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) { const headers = request.headers ?? {}; const expect = headers.Expect || headers.expect; let timeoutId = -1; let sendBody = true; if (!externalAgent && expect === "100-continue") { sendBody = await Promise.race([ new Promise((resolve) => { timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); }), new Promise((resolve) => { httpRequest.on("continue", () => { timing.clearTimeout(timeoutId); resolve(true); }); httpRequest.on("response", () => { timing.clearTimeout(timeoutId); resolve(false); }); httpRequest.on("error", () => { timing.clearTimeout(timeoutId); resolve(false); }); }) ]); } if (sendBody) { writeBody(httpRequest, request.body); } } function writeBody(httpRequest, body) { if (body instanceof Readable) { body.pipe(httpRequest); return; } if (body) { const isBuffer = Buffer.isBuffer(body); const isString = typeof body === "string"; if (isBuffer || isString) { if (isBuffer && body.byteLength === 0) { httpRequest.end(); } else { httpRequest.end(body); } return; } const uint8 = body; if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); return; } httpRequest.end(Buffer.from(body)); return; } httpRequest.end(); } // node_modules/@smithy/node-http-handler/dist-es/node-http-handler.js var NodeHttpHandler = class _NodeHttpHandler { config; configProvider; socketWarningTimestamp = 0; externalAgent = false; metadata = { handlerProtocol: "http/1.1" }; static create(instanceOrOptions) { if (typeof instanceOrOptions?.handle === "function") { return instanceOrOptions; } return new _NodeHttpHandler(instanceOrOptions); } static checkSocketUsage(agent, socketWarningTimestamp, logger2 = console) { const { sockets, requests, maxSockets } = agent; if (typeof maxSockets !== "number" || maxSockets === Infinity) { return socketWarningTimestamp; } const interval = 15e3; if (Date.now() - interval < socketWarningTimestamp) { return socketWarningTimestamp; } if (sockets && requests) { for (const origin in sockets) { const socketsInUse = sockets[origin]?.length ?? 0; const requestsEnqueued = requests[origin]?.length ?? 0; if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { logger2?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`); return Date.now(); } } } return socketWarningTimestamp; } constructor(options) { this.configProvider = new Promise((resolve, reject) => { if (typeof options === "function") { options().then((_options) => { resolve(this.resolveDefaultConfig(_options)); }).catch(reject); } else { resolve(this.resolveDefaultConfig(options)); } }); } resolveDefaultConfig(options) { const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, logger: logger2 } = options || {}; const keepAlive = true; const maxSockets = 50; return { connectionTimeout, requestTimeout, socketTimeout, socketAcquisitionWarningTimeout, throwOnRequestTimeout, httpAgent: (() => { if (httpAgent instanceof hAgent || typeof httpAgent?.destroy === "function") { this.externalAgent = true; return httpAgent; } return new hAgent({ keepAlive, maxSockets, ...httpAgent }); })(), httpsAgent: (() => { if (httpsAgent instanceof hsAgent || typeof httpsAgent?.destroy === "function") { this.externalAgent = true; return httpsAgent; } return new hsAgent({ keepAlive, maxSockets, ...httpsAgent }); })(), logger: logger2 }; } destroy() { this.config?.httpAgent?.destroy(); this.config?.httpsAgent?.destroy(); } async handle(request, { abortSignal, requestTimeout } = {}) { if (!this.config) { this.config = await this.configProvider; } return new Promise((_resolve, _reject) => { const config = this.config; let writeRequestBodyPromise = void 0; const timeouts = []; const resolve = async (arg) => { await writeRequestBodyPromise; timeouts.forEach(timing.clearTimeout); _resolve(arg); }; const reject = async (arg) => { await writeRequestBodyPromise; timeouts.forEach(timing.clearTimeout); _reject(arg); }; if (abortSignal?.aborted) { const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); return; } const isSSL = request.protocol === "https:"; const headers = request.headers ?? {}; const expectContinue = (headers.Expect ?? headers.expect) === "100-continue"; let agent = isSSL ? config.httpsAgent : config.httpAgent; if (expectContinue && !this.externalAgent) { agent = new (isSSL ? hsAgent : hAgent)({ keepAlive: false, maxSockets: Infinity }); } timeouts.push(timing.setTimeout(() => { this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, config.logger); }, config.socketAcquisitionWarningTimeout ?? (config.requestTimeout ?? 2e3) + (config.connectionTimeout ?? 1e3))); const queryString = buildQueryString(request.query || {}); let auth = void 0; if (request.username != null || request.password != null) { const username = request.username ?? ""; const password = request.password ?? ""; auth = `${username}:${password}`; } let path = request.path; if (queryString) { path += `?${queryString}`; } if (request.fragment) { path += `#${request.fragment}`; } let hostname = request.hostname ?? ""; if (hostname[0] === "[" && hostname.endsWith("]")) { hostname = request.hostname.slice(1, -1); } else { hostname = request.hostname; } const nodeHttpsOptions = { headers: request.headers, host: hostname, method: request.method, path, port: request.port, agent, auth }; const requestFunc = isSSL ? hsRequest : hRequest; const req = requestFunc(nodeHttpsOptions, (res) => { const httpResponse = new HttpResponse({ statusCode: res.statusCode || -1, reason: res.statusMessage, headers: getTransformedHeaders(res.headers), body: res }); resolve({ response: httpResponse }); }); req.on("error", (err) => { if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { reject(Object.assign(err, { name: "TimeoutError" })); } else { reject(err); } }); if (abortSignal) { const onAbort = () => { req.destroy(); const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); }; if (typeof abortSignal.addEventListener === "function") { const signal = abortSignal; signal.addEventListener("abort", onAbort, { once: true }); req.once("close", () => signal.removeEventListener("abort", onAbort)); } else { abortSignal.onabort = onAbort; } } const effectiveRequestTimeout = requestTimeout ?? config.requestTimeout; timeouts.push(setConnectionTimeout(req, reject, config.connectionTimeout)); timeouts.push(setRequestTimeout(req, reject, effectiveRequestTimeout, config.throwOnRequestTimeout, config.logger ?? console)); timeouts.push(setSocketTimeout(req, reject, config.socketTimeout)); const httpAgent = nodeHttpsOptions.agent; if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { timeouts.push(setSocketKeepAlive(req, { keepAlive: httpAgent.keepAlive, keepAliveMsecs: httpAgent.keepAliveMsecs })); } writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e) => { timeouts.forEach(timing.clearTimeout); return _reject(e); }); }); } updateHttpClientConfig(key, value) { this.config = void 0; this.configProvider = this.configProvider.then((config) => { return { ...config, [key]: value }; }); } httpHandlerConfigs() { return this.config ?? {}; } }; // node_modules/@smithy/node-http-handler/dist-es/stream-collector/collector.js import { Writable } from "stream"; var Collector = class extends Writable { bufferedBytes = []; _write(chunk, encoding, callback) { this.bufferedBytes.push(chunk); callback(); } }; // node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js var streamCollector = (stream) => { if (isReadableStreamInstance(stream)) { return collectReadableStream(stream); } return new Promise((resolve, reject) => { const collector = new Collector(); stream.pipe(collector); stream.on("error", (err) => { collector.end(); reject(err); }); collector.on("error", reject); collector.on("finish", function() { const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); resolve(bytes); }); }); }; var isReadableStreamInstance = (stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream; async function collectReadableStream(stream) { const chunks = []; const reader = stream.getReader(); let isDone = false; let length = 0; while (!isDone) { const { done, value } = await reader.read(); if (value) { chunks.push(value); length += value.length; } isDone = done; } const collected = new Uint8Array(length); let offset = 0; for (const chunk of chunks) { collected.set(chunk, offset); offset += chunk.length; } return collected; } // node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js var expectNumber = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value === "string") { const parsed = parseFloat(value); if (!Number.isNaN(parsed)) { if (String(parsed) !== String(value)) { logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); } return parsed; } } if (typeof value === "number") { return value; } throw new TypeError(`Expected number, got ${typeof value}: ${value}`); }; var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); var expectFloat32 = (value) => { const expected = expectNumber(value); if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { if (Math.abs(expected) > MAX_FLOAT) { throw new TypeError(`Expected 32-bit float, got ${value}`); } } return expected; }; var expectLong = (value) => { if (value === null || value === void 0) { return void 0; } if (Number.isInteger(value) && !Number.isNaN(value)) { return value; } throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); }; var expectShort = (value) => expectSizedInt(value, 16); var expectByte = (value) => expectSizedInt(value, 8); var expectSizedInt = (value, size) => { const expected = expectLong(value); if (expected !== void 0 && castInt(expected, size) !== expected) { throw new TypeError(`Expected ${size}-bit integer, got ${value}`); } return expected; }; var castInt = (value, size) => { switch (size) { case 32: return Int32Array.of(value)[0]; case 16: return Int16Array.of(value)[0]; case 8: return Int8Array.of(value)[0]; } }; var strictParseDouble = (value) => { if (typeof value == "string") { return expectNumber(parseNumber(value)); } return expectNumber(value); }; var strictParseFloat32 = (value) => { if (typeof value == "string") { return expectFloat32(parseNumber(value)); } return expectFloat32(value); }; var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; var parseNumber = (value) => { const matches = value.match(NUMBER_REGEX); if (matches === null || matches[0].length !== value.length) { throw new TypeError(`Expected real number, got implicit NaN`); } return parseFloat(value); }; var strictParseShort = (value) => { if (typeof value === "string") { return expectShort(parseNumber(value)); } return expectShort(value); }; var strictParseByte = (value) => { if (typeof value === "string") { return expectByte(parseNumber(value)); } return expectByte(value); }; var stackTraceWarning = (message) => { return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); }; var logger = { warn: console.warn }; // node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; function dateToUtcString(date) { const year = date.getUTCFullYear(); const month = date.getUTCMonth(); const dayOfWeek = date.getUTCDay(); const dayOfMonthInt = date.getUTCDate(); const hoursInt = date.getUTCHours(); const minutesInt = date.getUTCMinutes(); const secondsInt = date.getUTCSeconds(); const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; } var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); var parseRfc3339DateTime = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value !== "string") { throw new TypeError("RFC-3339 date-times must be expressed as strings"); } const match = RFC3339.exec(value); if (!match) { throw new TypeError("Invalid RFC-3339 date-time value"); } const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; const year = strictParseShort(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); }; var RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/); var parseRfc3339DateTimeWithOffset = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value !== "string") { throw new TypeError("RFC-3339 date-times must be expressed as strings"); } const match = RFC3339_WITH_OFFSET.exec(value); if (!match) { throw new TypeError("Invalid RFC-3339 date-time value"); } const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; const year = strictParseShort(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); if (offsetStr.toUpperCase() != "Z") { date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); } return date; }; var IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); var RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); var ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/); var parseRfc7231DateTime = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value !== "string") { throw new TypeError("RFC-7231 date-times must be expressed as strings"); } let match = IMF_FIXDATE.exec(value); if (match) { const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); } match = RFC_850_DATE.exec(value); if (match) { const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds })); } match = ASC_TIME.exec(value); if (match) { const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); } throw new TypeError("Invalid RFC-7231 date-time value"); }; var parseEpochTimestamp = (value) => { if (value === null || value === void 0) { return void 0; } let valueAsDouble; if (typeof value === "number") { valueAsDouble = value; } else if (typeof value === "string") { valueAsDouble = strictParseDouble(value); } else if (typeof value === "object" && value.tag === 1) { valueAsDouble = value.value; } else { throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); } if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); } return new Date(Math.round(valueAsDouble * 1e3)); }; var buildDate = (year, month, day, time) => { const adjustedMonth = month - 1; validateDayOfMonth(year, adjustedMonth, day); return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds))); }; var parseTwoDigitYear = (value) => { const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); if (valueInThisCentury < thisYear) { return valueInThisCentury + 100; } return valueInThisCentury; }; var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; var adjustRfc850Year = (input) => { if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds())); } return input; }; var parseMonthByShortName = (value) => { const monthIdx = MONTHS.indexOf(value); if (monthIdx < 0) { throw new TypeError(`Invalid month: ${value}`); } return monthIdx + 1; }; var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; var validateDayOfMonth = (year, month, day) => { let maxDays = DAYS_IN_MONTH[month]; if (month === 1 && isLeapYear(year)) { maxDays = 29; } if (day > maxDays) { throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); } }; var isLeapYear = (year) => { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }; var parseDateValue = (value, type, lower, upper) => { const dateVal = strictParseByte(stripLeadingZeroes(value)); if (dateVal < lower || dateVal > upper) { throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); } return dateVal; }; var parseMilliseconds = (value) => { if (value === null || value === void 0) { return 0; } return strictParseFloat32("0." + value) * 1e3; }; var parseOffsetToMilliseconds = (value) => { const directionStr = value[0]; let direction = 1; if (directionStr == "+") { direction = 1; } else if (directionStr == "-") { direction = -1; } else { throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); } const hour = Number(value.substring(1, 3)); const minute = Number(value.substring(4, 6)); return direction * (hour * 60 + minute) * 60 * 1e3; }; var stripLeadingZeroes = (value) => { let idx = 0; while (idx < value.length - 1 && value.charAt(idx) === "0") { idx++; } if (idx === 0) { return value; } return value.slice(idx); }; // node_modules/@smithy/util-base64/dist-es/fromBase64.js var BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; var 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 = fromString(input, "base64"); return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); }; // node_modules/@smithy/util-base64/dist-es/toBase64.js var toBase64 = (_input) => { let input; if (typeof _input === "string") { input = 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 fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("base64"); }; // node_modules/@smithy/util-hex-encoding/dist-es/index.js var SHORT_TO_HEX = {}; var HEX_TO_SHORT = {}; for (let i = 0; i < 256; i++) { let encodedByte = i.toString(16).toLowerCase(); if (encodedByte.length === 1) { encodedByte = `0${encodedByte}`; } 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; } export { HttpResponse, fromBase64, toBase64, escapeUri, NodeHttpHandler, streamCollector, fromHex, toHex, dateToUtcString, parseRfc3339DateTime, parseRfc3339DateTimeWithOffset, parseRfc7231DateTime, parseEpochTimestamp }; //# sourceMappingURL=chunk-W3M6RT2M.js.map