This commit is contained in:
2025-01-04 00:34:03 +01:00
parent 41829408dc
commit 0ca14bbc19
18111 changed files with 1871397 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
export class NoOpLogger {
trace() { }
debug() { }
info() { }
warn() { }
error() { }
}

View File

@@ -0,0 +1,24 @@
import { constructStack } from "@smithy/middleware-stack";
export class Client {
constructor(config) {
this.middlewareStack = constructStack();
this.config = config;
}
send(command, optionsOrCb, cb) {
const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined;
const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
const handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
if (callback) {
handler(command)
.then((result) => callback(null, result.output), (err) => callback(err))
.catch(() => { });
}
else {
return handler(command).then((result) => result.output);
}
}
destroy() {
if (this.config.requestHandler.destroy)
this.config.requestHandler.destroy();
}
}

View File

@@ -0,0 +1,11 @@
import { Uint8ArrayBlobAdapter } from "@smithy/util-stream";
export const collectBody = async (streamBody = new Uint8Array(), context) => {
if (streamBody instanceof Uint8Array) {
return Uint8ArrayBlobAdapter.mutate(streamBody);
}
if (!streamBody) {
return Uint8ArrayBlobAdapter.mutate(new Uint8Array());
}
const fromContext = context.streamCollector(streamBody);
return Uint8ArrayBlobAdapter.mutate(await fromContext);
};

View File

@@ -0,0 +1,114 @@
import { constructStack } from "@smithy/middleware-stack";
import { SMITHY_CONTEXT_KEY } from "@smithy/types";
export class Command {
constructor() {
this.middlewareStack = constructStack();
}
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,
[SMITHY_CONTEXT_KEY]: {
...smithyContext,
},
...additionalContext,
};
const { requestHandler } = configuration;
return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext);
}
}
class ClassBuilder {
constructor() {
this._init = () => { };
this._ep = {};
this._middlewareFn = () => [];
this._commandName = "";
this._clientName = "";
this._additionalContext = {};
this._smithyContext = {};
this._inputFilterSensitiveLog = (_) => _;
this._outputFilterSensitiveLog = (_) => _;
this._serializer = null;
this._deserializer = null;
}
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;
}
build() {
const closure = this;
let CommandRef;
return (CommandRef = class extends Command {
static getEndpointParameterInstructions() {
return closure._ep;
}
constructor(...[input]) {
super();
this.serialize = closure._serializer;
this.deserialize = closure._deserializer;
this.input = input ?? {};
closure._init(this);
}
resolveMiddleware(stack, configuration, options) {
return this.resolveMiddlewareWithContext(stack, configuration, options, {
CommandCtor: CommandRef,
middlewareFn: closure._middlewareFn,
clientName: closure._clientName,
commandName: closure._commandName,
inputFilterSensitiveLog: closure._inputFilterSensitiveLog,
outputFilterSensitiveLog: closure._outputFilterSensitiveLog,
smithyContext: closure._smithyContext,
additionalContext: closure._additionalContext,
});
}
});
}
}

View File

@@ -0,0 +1 @@
export const SENSITIVE_STRING = "***SensitiveInformation***";

View File

@@ -0,0 +1,21 @@
export 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;
}
};

View File

