@smooai/utils
Version:
A collection of shared utilities and tools used across SmooAI projects. This package provides common functionality to standardize and simplify development across all SmooAI repositories.
1,285 lines • 231 kB
JavaScript
import { t as __commonJSMin } from "./chunk-B6ditiVD.mjs";
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/tslib.mjs
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
}
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/utils/uuid.mjs
/**
* https://stackoverflow.com/a/2117523
*/
let uuid4 = function() {
const { crypto } = globalThis;
if (crypto?.randomUUID) {
uuid4 = crypto.randomUUID.bind(crypto);
return crypto.randomUUID();
}
const u8 = new Uint8Array(1);
const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16));
};
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/errors.mjs
function isAbortError(err) {
return typeof err === "object" && err !== null && ("name" in err && err.name === "AbortError" || "message" in err && String(err.message).includes("FetchRequestCanceledException"));
}
const castToError = (err) => {
if (err instanceof Error) return err;
if (typeof err === "object" && err !== null) {
try {
if (Object.prototype.toString.call(err) === "[object Error]") {
const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
if (err.stack) error.stack = err.stack;
if (err.cause && !error.cause) error.cause = err.cause;
if (err.name) error.name = err.name;
return error;
}
} catch {}
try {
return new Error(JSON.stringify(err));
} catch {}
}
return new Error(err);
};
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/core/error.mjs
var OpenAIError = class extends Error {};
var APIError = class APIError extends OpenAIError {
constructor(status, error, message, headers) {
super(`${APIError.makeMessage(status, error, message)}`);
this.status = status;
this.headers = headers;
this.requestID = headers?.get("x-request-id");
this.error = error;
const data = error;
this.code = data?.["code"];
this.param = data?.["param"];
this.type = data?.["type"];
}
static makeMessage(status, error, message) {
const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
if (status && msg) return `${status} ${msg}`;
if (status) return `${status} status code (no body)`;
if (msg) return msg;
return "(no status code or body)";
}
static generate(status, errorResponse, message, headers) {
if (!status || !headers) return new APIConnectionError({
message,
cause: castToError(errorResponse)
});
const error = errorResponse?.["error"];
if (status === 400) return new BadRequestError(status, error, message, headers);
if (status === 401) return new AuthenticationError(status, error, message, headers);
if (status === 403) return new PermissionDeniedError(status, error, message, headers);
if (status === 404) return new NotFoundError(status, error, message, headers);
if (status === 409) return new ConflictError(status, error, message, headers);
if (status === 422) return new UnprocessableEntityError(status, error, message, headers);
if (status === 429) return new RateLimitError(status, error, message, headers);
if (status >= 500) return new InternalServerError(status, error, message, headers);
return new APIError(status, error, message, headers);
}
};
var APIUserAbortError = class extends APIError {
constructor({ message } = {}) {
super(void 0, void 0, message || "Request was aborted.", void 0);
}
};
var APIConnectionError = class extends APIError {
constructor({ message, cause }) {
super(void 0, void 0, message || "Connection error.", void 0);
if (cause) this.cause = cause;
}
};
var APIConnectionTimeoutError = class extends APIConnectionError {
constructor({ message } = {}) {
super({ message: message ?? "Request timed out." });
}
};
var BadRequestError = class extends APIError {};
var AuthenticationError = class extends APIError {};
var PermissionDeniedError = class extends APIError {};
var NotFoundError = class extends APIError {};
var ConflictError = class extends APIError {};
var UnprocessableEntityError = class extends APIError {};
var RateLimitError = class extends APIError {};
var InternalServerError = class extends APIError {};
var LengthFinishReasonError = class extends OpenAIError {
constructor() {
super(`Could not parse response content as the length limit was reached`);
}
};
var ContentFilterFinishReasonError = class extends OpenAIError {
constructor() {
super(`Could not parse response content as the request was rejected by the content filter`);
}
};
var InvalidWebhookSignatureError = class extends Error {
constructor(message) {
super(message);
}
};
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/utils/values.mjs
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
const isAbsoluteURL = (url) => {
return startsWithSchemeRegexp.test(url);
};
let isArray = (val) => (isArray = Array.isArray, isArray(val));
let isReadonlyArray = isArray;
/** Returns an object if the given value isn't an object, otherwise returns as-is */
function maybeObj(x) {
if (typeof x !== "object") return {};
return x ?? {};
}
function isEmptyObj(obj) {
if (!obj) return true;
for (const _k in obj) return false;
return true;
}
function hasOwn(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
function isObj(obj) {
return obj != null && typeof obj === "object" && !Array.isArray(obj);
}
const validatePositiveInteger = (name, n) => {
if (typeof n !== "number" || !Number.isInteger(n)) throw new OpenAIError(`${name} must be an integer`);
if (n < 0) throw new OpenAIError(`${name} must be a positive integer`);
return n;
};
const safeJSON = (text) => {
try {
return JSON.parse(text);
} catch (err) {
return;
}
};
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/utils/sleep.mjs
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/version.mjs
const VERSION = "5.15.0";
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/detect-platform.mjs
const isRunningInBrowser = () => {
return typeof window !== "undefined" && typeof window.document !== "undefined" && typeof navigator !== "undefined";
};
/**
* Note this does not detect 'browser'; for that, use getBrowserInfo().
*/
function getDetectedPlatform() {
if (typeof Deno !== "undefined" && Deno.build != null) return "deno";
if (typeof EdgeRuntime !== "undefined") return "edge";
if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") return "node";
return "unknown";
}
const getPlatformProperties = () => {
const detectedPlatform = getDetectedPlatform();
if (detectedPlatform === "deno") return {
"X-Stainless-Lang": "js",
"X-Stainless-Package-Version": VERSION,
"X-Stainless-OS": normalizePlatform(Deno.build.os),
"X-Stainless-Arch": normalizeArch(Deno.build.arch),
"X-Stainless-Runtime": "deno",
"X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
};
if (typeof EdgeRuntime !== "undefined") return {
"X-Stainless-Lang": "js",
"X-Stainless-Package-Version": VERSION,
"X-Stainless-OS": "Unknown",
"X-Stainless-Arch": `other:${EdgeRuntime}`,
"X-Stainless-Runtime": "edge",
"X-Stainless-Runtime-Version": globalThis.process.version
};
if (detectedPlatform === "node") return {
"X-Stainless-Lang": "js",
"X-Stainless-Package-Version": VERSION,
"X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"),
"X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"),
"X-Stainless-Runtime": "node",
"X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
};
const browserInfo = getBrowserInfo();
if (browserInfo) return {
"X-Stainless-Lang": "js",
"X-Stainless-Package-Version": VERSION,
"X-Stainless-OS": "Unknown",
"X-Stainless-Arch": "unknown",
"X-Stainless-Runtime": `browser:${browserInfo.browser}`,
"X-Stainless-Runtime-Version": browserInfo.version
};
return {
"X-Stainless-Lang": "js",
"X-Stainless-Package-Version": VERSION,
"X-Stainless-OS": "Unknown",
"X-Stainless-Arch": "unknown",
"X-Stainless-Runtime": "unknown",
"X-Stainless-Runtime-Version": "unknown"
};
};
function getBrowserInfo() {
if (typeof navigator === "undefined" || !navigator) return null;
for (const { key, pattern } of [
{
key: "edge",
pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/
},
{
key: "ie",
pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/
},
{
key: "ie",
pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/
},
{
key: "chrome",
pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/
},
{
key: "firefox",
pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/
},
{
key: "safari",
pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/
}
]) {
const match = pattern.exec(navigator.userAgent);
if (match) return {
browser: key,
version: `${match[1] || 0}.${match[2] || 0}.${match[3] || 0}`
};
}
return null;
}
const normalizeArch = (arch) => {
if (arch === "x32") return "x32";
if (arch === "x86_64" || arch === "x64") return "x64";
if (arch === "arm") return "arm";
if (arch === "aarch64" || arch === "arm64") return "arm64";
if (arch) return `other:${arch}`;
return "unknown";
};
const normalizePlatform = (platform) => {
platform = platform.toLowerCase();
if (platform.includes("ios")) return "iOS";
if (platform === "android") return "Android";
if (platform === "darwin") return "MacOS";
if (platform === "win32") return "Windows";
if (platform === "freebsd") return "FreeBSD";
if (platform === "openbsd") return "OpenBSD";
if (platform === "linux") return "Linux";
if (platform) return `Other:${platform}`;
return "Unknown";
};
let _platformHeaders;
const getPlatformHeaders = () => {
return _platformHeaders ?? (_platformHeaders = getPlatformProperties());
};
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/shims.mjs
function getDefaultFetch() {
if (typeof fetch !== "undefined") return fetch;
throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
}
function makeReadableStream(...args) {
const ReadableStream = globalThis.ReadableStream;
if (typeof ReadableStream === "undefined") throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
return new ReadableStream(...args);
}
function ReadableStreamFrom(iterable) {
let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
return makeReadableStream({
start() {},
async pull(controller) {
const { done, value } = await iter.next();
if (done) controller.close();
else controller.enqueue(value);
},
async cancel() {
await iter.return?.();
}
});
}
/**
* Most browsers don't yet have async iterable support for ReadableStream,
* and Node has a very different way of reading bytes from its "ReadableStream".
*
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
*/
function ReadableStreamToAsyncIterable(stream) {
if (stream[Symbol.asyncIterator]) return stream;
const reader = stream.getReader();
return {
async next() {
try {
const result = await reader.read();
if (result?.done) reader.releaseLock();
return result;
} catch (e) {
reader.releaseLock();
throw e;
}
},
async return() {
const cancelPromise = reader.cancel();
reader.releaseLock();
await cancelPromise;
return {
done: true,
value: void 0
};
},
[Symbol.asyncIterator]() {
return this;
}
};
}
/**
* Cancels a ReadableStream we don't need to consume.
* See https://undici.nodejs.org/#/?id=garbage-collection
*/
async function CancelReadableStream(stream) {
if (stream === null || typeof stream !== "object") return;
if (stream[Symbol.asyncIterator]) {
await stream[Symbol.asyncIterator]().return?.();
return;
}
const reader = stream.getReader();
const cancelPromise = reader.cancel();
reader.releaseLock();
await cancelPromise;
}
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/request-options.mjs
const FallbackEncoder = ({ headers, body }) => {
return {
bodyHeaders: { "content-type": "application/json" },
body: JSON.stringify(body)
};
};
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/qs/formats.mjs
const default_format = "RFC3986";
const default_formatter = (v) => String(v);
const formatters = {
RFC1738: (v) => String(v).replace(/%20/g, "+"),
RFC3986: default_formatter
};
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/qs/utils.mjs
let has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key));
const hex_table = /* @__PURE__ */ (() => {
const array = [];
for (let i = 0; i < 256; ++i) array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase());
return array;
})();
const limit = 1024;
const encode = (str, _defaultEncoder, charset, _kind, format) => {
if (str.length === 0) return str;
let string = str;
if (typeof str === "symbol") string = Symbol.prototype.toString.call(str);
else if (typeof str !== "string") string = String(str);
if (charset === "iso-8859-1") return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) {
return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
});
let out = "";
for (let j = 0; j < string.length; j += limit) {
const segment = string.length >= limit ? string.slice(j, j + limit) : string;
const arr = [];
for (let i = 0; i < segment.length; ++i) {
let c = segment.charCodeAt(i);
if (c === 45 || c === 46 || c === 95 || c === 126 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || format === "RFC1738" && (c === 40 || c === 41)) {
arr[arr.length] = segment.charAt(i);
continue;
}
if (c < 128) {
arr[arr.length] = hex_table[c];
continue;
}
if (c < 2048) {
arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63];
continue;
}
if (c < 55296 || c >= 57344) {
arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63];
continue;
}
i += 1;
c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023);
arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63];
}
out += arr.join("");
}
return out;
};
function is_buffer(obj) {
if (!obj || typeof obj !== "object") return false;
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
}
function maybe_map(val, fn) {
if (isArray(val)) {
const mapped = [];
for (let i = 0; i < val.length; i += 1) mapped.push(fn(val[i]));
return mapped;
}
return fn(val);
}
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/qs/stringify.mjs
const array_prefix_generators = {
brackets(prefix) {
return String(prefix) + "[]";
},
comma: "comma",
indices(prefix, key) {
return String(prefix) + "[" + key + "]";
},
repeat(prefix) {
return String(prefix);
}
};
const push_to_array = function(arr, value_or_array) {
Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]);
};
let toISOString;
const defaults = {
addQueryPrefix: false,
allowDots: false,
allowEmptyArrays: false,
arrayFormat: "indices",
charset: "utf-8",
charsetSentinel: false,
delimiter: "&",
encode: true,
encodeDotInKeys: false,
encoder: encode,
encodeValuesOnly: false,
format: default_format,
formatter: default_formatter,
/** @deprecated */
indices: false,
serializeDate(date) {
return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date);
},
skipNulls: false,
strictNullHandling: false
};
function is_non_nullish_primitive(v) {
return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint";
}
const sentinel = {};
function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {
let obj = object;
let tmp_sc = sideChannel;
let step = 0;
let find_flag = false;
while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) {
const pos = tmp_sc.get(object);
step += 1;
if (typeof pos !== "undefined") if (pos === step) throw new RangeError("Cyclic object value");
else find_flag = true;
if (typeof tmp_sc.get(sentinel) === "undefined") step = 0;
}
if (typeof filter === "function") obj = filter(prefix, obj);
else if (obj instanceof Date) obj = serializeDate?.(obj);
else if (generateArrayPrefix === "comma" && isArray(obj)) obj = maybe_map(obj, function(value) {
if (value instanceof Date) return serializeDate?.(value);
return value;
});
if (obj === null) {
if (strictNullHandling) return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, "key", format) : prefix;
obj = "";
}
if (is_non_nullish_primitive(obj) || is_buffer(obj)) {
if (encoder) {
const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format);
return [formatter?.(key_value) + "=" + formatter?.(encoder(obj, defaults.encoder, charset, "value", format))];
}
return [formatter?.(prefix) + "=" + formatter?.(String(obj))];
}
const values = [];
if (typeof obj === "undefined") return values;
let obj_keys;
if (generateArrayPrefix === "comma" && isArray(obj)) {
if (encodeValuesOnly && encoder) obj = maybe_map(obj, encoder);
obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }];
} else if (isArray(filter)) obj_keys = filter;
else {
const keys = Object.keys(obj);
obj_keys = sort ? keys.sort(sort) : keys;
}
const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix);
const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix;
if (allowEmptyArrays && isArray(obj) && obj.length === 0) return adjusted_prefix + "[]";
for (let j = 0; j < obj_keys.length; ++j) {
const key = obj_keys[j];
const value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key];
if (skipNulls && value === null) continue;
const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key;
const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]");
sideChannel.set(object, step);
const valueSideChannel = /* @__PURE__ */ new WeakMap();
valueSideChannel.set(sentinel, sideChannel);
push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel));
}
return values;
}
function normalize_stringify_options(opts = defaults) {
if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");
if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") throw new TypeError("Encoder has to be a function.");
const charset = opts.charset || defaults.charset;
if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
let format = default_format;
if (typeof opts.format !== "undefined") {
if (!has(formatters, opts.format)) throw new TypeError("Unknown format option provided.");
format = opts.format;
}
const formatter = formatters[format];
let filter = defaults.filter;
if (typeof opts.filter === "function" || isArray(opts.filter)) filter = opts.filter;
let arrayFormat;
if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) arrayFormat = opts.arrayFormat;
else if ("indices" in opts) arrayFormat = opts.indices ? "indices" : "repeat";
else arrayFormat = defaults.arrayFormat;
if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;
return {
addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix,
allowDots,
allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
arrayFormat,
charset,
charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel,
commaRoundTrip: !!opts.commaRoundTrip,
delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter,
encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode,
encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys,
encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder,
encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
filter,
format,
formatter,
serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate,
skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls,
sort: typeof opts.sort === "function" ? opts.sort : null,
strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling
};
}
function stringify(object, opts = {}) {
let obj = object;
const options = normalize_stringify_options(opts);
let obj_keys;
let filter;
if (typeof options.filter === "function") {
filter = options.filter;
obj = filter("", obj);
} else if (isArray(options.filter)) {
filter = options.filter;
obj_keys = filter;
}
const keys = [];
if (typeof obj !== "object" || obj === null) return "";
const generateArrayPrefix = array_prefix_generators[options.arrayFormat];
const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip;
if (!obj_keys) obj_keys = Object.keys(obj);
if (options.sort) obj_keys.sort(options.sort);
const sideChannel = /* @__PURE__ */ new WeakMap();
for (let i = 0; i < obj_keys.length; ++i) {
const key = obj_keys[i];
if (options.skipNulls && obj[key] === null) continue;
push_to_array(keys, inner_stringify(obj[key], key, generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel));
}
const joined = keys.join(options.delimiter);
let prefix = options.addQueryPrefix === true ? "?" : "";
if (options.charsetSentinel) if (options.charset === "iso-8859-1") prefix += "utf8=%26%2310003%3B&";
else prefix += "utf8=%E2%9C%93&";
return joined.length > 0 ? prefix + joined : "";
}
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/utils/bytes.mjs
function concatBytes(buffers) {
let length = 0;
for (const buffer of buffers) length += buffer.length;
const output = new Uint8Array(length);
let index = 0;
for (const buffer of buffers) {
output.set(buffer, index);
index += buffer.length;
}
return output;
}
let encodeUTF8_;
function encodeUTF8(str) {
let encoder;
return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str);
}
let decodeUTF8_;
function decodeUTF8(bytes) {
let decoder;
return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes);
}
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/decoders/line.mjs
var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex;
/**
* A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
* reading lines from text.
*
* https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
*/
var LineDecoder = class {
constructor() {
_LineDecoder_buffer.set(this, void 0);
_LineDecoder_carriageReturnIndex.set(this, void 0);
__classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f");
__classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
}
decode(chunk) {
if (chunk == null) return [];
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk;
__classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f");
const lines = [];
let patternIndex;
while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) {
__classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f");
continue;
}
if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
__classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f");
__classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
continue;
}
const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex));
lines.push(line);
__classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f");
__classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
}
return lines;
}
flush() {
if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) return [];
return this.decode("\n");
}
};
_LineDecoder_buffer = /* @__PURE__ */ new WeakMap(), _LineDecoder_carriageReturnIndex = /* @__PURE__ */ new WeakMap();
LineDecoder.NEWLINE_CHARS = new Set(["\n", "\r"]);
LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
/**
* This function searches the buffer for the end patterns, (\r or \n)
* and returns an object with the index preceding the matched newline and the
* index after the newline char. `null` is returned if no new line is found.
*
* ```ts
* findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
* ```
*/
function findNewlineIndex(buffer, startIndex) {
const newline = 10;
const carriage = 13;
for (let i = startIndex ?? 0; i < buffer.length; i++) {
if (buffer[i] === newline) return {
preceding: i,
index: i + 1,
carriage: false
};
if (buffer[i] === carriage) return {
preceding: i,
index: i + 1,
carriage: true
};
}
return null;
}
function findDoubleNewlineIndex(buffer) {
const newline = 10;
const carriage = 13;
for (let i = 0; i < buffer.length - 1; i++) {
if (buffer[i] === newline && buffer[i + 1] === newline) return i + 2;
if (buffer[i] === carriage && buffer[i + 1] === carriage) return i + 2;
if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) return i + 4;
}
return -1;
}
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/utils/log.mjs
const levelNumbers = {
off: 0,
error: 200,
warn: 300,
info: 400,
debug: 500
};
const parseLogLevel = (maybeLevel, sourceName, client) => {
if (!maybeLevel) return;
if (hasOwn(levelNumbers, maybeLevel)) return maybeLevel;
loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
};
function noop() {}
function makeLogFn(fnLevel, logger, logLevel) {
if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) return noop;
else return logger[fnLevel].bind(logger);
}
const noopLogger = {
error: noop,
warn: noop,
info: noop,
debug: noop
};
let cachedLoggers = /* @__PURE__ */ new WeakMap();
function loggerFor(client) {
const logger = client.logger;
const logLevel = client.logLevel ?? "off";
if (!logger) return noopLogger;
const cachedLogger = cachedLoggers.get(logger);
if (cachedLogger && cachedLogger[0] === logLevel) return cachedLogger[1];
const levelLogger = {
error: makeLogFn("error", logger, logLevel),
warn: makeLogFn("warn", logger, logLevel),
info: makeLogFn("info", logger, logLevel),
debug: makeLogFn("debug", logger, logLevel)
};
cachedLoggers.set(logger, [logLevel, levelLogger]);
return levelLogger;
}
const formatRequestDetails = (details) => {
if (details.options) {
details.options = { ...details.options };
delete details.options["headers"];
}
if (details.headers) details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [name, name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value]));
if ("retryOfRequestLogID" in details) {
if (details.retryOfRequestLogID) details.retryOf = details.retryOfRequestLogID;
delete details.retryOfRequestLogID;
}
return details;
};
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/core/streaming.mjs
var _Stream_client;
var Stream = class Stream {
constructor(iterator, controller, client) {
this.iterator = iterator;
_Stream_client.set(this, void 0);
this.controller = controller;
__classPrivateFieldSet(this, _Stream_client, client, "f");
}
static fromSSEResponse(response, controller, client) {
let consumed = false;
const logger = client ? loggerFor(client) : console;
async function* iterator() {
if (consumed) throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
consumed = true;
let done = false;
try {
for await (const sse of _iterSSEMessages(response, controller)) {
if (done) continue;
if (sse.data.startsWith("[DONE]")) {
done = true;
continue;
}
if (sse.event === null || !sse.event.startsWith("thread.")) {
let data;
try {
data = JSON.parse(sse.data);
} catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
if (data && data.error) throw new APIError(void 0, data.error, void 0, response.headers);
yield data;
} else {
let data;
try {
data = JSON.parse(sse.data);
} catch (e) {
console.error(`Could not parse message into JSON:`, sse.data);
console.error(`From chunk:`, sse.raw);
throw e;
}
if (sse.event == "error") throw new APIError(void 0, data.error, data.message, void 0);
yield {
event: sse.event,
data
};
}
}
done = true;
} catch (e) {
if (isAbortError(e)) return;
throw e;
} finally {
if (!done) controller.abort();
}
}
return new Stream(iterator, controller, client);
}
/**
* Generates a Stream from a newline-separated ReadableStream
* where each item is a JSON value.
*/
static fromReadableStream(readableStream, controller, client) {
let consumed = false;
async function* iterLines() {
const lineDecoder = new LineDecoder();
const iter = ReadableStreamToAsyncIterable(readableStream);
for await (const chunk of iter) for (const line of lineDecoder.decode(chunk)) yield line;
for (const line of lineDecoder.flush()) yield line;
}
async function* iterator() {
if (consumed) throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
consumed = true;
let done = false;
try {
for await (const line of iterLines()) {
if (done) continue;
if (line) yield JSON.parse(line);
}
done = true;
} catch (e) {
if (isAbortError(e)) return;
throw e;
} finally {
if (!done) controller.abort();
}
}
return new Stream(iterator, controller, client);
}
[(_Stream_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
return this.iterator();
}
/**
* Splits the stream into two streams which can be
* independently read from at different speeds.
*/
tee() {
const left = [];
const right = [];
const iterator = this.iterator();
const teeIterator = (queue) => {
return { next: () => {
if (queue.length === 0) {
const result = iterator.next();
left.push(result);
right.push(result);
}
return queue.shift();
} };
};
return [new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f"))];
}
/**
* Converts this stream to a newline-separated ReadableStream of
* JSON stringified values in the stream
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
*/
toReadableStream() {
const self = this;
let iter;
return makeReadableStream({
async start() {
iter = self[Symbol.asyncIterator]();
},
async pull(ctrl) {
try {
const { value, done } = await iter.next();
if (done) return ctrl.close();
const bytes = encodeUTF8(JSON.stringify(value) + "\n");
ctrl.enqueue(bytes);
} catch (err) {
ctrl.error(err);
}
},
async cancel() {
await iter.return?.();
}
});
}
};
async function* _iterSSEMessages(response, controller) {
if (!response.body) {
controller.abort();
if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") throw new OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
throw new OpenAIError(`Attempted to iterate over a response with no body`);
}
const sseDecoder = new SSEDecoder();
const lineDecoder = new LineDecoder();
const iter = ReadableStreamToAsyncIterable(response.body);
for await (const sseChunk of iterSSEChunks(iter)) for (const line of lineDecoder.decode(sseChunk)) {
const sse = sseDecoder.decode(line);
if (sse) yield sse;
}
for (const line of lineDecoder.flush()) {
const sse = sseDecoder.decode(line);
if (sse) yield sse;
}
}
/**
* Given an async iterable iterator, iterates over it and yields full
* SSE chunks, i.e. yields when a double new-line is encountered.
*/
async function* iterSSEChunks(iterator) {
let data = new Uint8Array();
for await (const chunk of iterator) {
if (chunk == null) continue;
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk;
let newData = new Uint8Array(data.length + binaryChunk.length);
newData.set(data);
newData.set(binaryChunk, data.length);
data = newData;
let patternIndex;
while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
yield data.slice(0, patternIndex);
data = data.slice(patternIndex);
}
}
if (data.length > 0) yield data;
}
var SSEDecoder = class {
constructor() {
this.event = null;
this.data = [];
this.chunks = [];
}
decode(line) {
if (line.endsWith("\r")) line = line.substring(0, line.length - 1);
if (!line) {
if (!this.event && !this.data.length) return null;
const sse = {
event: this.event,
data: this.data.join("\n"),
raw: this.chunks
};
this.event = null;
this.data = [];
this.chunks = [];
return sse;
}
this.chunks.push(line);
if (line.startsWith(":")) return null;
let [fieldname, _, value] = partition(line, ":");
if (value.startsWith(" ")) value = value.substring(1);
if (fieldname === "event") this.event = value;
else if (fieldname === "data") this.data.push(value);
return null;
}
};
function partition(str, delimiter) {
const index = str.indexOf(delimiter);
if (index !== -1) return [
str.substring(0, index),
delimiter,
str.substring(index + delimiter.length)
];
return [
str,
"",
""
];
}
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/parse.mjs
async function defaultParseResponse(client, props) {
const { response, requestLogID, retryOfRequestLogID, startTime } = props;
const body = await (async () => {
if (props.options.stream) {
loggerFor(client).debug("response", response.status, response.url, response.headers, response.body);
if (props.options.__streamClass) return props.options.__streamClass.fromSSEResponse(response, props.controller, client);
return Stream.fromSSEResponse(response, props.controller, client);
}
if (response.status === 204) return null;
if (props.options.__binaryResponse) return response;
const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim();
if (mediaType?.includes("application/json") || mediaType?.endsWith("+json")) return addRequestID(await response.json(), response);
return await response.text();
})();
loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
retryOfRequestLogID,
url: response.url,
status: response.status,
body,
durationMs: Date.now() - startTime
}));
return body;
}
function addRequestID(value, response) {
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
return Object.defineProperty(value, "_request_id", {
value: response.headers.get("x-request-id"),
enumerable: false
});
}
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/core/api-promise.mjs
var _APIPromise_client;
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
var APIPromise = class APIPromise extends Promise {
constructor(client, responsePromise, parseResponse = defaultParseResponse) {
super((resolve) => {
resolve(null);
});
this.responsePromise = responsePromise;
this.parseResponse = parseResponse;
_APIPromise_client.set(this, void 0);
__classPrivateFieldSet(this, _APIPromise_client, client, "f");
}
_thenUnwrap(transform) {
return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response));
}
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
asResponse() {
return this.responsePromise.then((p) => p.response);
}
/**
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
* returned via the X-Request-ID header which is useful for debugging requests and reporting
* issues to OpenAI.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
async withResponse() {
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
return {
data,
response,
request_id: response.headers.get("x-request-id")
};
}
parse() {
if (!this.parsedPromise) this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
return this.parsedPromise;
}
then(onfulfilled, onrejected) {
return this.parse().then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.parse().catch(onrejected);
}
finally(onfinally) {
return this.parse().finally(onfinally);
}
};
_APIPromise_client = /* @__PURE__ */ new WeakMap();
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/core/pagination.mjs
var _AbstractPage_client;
var AbstractPage = class {
constructor(client, response, body, options) {
_AbstractPage_client.set(this, void 0);
__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
this.options = options;
this.response = response;
this.body = body;
}
hasNextPage() {
if (!this.getPaginatedItems().length) return false;
return this.nextPageRequestOptions() != null;
}
async getNextPage() {
const nextOptions = this.nextPageRequestOptions();
if (!nextOptions) throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
}
async *iterPages() {
let page = this;
yield page;
while (page.hasNextPage()) {
page = await page.getNextPage();
yield page;
}
}
async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
for await (const page of this.iterPages()) for (const item of page.getPaginatedItems()) yield item;
}
};
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
var PagePromise = class extends APIPromise {
constructor(client, request, Page) {
super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options));
}
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
async *[Symbol.asyncIterator]() {
const page = await this;
for await (const item of page) yield item;
}
};
/**
* Note: no pagination actually occurs yet, this is for forwards-compatibility.
*/
var Page = class extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.object = body.object;
}
getPaginatedItems() {
return this.data ?? [];
}
nextPageRequestOptions() {
return null;
}
};
var CursorPage = class extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) return false;
return super.hasNextPage();
}
nextPageRequestOptions() {
const data = this.getPaginatedItems();
const id = data[data.length - 1]?.id;
if (!id) return null;
return {
...this.options,
query: {
...maybeObj(this.options.query),
after: id
}
};
}
};
var ConversationCursorPage = class extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.last_id = body.last_id || "";
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) return false;
return super.hasNextPage();
}
nextPageRequestOptions() {
const cursor = this.last_id;
if (!cursor) return null;
return {
...this.options,
query: {
...maybeObj(this.options.query),
after: cursor
}
};
}
};
//#endregion
//#region node_modules/.pnpm/openai@5.15.0_zod@4.1.5/node_modules/openai/internal/uploads.mjs
const checkFileSupport = () => {
if (typeof File === "undefined") {
const { process } = globalThis;
const isOldNode = typeof process?.versions?.node === "string" && parseInt(process.versions.node.split(".")) < 20;
throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
}
};
/**
* Construct a `File` instance. This is used to ensure a helpful error is thrown
* for environments that don't define a global `File` yet.
*/
function makeFile(fileBits, fileName, options) {
checkFileSupport();
return new File(fileBits, fileName ?? "unknown_file", options);
}
function getName(value) {
return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0;
}
const isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
const multipartFormRequestOptions = async (opts, fetch) => {
return {
...opts,
body: await createForm(opts.body, fetch)
};
};
const supportsFormDataMap = /* @__PURE__ */ new WeakMap();
/**
* node-fetch doesn't support the global FormData object in recent node versions. Instead of sending
* properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]".
* This function detects if the fetch function provided supports the global FormData object to avoid
* confusing error messages later on.
*/
function supportsFormData(fetchObject) {
const fetch = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
const cached = supportsFormDataMap.get(fetch);
if (cached) return cached;
const promise = (async () => {
try {
const FetchResponse = "Response" in fetch ? fetch.Response : (await fetch("data:,")).constructor;
const data = new FormData();
if (data.toString() === await new FetchResponse(data).text()) return false;
return true;
} catch {
return true;
}
})();
supportsFormDataMap.set(fetch, promise);
return promise;
}
const createForm = async (body, fetch) => {
if (!await supportsFormData(fetch)) throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
const form = new FormData();
await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
return form;
};
const isNamedBlob = (value) => value instanceof Blob && "name" in value;
const addFormValue = async (form, key, value) => {
if (value === void 0) return;
if (value == null) throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") form.append(key, String(value));
else if (value instanceof Response) form.append(key, makeFile([await value.blob()], getName(value)));
else if (isAsyncIterable(value)) form.append(key, makeFile([await new Response(