UNPKG

autumn-js

Version:
1,709 lines (1,684 loc) 1.42 MB
'use strict'; var z66 = require('zod/v4-mini'); var z2 = require('zod/v4/core'); function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var z66__namespace = /*#__PURE__*/_interopNamespace(z66); var z2__namespace = /*#__PURE__*/_interopNamespace(z2); var __defProp = Object.defineProperty; var __typeError = (msg) => { throw TypeError(msg); }; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value); // ../sdk/src/lib/url.ts var hasOwn = Object.prototype.hasOwnProperty; function pathToFunc(pathPattern, options) { const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g; return function buildURLPath(params = {}) { return pathPattern.replace(paramRE, function(_, placeholder) { if (!hasOwn.call(params, placeholder)) { throw new Error(`Parameter '${placeholder}' is required`); } const value = params[placeholder]; if (typeof value !== "string" && typeof value !== "number") { throw new Error( `Parameter '${placeholder}' must be a string or number` ); } return `${value}`; }).replace(/^\/+/, ""); }; } // ../sdk/src/lib/config.ts var ServerList = [ /** * Production server */ "https://api.useautumn.com" ]; function serverURLFromOptions(options) { let serverURL = options.serverURL; const params = {}; if (!serverURL) { const serverIdx = options.serverIdx ?? 0; if (serverIdx < 0 || serverIdx >= ServerList.length) { throw new Error(`Invalid server index ${serverIdx}`); } serverURL = ServerList[serverIdx] || ""; } const u = pathToFunc(serverURL)(params); return new URL(u); } var SDK_METADATA = { language: "typescript", openapiDocVersion: "2.3.0", sdkVersion: "0.10.17", genVersion: "2.882.0", userAgent: "speakeasy-sdk/typescript 0.10.17 2.882.0 2.3.0 @useautumn/sdk" }; // ../sdk/src/lib/files.ts var files_exports = {}; __export(files_exports, { bytesToBlob: () => bytesToBlob, getContentTypeFromFileName: () => getContentTypeFromFileName, readableStreamToArrayBuffer: () => readableStreamToArrayBuffer }); async function readableStreamToArrayBuffer(readable) { const reader = readable.getReader(); const chunks = []; let totalLength = 0; let done = false; while (!done) { const { value, done: doneReading } = await reader.read(); if (doneReading) { done = true; } else { chunks.push(value); totalLength += value.length; } } const concatenatedChunks = new Uint8Array(totalLength); let offset = 0; for (const chunk of chunks) { concatenatedChunks.set(chunk, offset); offset += chunk.length; } return concatenatedChunks.buffer; } function getContentTypeFromFileName(fileName) { if (!fileName) return null; const ext = fileName.toLowerCase().split(".").pop(); if (!ext) return null; const mimeTypes = { json: "application/json", xml: "application/xml", html: "text/html", htm: "text/html", txt: "text/plain", csv: "text/csv", pdf: "application/pdf", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", svg: "image/svg+xml", js: "application/javascript", css: "text/css", zip: "application/zip", tar: "application/x-tar", gz: "application/gzip", mp4: "video/mp4", mp3: "audio/mpeg", wav: "audio/wav", webp: "image/webp", ico: "image/x-icon", woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf" }; return mimeTypes[ext] || null; } function bytesToBlob(content, contentType) { if (content instanceof Uint8Array) { return new Blob([new Uint8Array(content)], { type: contentType }); } return new Blob([content], { type: contentType }); } // ../sdk/src/lib/http.ts var DEFAULT_FETCHER = (input, init) => { if (init == null) { return fetch(input); } else { return fetch(input, init); } }; var HTTPClient = class _HTTPClient { constructor(options = {}) { this.options = options; __publicField(this, "fetcher"); __publicField(this, "requestHooks", []); __publicField(this, "requestErrorHooks", []); __publicField(this, "responseHooks", []); this.fetcher = options.fetcher || DEFAULT_FETCHER; } async request(request) { let req = request; for (const hook of this.requestHooks) { const nextRequest = await hook(req); if (nextRequest) { req = nextRequest; } } try { const res = await this.fetcher(req); for (const hook of this.responseHooks) { await hook(res, req); } return res; } catch (err) { for (const hook of this.requestErrorHooks) { await hook(err, req); } throw err; } } addHook(...args) { if (args[0] === "beforeRequest") { this.requestHooks.push(args[1]); } else if (args[0] === "requestError") { this.requestErrorHooks.push(args[1]); } else if (args[0] === "response") { this.responseHooks.push(args[1]); } else { throw new Error(`Invalid hook type: ${args[0]}`); } return this; } removeHook(...args) { let target; if (args[0] === "beforeRequest") { target = this.requestHooks; } else if (args[0] === "requestError") { target = this.requestErrorHooks; } else if (args[0] === "response") { target = this.responseHooks; } else { throw new Error(`Invalid hook type: ${args[0]}`); } const index = target.findIndex((v) => v === args[1]); if (index >= 0) { target.splice(index, 1); } return this; } clone() { const child = new _HTTPClient(this.options); child.requestHooks = this.requestHooks.slice(); child.requestErrorHooks = this.requestErrorHooks.slice(); child.responseHooks = this.responseHooks.slice(); return child; } }; var mediaParamSeparator = /\s*;\s*/g; function matchContentType(response, pattern) { if (pattern === "*") { return true; } let contentType = response.headers.get("content-type")?.trim() || "application/octet-stream"; contentType = contentType.toLowerCase(); const wantParts = pattern.toLowerCase().trim().split(mediaParamSeparator); const [wantType = "", ...wantParams] = wantParts; if (wantType.split("/").length !== 2) { return false; } const gotParts = contentType.split(mediaParamSeparator); const [gotType = "", ...gotParams] = gotParts; const [type = "", subtype = ""] = gotType.split("/"); if (!type || !subtype) { return false; } if (wantType !== "*/*" && gotType !== wantType && `${type}/*` !== wantType && `*/${subtype}` !== wantType) { return false; } if (gotParams.length < wantParams.length) { return false; } const params = new Set(gotParams); for (const wantParam of wantParams) { if (!params.has(wantParam)) { return false; } } return true; } var codeRangeRE = new RegExp("^[0-9]xx$", "i"); function matchStatusCode(response, codes) { const actual = `${response.status}`; const expectedCodes = Array.isArray(codes) ? codes : [codes]; if (!expectedCodes.length) { return false; } return expectedCodes.some((ec) => { const code = `${ec}`; if (code === "default") { return true; } if (!codeRangeRE.test(`${code}`)) { return code === actual; } const expectFamily = code.charAt(0); if (!expectFamily) { throw new Error("Invalid status code range"); } const actualFamily = actual.charAt(0); if (!actualFamily) { throw new Error(`Invalid response status code: ${actual}`); } return actualFamily === expectFamily; }); } function matchResponse(response, code, contentTypePattern) { return matchStatusCode(response, code) && matchContentType(response, contentTypePattern); } function isConnectionError(err) { if (typeof err !== "object" || err == null) { return false; } const isBrowserErr = err instanceof TypeError && err.message.toLowerCase().startsWith("failed to fetch"); const isNodeErr = err instanceof TypeError && err.message.toLowerCase().startsWith("fetch failed"); const isBunErr = "name" in err && err.name === "ConnectionError"; const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnreset"; return isBrowserErr || isNodeErr || isGenericErr || isBunErr; } function isTimeoutError(err) { if (typeof err !== "object" || err == null) { return false; } const isNative = "name" in err && err.name === "TimeoutError"; const isLegacyNative = "code" in err && err.code === 23; const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted"; return isNative || isLegacyNative || isGenericErr; } function isAbortError(err) { if (typeof err !== "object" || err == null) { return false; } const isNative = "name" in err && err.name === "AbortError"; const isLegacyNative = "code" in err && err.code === 20; const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted"; return isNative || isLegacyNative || isGenericErr; } function bytesToBase64(u8arr) { return btoa(String.fromCodePoint(...u8arr)); } function bytesFromBase64(encoded) { return Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0)); } function stringToBytes(str) { return new TextEncoder().encode(str); } function stringToBase64(str) { return bytesToBase64(stringToBytes(str)); } z66__namespace.union([ z66__namespace.custom((x) => x instanceof Uint8Array), z66__namespace.pipe(z66__namespace.string(), z66__namespace.transform(stringToBytes)) ]); z66__namespace.union([ z66__namespace.custom((x) => x instanceof Uint8Array), z66__namespace.pipe(z66__namespace.string(), z66__namespace.transform(bytesFromBase64)) ]); // ../sdk/src/lib/is-plain-object.ts function isPlainObject(value) { if (typeof value !== "object" || value === null) { return false; } const prototype = Object.getPrototypeOf(value); return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); } function formEncoder(sep) { return (key, value, options) => { let out = ""; const pairs = options?.explode ? explode(key, value) : [[key, value]]; if (pairs.every(([_, v]) => v == null)) { return; } const encodeString = (v) => { return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; }; const encodeValue = (v) => encodeString(serializeValue(v)); const encodedSep = encodeString(sep); pairs.forEach(([pk, pv]) => { let tmp = ""; let encValue = null; if (pv == null) { return; } else if (Array.isArray(pv)) { encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(encodedSep); } else if (isPlainObject(pv)) { encValue = mapDefinedEntries(Object.entries(pv), ([k, v]) => { return `${encodeString(k)}${encodedSep}${encodeValue(v)}`; })?.join(encodedSep); } else { encValue = `${encodeValue(pv)}`; } if (encValue == null) { return; } tmp = `${encodeString(pk)}=${encValue}`; if (!tmp || tmp === "=") { return; } out += `&${tmp}`; }); return out.slice(1); }; } var encodeForm = formEncoder(","); function encodeJSON(key, value, options) { if (typeof value === "undefined") { return; } const encodeString = (v) => { return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; }; const encVal = encodeString(JSON.stringify(value, jsonReplacer)); return options?.explode ? encVal : `${encodeString(key)}=${encVal}`; } var encodeSimple = (key, value, options) => { let out = ""; const pairs = options?.explode ? explode(key, value) : [[key, value]]; if (pairs.every(([_, v]) => v == null)) { return; } const encodeString = (v) => { return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; }; const encodeValue = (v) => encodeString(serializeValue(v)); pairs.forEach(([pk, pv]) => { let tmp = ""; if (pv == null) { return; } else if (Array.isArray(pv)) { tmp = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(","); } else if (isPlainObject(pv)) { const mapped = mapDefinedEntries(Object.entries(pv), ([k, v]) => { return `,${encodeString(k)},${encodeValue(v)}`; }); tmp = mapped?.join("").slice(1); } else { const k = options?.explode && isPlainObject(value) ? `${pk}=` : ""; tmp = `${k}${encodeValue(pv)}`; } out += tmp ? `,${tmp}` : ""; }); return out.slice(1); }; function explode(key, value) { if (Array.isArray(value)) { return value.map((v) => [key, v]); } else if (isPlainObject(value)) { const o = value ?? {}; return Object.entries(o).map(([k, v]) => [k, v]); } else { return [[key, value]]; } } function serializeValue(value) { if (value == null) { return ""; } else if (value instanceof Date) { return value.toISOString(); } else if (value instanceof Uint8Array) { return bytesToBase64(value); } else if (typeof value === "object") { return JSON.stringify(value, jsonReplacer); } return `${value}`; } function jsonReplacer(_, value) { if (value instanceof Uint8Array) { return bytesToBase64(value); } else { return value; } } function mapDefined(inp, mapper) { const res = inp.reduce((acc, v) => { if (v == null) { return acc; } const m = mapper(v); if (m == null) { return acc; } acc.push(m); return acc; }, []); return res.length ? res : null; } function mapDefinedEntries(inp, mapper) { const acc = []; for (const [k, v] of inp) { if (v == null) { continue; } const m = mapper([k, v]); if (m == null) { continue; } acc.push(m); } return acc.length ? acc : null; } // ../sdk/src/models/autumn-error.ts var AutumnError = class extends Error { constructor(message, httpMeta) { super(message); /** HTTP status code */ __publicField(this, "statusCode"); /** HTTP body */ __publicField(this, "body"); /** HTTP headers */ __publicField(this, "headers"); /** HTTP content type */ __publicField(this, "contentType"); /** Raw response */ __publicField(this, "rawResponse"); this.statusCode = httpMeta.response.status; this.body = httpMeta.body; this.headers = httpMeta.response.headers; this.contentType = httpMeta.response.headers.get("content-type") || ""; this.rawResponse = httpMeta.response; this.name = "AutumnError"; } }; // ../sdk/src/models/autumn-default-error.ts var AutumnDefaultError = class extends AutumnError { constructor(message, httpMeta) { if (message) { message += `: `; } message += `Status ${httpMeta.response.status}`; const contentType = httpMeta.response.headers.get("content-type") || `""`; if (contentType !== "application/json") { message += ` Content-Type ${contentType.includes(" ") ? `"${contentType}"` : contentType}`; } const body = httpMeta.body || `""`; message += body.length > 100 ? "\n" : ". "; let bodyDisplay = body; if (body.length > 1e4) { const truncated = body.substring(0, 1e4); const remaining = body.length - 1e4; bodyDisplay = `${truncated}...and ${remaining} more chars`; } message += `Body: ${bodyDisplay}`; message = message.trim(); super(message, httpMeta); this.name = "AutumnDefaultError"; } }; var SDKValidationError = class extends Error { constructor(message, cause, rawValue) { super(`${message}: ${cause}`); /** * The raw value that failed validation. */ __publicField(this, "rawValue"); /** * The raw message that failed validation. */ __publicField(this, "rawMessage"); this.name = "SDKValidationError"; this.cause = cause; this.rawValue = rawValue; this.rawMessage = message; } // Allows for backwards compatibility for `instanceof` checks of `ResponseValidationError` static [Symbol.hasInstance](instance) { if (!(instance instanceof Error)) return false; if (!("rawValue" in instance)) return false; if (!("rawMessage" in instance)) return false; if (!("pretty" in instance)) return false; if (typeof instance.pretty !== "function") return false; return true; } /** * Return a pretty-formatted error message if the underlying validation error * is a ZodError or some other recognized error type, otherwise return the * default error message. */ pretty() { if (this.cause instanceof z2__namespace.$ZodError) { return `${this.rawMessage} ${formatZodError(this.cause)}`; } else { return this.toString(); } } }; function formatZodError(err) { return z2__namespace.prettifyError(err); } // ../sdk/src/models/response-validation-error.ts var ResponseValidationError = class extends AutumnError { constructor(message, extra) { super(message, extra); /** * The raw value that failed validation. */ __publicField(this, "rawValue"); /** * The raw message that failed validation. */ __publicField(this, "rawMessage"); this.name = "ResponseValidationError"; this.cause = extra.cause; this.rawValue = extra.rawValue; this.rawMessage = extra.rawMessage; } /** * Return a pretty-formatted error message if the underlying validation error * is a ZodError or some other recognized error type, otherwise return the * default error message. */ pretty() { if (this.cause instanceof z2__namespace.$ZodError) { return `${this.rawMessage} ${formatZodError(this.cause)}`; } else { return this.toString(); } } }; // ../sdk/src/types/fp.ts function OK(value) { return { ok: true, value }; } function ERR(error) { return { ok: false, error }; } async function unwrapAsync(pr) { const r = await pr; if (!r.ok) { throw r.error; } return r.value; } // ../sdk/src/lib/matchers.ts var DEFAULT_CONTENT_TYPES = { jsonl: "application/jsonl", json: "application/json", text: "text/plain", bytes: "application/octet-stream", stream: "application/octet-stream", sse: "text/event-stream", nil: "*", fail: "*" }; function json(codes, schema, options) { return { ...options, enc: "json", codes, schema }; } function fail(codes) { return { enc: "fail", codes }; } function match(...matchers) { return async function matchFunc(response, request, options) { let raw; let matcher; for (const match2 of matchers) { const { codes } = match2; const ctpattern = "ctype" in match2 ? match2.ctype : DEFAULT_CONTENT_TYPES[match2.enc]; if (ctpattern && matchResponse(response, codes, ctpattern)) { matcher = match2; break; } else if (!ctpattern && matchStatusCode(response, codes)) { matcher = match2; break; } } if (!matcher) { return [{ ok: false, error: new AutumnDefaultError("Unexpected Status or Content-Type", { response, request, body: await response.text().catch(() => "") }) }, raw]; } const encoding = matcher.enc; let body = ""; switch (encoding) { case "json": body = await response.text(); raw = JSON.parse(body); break; case "jsonl": raw = response.body; break; case "bytes": raw = new Uint8Array(await response.arrayBuffer()); break; case "stream": raw = response.body; break; case "text": body = await response.text(); raw = body; break; case "sse": raw = response.body; break; case "nil": body = await response.text(); raw = void 0; break; case "fail": body = await response.text(); raw = body; break; default: throw new Error( `Unsupported response type: ${encoding}` ); } if (matcher.enc === "fail") { return [{ ok: false, error: new AutumnDefaultError("API error occurred", { request, response, body }) }, raw]; } const resultKey = matcher.key || options?.resultKey; let data; if ("err" in matcher) { data = { ...options?.extraFields, ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null, ...isPlainObject(raw) ? raw : null, request$: request, response$: response, body$: body }; } else if (resultKey) { data = { ...options?.extraFields, ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null, [resultKey]: raw }; } else if (matcher.hdrs) { data = { ...options?.extraFields, ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null, ...isPlainObject(raw) ? raw : null }; } else { data = raw; } if ("err" in matcher) { const result = safeParseResponse( data, (v) => matcher.schema.parse(v), "Response validation failed", { request, response, body } ); return [result.ok ? { ok: false, error: result.value } : result, raw]; } else { return [ safeParseResponse( data, (v) => matcher.schema.parse(v), "Response validation failed", { request, response, body } ), raw ]; } }; } var headerValRE = /, */; function unpackHeaders(headers) { const out = {}; for (const [k, v] of headers.entries()) { out[k] = v.split(headerValRE); } return out; } function safeParseResponse(rawValue, fn, errorMessage, httpMeta) { try { return OK(fn(rawValue)); } catch (err) { return ERR( new ResponseValidationError(errorMessage, { cause: err, rawValue, rawMessage: errorMessage, ...httpMeta }) ); } } // ../sdk/src/lib/primitives.ts function remap(inp, mappings) { let out = {}; if (!Object.keys(mappings).length) { out = inp; return out; } for (const [k, v] of Object.entries(inp)) { const j = mappings[k]; if (j === null) { continue; } out[j ?? k] = v; } return out; } function compactMap(values) { const out = {}; for (const [k, v] of Object.entries(values)) { if (typeof v !== "undefined") { out[k] = v; } } return out; } function safeParse(rawValue, fn, errorMessage) { try { return OK(fn(rawValue)); } catch (err) { return ERR(new SDKValidationError(errorMessage, err, rawValue)); } } // ../sdk/src/lib/dlv.ts function dlv(obj, key, def, p, undef) { key = Array.isArray(key) ? key : key.split("."); for (p = 0; p < key.length; p++) { const k = key[p]; obj = k != null && obj ? obj[k] : undef; } return obj === undef ? def : obj; } // ../sdk/src/lib/env.ts var envSchema = z66__namespace.object({ AUTUMN_SECRET_KEY: z66__namespace.optional(z66__namespace.string()), AUTUMN_X_API_VERSION: z66__namespace._default(z66__namespace.string(), "2.3.0"), AUTUMN_FAIL_OPEN: z66__namespace.pipe( z66__namespace._default(z66__namespace.enum(["true", "false"]), "true"), z66__namespace.transform((v) => v === "true") ), AUTUMN_DEBUG: z66__namespace.optional(z66__namespace.coerce.boolean()) }); function isDeno() { if ("Deno" in globalThis) { return true; } return false; } var envMemo = void 0; function env() { if (envMemo) { return envMemo; } let envObject = {}; if (isDeno()) { envObject = globalThis.Deno?.env?.toObject?.() ?? {}; } else { envObject = dlv(globalThis, "process.env") ?? {}; } envMemo = envSchema.parse(envObject); return envMemo; } function fillGlobals(options) { const clone = { ...options }; const envVars = env(); if (typeof envVars.AUTUMN_X_API_VERSION !== "undefined") { clone.xApiVersion ?? (clone.xApiVersion = envVars.AUTUMN_X_API_VERSION); } if (typeof envVars.AUTUMN_FAIL_OPEN !== "undefined") { clone.failOpen ?? (clone.failOpen = envVars.AUTUMN_FAIL_OPEN); } return clone; } // ../sdk/src/lib/security.ts var SecurityError = class _SecurityError extends Error { constructor(code, message) { super(message); this.code = code; this.name = "SecurityError"; } static incomplete() { return new _SecurityError( "incomplete" /* Incomplete */, "Security requirements not met in order to perform the operation" ); } static unrecognizedType(type) { return new _SecurityError( "unrecognized_security_type" /* UnrecognisedSecurityType */, `Unrecognised security type: ${type}` ); } }; function resolveSecurity(...options) { const state = { basic: {}, headers: {}, queryParams: {}, cookies: {}, oauth2: { type: "none" } }; const option = options.find((opts) => { return opts.every((o) => { if (o.value == null) { return false; } else if (o.type === "http:basic") { return o.value.username != null || o.value.password != null; } else if (o.type === "http:custom") { return null; } else if (o.type === "oauth2:password") { return typeof o.value === "string" && !!o.value; } else if (o.type === "oauth2:client_credentials") { if (typeof o.value == "string") { return !!o.value; } return o.value.clientID != null || o.value.clientSecret != null; } else if (typeof o.value === "string") { return !!o.value; } else { throw new Error( `Unrecognized security type: ${o.type} (value type: ${typeof o.value})` ); } }); }); if (option == null) { return null; } option.forEach((spec) => { if (spec.value == null) { return; } const { type } = spec; switch (type) { case "apiKey:header": state.headers[spec.fieldName] = spec.value; break; case "apiKey:query": state.queryParams[spec.fieldName] = spec.value; break; case "apiKey:cookie": state.cookies[spec.fieldName] = spec.value; break; case "http:basic": applyBasic(state, spec); break; case "http:custom": break; case "http:bearer": applyBearer(state, spec); break; case "oauth2": applyBearer(state, spec); break; case "oauth2:password": applyBearer(state, spec); break; case "oauth2:client_credentials": break; case "openIdConnect": applyBearer(state, spec); break; default: throw SecurityError.unrecognizedType((type)); } }); return state; } function applyBasic(state, spec) { if (spec.value == null) { return; } state.basic = spec.value; } function applyBearer(state, spec) { if (typeof spec.value !== "string" || !spec.value) { return; } let value = spec.value; if (value.slice(0, 7).toLowerCase() !== "bearer ") { value = `Bearer ${value}`; } if (spec.fieldName !== void 0) { state.headers[spec.fieldName] = value; } } function resolveGlobalSecurity(security, allowedFields) { let inputs = [ [ { fieldName: "Authorization", type: "http:bearer", value: security?.secretKey ?? env().AUTUMN_SECRET_KEY } ] ]; return resolveSecurity(...inputs); } async function extractSecurity(sec) { if (sec == null) { return; } return typeof sec === "function" ? sec() : sec; } // ../sdk/src/types/unrecognized.ts function unrecognized(value) { globalCount++; return value; } var globalCount = 0; var refCount = 0; function startCountingUnrecognized() { refCount++; const start = globalCount; return { /** * Ends counting and returns the delta. * @param delta - If provided, only this amount is added to the parent counter * (used for nested unions where we only want to record the winning option's count). * If not provided, records all counts since start(). */ end: (delta) => { const count = globalCount - start; globalCount = start + (delta ?? count); if (--refCount === 0) globalCount = 0; return count; } }; } // ../sdk/src/types/default-to-zero-value.ts var globalCount2 = 0; var refCount2 = 0; function defaultToZeroValue(value) { globalCount2++; return unrecognized(value); } function startCountingDefaultToZeroValue() { refCount2++; const start = globalCount2; return { /** * Ends counting and returns the delta. * @param delta - If provided, only this amount is added to the parent counter * (used for nested unions where we only want to record the winning option's count). * If not provided, records all counts since start(). */ end: (delta) => { const count = globalCount2 - start; globalCount2 = start + (delta ?? count); if (--refCount2 === 0) globalCount2 = 0; return count; } }; } // ../sdk/src/types/primitives.ts function string4() { return z66__namespace.union([ z66__namespace.string(), // Null or undefined -> "" zodDefaultToZeroValue(""), // Any other value -> String(x) z66__namespace.pipe(z66__namespace.any(), z66__namespace.transform((x) => unrecognized(JSON.stringify(x)))) ]); } function boolean2() { return z66__namespace.union([ z66__namespace.boolean(), // String "true" (case insensitive) -> true, "false" -> false z66__namespace.pipe( z66__namespace.string(), z66__namespace.transform((x, ctx) => { const lower = x.toLowerCase(); if (lower === "true") return unrecognized(true); if (lower === "false") return unrecognized(false); ctx.issues.push({ input: x, code: "invalid_type", expected: "boolean", received: "string" }); return z66__namespace.NEVER; }) ), zodDefaultToZeroValue(false) ]); } function number2() { return z66__namespace.union([ z66__namespace.number(), // String -> Number z66__namespace.pipe( z66__namespace.string(), z66__namespace.transform((x, ctx) => { const num = Number(x); if (isNaN(num)) { ctx.issues.push({ input: x, code: "invalid_type", expected: "number", received: "string" }); return z66__namespace.NEVER; } return unrecognized(num); }) ), // Null or undefined -> 0 zodDefaultToZeroValue(0) ]); } function bigint() { return z66__namespace.union([ z66__namespace.pipe( z66__namespace.string(), z66__namespace.transform((x, ctx) => { try { return BigInt(x); } catch (error) { ctx.issues.push({ input: x, code: "invalid_type", expected: "bigint", received: "string" }); return z66__namespace.NEVER; } }) ), zodDefaultToZeroValue(0n) ]); } function date2() { return z66__namespace.union([ z66__namespace.pipe( z66__namespace.pipe( z66__namespace.union([z66__namespace.string(), zodDefaultToZeroValue(0)]), z66__namespace.transform((x) => new Date(x)) ), z66__namespace.date() ), z66__namespace.pipe( z66__namespace.number(), z66__namespace.transform((x, ctx) => { const date3 = new Date(x); if (isNaN(date3.getTime())) { ctx.issues.push({ input: x, code: "invalid_type", expected: "date", received: "number" }); return z66__namespace.NEVER; } return unrecognized(date3); }) ) ]); } function literal2(value) { return z66__namespace.union([z66__namespace.literal(value), zodDefaultToZeroValue(value)]); } function literalBigInt(value) { return z66__namespace.pipe(z66__namespace.literal(String(value)), z66__namespace.transform((x) => BigInt(x))); } function optional3(t) { return z66__namespace.optional(z66__namespace.union([ // Null -> undefined z66__namespace.pipe(z66__namespace.null(), z66__namespace.transform(() => unrecognized(void 0))), t ])); } function nullable(t) { return z66__namespace.union([ z66__namespace.null(), // Undefined -> null z66__namespace.pipe(z66__namespace.undefined(), z66__namespace.transform(() => defaultToZeroValue(null))), t ]); } function zodDefaultToZeroValue(value) { return z66__namespace.pipe( z66__namespace.any(), z66__namespace.transform((input, ctx) => { if (input === void 0) return defaultToZeroValue(value); if (input === null) return defaultToZeroValue(value); ctx.issues.push({ input, code: "invalid_type", expected: "undefined", received: "unknown" }); return z66__namespace.NEVER; }) ); } // ../sdk/src/types/rfcdate.ts var dateRE = /^\d{4}-\d{2}-\d{2}$/; var RFCDate = class _RFCDate { /** * Creates a new RFCDate instance using the provided input. * If a string is used then in must be in the format YYYY-MM-DD. * * @param date A Date object or a date string in YYYY-MM-DD format * @example * new RFCDate("2022-01-01") * @example * new RFCDate(new Date()) */ constructor(date3) { __publicField(this, "serialized"); if (typeof date3 === "string" && !dateRE.test(date3)) { throw new RangeError( "RFCDate: date strings must be in the format YYYY-MM-DD: " + date3 ); } const value = new Date(date3); if (isNaN(+value)) { throw new RangeError("RFCDate: invalid date provided: " + date3); } this.serialized = value.toISOString().slice(0, "YYYY-MM-DD".length); if (!dateRE.test(this.serialized)) { throw new TypeError( `RFCDate: failed to build valid date with given value: ${date3} serialized to ${this.serialized}` ); } } /** * Creates a new RFCDate instance using today's date. */ static today() { return new _RFCDate(/* @__PURE__ */ new Date()); } toJSON() { return this.toString(); } toString() { return this.serialized; } }; // ../sdk/src/types/smart-union.ts function smartUnion(options) { return z66__namespace.pipe( z66__namespace.unknown(), z66__namespace.transform((input, ctx) => { const candidates = []; const errors = options.map(() => []); const parentUnrecognizedCtr = startCountingUnrecognized(); const parentZeroDefaultCtr = startCountingDefaultToZeroValue(); for (const [i, option] of options.entries()) { const unrecognizedCtr = startCountingUnrecognized(); const zeroDefaultCtr = startCountingDefaultToZeroValue(); const result = option.safeParse(input); const inexactCount = unrecognizedCtr.end(); const zeroDefaultCount = zeroDefaultCtr.end(); if (result.success) { candidates.push({ data: result.data, inexactCount, zeroDefaultCount, fieldCount: -1 // We'll count this later if needed }); continue; } errors[i].push(...result.error.issues); } if (candidates.length === 0) { parentUnrecognizedCtr.end(0); parentZeroDefaultCtr.end(0); ctx.issues.push({ input, code: "invalid_union", errors }); return z66__namespace.NEVER; } let best = candidates[0]; for (const candidate of candidates) { if (candidates.length > 1) { candidate.fieldCount = countFieldsRecursive(candidate.data); } best = better(candidate, best); } parentUnrecognizedCtr.end(best.inexactCount); parentZeroDefaultCtr.end(best.zeroDefaultCount); return best.data; }) ); } function better(a, b) { const aIsExact = a.inexactCount === 0; const bIsExact = b.inexactCount === 0; if (aIsExact !== bIsExact) { return aIsExact ? a : b; } const actualFieldCountA = a.fieldCount - a.zeroDefaultCount; const actualFieldCountB = b.fieldCount - b.zeroDefaultCount; if (actualFieldCountA !== actualFieldCountB) { return actualFieldCountA > actualFieldCountB ? a : b; } return a.inexactCount < b.inexactCount ? a : b; } function countFieldsRecursive(parsed) { let fieldCount = 0; const queue = [parsed]; let index = 0; while (index < queue.length) { const value = queue[index++]; if (value === void 0) { continue; } const type = typeof value; if (value === null || type === "number" || type === "string" || type === "boolean" || type === "bigint" || value instanceof Date || value instanceof RFCDate) { fieldCount++; continue; } if (Array.isArray(value)) { queue.push(...value); continue; } if (type === "object") { queue.push(...Object.values(value)); } } return fieldCount; } // ../sdk/src/models/aggregate-events-op.ts var Range = { TwentyFourh: "24h", Sevend: "7d", Thirtyd: "30d", Ninetyd: "90d", LastCycle: "last_cycle", Onebc: "1bc", Threebc: "3bc" }; var BinSize = { Day: "day", Hour: "hour", Week: "week", Month: "month" }; var AggregateEventsFeatureId$outboundSchema = smartUnion([z66__namespace.string(), z66__namespace.array(z66__namespace.string())]); function aggregateEventsFeatureIdToJSON(aggregateEventsFeatureId) { return JSON.stringify( AggregateEventsFeatureId$outboundSchema.parse(aggregateEventsFeatureId) ); } var Range$outboundSchema = z66__namespace.enum(Range); var BinSize$outboundSchema = z66__namespace.enum( BinSize ); var AggregateEventsCustomRange$outboundSchema = z66__namespace.object({ start: z66__namespace.number(), end: z66__namespace.number() }); function aggregateEventsCustomRangeToJSON(aggregateEventsCustomRange) { return JSON.stringify( AggregateEventsCustomRange$outboundSchema.parse(aggregateEventsCustomRange) ); } var EventsAggregateParams$outboundSchema = z66__namespace.pipe( z66__namespace.object({ customerId: z66__namespace.optional(z66__namespace.string()), entityId: z66__namespace.optional(z66__namespace.string()), featureId: smartUnion([z66__namespace.string(), z66__namespace.array(z66__namespace.string())]), groupBy: z66__namespace.optional(z66__namespace.string()), range: z66__namespace.optional(Range$outboundSchema), binSize: z66__namespace._default(BinSize$outboundSchema, "day"), customRange: z66__namespace.optional( z66__namespace.lazy(() => AggregateEventsCustomRange$outboundSchema) ), filterBy: z66__namespace.optional(z66__namespace.record(z66__namespace.string(), z66__namespace.string())), maxGroups: z66__namespace.optional(z66__namespace.int()) }), z66__namespace.transform((v) => { return remap(v, { customerId: "customer_id", entityId: "entity_id", featureId: "feature_id", groupBy: "group_by", binSize: "bin_size", customRange: "custom_range", filterBy: "filter_by", maxGroups: "max_groups" }); }) ); function eventsAggregateParamsToJSON(eventsAggregateParams) { return JSON.stringify( EventsAggregateParams$outboundSchema.parse(eventsAggregateParams) ); } var AggregateEventsList$inboundSchema = z66__namespace.pipe( z66__namespace.object({ period: number2(), values: z66__namespace.record(z66__namespace.string(), number2()), grouped_values: optional3( z66__namespace.record(z66__namespace.string(), z66__namespace.record(z66__namespace.string(), number2())) ) }), z66__namespace.transform((v) => { return remap(v, { "grouped_values": "groupedValues" }); }) ); function aggregateEventsListFromJSON(jsonString) { return safeParse( jsonString, (x) => AggregateEventsList$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'AggregateEventsList' from JSON` ); } var Total$inboundSchema = z66__namespace.object({ count: number2(), sum: number2() }); function totalFromJSON(jsonString) { return safeParse( jsonString, (x) => Total$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'Total' from JSON` ); } var AggregateEventsResponse$inboundSchema = z66__namespace.object({ list: z66__namespace.array(z66__namespace.lazy(() => AggregateEventsList$inboundSchema)), total: z66__namespace.record(z66__namespace.string(), z66__namespace.lazy(() => Total$inboundSchema)) }); function aggregateEventsResponseFromJSON(jsonString) { return safeParse( jsonString, (x) => AggregateEventsResponse$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'AggregateEventsResponse' from JSON` ); } function inboundSchema(enumObj) { const options = Object.values(enumObj); return z66__namespace.union([ ...options.map((x) => z66__namespace.literal(x)), z66__namespace.pipe(z66__namespace.string(), z66__namespace.transform((x) => unrecognized(x))) ]); } // ../sdk/src/models/attach-op.ts var AttachPriceInterval = { OneOff: "one_off", Week: "week", Month: "month", Quarter: "quarter", SemiAnnual: "semi_annual", Year: "year" }; var AttachItemResetInterval = { OneOff: "one_off", Minute: "minute", Hour: "hour", Day: "day", Week: "week", Month: "month", Quarter: "quarter", SemiAnnual: "semi_annual", Year: "year" }; var AttachItemTierBehavior = { Graduated: "graduated", Volume: "volume" }; var AttachItemPriceInterval = { OneOff: "one_off", Week: "week", Month: "month", Quarter: "quarter", SemiAnnual: "semi_annual", Year: "year" }; var AttachItemBillingMethod = { Prepaid: "prepaid", UsageBased: "usage_based" }; var AttachItemOnIncrease = { BillImmediately: "bill_immediately", ProrateImmediately: "prorate_immediately", ProrateNextCycle: "prorate_next_cycle", BillNextCycle: "bill_next_cycle" }; var AttachItemOnDecrease = { Prorate: "prorate", ProrateImmediately: "prorate_immediately", ProrateNextCycle: "prorate_next_cycle", None: "none", NoProrations: "no_prorations" }; var AttachItemExpiryDurationType = { Month: "month", Forever: "forever" }; var AttachAddItemResetInterval = { OneOff: "one_off", Minute: "minute", Hour: "hour", Day: "day", Week: "week", Month: "month", Quarter: "quarter", SemiAnnual: "semi_annual", Year: "year" }; var AttachAddItemTierBehavior = { Graduated: "graduated", Volume: "volume" }; var AttachAddItemPriceInterval = { OneOff: "one_off", Week: "week", Month: "month", Quarter: "quarter", SemiAnnual: "semi_annual", Year: "year" }; var AttachAddItemBillingMethod = { Prepaid: "prepaid", UsageBased: "usage_based" }; var AttachAddItemOnIncrease = { BillImmediately: "bill_immediately", ProrateImmediately: "prorate_immediately", ProrateNextCycle: "prorate_next_cycle", BillNextCycle: "bill_next_cycle" }; var AttachAddItemOnDecrease = { Prorate: "prorate", ProrateImmediately: "prorate_immediately", ProrateNextCycle: "prorate_next_cycle", None: "none", NoProrations: "no_prorations" }; var AttachAddItemExpiryDurationType = { Month: "month", Forever: "forever" }; var AttachRemoveItemBillingMethod = { Prepaid: "prepaid", UsageBased: "usage_based" }; var AttachIntervalRemoveItemEnum2 = { OneOff: "one_off", Minute: "minute", Hour: "hour", Day: "day", Week: "week", Month: "month", Quarter: "quarter", SemiAnnual: "semi_annual", Year: "year" }; var AttachIntervalRemoveItemEnum1 = { OneOff: "one_off", Week: "week", Month: "month", Quarter: "quarter", SemiAnnual: "semi_annual", Year: "year" }; var AttachDurationType = { Day: "day", Month: "month", Year: "year" }; var AttachOnEnd = { Bill: "bill", Revert: "revert" }; var AttachPurchaseLimitInterval = { Hour: "hour", Day: "day", Week: "week", Month: "month" }; var AttachLimitType = { Absolute: "absolute", UsagePercentage: "usage_percentage" }; var AttachUsageLimitInterval = { Day: "day", Week: "week", Month: "month", Year: "year" }; var AttachThresholdType = { Usage: "usage", UsagePercentage: "usage_percentage", Remaining: "remaining", RemainingPercentage: "remaining_percentage" }; var AttachProrationBehavior = { ProrateImmediately: "prorate_immediately", None: "none" }; var AttachRedirectMode = { Always: "always", IfRequired: "if_required", Never: "never" }; var AttachPlanSchedule = { Immediate: "immediate", EndOfCycle: "end_of_cycle" }; var AttachCode = { ThreedsRequired: "3ds_required", PaymentMethodRequired: "payment_method_required", PaymentFailed: "payment_failed", PaymentProcessing: "payment_processing" }; var AttachFeatureQuantity$outboundSchema = z66__namespace.pipe( z66__namespace.object({ featureId: z66__namespace.string(), quantity: z66__namespace.optional(z66__namespace.number()), adjustable: z66__namespace.optional(z66__namespace.boolean()) }), z66__namespace.transform((v) => { return remap(v, { featureId: "feature_id" }); }) ); function attachFeatureQuantityToJSON(attachFeatureQuantity) { return JSON.stringify( AttachFeatureQuantity$outboundSchema.parse(attachFeatureQuantity) ); } var AttachPriceInterval$outboundSchema = z66__namespace.enum(AttachPriceInterval); var AttachBasePrice$outboundSchema = z66__namespace.pipe( z66__namespace.object({ amount: z66__namespace.number(), interval: AttachPriceInterval$outboundSchema, intervalCount: z66__namespace.optional(z66__namespace.number()) }), z66__namespace.transform((v) => { return remap(v, { intervalCount: "interval_count" }); }) ); function attachBasePriceToJSON(attachBasePrice) { return JSON.stringify(AttachBasePrice$outboundSchema.parse(attachBasePrice)); } var AttachItemResetInterval$outboundSchema = z66__namespace.enum(AttachItemResetInterval); var AttachItemReset$outboundSchema = z66__namespace.pipe( z66__namespace.object({ interval: AttachItemResetInterval$outboundSchema, intervalCount: z66__namespace.optional(z66__namespace.number()) }), z66__namespace.transform((v) => { return remap(v, { intervalCount: "interval_count" }); }) ); function attachItemResetToJSON(attachItemReset) { return JSON.stringify(AttachItemReset$outboundSchema.parse(attachItemReset)); } var AttachItemTo$outboundSchema = smartUnion([z66__namespace.number(), z66__namespace.string()]); function attachItemToToJSON(attachItemTo) { return JSON.stringify(AttachItemTo$outboundSchema.parse(attachItemTo)); } var AttachItemTier$outboundSchema = z66__namespace.pipe( z66__namespace.object({ to: smartUnion([z66__namespace.number(), z66__namespace.string()]), amount: z66__namespace.optional(z66__namespace.number()), flatAmount: z66__namespace.optional(z66__namespace.number()) }), z66__namespace.transform((v) => { return remap(v, { flatAmount: "flat_amount" }); }) ); function attachItemTierToJSON(attachItemTier) { return JSON.stringify(AttachItemTier$outboundSchema.parse(attachItemTier)); } var AttachItemTierBehavior$outboundSchema = z66__namespace.enum(AttachItemTierBehavior); var AttachItemPriceInterval$outboundSchema = z66__namespace.enum(AttachItemPriceInterval); var AttachItemBillingMethod$outboundSchema = z66__namespace.enum(AttachItemBillingMethod); var AttachItemPrice$outboundSchema = z66__namespace.pipe( z66__namespace.object({ amount: z66__namespace.optional(z66__namespace.number()), tiers: z66__namespace.optional(z66__namespace.array(z66__namespace.lazy(() => AttachItemTier$outboundSchema))), tierBehavior: z66__namespace.optional(AttachItemTierBehavior$outboundSchema), interval: AttachItemPriceInterval$outboundSchema, intervalCount: z66__namespace._default(z66__namespace.number(), 1), billingUnits: z66__namespace._default(z66__namespace.number(), 1), billingMethod: AttachItemBillingMethod$outboundSchema, maxPurchase: z66__namespace.optional(z66__namespace.nullable(z66__namespace.number())) }), z66__namespace.transform((v) => { return remap(v, { tierBehavior: "tier_behavior", intervalCount: "interval_count", billingUnits: "billing_units", billingMethod: "billing_method", maxPurchase: "max_purchase" }); }) ); function attachItemPriceToJSON(attachItemPrice) { return JSON.stringify(AttachItemPrice$outboundSchema.parse(at