@@ -0,0 +1,187 @@
import { strictParseByte, strictParseDouble, strictParseFloat32, strictParseShort } from "./parse-utils";
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
export 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`;
}
const RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);
export const parseRfc3339DateTime = (value) => {
if (value === null || value === undefined) {
return undefined;
}
if (typeof value !== "string") {
throw new TypeError("RFC-3339 date-times must be expressed as strings");
}
const match = RFC3339.exec(value);
if (!match) {
throw new TypeError("Invalid RFC-3339 date-time value");
}
const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match;
const year = 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 });
};
const RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);
export const parseRfc3339DateTimeWithOffset = (value) => {
if (value === null || value === undefined) {
return undefined;
}
if (typeof value !== "string") {
throw new TypeError("RFC-3339 date-times must be expressed as strings");
}
const match = RFC3339_WITH_OFFSET.exec(value);
if (!match) {
throw new TypeError("Invalid RFC-3339 date-time value");
}
const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match;
const year = 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;
};
const IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
const RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
const ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/);
export const parseRfc7231DateTime = (value) => {
if (value === null || value === undefined) {
return undefined;
}
if (typeof value !== "string") {
throw new TypeError("RFC-7231 date-times must be expressed as strings");
}
let match = IMF_FIXDATE.exec(value);
if (match) {
const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match;
return buildDate(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");
};
export const parseEpochTimestamp = (value) => {
if (value === null || value === undefined) {
return undefined;
}
let valueAsDouble;
if (typeof value === "number") {
valueAsDouble = value;
}
else if (typeof value === "string") {
valueAsDouble = strictParseDouble(value);
}
else {
throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");
}
if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) {
throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");
}
return new Date(Math.round(valueAsDouble * 1000));
};
const buildDate = (year, month, day, time) => {
const adjustedMonth = month - 1;
validateDayOfMonth(year, adjustedMonth, day);
return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds)));
};
const parseTwoDigitYear = (value) => {
const thisYear = new Date().getUTCFullYear();
const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value));
if (valueInThisCentury < thisYear) {
return valueInThisCentury + 100;
}
return valueInThisCentury;
};
const FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1000;
const adjustRfc850Year = (input) => {
if (input.getTime() - new Date().getTime() > FIFTY_YEARS_IN_MILLIS) {
return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds()));
}
return input;
};
const parseMonthByShortName = (value) => {
const monthIdx = MONTHS.indexOf(value);
if (monthIdx < 0) {
throw new TypeError(`Invalid month: ${value}`);
}
return monthIdx + 1;
};
const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const validateDayOfMonth = (year, month, day) => {
let maxDays = DAYS_IN_MONTH[month];
if (month === 1 && isLeapYear(year)) {
maxDays = 29;
}
if (day > maxDays) {
throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`);
}
};
const isLeapYear = (year) => {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
};
const parseDateValue = (value, type, lower, upper) => {
const dateVal = strictParseByte(stripLeadingZeroes(value));
if (dateVal < lower || dateVal > upper) {
throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`);
}
return dateVal;
};
const parseMilliseconds = (value) => {
if (value === null || value === undefined) {
return 0;
}
return strictParseFloat32("0." + value) * 1000;
};
const parseOffsetToMilliseconds = (value) => {
const directionStr = value[0];
let direction = 1;
if (directionStr == "+") {
direction = 1;
}
else if (directionStr == "-") {
direction = -1;
}
else {
throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`);
}
const hour = Number(value.substring(1, 3));
const minute = Number(value.substring(4, 6));
return direction * (hour * 60 + minute) * 60 * 1000;
};
const stripLeadingZeroes = (value) => {
let idx = 0;
while (idx < value.length - 1 && value.charAt(idx) === "0") {
idx++;
}
if (idx === 0) {
return value;
}
return value.slice(idx);
};

View File

@@ -0,0 +1,22 @@
import { decorateServiceException } from "./exceptions";
export 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);
};
export 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"],
});

View File

@@ -0,0 +1,26 @@
export 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 {};
}
};

View File

@@ -0,0 +1,6 @@
let warningEmitted = false;
export const emitWarningIfUnsupportedVersion = (version) => {
if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) {
warningEmitted = true;
}
};

View File

@@ -0,0 +1,22 @@
export class ServiceException extends Error {
constructor(options) {
super(options.message);
Object.setPrototypeOf(this, ServiceException.prototype);
this.name = options.name;
this.$fault = options.$fault;
this.$metadata = options.$metadata;
}
}
export 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;
};

View File

@@ -0,0 +1,5 @@
export function extendedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return "%" + c.charCodeAt(0).toString(16).toUpperCase();
});
}

View File

@@ -0,0 +1,31 @@
import { AlgorithmId } from "@smithy/types";
export { AlgorithmId };
export const getChecksumConfiguration = (runtimeConfig) => {
const checksumAlgorithms = [];
for (const id in AlgorithmId) {
const algorithmId = AlgorithmId[id];
if (runtimeConfig[algorithmId] === undefined) {
continue;
}
checksumAlgorithms.push({
algorithmId: () => algorithmId,
checksumConstructor: () => runtimeConfig[algorithmId],
});
}
return {
_checksumAlgorithms: checksumAlgorithms,
addChecksumAlgorithm(algo) {
this._checksumAlgorithms.push(algo);
},
checksumAlgorithms() {
return this._checksumAlgorithms;
},
};
};
export const resolveChecksumRuntimeConfig = (clientConfig) => {
const runtimeConfig = {};
clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
});
return runtimeConfig;
};

View File

@@ -0,0 +1,15 @@
import { getChecksumConfiguration, resolveChecksumRuntimeConfig } from "./checksum";
import { getRetryConfiguration, resolveRetryRuntimeConfig } from "./retry";
export const getDefaultExtensionConfiguration = (runtimeConfig) => {
return {
...getChecksumConfiguration(runtimeConfig),
...getRetryConfiguration(runtimeConfig),
};
};
export const getDefaultClientConfiguration = getDefaultExtensionConfiguration;
export const resolveDefaultRuntimeConfig = (config) => {
return {
...resolveChecksumRuntimeConfig(config),
...resolveRetryRuntimeConfig(config),
};
};

View File

@@ -0,0 +1 @@
export * from "./defaultExtensionConfiguration";

View File

@@ -0,0 +1,16 @@
export const getRetryConfiguration = (runtimeConfig) => {
let _retryStrategy = runtimeConfig.retryStrategy;
return {
setRetryStrategy(retryStrategy) {
_retryStrategy = retryStrategy;
},
retryStrategy() {
return _retryStrategy;
},
};
};
export const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => {
const runtimeConfig = {};
runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
return runtimeConfig;
};

View File

@@ -0,0 +1 @@
export const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray];

View File

@@ -0,0 +1,12 @@
export 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;
};

View File

@@ -0,0 +1,22 @@
export * from "./NoOpLogger";
export * from "./client";
export * from "./collect-stream-body";
export * from "./command";
export * from "./constants";
export * from "./create-aggregated-client";
export * from "./date-utils";
export * from "./default-error-handler";
export * from "./defaults-mode";
export * from "./emitWarningIfUnsupportedVersion";
export * from "./extensions";
export * from "./exceptions";
export * from "./extended-encode-uri-component";
export * from "./get-array-if-single-item";
export * from "./get-value-from-text-node";
export * from "./lazy-json";
export * from "./object-mapping";
export * from "./parse-utils";
export * from "./resolve-path";
export * from "./ser-utils";
export * from "./serde-json";
export * from "./split-every";

View File

@@ -0,0 +1,33 @@
export const StringWrapper = function () {
const Class = Object.getPrototypeOf(this).constructor;
const Constructor = Function.bind.apply(String, [null, ...arguments]);
const instance = new Constructor();
Object.setPrototypeOf(instance, Class.prototype);
return instance;
};
StringWrapper.prototype = Object.create(String.prototype, {
constructor: {
value: StringWrapper,
enumerable: false,
writable: true,
configurable: true,
},
});
Object.setPrototypeOf(StringWrapper, String);
export class LazyJsonString extends StringWrapper {
deserializeJSON() {
return JSON.parse(super.toString());
}
toJSON() {
return super.toString();
}
static fromObject(object) {
if (object instanceof LazyJsonString) {
return object;
}
else if (object instanceof String || typeof object === "string") {
return new LazyJsonString(object);
}
return new LazyJsonString(JSON.stringify(object));
}
}

View File

@@ -0,0 +1,92 @@
export 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;
}
export const convertMap = (target) => {
const output = {};
for (const [k, v] of Object.entries(target || {})) {
output[k] = [, v];
}
return output;
};
export 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 = (_) => _;

View File

@@ -0,0 +1,230 @@
export const parseBoolean = (value) => {
switch (value) {
case "true":
return true;
case "false":
return false;
default:
throw new Error(`Unable to parse boolean value "${value}"`);
}
};
export const expectBoolean = (value) => {
if (value === null || value === undefined) {
return undefined;
}
if (typeof value === "number") {
if (value === 0 || value === 1) {
logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));
}
if (value === 0) {
return false;
}
if (value === 1) {
return true;
}
}
if (typeof value === "string") {
const lower = value.toLowerCase();
if (lower === "false" || lower === "true") {
logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));
}
if (lower === "false") {
return false;
}
if (lower === "true") {
return true;
}
}
if (typeof value === "boolean") {
return value;
}
throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`);
};
export const expectNumber = (value) => {
if (value === null || value === undefined) {
return undefined;
}
if (typeof value === "string") {
const parsed = parseFloat(value);
if (!Number.isNaN(parsed)) {
if (String(parsed) !== String(value)) {
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}`);
};
const MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));
export const expectFloat32 = (value) => {
const expected = expectNumber(value);
if (expected !== undefined && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) {
if (Math.abs(expected) > MAX_FLOAT) {
throw new TypeError(`Expected 32-bit float, got ${value}`);
}
}
return expected;
};
export const expectLong = (value) => {
if (value === null || value === undefined) {
return undefined;
}
if (Number.isInteger(value) && !Number.isNaN(value)) {
return value;
}
throw new TypeError(`Expected integer, got ${typeof value}: ${value}`);
};
export const expectInt = expectLong;
export const expectInt32 = (value) => expectSizedInt(value, 32);
export const expectShort = (value) => expectSizedInt(value, 16);
export const expectByte = (value) => expectSizedInt(value, 8);
const expectSizedInt = (value, size) => {
const expected = expectLong(value);
if (expected !== undefined && castInt(expected, size) !== expected) {
throw new TypeError(`Expected ${size}-bit integer, got ${value}`);
}
return expected;
};
const castInt = (value, size) => {
switch (size) {
case 32:
return Int32Array.of(value)[0];
case 16:
return Int16Array.of(value)[0];
case 8:
return Int8Array.of(value)[0];
}
};
export const expectNonNull = (value, location) => {
if (value === null || value === undefined) {
if (location) {
throw new TypeError(`Expected a non-null value for ${location}`);
}
throw new TypeError("Expected a non-null value");
}
return value;
};
export const expectObject = (value) => {
if (value === null || value === undefined) {
return undefined;
}
if (typeof value === "object" && !Array.isArray(value)) {
return value;
}
const receivedType = Array.isArray(value) ? "array" : typeof value;
throw new TypeError(`Expected object, got ${receivedType}: ${value}`);
};
export const expectString = (value) => {
if (value === null || value === undefined) {
return undefined;
}
if (typeof value === "string") {
return value;
}
if (["boolean", "number", "bigint"].includes(typeof value)) {
logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));
return String(value);
}
throw new TypeError(`Expected string, got ${typeof value}: ${value}`);
};
export const expectUnion = (value) => {
if (value === null || value === undefined) {
return undefined;
}
const asObject = expectObject(value);
const setKeys = Object.entries(asObject)
.filter(([, v]) => v != null)
.map(([k]) => k);
if (setKeys.length === 0) {
throw new TypeError(`Unions must have exactly one non-null member. None were found.`);
}
if (setKeys.length > 1) {
throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`);
}
return asObject;
};
export const strictParseDouble = (value) => {
if (typeof value == "string") {
return expectNumber(parseNumber(value));
}
return expectNumber(value);
};
export const strictParseFloat = strictParseDouble;
export const strictParseFloat32 = (value) => {
if (typeof value == "string") {
return expectFloat32(parseNumber(value));
}
return expectFloat32(value);
};
const NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;
const parseNumber = (value) => {
const matches = value.match(NUMBER_REGEX);
if (matches === null || matches[0].length !== value.length) {
throw new TypeError(`Expected real number, got implicit NaN`);
}
return parseFloat(value);
};
export const limitedParseDouble = (value) => {
if (typeof value == "string") {
return parseFloatString(value);
}
return expectNumber(value);
};
export const handleFloat = limitedParseDouble;
export const limitedParseFloat = limitedParseDouble;
export const limitedParseFloat32 = (value) => {
if (typeof value == "string") {
return parseFloatString(value);
}
return expectFloat32(value);
};
const parseFloatString = (value) => {
switch (value) {
case "NaN":
return NaN;
case "Infinity":
return Infinity;
case "-Infinity":
return -Infinity;
default:
throw new Error(`Unable to parse float value: ${value}`);
}
};
export const strictParseLong = (value) => {
if (typeof value === "string") {
return expectLong(parseNumber(value));
}
return expectLong(value);
};
export const strictParseInt = strictParseLong;
export const strictParseInt32 = (value) => {
if (typeof value === "string") {
return expectInt32(parseNumber(value));
}
return expectInt32(value);
};
export const strictParseShort = (value) => {
if (typeof value === "string") {
return expectShort(parseNumber(value));
}
return expectShort(value);
};
export const strictParseByte = (value) => {
if (typeof value === "string") {
return expectByte(parseNumber(value));
}
return expectByte(value);
};
const stackTraceWarning = (message) => {
return String(new TypeError(message).stack || message)
.split("\n")
.slice(0, 5)
.filter((s) => !s.includes("stackTraceWarning"))
.join("\n");
};
export const logger = {
warn: console.warn,
};

View File

@@ -0,0 +1,19 @@
import { extendedEncodeURIComponent } from "./extended-encode-uri-component";
export const resolvedPath = (resolvedPath, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => {
if (input != null && input[memberName] !== undefined) {
const labelValue = labelValueProvider();
if (labelValue.length <= 0) {
throw new Error("Empty value provided for input HTTP label: " + memberName + ".");
}
resolvedPath = resolvedPath.replace(uriLabel, isGreedyLabel
? labelValue
.split("/")
.map((segment) => extendedEncodeURIComponent(segment))
.join("/")
: extendedEncodeURIComponent(labelValue));
}
else {
throw new Error("No value provided for input HTTP label: " + memberName + ".");
}
return resolvedPath;
};

View File

@@ -0,0 +1,13 @@
export const serializeFloat = (value) => {
if (value !== value) {
return "NaN";
}
switch (value) {
case Infinity:
return "Infinity";
case -Infinity:
return "-Infinity";
default:
return value;
}
};

View File

@@ -0,0 +1,19 @@
export 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;
};

View File

@@ -0,0 +1,27 @@
export 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;
}