diff --git a/.gitignore b/.gitignore index 174e7fd..8b556c3 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,7 @@ screenshots/ui/ # Tauri bundler embeds these into the binary, so they are a build artifact, # not a source. 126 files / 4.4 MB slipped in with the icon fix. dist-desktop/ + +# Build output — committed by accident twice now (dist-desktop in #23, .vercel in f018dab). +.vercel/ +dist/ diff --git a/.vercel/output/config.json b/.vercel/output/config.json deleted file mode 100644 index 14cdd46..0000000 --- a/.vercel/output/config.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "version": 3, - "framework": { - "name": "nitro", - "version": "3.0.260603-beta" - }, - "overrides": {}, - "routes": [ - { - "headers": { - "cache-control": "public, max-age=31536000, immutable" - }, - "src": "/assets/(.*)" - }, - { - "handle": "filesystem" - }, - { - "src": "/(.*)", - "dest": "/__server" - } - ] -} \ No newline at end of file diff --git a/.vercel/output/functions/__server.func/.vc-config.json b/.vercel/output/functions/__server.func/.vc-config.json deleted file mode 100644 index b21e60e..0000000 --- a/.vercel/output/functions/__server.func/.vc-config.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "handler": "index.mjs", - "launcherType": "Nodejs", - "shouldAddHelpers": false, - "supportsResponseStreaming": true, - "runtime": "nodejs22.x" -} \ No newline at end of file diff --git a/.vercel/output/functions/__server.func/_chunks/core.mjs b/.vercel/output/functions/__server.func/_chunks/core.mjs deleted file mode 100644 index 20dc51c..0000000 --- a/.vercel/output/functions/__server.func/_chunks/core.mjs +++ /dev/null @@ -1,5 +0,0 @@ -//#region __vite-optional-peer-dep:@opentelemetry/api:@better-auth/core -var core_default = {}; -throw new Error(`Could not resolve "@opentelemetry/api" imported by "@better-auth/core". Is it installed?`); -//#endregion -export { core_default as default }; diff --git a/.vercel/output/functions/__server.func/_chunks/ssr-renderer.mjs b/.vercel/output/functions/__server.func/_chunks/ssr-renderer.mjs deleted file mode 100644 index e55311b..0000000 --- a/.vercel/output/functions/__server.func/_chunks/ssr-renderer.mjs +++ /dev/null @@ -1,15 +0,0 @@ -import { i as toRequest, n as HTTPError } from "../_libs/h3+rou3+srvx.mjs"; -//#region node_modules/nitro/dist/runtime/vite.mjs -function fetchViteEnv(viteEnvName, input, init) { - const viteEnv = (globalThis.__nitro_vite_envs__ || {})[viteEnvName]; - if (!viteEnv) throw HTTPError.status(404); - return Promise.resolve(viteEnv.fetch(toRequest(input, init))); -} -//#endregion -//#region node_modules/nitro/dist/runtime/internal/vite/ssr-renderer.mjs -/** @param {{ req: Request }} HTTPEvent */ -function ssrRenderer({ req }) { - return fetchViteEnv("ssr", req); -} -//#endregion -export { ssrRenderer as default }; diff --git a/.vercel/output/functions/__server.func/_libs/@anthropic-ai/sdk+[...].mjs b/.vercel/output/functions/__server.func/_libs/@anthropic-ai/sdk+[...].mjs deleted file mode 100644 index bef4224..0000000 --- a/.vercel/output/functions/__server.func/_libs/@anthropic-ai/sdk+[...].mjs +++ /dev/null @@ -1,11131 +0,0 @@ -import { r as __exportAll, t as __commonJSMin } from "../../_runtime.mjs"; -import { Readable } from "node:stream"; -import { pipeline } from "node:stream/promises"; -import * as crypto from "node:crypto"; -import { randomUUID } from "node:crypto"; -import * as cp from "node:child_process"; -import { execFile } from "node:child_process"; -import * as fs$2 from "node:fs/promises"; -import * as fssync from "node:fs"; -import * as path$1 from "node:path"; -import * as readline from "node:readline"; -import { promisify } from "node:util"; -//#region node_modules/@anthropic-ai/sdk/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/@anthropic-ai/sdk/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")); -} -var 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/@anthropic-ai/sdk/core/error.mjs -var AnthropicError = class extends Error {}; -var APIError = class APIError extends AnthropicError { - constructor(status, error, message, headers, type) { - super(`${APIError.makeMessage(status, error, message)}`); - this.status = status; - this.headers = headers; - this.requestID = headers?.get("request-id"); - this.error = error; - this.type = type ?? null; - } - 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; - const type = error?.["error"]?.["type"]; - if (status === 400) return new BadRequestError(status, error, message, headers, type); - if (status === 401) return new AuthenticationError(status, error, message, headers, type); - if (status === 403) return new PermissionDeniedError(status, error, message, headers, type); - if (status === 404) return new NotFoundError(status, error, message, headers, type); - if (status === 409) return new ConflictError(status, error, message, headers, type); - if (status === 422) return new UnprocessableEntityError(status, error, message, headers, type); - if (status === 429) return new RateLimitError(status, error, message, headers, type); - if (status >= 500) return new InternalServerError(status, error, message, headers, type); - return new APIError(status, error, message, headers, type); - } -}; -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." }); - } -}; -/** -* An error that opts into the SDK's retry policy: throw it (e.g. from -* middleware) to have the attempt retried. -* -* Note that the request will only be retried when `maxRetries` has not been exhausted. -*/ -var RetryableError = class extends AnthropicError { - constructor(message, { cause } = {}) { - super(message ?? "Retryable error."); - if (cause !== void 0) this.cause = cause; - } -}; -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 {}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs -/** -* An error that can be thrown from a tool's `run` method to return structured -* content blocks as the error result, rather than just a string message. -* -* When the ToolRunner catches this error, it will use the `content` property -* as the tool result with `is_error: true`. -* -* @example -* ```ts -* const tool = { -* name: 'my_tool', -* run: async (input) => { -* if (somethingWentWrong) { -* throw new ToolError([ -* { type: 'text', text: 'Error details here' }, -* { type: 'image', source: { type: 'base64', data: '...', media_type: 'image/png' } }, -* ]); -* } -* return 'success'; -* }, -* }; -* ``` -*/ -var ToolError = class extends Error { - constructor(content) { - const message = typeof content === "string" ? content : content.map((block) => { - if (block.type === "text") return block.text; - return `[${block.type}]`; - }).join(" "); - super(message); - this.name = "ToolError"; - this.content = content; - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs -/** -* https://stackoverflow.com/a/2117523 -*/ -var uuid4 = function() { - const { crypto } = globalThis; - if (crypto?.randomUUID) { - uuid4 = crypto.randomUUID.bind(crypto); - return crypto.randomUUID(); - } - const u8 = /* @__PURE__ */ 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/@anthropic-ai/sdk/internal/utils/values.mjs -var startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; -var isAbsoluteURL = (url) => { - return startsWithSchemeRegexp.test(url); -}; -var isArray = (val) => (isArray = Array.isArray, isArray(val)); -var 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); -} -var validatePositiveInteger = (name, n) => { - if (typeof n !== "number" || !Number.isInteger(n)) throw new AnthropicError(`${name} must be an integer`); - if (n < 0) throw new AnthropicError(`${name} must be a positive integer`); - return n; -}; -var safeJSON = (text) => { - try { - return JSON.parse(text); - } catch (err) { - return; - } -}; -var pop = (obj, key) => { - const value = obj[key]; - delete obj[key]; - return value; -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs -/** -* Resolve after `ms`, or immediately when `signal` aborts. -* -* When a `signal` is passed the abort listener is always removed so repeated -* calls do not accumulate listeners on a long-lived signal. Resolves (rather -* than rejects) on abort — callers treat abort as "wake up early," not as a -* failure; callers that want to unwind should check the signal themselves. -*/ -var sleep = (ms, signal) => new Promise((resolve) => { - if (signal?.aborted) return resolve(); - const onAbort = () => { - clearTimeout(timer); - resolve(); - }; - const timer = setTimeout(() => { - signal?.removeEventListener("abort", onAbort); - resolve(); - }, ms); - signal?.addEventListener("abort", onAbort, { once: true }); -}); -//#endregion -//#region node_modules/@anthropic-ai/sdk/version.mjs -var VERSION = "0.115.0"; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs -var 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"; -} -var 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; -} -var 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"; -}; -var 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"; -}; -var _platformHeaders; -var getPlatformHeaders = () => { - return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/request-signal.mjs -/** -* Tracks the removal of the per-request abort listener that -* `fetchWithTimeout` attaches to a caller-provided signal, so the listener's -* lifetime matches the request instead of the signal. -* -* Without removal, a long-lived signal (e.g. one AbortController reused for -* a whole session) accumulates one `{ once: true }` listener plus its bound -* AbortController per HTTP attempt until the signal fires or is collected, -* and Node warns at the 11th listener. The listener must survive until the -* response body is settled - removing it when fetch resolves (headers) would -* break aborting an in-flight body read - so the code that finishes the body -* (response parsing, stream teardown, retry/error handling) calls -* `releaseRequestSignal` with the request's controller. -*/ -var cleanups = /* @__PURE__ */ new WeakMap(); -var registry = typeof globalThis.FinalizationRegistry === "function" ? new globalThis.FinalizationRegistry((controller) => releaseRequestSignal(controller)) : null; -function makeCleanup(signal, listener) { - return () => signal.removeEventListener("abort", listener); -} -function registerRequestSignalCleanup(controller, signal, listener) { - cleanups.set(controller, makeCleanup(signal, listener)); -} -function armAbandonmentBackstop(body, controller) { - if (cleanups.has(controller)) registry?.register(body, controller, controller); -} -function releaseRequestSignal(controller) { - const cleanup = cleanups.get(controller); - if (cleanup) { - cleanups.delete(controller); - registry?.unregister(controller); - cleanup(); - } -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/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 Anthropic({ 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/@anthropic-ai/sdk/internal/request-options.mjs -var FallbackEncoder = ({ headers, body }) => { - return { - bodyHeaders: { "content-type": "application/json" }, - body: JSON.stringify(body) - }; -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs -var default_format = "RFC3986"; -var default_formatter = (v) => String(v); -var formatters = { - RFC1738: (v) => String(v).replace(/%20/g, "+"), - RFC3986: default_formatter -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs -var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)); -var hex_table = /* @__PURE__ */ (() => { - const array = []; - for (let i = 0; i < 256; ++i) array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); - return array; -})(); -var limit = 1024; -var 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/@anthropic-ai/sdk/internal/qs/stringify.mjs -var array_prefix_generators = { - brackets(prefix) { - return String(prefix) + "[]"; - }, - comma: "comma", - indices(prefix, key) { - return String(prefix) + "[" + key + "]"; - }, - repeat(prefix) { - return String(prefix); - } -}; -var push_to_array = function(arr, value_or_array) { - Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); -}; -var toISOString; -var 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"; -} -var 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/@anthropic-ai/sdk/internal/utils/query.mjs -function stringifyQuery(query) { - return stringify(query, { arrayFormat: "brackets" }); -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs -var GRANT_TYPE_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer"; -var GRANT_TYPE_REFRESH_TOKEN = "refresh_token"; -var TOKEN_ENDPOINT = "/v1/oauth/token"; -/** -* `anthropic-beta` value required on authenticated API requests using an -* OAuth bearer token, and on `refresh_token` grants against the token endpoint. -*/ -var OAUTH_API_BETA_HEADER = "oauth-2025-04-20"; -/** -* `anthropic-beta` value required on jwt-bearer exchanges against the token -* endpoint. It routes the request to the federation service; it must NOT be -* sent on `refresh_token` grants, which are handled by a different backend. -*/ -var FEDERATION_BETA_HEADER = "oidc-federation-2026-04-01"; -var MAX_TOKEN_RESPONSE_BYTES = 1 << 20; -/** -* Rejects base URLs that would cause a JWT assertion or refresh token to be -* sent over cleartext HTTP. Loopback hosts are allowed for local development. -*/ -function requireSecureTokenEndpoint(baseURL) { - if (!baseURL) return; - let u; - try { - u = new URL(baseURL); - } catch (err) { - throw new WorkloadIdentityError(`Invalid token endpoint base URL "${baseURL}": ${err}`); - } - if (u.protocol === "https:") return; - const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, ""); - if (u.protocol === "http:" && (host === "localhost" || host === "127.0.0.1" || host === "::1")) return; - throw new WorkloadIdentityError(`Refusing to send credential over non-https token endpoint "${baseURL}"`); -} -/** -* Reads the response body as text, parses it as a token-endpoint JSON -* response, validates `access_token` is present, and rejects a non-Bearer -* `token_type` when one is provided. Reads at most -* {@link MAX_TOKEN_RESPONSE_BYTES} from the body stream. -*/ -async function parseTokenResponse(resp, requestId) { - const text = await readLimitedText(resp); - let data; - try { - data = JSON.parse(text); - } catch { - throw new WorkloadIdentityError(`Token endpoint returned non-JSON response (status ${resp.status})`, resp.status, redactSensitive(text), requestId); - } - if (!data.access_token) throw new WorkloadIdentityError(`Token endpoint response missing access_token: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId); - if (data.token_type && data.token_type.toLowerCase() !== "bearer") throw new WorkloadIdentityError(`Token endpoint response: unsupported token_type "${data.token_type}" (want Bearer)`, resp.status, redactSensitive(data), requestId); - return data; -} -var MAX_ERROR_BODY_CHARS = 2e3; -var SAFE_ERROR_KEYS = /* @__PURE__ */ new Set([ - "error", - "error_description", - "error_uri" -]); -/** -* Returns a redacted copy of a token-endpoint error body for safe inclusion -* in an exception. Strings are truncated; objects keep only the RFC 6749 -* §5.2 error fields. -*/ -function redactSensitive(body) { - if (body == null) return body; - if (typeof body === "string") { - let parsed; - try { - parsed = JSON.parse(body); - } catch { - if (body.length <= MAX_ERROR_BODY_CHARS) return body; - return body.slice(0, MAX_ERROR_BODY_CHARS) + `... <${body.length - MAX_ERROR_BODY_CHARS} more chars>`; - } - return JSON.stringify(redactSensitive(parsed)); - } - if (typeof body === "object" && !Array.isArray(body)) { - const out = {}; - for (const [k, v] of Object.entries(body)) if (SAFE_ERROR_KEYS.has(k)) out[k] = v; - return out; - } - return null; -} -/** -* Best-effort safety check on a credentials file before reading it. -* -* On POSIX: resolves symlinks (so containerized deployments that mount the -* credential as a symlink to a tmpfs-backed file keep working), then rejects -* the resolved target if it is group- or world- readable or writable. A uid -* mismatch on the resolved target is surfaced via `onWarn` since -* root-written/app-read is common in init-container setups. No-op on Windows. -*/ -async function checkCredentialsFileSafety(path, onWarn = (m) => console.warn(`anthropic-sdk: ${m}`)) { - if (typeof process === "undefined" || process.platform === "win32") return; - const fs = await import("node:fs"); - let resolved = path; - let st; - try { - resolved = await fs.promises.realpath(path); - st = await fs.promises.stat(resolved); - } catch { - return; - } - const mode = st.mode & 511; - if (mode & 18) throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-writable (mode 0o${mode.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${resolved}\`.`); - if (mode & 36) throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-readable (mode 0o${mode.toString(8)}); run \`chmod 600 ${resolved}\` before retrying.`); - if (typeof process.getuid === "function" && st.uid !== process.getuid()) onWarn(`credentials file at ${resolved} is owned by uid ${st.uid} (current process uid ${process.getuid()}); verify this is intentional.`); -} -/** -* Atomically writes JSON to `targetPath` via a `.tmp` sibling + rename, -* with fsync on the file and (best-effort) on the parent directory. -* Creates the parent directory with mode 0700 and the file with mode 0600. -*/ -async function writeCredentialsFileAtomic(targetPath, data) { - const fs = await import("node:fs"); - const dir = (await import("node:path")).dirname(targetPath); - await fs.promises.mkdir(dir, { - recursive: true, - mode: 448 - }); - const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; - try { - const fh = await fs.promises.open(tmpPath, "w", 384); - try { - await fh.writeFile(JSON.stringify(data, null, 2)); - await fh.sync(); - } finally { - await fh.close(); - } - await fs.promises.rename(tmpPath, targetPath); - } catch (err) { - await fs.promises.unlink(tmpPath).catch(() => {}); - throw err; - } - try { - const dirFh = await fs.promises.open(dir, "r"); - try { - await dirFh.sync(); - } finally { - await dirFh.close(); - } - } catch {} -} -async function readLimitedText(resp) { - if (!resp.body) return ""; - const reader = resp.body.getReader(); - const chunks = []; - let received = 0; - for (;;) { - const { done, value } = await reader.read(); - if (done) break; - if (received + value.length > MAX_TOKEN_RESPONSE_BYTES) { - const remaining = MAX_TOKEN_RESPONSE_BYTES - received; - if (remaining > 0) chunks.push(value.subarray(0, remaining)); - await reader.cancel(); - break; - } - chunks.push(value); - received += value.length; - } - let merged; - if (chunks.length === 1) merged = chunks[0]; - else { - merged = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0)); - let offset = 0; - for (const c of chunks) { - merged.set(c, offset); - offset += c.length; - } - } - return new TextDecoder("utf-8").decode(merged); -} -var WorkloadIdentityError = class extends AnthropicError { - constructor(message, statusCode = null, body = null, requestId = null) { - super(message); - this.statusCode = statusCode; - this.body = body; - this.requestId = requestId; - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/utils/time.mjs -/** Current time as unix epoch seconds. */ -function nowAsSeconds() { - return Math.floor(Date.now() / 1e3); -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs -/** -* Wraps an {@link AccessTokenProvider} with two-tier proactive refresh -* and concurrent deduplication. -* -* Refresh policy on each {@link getToken} call: -* -* - No cached token → call provider (blocking), cache, return. -* - Cached with `expiresAt == null` → return cached forever. -* - More than 120s remaining → return cached. -* - 30–120s remaining (advisory window) → return stale token immediately, -* kick off background refresh. On failure, log and keep stale. -* - Less than 30s remaining or expired (mandatory) → block and refresh. -* On failure, throw. -* -* Concurrent mandatory callers coalesce into a single provider call. -*/ -var TokenCache = class { - constructor(provider, onAdvisoryRefreshError) { - this.cached = null; - this.pendingRefresh = null; - this.nextForce = false; - this.lastAdvisoryError = 0; - this.provider = provider; - this.onAdvisoryRefreshError = onAdvisoryRefreshError; - } - async getToken() { - const force = this.nextForce; - this.nextForce = false; - const cached = this.cached; - if (force || cached == null) return (await this.refresh(force)).token; - if (cached.expiresAt == null) return cached.token; - const remaining = cached.expiresAt - nowAsSeconds(); - if (remaining > 120) return cached.token; - if (remaining > 30) { - this.backgroundRefresh(); - return cached.token; - } - return (await this.refresh()).token; - } - /** - * Clears the cached token and marks the next {@link getToken} as a forced - * refresh, so the underlying provider bypasses any on-disk freshness check. - * Called after a 401 — the server has just told us the token is bad even - * if its `expires_at` still looks fresh. - */ - invalidate() { - this.cached = null; - this.nextForce = true; - } - /** - * Mandatory refresh. Joins any in-flight refresh unless forced — a forced - * refresh must not coalesce into a non-forced one that may re-serve the - * same stale disk token. - */ - refresh(force = false) { - if (this.pendingRefresh && !force) return this.pendingRefresh; - return this.doRefresh(force); - } - /** - * Advisory background refresh. Shares the same in-flight promise as - * mandatory refreshes for deduplication, but swallows errors so the - * stale cached token keeps being served. Backs off for - * {@link ADVISORY_REFRESH_BACKOFF_IN_SECONDS} after a failure so an - * outage during the advisory window doesn't hammer the token endpoint. - */ - backgroundRefresh() { - if (this.pendingRefresh) return; - if (nowAsSeconds() - this.lastAdvisoryError < 5) return; - this.doRefresh().catch((err) => { - this.lastAdvisoryError = nowAsSeconds(); - this.onAdvisoryRefreshError?.(err); - }); - } - /** - * Core refresh. Sets {@link pendingRefresh} so concurrent callers - * (both advisory and mandatory) coalesce into a single provider call. - */ - doRefresh(force = false) { - this.pendingRefresh = this.provider(force ? { forceRefresh: true } : void 0).then((token) => { - this.cached = token; - this.pendingRefresh = null; - return token; - }, (err) => { - this.pendingRefresh = null; - throw err; - }); - return this.pendingRefresh; - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/utils/env.mjs -/** -* Read an environment variable. -* -* Trims beginning and trailing whitespace. -* -* Will return undefined if the environment variable doesn't exist or cannot be accessed. -*/ -var readEnv = (env) => { - if (typeof globalThis.process !== "undefined") return globalThis.process.env?.[env]?.trim() || void 0; - if (typeof globalThis.Deno !== "undefined") return globalThis.Deno.env?.get?.(env)?.trim() || void 0; -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/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; -} -var encodeUTF8_; -function encodeUTF8(str) { - let encoder; - return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str); -} -var decodeUTF8_; -function decodeUTF8(bytes) { - let decoder; - return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes); -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/utils/log.mjs -var defaultLogLevel = "warn"; -var levelNumbers = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500 -}; -var parseLogLevel = (maybeLevel, sourceName, logger) => { - if (!maybeLevel) return; - if (hasOwn(levelNumbers, maybeLevel)) return maybeLevel; - logger.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); -} -var noopLogger = { - error: noop, - warn: noop, - info: noop, - debug: noop -}; -var cachedLoggers = /* @__PURE__ */ new WeakMap(); -function filterLogger(logger, logLevel) { - 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; -} -function loggerFor(client) { - const logger = client.logger; - const logLevel = client.logLevel ?? "off"; - if (!logger) return noopLogger; - return filterLogger(logger, logLevel); -} -var lastEnvLevel; -var cachedDefaultLogger; -/** -* A logger matching the client defaults — `console`, filtered to -* `ANTHROPIC_LOG` or {@link defaultLogLevel} — for contexts with no client to -* read the configured `logger`/`logLevel` from. -* -* Cached per `ANTHROPIC_LOG` value so an invalid value warns once, like a -* client construction does, rather than on every request. -*/ -function defaultLogger() { - const envLevel = readEnv("ANTHROPIC_LOG"); - if (!cachedDefaultLogger || envLevel !== lastEnvLevel) { - lastEnvLevel = envLevel; - cachedDefaultLogger = filterLogger(console, parseLogLevel(envLevel, "process.env['ANTHROPIC_LOG']", filterLogger(console, "warn")) ?? "warn"); - } - return cachedDefaultLogger; -} -var 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() === "api-key" || name.toLowerCase() === "x-api-key" || 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/@anthropic-ai/sdk/core/credentials.mjs -var PROFILE_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/; -function validateProfileName(name) { - if (!name) throw new Error("profile name is empty"); - if (name === "." || name === "..") throw new Error(`profile name "${name}" is not allowed`); - if (name.includes("/") || name.includes("\\")) throw new Error(`profile name "${name}" must not contain path separators`); - if (!PROFILE_NAME_PATTERN.test(name)) throw new Error(`profile name "${name}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`); -} -/** -* Same as {@link loadConfig}, but also reports whether the config was loaded -* from a profile file on disk (`fromFile: true`) or synthesized entirely from -* environment variables (`fromFile: false`). -*/ -var loadConfigWithSource = async (profile) => { - var _a, _b; - const rootConfigPath = await getRootConfigPath(); - if (rootConfigPath === null) return null; - const profileName = profile ?? await getActiveProfileName(); - if (profileName === null) return null; - validateProfileName(profileName); - const fs = await import("node:fs"); - const configPath = (await import("node:path")).join(rootConfigPath, "configs", `${profileName}.json`); - let configRaw; - try { - configRaw = await fs.promises.readFile(configPath, "utf-8"); - } catch (err) { - if (err?.code !== "ENOENT") throw new Error(`failed to read config file ${configPath}: ${err}`); - configRaw = null; - } - if (configRaw === null) { - const organizationId = readEnv("ANTHROPIC_ORGANIZATION_ID"); - const identityTokenFile = readEnv("ANTHROPIC_IDENTITY_TOKEN_FILE"); - const federationRuleId = readEnv("ANTHROPIC_FEDERATION_RULE_ID"); - if (federationRuleId && organizationId) return { - fromFile: false, - config: { - organization_id: organizationId, - workspace_id: readEnv("ANTHROPIC_WORKSPACE_ID"), - base_url: readEnv("ANTHROPIC_BASE_URL"), - authentication: { - type: "oidc_federation", - federation_rule_id: federationRuleId, - service_account_id: readEnv("ANTHROPIC_SERVICE_ACCOUNT_ID"), - identity_token: identityTokenFile ? { - source: "file", - path: identityTokenFile - } : void 0, - scope: readEnv("ANTHROPIC_SCOPE") - } - } - }; - return null; - } - let config; - try { - config = JSON.parse(configRaw); - } catch (err) { - throw new Error(`failed to parse config file ${configPath}: ${err}`); - } - if (!config.authentication) throw new Error(`config file ${configPath} is missing "authentication"`); - const authType = config.authentication.type; - if (authType !== "oidc_federation" && authType !== "user_oauth") throw new Error(`authentication.type "${authType}" is not a known authentication type`); - config.organization_id ?? (config.organization_id = readEnv("ANTHROPIC_ORGANIZATION_ID")); - config.workspace_id ?? (config.workspace_id = readEnv("ANTHROPIC_WORKSPACE_ID")); - config.base_url ?? (config.base_url = readEnv("ANTHROPIC_BASE_URL")); - (_a = config.authentication).scope ?? (_a.scope = readEnv("ANTHROPIC_SCOPE")); - if (config.authentication.type === "oidc_federation") { - if (!config.authentication.identity_token) { - const identityTokenFile = readEnv("ANTHROPIC_IDENTITY_TOKEN_FILE"); - if (identityTokenFile) config.authentication.identity_token = { - source: "file", - path: identityTokenFile - }; - } - if (!config.authentication.federation_rule_id) config.authentication.federation_rule_id = readEnv("ANTHROPIC_FEDERATION_RULE_ID") ?? ""; - (_b = config.authentication).service_account_id ?? (_b.service_account_id = readEnv("ANTHROPIC_SERVICE_ACCOUNT_ID")); - } - return { - config, - fromFile: true - }; -}; -/** -* Resolves the credentials file path for the given config. -* -* Uses `authentication.credentials_path` from the config if set, otherwise -* falls back to `/credentials/.json`. -* -* Returns `null` when running in a browser or the path cannot be resolved. -*/ -var getCredentialsPath = async (config, profile) => { - if (config?.authentication.credentials_path) return config.authentication.credentials_path; - const rootConfigPath = await getRootConfigPath(); - if (!rootConfigPath) return null; - const profileName = profile ?? await getActiveProfileName(); - if (!profileName) return null; - validateProfileName(profileName); - return (await import("node:path")).join(rootConfigPath, "credentials", `${profileName}.json`); -}; -var getRootConfigPath = async () => { - if (!supportsLocalConfigFiles()) return null; - const path = await import("node:path"); - const configDir = readEnv("ANTHROPIC_CONFIG_DIR"); - if (configDir) return configDir; - if (getPlatformHeaders()["X-Stainless-OS"] === "Windows") { - const appData = readEnv("APPDATA"); - if (appData) return path.join(appData, "Anthropic"); - const userProfile = readEnv("USERPROFILE"); - if (userProfile) return path.join(userProfile, "AppData", "Roaming", "Anthropic"); - return null; - } - const xdgConfigHome = readEnv("XDG_CONFIG_HOME"); - if (xdgConfigHome) return path.join(xdgConfigHome, "anthropic"); - const home = readEnv("HOME"); - if (home) return path.join(home, ".config", "anthropic"); - return null; -}; -var supportsLocalConfigFiles = () => { - const runtime = getPlatformHeaders()["X-Stainless-Runtime"]; - return runtime === "node" || runtime === "deno"; -}; -var getActiveProfileName = async () => { - const rootConfigPath = await getRootConfigPath(); - if (!rootConfigPath) return null; - const profileName = readEnv("ANTHROPIC_PROFILE"); - if (profileName) return profileName; - const fs = await import("node:fs"); - const filePath = (await import("node:path")).join(rootConfigPath, "active_config"); - try { - return (await fs.promises.readFile(filePath, "utf-8")).trim() || "default"; - } catch (err) { - if (err?.code !== "ENOENT") throw new Error(`failed to read ${filePath}: ${err}`); - return "default"; - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs -/** -* Reads a JWT from a file on every call. Supports automatic rotation -* (e.g. Kubernetes projected service-account tokens). -*/ -function identityTokenFromFile(path) { - if (!path) throw new AnthropicError("Identity token file path is empty"); - return async () => { - const fs = await import("node:fs"); - let content; - try { - content = await fs.promises.readFile(path, "utf-8"); - } catch (err) { - throw new AnthropicError(`Failed to read identity token file at ${path}: ${err}`); - } - const token = content.trim(); - if (!token) throw new AnthropicError(`Identity token file at ${path} is empty`); - return token; - }; -} -/** -* Wraps a static JWT string as an {@link IdentityTokenProvider}. -*/ -function identityTokenFromValue(token) { - if (!token) throw new AnthropicError("Identity token value is empty"); - return () => token; -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs -/** -* Exchanges an external OIDC JWT for an Anthropic access token via the -* RFC 7523 jwt-bearer grant. -* -* Each invocation performs a fresh token exchange. Wrap in a -* {@link TokenCache} to avoid exchanging on every request. -* -* Federation grants do not return a refresh token — callers re-exchange -* their assertion on expiry. -*/ -function oidcFederationProvider(config) { - return async () => { - requireSecureTokenEndpoint(config.baseURL); - const jwt = await config.identityTokenProvider(); - if (jwt.length > 16 * 1024) throw new WorkloadIdentityError(`Identity token is ${Math.ceil(jwt.length / 1024)} KiB, exceeds the 16 KiB assertion limit`); - const body = { - grant_type: GRANT_TYPE_JWT_BEARER, - assertion: jwt, - federation_rule_id: config.federationRuleId, - organization_id: config.organizationId - }; - if (config.serviceAccountId) body["service_account_id"] = config.serviceAccountId; - if (config.workspaceId) body["workspace_id"] = config.workspaceId; - const url = `${config.baseURL}${TOKEN_ENDPOINT}`; - let resp; - try { - resp = await config.fetch(url, { - method: "POST", - headers: { - "Content-Type": "application/json", - "anthropic-beta": `${OAUTH_API_BETA_HEADER},${FEDERATION_BETA_HEADER}`, - "User-Agent": config.userAgent || `anthropic-sdk-typescript/0.115.0 oidcFederationProvider` - }, - body: JSON.stringify(body) - }); - } catch (err) { - throw new WorkloadIdentityError(`Failed to reach token endpoint ${url}: ${err}`); - } - const requestId = resp.headers.get("Request-Id"); - if (!resp.ok) { - const redacted = redactSensitive(await resp.text().catch(() => "")); - let hint = ""; - if (resp.status === 401) hint = ` Ensure your federation rule matches your identity token. ${config.workspaceId ? "" : "If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`; - throw new WorkloadIdentityError(`Token exchange failed with status ${resp.status}${requestId ? ` (request-id ${requestId})` : ""}: ${redacted}${hint}`, resp.status, redacted, requestId); - } - const data = await parseTokenResponse(resp, requestId); - const expiresIn = Number(data.expires_in); - if (!Number.isFinite(expiresIn)) throw new WorkloadIdentityError(`Token endpoint response missing required fields: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId); - return { - token: data.access_token, - expiresAt: nowAsSeconds() + expiresIn - }; - }; -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs -/** -* Reads a user-oauth credential file. Returns the cached access token while -* fresh; on expiry performs a `refresh_token` grant and writes the new -* tokens back to the credentials file (atomic replace, fsync'd). -* -* If `clientId` is empty, the access token is treated as static — the -* credentials file is read on every call but no refresh is attempted, and -* an expired token without a `refresh_token` raises. -*/ -function userOAuthProvider(config) { - return async (opts) => { - const fs = await import("node:fs"); - await checkCredentialsFileSafety(config.credentialsPath, config.onSafetyWarning); - let raw; - try { - raw = await fs.promises.readFile(config.credentialsPath, "utf-8"); - } catch (err) { - throw new WorkloadIdentityError(`Credentials file not found at ${config.credentialsPath}: ${err}`); - } - let creds; - try { - creds = JSON.parse(raw); - } catch (err) { - throw new WorkloadIdentityError(`Credentials file at ${config.credentialsPath} is not valid JSON: ${err}`); - } - const accessToken = creds.access_token; - if (!accessToken) throw new WorkloadIdentityError(`Credentials file at ${config.credentialsPath} must include 'access_token'`); - const expiresAt = creds.expires_at; - if (!opts?.forceRefresh && (expiresAt == null || nowAsSeconds() < expiresAt - 30)) return { - token: accessToken, - expiresAt: expiresAt ?? null - }; - const refreshToken = creds.refresh_token; - if (!config.clientId || !refreshToken) throw new WorkloadIdentityError(`Access token at ${config.credentialsPath} has expired and no refresh is available (client_id ${config.clientId ? "set" : "empty"}, refresh_token ${refreshToken ? "set" : "empty"})`); - requireSecureTokenEndpoint(config.baseURL); - const body = { - grant_type: GRANT_TYPE_REFRESH_TOKEN, - refresh_token: refreshToken, - client_id: config.clientId - }; - const url = `${config.baseURL}${TOKEN_ENDPOINT}`; - let resp; - try { - resp = await config.fetch(url, { - method: "POST", - headers: { - "Content-Type": "application/json", - "anthropic-beta": OAUTH_API_BETA_HEADER, - "User-Agent": config.userAgent || `anthropic-sdk-typescript/0.115.0 userOAuthProvider` - }, - body: JSON.stringify(body) - }); - } catch (err) { - throw new WorkloadIdentityError(`User OAuth refresh failed to reach token endpoint: ${err}`); - } - const requestId = resp.headers.get("Request-Id"); - if (!resp.ok) { - const text = await resp.text().catch(() => ""); - throw new WorkloadIdentityError(`User OAuth refresh failed (HTTP ${resp.status}): ${redactSensitive(text)}`, resp.status, redactSensitive(text), requestId); - } - const data = await parseTokenResponse(resp, requestId); - const expiresIn = Number(data.expires_in); - if (!Number.isFinite(expiresIn)) throw new WorkloadIdentityError(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId); - const newExpiresAt = nowAsSeconds() + expiresIn; - const newRefreshToken = data.refresh_token || refreshToken; - await writeCredentialsFileAtomic(config.credentialsPath, { - ...creds, - version: "1.0", - type: "oauth_token", - access_token: data.access_token, - expires_at: newExpiresAt, - refresh_token: newRefreshToken - }); - return { - token: data.access_token, - expiresAt: newExpiresAt - }; - }; -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs -function resolveCredentialsFromConfig(config, options) { - const provider = buildProvider(config, config.authentication.credentials_path ?? null, (config.base_url || options.baseURL).replace(/\/+$/, ""), options); - const extraHeaders = {}; - if (config.workspace_id && config.authentication.type === "user_oauth") extraHeaders["anthropic-workspace-id"] = config.workspace_id; - return { - provider, - extraHeaders, - baseURL: config.base_url || void 0 - }; -} -/** -* Resolves a {@link CredentialResult} from the environment. Returns `null` -* when no credentials can be resolved. -* -* Resolution order: -* -* 1. Config file for the active profile (or the explicit `profile` argument) -* → dispatch on `authentication.type` (`oidc_federation`, `user_oauth`) -* 2. Environment variables `ANTHROPIC_FEDERATION_RULE_ID` + -* `ANTHROPIC_ORGANIZATION_ID` (+ identity token) → OIDC federation -* 3. Nothing matches → `null` -* -* Passing `profile` selects `/configs/.json` directly, -* skipping `ANTHROPIC_PROFILE` / `active_config` resolution. -*/ -async function defaultCredentials(options, profile) { - const loaded = await loadConfigWithSource(profile); - if (!loaded) return null; - const { config, fromFile } = loaded; - return resolveCredentialsFromConfig(config.authentication.credentials_path || !fromFile ? config : { - ...config, - authentication: { - ...config.authentication, - credentials_path: await getCredentialsPath(config, profile) ?? void 0 - } - }, options); -} -function buildProvider(config, credentialsPath, baseURL, options) { - switch (config.authentication.type) { - case "oidc_federation": { - const auth = config.authentication; - const identityProvider = resolveIdentityTokenProvider(auth); - if (!identityProvider) throw new WorkloadIdentityError("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)"); - if (!auth.federation_rule_id) throw new WorkloadIdentityError("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence)."); - if (!config.organization_id) throw new WorkloadIdentityError("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)"); - const exchange = oidcFederationProvider({ - identityTokenProvider: identityProvider, - federationRuleId: auth.federation_rule_id, - organizationId: config.organization_id, - serviceAccountId: auth.service_account_id, - workspaceId: config.workspace_id, - baseURL, - fetch: options.fetch, - userAgent: options.userAgent - }); - if (credentialsPath) return cachedExchangeProvider(exchange, credentialsPath, options.onCacheWriteError, options.onSafetyWarning); - return exchange; - } - case "user_oauth": - if (!credentialsPath) throw new WorkloadIdentityError("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to /credentials/.json)"); - return userOAuthProvider({ - credentialsPath, - clientId: config.authentication.client_id, - baseURL, - fetch: options.fetch, - userAgent: options.userAgent, - onSafetyWarning: options.onSafetyWarning - }); - default: { - const t = config.authentication.type; - throw new WorkloadIdentityError(`authentication.type "${t}" is not a known authentication type`); - } - } -} -/** -* Resolves the identity token provider from config fields or environment variables. -* -* Resolution order: -* 1. `identity_token.path` from the config (source: "file") -* 2. `ANTHROPIC_IDENTITY_TOKEN_FILE` env var -* 3. `ANTHROPIC_IDENTITY_TOKEN` env var (static value) -*/ -function resolveIdentityTokenProvider(auth) { - if (auth.identity_token) { - const source = auth.identity_token.source; - if (source !== "file") throw new WorkloadIdentityError(`identity_token.source "${source}" is not supported by this SDK version (only "file")`); - if (!auth.identity_token.path) throw new WorkloadIdentityError(`identity_token.source "file" requires a non-empty path`); - return identityTokenFromFile(auth.identity_token.path); - } - const tokenFile = readEnv("ANTHROPIC_IDENTITY_TOKEN_FILE"); - if (tokenFile) return identityTokenFromFile(tokenFile); - const tokenValue = readEnv("ANTHROPIC_IDENTITY_TOKEN"); - if (tokenValue) return identityTokenFromValue(tokenValue); - return null; -} -/** -* Wraps a federation exchange provider with credential file caching. -* Checks the file for a fresh token before exchanging, and writes the -* result back after a successful exchange (best-effort, atomic replace). -* -* Note: this is not cross-process serialized — two SDK instances that -* miss the cache simultaneously will both perform a full exchange and -* the last writer wins. That is acceptable: federation exchanges are -* idempotent and the cache is an optimization, not a correctness gate. -*/ -function cachedExchangeProvider(exchange, credentialsPath, onCacheWriteError, onSafetyWarning) { - return async (opts) => { - const fs = await import("node:fs"); - await checkCredentialsFileSafety(credentialsPath, onSafetyWarning); - let existing; - try { - const raw = await fs.promises.readFile(credentialsPath, "utf-8"); - existing = JSON.parse(raw); - const token = existing?.["access_token"]; - if (token && !opts?.forceRefresh) { - const expiresAt = existing?.["expires_at"]; - if (expiresAt == null || nowAsSeconds() < expiresAt - 30) return { - token, - expiresAt: expiresAt ?? null - }; - } - } catch (err) { - if (err?.code !== "ENOENT" && !(err instanceof SyntaxError)) onCacheWriteError?.(err); - } - const result = await exchange(opts); - try { - await writeCredentialsFileAtomic(credentialsPath, { - ...existing ?? {}, - version: "1.0", - type: "oauth_token", - access_token: result.token, - expires_at: result.expiresAt - }); - } catch (err) { - onCacheWriteError?.(err); - } - return result; - }; -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs -var _LineDecoder_buffer; -var _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, /* @__PURE__ */ 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 = /* @__PURE__ */ 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/@anthropic-ai/sdk/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"); - } - /** - * Iterate the raw Server-Sent Events from `response` — `{event, data, raw}` - * objects, before any JSON parsing or event-name filtering. - * - * This reads `response.body` directly (not a clone), so the response is - * consumed. Use this in middleware that fully replaces the stream body; for - * read-only observation of parsed events, use `ctx.parse()` instead. - */ - static rawEvents(response, controller = new AbortController()) { - return _iterSSEMessages(response, controller); - } - static fromSSEResponse(response, controller, client) { - let consumed = false; - const logger = client ? loggerFor(client) : console; - async function* iterator() { - if (consumed) throw new AnthropicError("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 (sse.event === "completion") try { - yield 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 (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop" || sse.event === "message" || sse.event === "user.message" || sse.event === "user.interrupt" || sse.event === "user.tool_confirmation" || sse.event === "user.custom_tool_result" || sse.event === "user.tool_result" || sse.event === "agent.message" || sse.event === "agent.thinking" || sse.event === "agent.tool_use" || sse.event === "agent.tool_result" || sse.event === "agent.mcp_tool_use" || sse.event === "agent.mcp_tool_result" || sse.event === "agent.custom_tool_use" || sse.event === "agent.thread_context_compacted" || sse.event === "session.status_running" || sse.event === "session.status_idle" || sse.event === "session.status_rescheduled" || sse.event === "session.status_terminated" || sse.event === "session.error" || sse.event === "session.deleted" || sse.event === "session.updated" || sse.event === "span.model_request_start" || sse.event === "span.model_request_end" || sse.event === "span.outcome_evaluation_start" || sse.event === "span.outcome_evaluation_ongoing" || sse.event === "span.outcome_evaluation_end" || sse.event === "user.define_outcome" || sse.event === "agent.thread_message_received" || sse.event === "agent.thread_message_sent" || sse.event === "agent.session_thread_message_received" || sse.event === "agent.session_thread_message_sent" || sse.event === "session.thread_created" || sse.event === "session.thread_status_created" || sse.event === "session.thread_status_running" || sse.event === "session.thread_status_idle" || sse.event === "session.thread_status_rescheduled" || sse.event === "session.thread_status_terminated" || sse.event === "event_start" || sse.event === "event_delta" || sse.event === "system.message") try { - yield 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 (sse.event === "ping") continue; - if (sse.event === "error") { - const body = safeJSON(sse.data) ?? sse.data; - const type = body?.error?.type; - throw new APIError(void 0, body, void 0, response.headers, type); - } - } - done = true; - } catch (e) { - if (isAbortError(e)) return; - throw e; - } finally { - if (!done) controller.abort(); - releaseRequestSignal(controller); - } - } - 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 AnthropicError("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(); - releaseRequestSignal(controller); - } - } - 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 AnthropicError(`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 AnthropicError(`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 = /* @__PURE__ */ 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/@anthropic-ai/sdk/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); - return Stream.fromSSEResponse(response, props.controller); - } - 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")) { - if (response.headers.get("content-length") === "0") return; - return addRequestID(await response.json(), response); - } - return await response.text(); - })().finally(() => { - if (!props.options.stream && !props.options.__binaryResponse) releaseRequestSignal(props.controller); - }); - 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("request-id"), - enumerable: false - }); -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/core/middleware.mjs -/** -* Errors thrown by the underlying `fetch`, as opposed to by a middleware. -* -* Tracked so the client can apply its connection-error retry policy to -* transport failures while letting errors thrown by middleware propagate to -* the caller untouched. -*/ -var fetchOriginErrors = /* @__PURE__ */ new WeakSet(); -/** Whether `err` was thrown by the underlying `fetch` rather than by a middleware. */ -function isFetchOriginError(err) { - return typeof err === "object" && err !== null && fetchOriginErrors.has(err); -} -/** -* Whether an error thrown by middleware should stay on the SDK's -* connection-error retry policy: fetch-origin, abort, `APIConnectionError`, or -* `RetryableError` — checked through the error's `cause` chain. -*/ -function isRetryableError(err) { - const seen = /* @__PURE__ */ new Set(); - while (typeof err === "object" && err !== null && !seen.has(err)) { - seen.add(err); - if (isFetchOriginError(err) || isAbortError(err) || err instanceof APIConnectionError || err instanceof RetryableError) return true; - err = err.cause; - } - return false; -} -/** -* Wraps `fetchFn` so each call runs through `middleware`, keeping the same -* call signature as `fetch` itself. -* -* With no middleware, calls are passed straight through to `fetchFn`. -* Otherwise the arguments are normalized into an {@link APIRequest} (headers -* coerced to a `Headers` instance, URL stringified) before entering the -* chain. The chain is composed per call, so mutations of a `middleware` -* array are picked up by later requests. -* -* `options` — the SDK request options behind this call, when there are any — -* is surfaced to middleware as `ctx.options` and drives `ctx.parse`. -* -* `client` supplies `ctx.logger` (the client's level-filtered logger); -* without it, `ctx.logger` falls back to the client defaults: `console`, -* filtered to `ANTHROPIC_LOG` or `'warn'`. -*/ -function wrapFetchWithMiddleware(fetchFn, middleware, options, client) { - return async (url, init = {}) => { - if (middleware.length === 0) return fetchFn.call(void 0, url, init); - const headers = init.headers instanceof Headers ? init.headers : new Headers(init.headers); - const response = await applyMiddleware(fetchFn, middleware, options, client)({ - ...init, - headers, - url: typeof url === "string" ? url : url instanceof URL ? url.href : url.url - }); - if (response.bodyUsed || response.body?.locked) throw new AnthropicError("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it"); - return response; - }; -} -/** -* Creates the {@link MiddlewareContext} shared by every middleware in one chain. -*/ -function createMiddlewareContext(options, client) { - const cache = /* @__PURE__ */ new WeakMap(); - return { - options, - logger: client ? loggerFor(client) : defaultLogger(), - parse(response) { - if (options?.stream && response.ok) return parseMiddlewareResponse(response, options); - let parsed = cache.get(response); - if (!parsed) { - parsed = parseMiddlewareResponse(response, options); - cache.set(response, parsed); - } - return parsed; - } - }; -} -/** -* Mirrors the client's own response parsing (`defaultParseResponse` in -* `internal/parse.ts`), reading through a clone so the body stays available -* to the rest of the chain and the client itself. -*/ -async function parseMiddlewareResponse(response, options) { - if (response.bodyUsed || response.body?.locked) throw new AnthropicError("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()"); - if (options?.stream && response.ok) return Stream.fromSSEResponse(response.clone(), new AbortController()); - if (response.status === 204) return null; - if (options?.__binaryResponse) return response; - const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim(); - if (mediaType?.includes("application/json") || mediaType?.endsWith("+json")) { - if (response.headers.get("content-length") === "0") return; - return addRequestID(await response.clone().json(), response); - } - return await response.clone().text(); -} -/** -* Composes `middleware` around `fetchFn` and returns the entry point of the chain. -*/ -function applyMiddleware(fetchFn, middleware, options, client) { - let next = async ({ url, ...init }) => { - try { - return await fetchFn.call(void 0, url, init); - } catch (err) { - const error = castToError(err); - fetchOriginErrors.add(error); - throw error; - } - }; - const ctx = createMiddlewareContext(options, client); - for (let i = middleware.length - 1; i >= 0; i--) { - const mw = middleware[i]; - const nextInner = next; - next = async (request) => mw(request, nextInner, ctx); - } - return next; -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/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 `request-id` header which is useful for debugging requests and resporting - * issues to Anthropic. - * - * 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("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/@anthropic-ai/sdk/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 AnthropicError("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; - } -}; -var Page = 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.first_id = body.first_id || null; - this.last_id = body.last_id || null; - } - getPaginatedItems() { - return this.data ?? []; - } - hasNextPage() { - if (this.has_more === false) return false; - return super.hasNextPage(); - } - nextPageRequestOptions() { - if (this.options.query?.["before_id"]) { - const first_id = this.first_id; - if (!first_id) return null; - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - before_id: first_id - } - }; - } - const cursor = this.last_id; - if (!cursor) return null; - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - after_id: cursor - } - }; - } -}; -var PageCursor = class extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.next_page = body.next_page || null; - } - getPaginatedItems() { - return this.data ?? []; - } - nextPageRequestOptions() { - const cursor = this.next_page; - if (!cursor) return null; - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - page: cursor - } - }; - } -}; -var BidirectionalPageCursor = class extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.next_page = body.next_page || null; - this.prev_page = body.prev_page || null; - } - getPaginatedItems() { - return this.data ?? []; - } - nextPageRequestOptions() { - const cursor = this.next_page; - if (!cursor) return null; - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - page: cursor - } - }; - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/uploads.mjs -var 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, stripPath) { - const val = 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)) || ""; - return stripPath ? val.split(/[\\/]/).pop() || void 0 : val; -} -var isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; -var multipartFormRequestOptions = async (opts, fetch, stripFilenames = true) => { - return { - ...opts, - body: await createForm(opts.body, fetch, stripFilenames) - }; -}; -var 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; -} -var createForm = async (body, fetch, stripFilenames = true) => { - 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, stripFilenames))); - return form; -}; -var isNamedBlob = (value) => value instanceof Blob && "name" in value; -var addFormValue = async (form, key, value, stripFilenames) => { - 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) { - let options = {}; - const contentType = value.headers.get("Content-Type"); - if (contentType) options = { type: contentType }; - form.append(key, makeFile([await value.blob()], getName(value, stripFilenames), options)); - } else if (isAsyncIterable(value)) form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value, stripFilenames))); - else if (isNamedBlob(value)) form.append(key, makeFile([value], getName(value, stripFilenames), { type: value.type })); - else if (Array.isArray(value)) await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry, stripFilenames))); - else if (typeof value === "object") await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop, stripFilenames))); - else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/to-file.mjs -/** -* This check adds the arrayBuffer() method type because it is available and used at runtime -*/ -var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; -/** -* This check adds the arrayBuffer() method type because it is available and used at runtime -*/ -var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); -var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; -/** -* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats -* @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts -* @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible -* @param {Object=} options additional properties -* @param {string=} options.type the MIME type of the content -* @param {number=} options.lastModified the last modified timestamp -* @returns a {@link File} with the given properties -*/ -async function toFile(value, name, options) { - checkFileSupport(); - value = await value; - name || (name = getName(value, true)); - if (isFileLike(value)) { - if (value instanceof File && name == null && options == null) return value; - return makeFile([await value.arrayBuffer()], name ?? value.name, { - type: value.type, - lastModified: value.lastModified, - ...options - }); - } - if (isResponseLike(value)) { - const blob = await value.blob(); - name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); - return makeFile(await getBytes(blob), name, options); - } - const parts = await getBytes(value); - if (!options?.type) { - const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); - if (typeof type === "string") options = { - ...options, - type - }; - } - return makeFile(parts, name, options); -} -async function getBytes(value) { - let parts = []; - if (typeof value === "string" || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) parts.push(value); - else if (isBlobLike(value)) parts.push(value instanceof Blob ? value : await value.arrayBuffer()); - else if (isAsyncIterable(value)) for await (const chunk of value) parts.push(...await getBytes(chunk)); - else { - const constructor = value?.constructor?.name; - throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); - } - return parts; -} -function propsForError(value) { - if (typeof value !== "object" || value === null) return ""; - return `; props: [${Object.getOwnPropertyNames(value).map((p) => `"${p}"`).join(", ")}]`; -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/core/resource.mjs -var APIResource = class { - constructor(client) { - this._client = client; - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/headers.mjs -var brand_privateNullableHeaders = Symbol.for("brand.privateNullableHeaders"); -function* iterateHeaders(headers) { - if (!headers) return; - if (brand_privateNullableHeaders in headers) { - const { values, nulls } = headers; - yield* values.entries(); - for (const name of nulls) yield [name, null]; - return; - } - let shouldClear = false; - let iter; - if (headers instanceof Headers) iter = headers.entries(); - else if (isReadonlyArray(headers)) iter = headers; - else { - shouldClear = true; - iter = Object.entries(headers ?? {}); - } - for (let row of iter) { - const name = row[0]; - if (typeof name !== "string") throw new TypeError("expected header name to be a string"); - const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; - let didClear = false; - for (const value of values) { - if (value === void 0) continue; - if (shouldClear && !didClear) { - didClear = true; - yield [name, clearSentinel]; - } - yield [name, value]; - } - } -} -/** Distinguishes iterateHeaders' synthetic clear-before-set from a user `null`. */ -var clearSentinel = Symbol("clear"); -/** -* Headers whose values accumulate across {@link buildHeaders} sources instead -* of the later source's value replacing the earlier one. Values are -* comma-appended (deduplicated, order-preserving) into a single header line. -*/ -var APPEND_HEADERS = /* @__PURE__ */ new Set(["x-stainless-helper"]); -var appendHeaderValue = (existing, addition) => { - const tokens = existing ? existing.split(",").map((t) => t.trim()).filter(Boolean) : []; - for (const tok of addition.split(",").map((t) => t.trim())) if (tok && !tokens.includes(tok)) tokens.push(tok); - return tokens.join(", "); -}; -var buildHeaders = (newHeaders) => { - const targetHeaders = new Headers(); - const nullHeaders = /* @__PURE__ */ new Set(); - for (const headers of newHeaders) { - const seenHeaders = /* @__PURE__ */ new Set(); - for (const [name, value] of iterateHeaders(headers)) { - const lowerName = name.toLowerCase(); - if (APPEND_HEADERS.has(lowerName)) { - if (value === clearSentinel) continue; - if (value === null) { - targetHeaders.delete(name); - nullHeaders.add(lowerName); - } else { - targetHeaders.set(name, appendHeaderValue(targetHeaders.get(name), value)); - nullHeaders.delete(lowerName); - } - continue; - } - if (value === clearSentinel || !seenHeaders.has(lowerName)) { - targetHeaders.delete(name); - seenHeaders.add(lowerName); - if (value === clearSentinel) continue; - } - if (value === null) { - targetHeaders.delete(name); - nullHeaders.add(lowerName); - } else { - targetHeaders.append(name, value); - nullHeaders.delete(lowerName); - } - } - } - return { - [brand_privateNullableHeaders]: true, - values: targetHeaders, - nulls: nullHeaders - }; -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/utils/path.mjs -/** -* Percent-encode everything that isn't safe to have in a path without encoding safe chars. -* -* Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: -* > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" -* > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" -* > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" -*/ -function encodeURIPath(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); -} -var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); -var createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { - if (statics.length === 1) return statics[0]; - let postPath = false; - const invalidSegments = []; - const path = statics.reduce((previousValue, currentValue, index) => { - if (/[?#]/.test(currentValue)) postPath = true; - const value = params[index]; - let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); - if (index !== params.length && (value == null || typeof value === "object" && value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { - encoded = value + ""; - invalidSegments.push({ - start: previousValue.length + currentValue.length, - length: encoded.length, - error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` - }); - } - return previousValue + currentValue + (index === params.length ? "" : encoded); - }, ""); - const pathOnly = path.split(/[?#]/, 1)[0]; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match; - while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) invalidSegments.push({ - start: match.index, - length: match[0].length, - error: `Value "${match[0]}" can\'t be safely passed as a path parameter` - }); - invalidSegments.sort((a, b) => a.start - b.start); - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = " ".repeat(segment.start - lastEnd); - const arrows = "^".repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ""); - throw new AnthropicError(`Path parameters result in path with invalid segments:\n${invalidSegments.map((e) => e.error).join("\n")}\n${path}\n${underline}`); - } - return path; -}; -/** -* URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. -*/ -var path$2 = /* @__PURE__ */ createPathTagFunction(encodeURIPath); -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/deployment-runs.mjs -var DeploymentRuns = class extends APIResource { - /** - * Get Deployment Run - * - * @example - * ```ts - * const betaManagedAgentsDeploymentRun = - * await client.beta.deploymentRuns.retrieve( - * 'deployment_run_id', - * ); - * ``` - */ - retrieve(deploymentRunID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/deployment_runs/${deploymentRunID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * List Deployment Runs - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsDeploymentRun of client.beta.deploymentRuns.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/deployment_runs?beta=true", PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/deployments.mjs -var Deployments = class extends APIResource { - /** - * Create Deployment - * - * @example - * ```ts - * const betaManagedAgentsDeployment = - * await client.beta.deployments.create({ - * agent: 'string', - * environment_id: 'x', - * initial_events: [ - * { - * content: [ - * { - * text: 'Where is my order #1234?', - * type: 'text', - * }, - * ], - * type: 'user.message', - * }, - * ], - * name: 'x', - * }); - * ``` - */ - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/deployments?beta=true", { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Get Deployment - * - * @example - * ```ts - * const betaManagedAgentsDeployment = - * await client.beta.deployments.retrieve( - * 'depl_011CZkZcDH3vPqd7xnEfwTai', - * ); - * ``` - */ - retrieve(deploymentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/deployments/${deploymentID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Update Deployment - * - * @example - * ```ts - * const betaManagedAgentsDeployment = - * await client.beta.deployments.update( - * 'depl_011CZkZcDH3vPqd7xnEfwTai', - * ); - * ``` - */ - update(deploymentID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/deployments/${deploymentID}?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * List Deployments - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsDeployment of client.beta.deployments.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/deployments?beta=true", PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Archive Deployment - * - * @example - * ```ts - * const betaManagedAgentsDeployment = - * await client.beta.deployments.archive( - * 'depl_011CZkZcDH3vPqd7xnEfwTai', - * ); - * ``` - */ - archive(deploymentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/deployments/${deploymentID}/archive?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Pause Deployment - * - * @example - * ```ts - * const betaManagedAgentsDeployment = - * await client.beta.deployments.pause( - * 'depl_011CZkZcDH3vPqd7xnEfwTai', - * ); - * ``` - */ - pause(deploymentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/deployments/${deploymentID}/pause?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Run Deployment Now - * - * @example - * ```ts - * const betaManagedAgentsDeploymentRun = - * await client.beta.deployments.run( - * 'depl_011CZkZcDH3vPqd7xnEfwTai', - * ); - * ``` - */ - run(deploymentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/deployments/${deploymentID}/run?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Unpause Deployment - * - * @example - * ```ts - * const betaManagedAgentsDeployment = - * await client.beta.deployments.unpause( - * 'depl_011CZkZcDH3vPqd7xnEfwTai', - * ); - * ``` - */ - unpause(deploymentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/deployments/${deploymentID}/unpause?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/dreams.mjs -var Dreams = class extends APIResource { - /** - * Create a Dream - * - * @example - * ```ts - * const betaDream = await client.beta.dreams.create({ - * inputs: [{ memory_store_id: 'x', type: 'memory_store' }], - * model: 'string', - * }); - * ``` - */ - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/dreams?beta=true", { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString() }, options?.headers]) - }); - } - /** - * Get a Dream - * - * @example - * ```ts - * const betaDream = await client.beta.dreams.retrieve( - * 'dream_id', - * ); - * ``` - */ - retrieve(dreamID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/dreams/${dreamID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString() }, options?.headers]) - }); - } - /** - * List Dreams - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaDream of client.beta.dreams.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/dreams?beta=true", PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString() }, options?.headers]) - }); - } - /** - * Archive a Dream - * - * @example - * ```ts - * const betaDream = await client.beta.dreams.archive( - * 'dream_id', - * ); - * ``` - */ - archive(dreamID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/dreams/${dreamID}/archive?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString() }, options?.headers]) - }); - } - /** - * Cancel a Dream - * - * @example - * ```ts - * const betaDream = await client.beta.dreams.cancel( - * 'dream_id', - * ); - * ``` - */ - cancel(dreamID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/dreams/${dreamID}/cancel?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString() }, options?.headers]) - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/stainless-helper-header.mjs -/** -* Single source of truth for the `x-stainless-helper` telemetry header — the -* key, the closed value vocabulary, and per-object helper tagging. The -* append-don't-clobber merge for the header itself lives in -* {@link import('../internal/headers').buildHeaders} via `APPEND_HEADERS`. -*/ -/** -* Telemetry header naming the SDK helper(s) a request came from. Always this -* lowercase form; `buildHeaders` matches it case-insensitively for its append -* semantics, but a single canonical casing keeps every call site greppable. -*/ -var STAINLESS_HELPER_HEADER = "x-stainless-helper"; -/** Telemetry header naming the SDK method (e.g. `stream`) in use. */ -var STAINLESS_HELPER_METHOD_HEADER = "x-stainless-helper-method"; -/** -* The `{ 'x-stainless-helper': value }` header dict, for passing into -* `buildHeaders` (which comma-appends `x-stainless-helper` across sources) -* or as `defaultHeaders`/per-request `headers`. -*/ -function helperHeader(value) { - return { [STAINLESS_HELPER_HEADER]: value }; -} -/** -* Symbol used to mark objects created by SDK helpers for tracking. -* The value is the helper name (e.g., 'mcpTool', 'betaZodTool'). -*/ -var SDK_HELPER_SYMBOL = Symbol("anthropic.sdk.stainlessHelper"); -function wasCreatedByStainlessHelper(value) { - return typeof value === "object" && value !== null && SDK_HELPER_SYMBOL in value; -} -/** -* Collects helper names from tools and messages arrays. -* Returns a deduplicated array of helper names found. -*/ -function collectStainlessHelpers(tools, messages) { - const helpers = /* @__PURE__ */ new Set(); - if (tools) { - for (const tool of tools) if (wasCreatedByStainlessHelper(tool)) helpers.add(tool[SDK_HELPER_SYMBOL]); - } - if (messages) for (const message of messages) { - if (wasCreatedByStainlessHelper(message)) helpers.add(message[SDK_HELPER_SYMBOL]); - const content = message.content; - if (Array.isArray(content)) { - for (const block of content) if (wasCreatedByStainlessHelper(block)) helpers.add(block[SDK_HELPER_SYMBOL]); - } - } - return Array.from(helpers); -} -/** -* Builds x-stainless-helper header value from tools and messages. -* Returns an empty object if no helpers are found. -*/ -function stainlessHelperHeader(tools, messages) { - const helpers = collectStainlessHelpers(tools, messages); - if (helpers.length === 0) return {}; - return { [STAINLESS_HELPER_HEADER]: helpers.join(", ") }; -} -/** -* Builds x-stainless-helper header value from a file object. -* Returns an empty object if the file is not marked with a helper. -*/ -function stainlessHelperHeaderFromFile(file) { - if (wasCreatedByStainlessHelper(file)) return { [STAINLESS_HELPER_HEADER]: file[SDK_HELPER_SYMBOL] }; - return {}; -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/files.mjs -var Files = class extends APIResource { - /** - * List Files - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const fileMetadata of client.beta.files.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/files?beta=true", Page, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, options?.headers]) - }); - } - /** - * Delete File - * - * @example - * ```ts - * const deletedFile = await client.beta.files.delete( - * 'file_id', - * ); - * ``` - */ - delete(fileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path$2`/v1/files/${fileID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, options?.headers]) - }); - } - /** - * Download File - * - * @example - * ```ts - * const response = await client.beta.files.download( - * 'file_id', - * ); - * - * const content = await response.blob(); - * console.log(content); - * ``` - */ - download(fileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/files/${fileID}/content?beta=true`, { - ...options, - headers: buildHeaders([{ - "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString(), - Accept: "application/binary" - }, options?.headers]), - __binaryResponse: true - }); - } - /** - * Get File Metadata - * - * @example - * ```ts - * const fileMetadata = - * await client.beta.files.retrieveMetadata('file_id'); - * ``` - */ - retrieveMetadata(fileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/files/${fileID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, options?.headers]) - }); - } - /** - * Upload File - * - * @example - * ```ts - * const fileMetadata = await client.beta.files.upload({ - * file: fs.createReadStream('path/to/file'), - * }); - * ``` - */ - upload(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/files?beta=true", multipartFormRequestOptions({ - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, - stainlessHelperHeaderFromFile(body.file), - options?.headers - ]) - }, this._client)); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/models.mjs -var Models$1 = class extends APIResource { - /** - * Get a specific model. - * - * The Models API response can be used to determine information about a specific - * model or resolve a model alias to a model ID. - * - * @example - * ```ts - * const betaModelInfo = await client.beta.models.retrieve( - * 'model_id', - * ); - * ``` - */ - retrieve(modelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/models/${modelID}?beta=true`, { - ...options, - headers: buildHeaders([{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, options?.headers]) - }); - } - /** - * List available models. - * - * The Models API response can be used to determine which models are available for - * use in the API. More recently released models are listed first. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaModelInfo of client.beta.models.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/models?beta=true", Page, { - query, - ...options, - headers: buildHeaders([{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, options?.headers]) - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/user-profiles.mjs -var UserProfiles = class extends APIResource { - /** - * Create User Profile - * - * @example - * ```ts - * const betaUserProfile = - * await client.beta.userProfiles.create(); - * ``` - */ - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/user_profiles?beta=true", { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, options?.headers]) - }); - } - /** - * Get User Profile - * - * @example - * ```ts - * const betaUserProfile = - * await client.beta.userProfiles.retrieve( - * 'uprof_011CZkZCu8hGbp5mYRQgUmz9', - * ); - * ``` - */ - retrieve(userProfileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/user_profiles/${userProfileID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, options?.headers]) - }); - } - /** - * Update User Profile - * - * @example - * ```ts - * const betaUserProfile = - * await client.beta.userProfiles.update( - * 'uprof_011CZkZCu8hGbp5mYRQgUmz9', - * ); - * ``` - */ - update(userProfileID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/user_profiles/${userProfileID}?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, options?.headers]) - }); - } - /** - * List User Profiles - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaUserProfile of client.beta.userProfiles.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/user_profiles?beta=true", PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, options?.headers]) - }); - } - /** - * Create Enrollment URL - * - * @example - * ```ts - * const betaUserProfileEnrollmentURL = - * await client.beta.userProfiles.createEnrollmentURL( - * 'uprof_011CZkZCu8hGbp5mYRQgUmz9', - * ); - * ``` - */ - createEnrollmentURL(userProfileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/user_profiles/${userProfileID}/enrollment_url?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, options?.headers]) - }); - } -}; -//#endregion -//#region node_modules/standardwebhooks/dist/timing_safe_equal.js -var require_timing_safe_equal = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.timingSafeEqual = void 0; - function assert(expr, msg = "") { - if (!expr) throw new Error(msg); - } - function timingSafeEqual(a, b) { - if (a.byteLength !== b.byteLength) return false; - if (!(a instanceof DataView)) a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a); - if (!(b instanceof DataView)) b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b); - assert(a instanceof DataView); - assert(b instanceof DataView); - const length = a.byteLength; - let out = 0; - let i = -1; - while (++i < length) out |= a.getUint8(i) ^ b.getUint8(i); - return out === 0; - } - exports.timingSafeEqual = timingSafeEqual; -})); -//#endregion -//#region node_modules/@stablelib/base64/lib/base64.js -var require_base64 = /* @__PURE__ */ __commonJSMin(((exports) => { - var __extends = exports && exports.__extends || (function() { - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d, b) { - d.__proto__ = b; - } || function(d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - }; - return extendStatics(d, b); - }; - return function(d, b) { - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - })(); - Object.defineProperty(exports, "__esModule", { value: true }); - /** - * Package base64 implements Base64 encoding and decoding. - */ - var INVALID_BYTE = 256; - /** - * Implements standard Base64 encoding. - * - * Operates in constant time. - */ - var Coder = function() { - function Coder(_paddingCharacter) { - if (_paddingCharacter === void 0) _paddingCharacter = "="; - this._paddingCharacter = _paddingCharacter; - } - Coder.prototype.encodedLength = function(length) { - if (!this._paddingCharacter) return (length * 8 + 5) / 6 | 0; - return (length + 2) / 3 * 4 | 0; - }; - Coder.prototype.encode = function(data) { - var out = ""; - var i = 0; - for (; i < data.length - 2; i += 3) { - var c = data[i] << 16 | data[i + 1] << 8 | data[i + 2]; - out += this._encodeByte(c >>> 18 & 63); - out += this._encodeByte(c >>> 12 & 63); - out += this._encodeByte(c >>> 6 & 63); - out += this._encodeByte(c >>> 0 & 63); - } - var left = data.length - i; - if (left > 0) { - var c = data[i] << 16 | (left === 2 ? data[i + 1] << 8 : 0); - out += this._encodeByte(c >>> 18 & 63); - out += this._encodeByte(c >>> 12 & 63); - if (left === 2) out += this._encodeByte(c >>> 6 & 63); - else out += this._paddingCharacter || ""; - out += this._paddingCharacter || ""; - } - return out; - }; - Coder.prototype.maxDecodedLength = function(length) { - if (!this._paddingCharacter) return (length * 6 + 7) / 8 | 0; - return length / 4 * 3 | 0; - }; - Coder.prototype.decodedLength = function(s) { - return this.maxDecodedLength(s.length - this._getPaddingLength(s)); - }; - Coder.prototype.decode = function(s) { - if (s.length === 0) return /* @__PURE__ */ new Uint8Array(0); - var paddingLength = this._getPaddingLength(s); - var length = s.length - paddingLength; - var out = new Uint8Array(this.maxDecodedLength(length)); - var op = 0; - var i = 0; - var haveBad = 0; - var v0 = 0, v1 = 0, v2 = 0, v3 = 0; - for (; i < length - 4; i += 4) { - v0 = this._decodeChar(s.charCodeAt(i + 0)); - v1 = this._decodeChar(s.charCodeAt(i + 1)); - v2 = this._decodeChar(s.charCodeAt(i + 2)); - v3 = this._decodeChar(s.charCodeAt(i + 3)); - out[op++] = v0 << 2 | v1 >>> 4; - out[op++] = v1 << 4 | v2 >>> 2; - out[op++] = v2 << 6 | v3; - haveBad |= v0 & INVALID_BYTE; - haveBad |= v1 & INVALID_BYTE; - haveBad |= v2 & INVALID_BYTE; - haveBad |= v3 & INVALID_BYTE; - } - if (i < length - 1) { - v0 = this._decodeChar(s.charCodeAt(i)); - v1 = this._decodeChar(s.charCodeAt(i + 1)); - out[op++] = v0 << 2 | v1 >>> 4; - haveBad |= v0 & INVALID_BYTE; - haveBad |= v1 & INVALID_BYTE; - } - if (i < length - 2) { - v2 = this._decodeChar(s.charCodeAt(i + 2)); - out[op++] = v1 << 4 | v2 >>> 2; - haveBad |= v2 & INVALID_BYTE; - } - if (i < length - 3) { - v3 = this._decodeChar(s.charCodeAt(i + 3)); - out[op++] = v2 << 6 | v3; - haveBad |= v3 & INVALID_BYTE; - } - if (haveBad !== 0) throw new Error("Base64Coder: incorrect characters for decoding"); - return out; - }; - Coder.prototype._encodeByte = function(b) { - var result = b; - result += 65; - result += 25 - b >>> 8 & 6; - result += 51 - b >>> 8 & -75; - result += 61 - b >>> 8 & -15; - result += 62 - b >>> 8 & 3; - return String.fromCharCode(result); - }; - Coder.prototype._decodeChar = function(c) { - var result = INVALID_BYTE; - result += (42 - c & c - 44) >>> 8 & -INVALID_BYTE + c - 43 + 62; - result += (46 - c & c - 48) >>> 8 & -INVALID_BYTE + c - 47 + 63; - result += (47 - c & c - 58) >>> 8 & -INVALID_BYTE + c - 48 + 52; - result += (64 - c & c - 91) >>> 8 & -INVALID_BYTE + c - 65 + 0; - result += (96 - c & c - 123) >>> 8 & -INVALID_BYTE + c - 97 + 26; - return result; - }; - Coder.prototype._getPaddingLength = function(s) { - var paddingLength = 0; - if (this._paddingCharacter) { - for (var i = s.length - 1; i >= 0; i--) { - if (s[i] !== this._paddingCharacter) break; - paddingLength++; - } - if (s.length < 4 || paddingLength > 2) throw new Error("Base64Coder: incorrect padding"); - } - return paddingLength; - }; - return Coder; - }(); - exports.Coder = Coder; - var stdCoder = new Coder(); - function encode(data) { - return stdCoder.encode(data); - } - exports.encode = encode; - function decode(s) { - return stdCoder.decode(s); - } - exports.decode = decode; - /** - * Implements URL-safe Base64 encoding. - * (Same as Base64, but '+' is replaced with '-', and '/' with '_'). - * - * Operates in constant time. - */ - var URLSafeCoder = function(_super) { - __extends(URLSafeCoder, _super); - function URLSafeCoder() { - return _super !== null && _super.apply(this, arguments) || this; - } - URLSafeCoder.prototype._encodeByte = function(b) { - var result = b; - result += 65; - result += 25 - b >>> 8 & 6; - result += 51 - b >>> 8 & -75; - result += 61 - b >>> 8 & -13; - result += 62 - b >>> 8 & 49; - return String.fromCharCode(result); - }; - URLSafeCoder.prototype._decodeChar = function(c) { - var result = INVALID_BYTE; - result += (44 - c & c - 46) >>> 8 & -INVALID_BYTE + c - 45 + 62; - result += (94 - c & c - 96) >>> 8 & -INVALID_BYTE + c - 95 + 63; - result += (47 - c & c - 58) >>> 8 & -INVALID_BYTE + c - 48 + 52; - result += (64 - c & c - 91) >>> 8 & -INVALID_BYTE + c - 65 + 0; - result += (96 - c & c - 123) >>> 8 & -INVALID_BYTE + c - 97 + 26; - return result; - }; - return URLSafeCoder; - }(Coder); - exports.URLSafeCoder = URLSafeCoder; - var urlSafeCoder = new URLSafeCoder(); - function encodeURLSafe(data) { - return urlSafeCoder.encode(data); - } - exports.encodeURLSafe = encodeURLSafe; - function decodeURLSafe(s) { - return urlSafeCoder.decode(s); - } - exports.decodeURLSafe = decodeURLSafe; - exports.encodedLength = function(length) { - return stdCoder.encodedLength(length); - }; - exports.maxDecodedLength = function(length) { - return stdCoder.maxDecodedLength(length); - }; - exports.decodedLength = function(s) { - return stdCoder.decodedLength(s); - }; -})); -//#endregion -//#region node_modules/fast-sha256/sha256.js -var require_sha256 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - (function(root, factory) { - var exports$1 = {}; - factory(exports$1); - var sha256 = exports$1["default"]; - for (var k in exports$1) sha256[k] = exports$1[k]; - if (typeof module === "object" && typeof module.exports === "object") module.exports = sha256; - else if (typeof define === "function" && define.amd) define(function() { - return sha256; - }); - else root.sha256 = sha256; - })(exports, function(exports$2) { - "use strict"; - exports$2.__esModule = true; - exports$2.digestLength = 32; - exports$2.blockSize = 64; - var K = new Uint32Array([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 - ]); - function hashBlocks(w, v, p, pos, len) { - var a, b, c, d, e, f, g, h, u, i, j, t1, t2; - while (len >= 64) { - a = v[0]; - b = v[1]; - c = v[2]; - d = v[3]; - e = v[4]; - f = v[5]; - g = v[6]; - h = v[7]; - for (i = 0; i < 16; i++) { - j = pos + i * 4; - w[i] = (p[j] & 255) << 24 | (p[j + 1] & 255) << 16 | (p[j + 2] & 255) << 8 | p[j + 3] & 255; - } - for (i = 16; i < 64; i++) { - u = w[i - 2]; - t1 = (u >>> 17 | u << 15) ^ (u >>> 19 | u << 13) ^ u >>> 10; - u = w[i - 15]; - t2 = (u >>> 7 | u << 25) ^ (u >>> 18 | u << 14) ^ u >>> 3; - w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0); - } - for (i = 0; i < 64; i++) { - t1 = (((e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7)) + (e & f ^ ~e & g) | 0) + (h + (K[i] + w[i] | 0) | 0) | 0; - t2 = ((a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10)) + (a & b ^ a & c ^ b & c) | 0; - h = g; - g = f; - f = e; - e = d + t1 | 0; - d = c; - c = b; - b = a; - a = t1 + t2 | 0; - } - v[0] += a; - v[1] += b; - v[2] += c; - v[3] += d; - v[4] += e; - v[5] += f; - v[6] += g; - v[7] += h; - pos += 64; - len -= 64; - } - return pos; - } - var Hash = function() { - function Hash() { - this.digestLength = exports$2.digestLength; - this.blockSize = exports$2.blockSize; - this.state = /* @__PURE__ */ new Int32Array(8); - this.temp = /* @__PURE__ */ new Int32Array(64); - this.buffer = /* @__PURE__ */ new Uint8Array(128); - this.bufferLength = 0; - this.bytesHashed = 0; - this.finished = false; - this.reset(); - } - Hash.prototype.reset = function() { - this.state[0] = 1779033703; - this.state[1] = 3144134277; - this.state[2] = 1013904242; - this.state[3] = 2773480762; - this.state[4] = 1359893119; - this.state[5] = 2600822924; - this.state[6] = 528734635; - this.state[7] = 1541459225; - this.bufferLength = 0; - this.bytesHashed = 0; - this.finished = false; - return this; - }; - Hash.prototype.clean = function() { - for (var i = 0; i < this.buffer.length; i++) this.buffer[i] = 0; - for (var i = 0; i < this.temp.length; i++) this.temp[i] = 0; - this.reset(); - }; - Hash.prototype.update = function(data, dataLength) { - if (dataLength === void 0) dataLength = data.length; - if (this.finished) throw new Error("SHA256: can't update because hash was finished."); - var dataPos = 0; - this.bytesHashed += dataLength; - if (this.bufferLength > 0) { - while (this.bufferLength < 64 && dataLength > 0) { - this.buffer[this.bufferLength++] = data[dataPos++]; - dataLength--; - } - if (this.bufferLength === 64) { - hashBlocks(this.temp, this.state, this.buffer, 0, 64); - this.bufferLength = 0; - } - } - if (dataLength >= 64) { - dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength); - dataLength %= 64; - } - while (dataLength > 0) { - this.buffer[this.bufferLength++] = data[dataPos++]; - dataLength--; - } - return this; - }; - Hash.prototype.finish = function(out) { - if (!this.finished) { - var bytesHashed = this.bytesHashed; - var left = this.bufferLength; - var bitLenHi = bytesHashed / 536870912 | 0; - var bitLenLo = bytesHashed << 3; - var padLength = bytesHashed % 64 < 56 ? 64 : 128; - this.buffer[left] = 128; - for (var i = left + 1; i < padLength - 8; i++) this.buffer[i] = 0; - this.buffer[padLength - 8] = bitLenHi >>> 24 & 255; - this.buffer[padLength - 7] = bitLenHi >>> 16 & 255; - this.buffer[padLength - 6] = bitLenHi >>> 8 & 255; - this.buffer[padLength - 5] = bitLenHi >>> 0 & 255; - this.buffer[padLength - 4] = bitLenLo >>> 24 & 255; - this.buffer[padLength - 3] = bitLenLo >>> 16 & 255; - this.buffer[padLength - 2] = bitLenLo >>> 8 & 255; - this.buffer[padLength - 1] = bitLenLo >>> 0 & 255; - hashBlocks(this.temp, this.state, this.buffer, 0, padLength); - this.finished = true; - } - for (var i = 0; i < 8; i++) { - out[i * 4 + 0] = this.state[i] >>> 24 & 255; - out[i * 4 + 1] = this.state[i] >>> 16 & 255; - out[i * 4 + 2] = this.state[i] >>> 8 & 255; - out[i * 4 + 3] = this.state[i] >>> 0 & 255; - } - return this; - }; - Hash.prototype.digest = function() { - var out = new Uint8Array(this.digestLength); - this.finish(out); - return out; - }; - Hash.prototype._saveState = function(out) { - for (var i = 0; i < this.state.length; i++) out[i] = this.state[i]; - }; - Hash.prototype._restoreState = function(from, bytesHashed) { - for (var i = 0; i < this.state.length; i++) this.state[i] = from[i]; - this.bytesHashed = bytesHashed; - this.finished = false; - this.bufferLength = 0; - }; - return Hash; - }(); - exports$2.Hash = Hash; - var HMAC = function() { - function HMAC(key) { - this.inner = new Hash(); - this.outer = new Hash(); - this.blockSize = this.inner.blockSize; - this.digestLength = this.inner.digestLength; - var pad = new Uint8Array(this.blockSize); - if (key.length > this.blockSize) new Hash().update(key).finish(pad).clean(); - else for (var i = 0; i < key.length; i++) pad[i] = key[i]; - for (var i = 0; i < pad.length; i++) pad[i] ^= 54; - this.inner.update(pad); - for (var i = 0; i < pad.length; i++) pad[i] ^= 106; - this.outer.update(pad); - this.istate = /* @__PURE__ */ new Uint32Array(8); - this.ostate = /* @__PURE__ */ new Uint32Array(8); - this.inner._saveState(this.istate); - this.outer._saveState(this.ostate); - for (var i = 0; i < pad.length; i++) pad[i] = 0; - } - HMAC.prototype.reset = function() { - this.inner._restoreState(this.istate, this.inner.blockSize); - this.outer._restoreState(this.ostate, this.outer.blockSize); - return this; - }; - HMAC.prototype.clean = function() { - for (var i = 0; i < this.istate.length; i++) this.ostate[i] = this.istate[i] = 0; - this.inner.clean(); - this.outer.clean(); - }; - HMAC.prototype.update = function(data) { - this.inner.update(data); - return this; - }; - HMAC.prototype.finish = function(out) { - if (this.outer.finished) this.outer.finish(out); - else { - this.inner.finish(out); - this.outer.update(out, this.digestLength).finish(out); - } - return this; - }; - HMAC.prototype.digest = function() { - var out = new Uint8Array(this.digestLength); - this.finish(out); - return out; - }; - return HMAC; - }(); - exports$2.HMAC = HMAC; - function hash(data) { - var h = new Hash().update(data); - var digest = h.digest(); - h.clean(); - return digest; - } - exports$2.hash = hash; - exports$2["default"] = hash; - function hmac(key, data) { - var h = new HMAC(key).update(data); - var digest = h.digest(); - h.clean(); - return digest; - } - exports$2.hmac = hmac; - function fillBuffer(buffer, hmac, info, counter) { - var num = counter[0]; - if (num === 0) throw new Error("hkdf: cannot expand more"); - hmac.reset(); - if (num > 1) hmac.update(buffer); - if (info) hmac.update(info); - hmac.update(counter); - hmac.finish(buffer); - counter[0]++; - } - var hkdfSalt = new Uint8Array(exports$2.digestLength); - function hkdf(key, salt, info, length) { - if (salt === void 0) salt = hkdfSalt; - if (length === void 0) length = 32; - var counter = new Uint8Array([1]); - var hmac_ = new HMAC(hmac(salt, key)); - var buffer = new Uint8Array(hmac_.digestLength); - var bufpos = buffer.length; - var out = new Uint8Array(length); - for (var i = 0; i < length; i++) { - if (bufpos === buffer.length) { - fillBuffer(buffer, hmac_, info, counter); - bufpos = 0; - } - out[i] = buffer[bufpos++]; - } - hmac_.clean(); - buffer.fill(0); - counter.fill(0); - return out; - } - exports$2.hkdf = hkdf; - function pbkdf2(password, salt, iterations, dkLen) { - var prf = new HMAC(password); - var len = prf.digestLength; - var ctr = /* @__PURE__ */ new Uint8Array(4); - var t = new Uint8Array(len); - var u = new Uint8Array(len); - var dk = new Uint8Array(dkLen); - for (var i = 0; i * len < dkLen; i++) { - var c = i + 1; - ctr[0] = c >>> 24 & 255; - ctr[1] = c >>> 16 & 255; - ctr[2] = c >>> 8 & 255; - ctr[3] = c >>> 0 & 255; - prf.reset(); - prf.update(salt); - prf.update(ctr); - prf.finish(u); - for (var j = 0; j < len; j++) t[j] = u[j]; - for (var j = 2; j <= iterations; j++) { - prf.reset(); - prf.update(u).finish(u); - for (var k = 0; k < len; k++) t[k] ^= u[k]; - } - for (var j = 0; j < len && i * len + j < dkLen; j++) dk[i * len + j] = t[j]; - } - for (var i = 0; i < len; i++) t[i] = u[i] = 0; - for (var i = 0; i < 4; i++) ctr[i] = 0; - prf.clean(); - return dk; - } - exports$2.pbkdf2 = pbkdf2; - }); -})); -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/webhooks.mjs -var import_dist = (/* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Webhook = exports.WebhookVerificationError = void 0; - var timing_safe_equal_1 = require_timing_safe_equal(); - var base64 = require_base64(); - var sha256 = require_sha256(); - var WEBHOOK_TOLERANCE_IN_SECONDS = 300; - var ExtendableError = class ExtendableError extends Error { - constructor(message) { - super(message); - Object.setPrototypeOf(this, ExtendableError.prototype); - this.name = "ExtendableError"; - this.stack = new Error(message).stack; - } - }; - var WebhookVerificationError = class WebhookVerificationError extends ExtendableError { - constructor(message) { - super(message); - Object.setPrototypeOf(this, WebhookVerificationError.prototype); - this.name = "WebhookVerificationError"; - } - }; - exports.WebhookVerificationError = WebhookVerificationError; - var Webhook = class Webhook { - constructor(secret, options) { - if (!secret) throw new Error("Secret can't be empty."); - if ((options === null || options === void 0 ? void 0 : options.format) === "raw") if (secret instanceof Uint8Array) this.key = secret; - else this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0)); - else { - if (typeof secret !== "string") throw new Error("Expected secret to be of type string"); - if (secret.startsWith(Webhook.prefix)) secret = secret.substring(Webhook.prefix.length); - this.key = base64.decode(secret); - } - } - verify(payload, headers_) { - const headers = {}; - for (const key of Object.keys(headers_)) headers[key.toLowerCase()] = headers_[key]; - const msgId = headers["webhook-id"]; - const msgSignature = headers["webhook-signature"]; - const msgTimestamp = headers["webhook-timestamp"]; - if (!msgSignature || !msgId || !msgTimestamp) throw new WebhookVerificationError("Missing required headers"); - const timestamp = this.verifyTimestamp(msgTimestamp); - const expectedSignature = this.sign(msgId, timestamp, payload).split(",")[1]; - const passedSignatures = msgSignature.split(" "); - const encoder = new globalThis.TextEncoder(); - for (const versionedSignature of passedSignatures) { - const [version, signature] = versionedSignature.split(","); - if (version !== "v1") continue; - if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) return JSON.parse(payload.toString()); - } - throw new WebhookVerificationError("No matching signature found"); - } - sign(msgId, timestamp, payload) { - if (typeof payload === "string") {} else if (payload.constructor.name === "Buffer") payload = payload.toString(); - else throw new Error("Expected payload to be of type string or Buffer."); - const encoder = new TextEncoder(); - const timestampNumber = Math.floor(timestamp.getTime() / 1e3); - const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`); - return `v1,${base64.encode(sha256.hmac(this.key, toSign))}`; - } - verifyTimestamp(timestampHeader) { - const now = Math.floor(Date.now() / 1e3); - const timestamp = parseInt(timestampHeader, 10); - if (isNaN(timestamp)) throw new WebhookVerificationError("Invalid Signature Headers"); - if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) throw new WebhookVerificationError("Message timestamp too old"); - if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) throw new WebhookVerificationError("Message timestamp too new"); - return /* @__PURE__ */ new Date(timestamp * 1e3); - } - }; - exports.Webhook = Webhook; - Webhook.prefix = "whsec_"; -})))(); -var Webhooks = class extends APIResource { - unwrap(body, { headers, key }) { - if (headers !== void 0) { - const keyStr = key === void 0 ? this._client.webhookKey : key; - if (keyStr === null) throw new Error("Webhook key must not be null in order to unwrap"); - new import_dist.Webhook(keyStr).verify(body, headers); - } - return JSON.parse(body); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/agents/versions.mjs -var Versions$1 = class extends APIResource { - /** - * List Agent Versions - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsAgent of client.beta.agents.versions.list( - * 'agent_011CZkYpogX7uDKUyvBTophP', - * )) { - * // ... - * } - * ``` - */ - list(agentID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList(path$2`/v1/agents/${agentID}/versions?beta=true`, PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/agents/agents.mjs -var Agents = class extends APIResource { - constructor() { - super(...arguments); - this.versions = new Versions$1(this._client); - } - /** - * Create Agent - * - * @example - * ```ts - * const betaManagedAgentsAgent = - * await client.beta.agents.create({ - * model: 'claude-sonnet-4-6', - * name: 'My First Agent', - * }); - * ``` - */ - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/agents?beta=true", { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Get Agent - * - * @example - * ```ts - * const betaManagedAgentsAgent = - * await client.beta.agents.retrieve( - * 'agent_011CZkYpogX7uDKUyvBTophP', - * ); - * ``` - */ - retrieve(agentID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.get(path$2`/v1/agents/${agentID}?beta=true`, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Update Agent - * - * @example - * ```ts - * const betaManagedAgentsAgent = - * await client.beta.agents.update( - * 'agent_011CZkYpogX7uDKUyvBTophP', - * { description: 'updated' }, - * ); - * ``` - */ - update(agentID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/agents/${agentID}?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * List Agents - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsAgent of client.beta.agents.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/agents?beta=true", PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Archive Agent - * - * @example - * ```ts - * const betaManagedAgentsAgent = - * await client.beta.agents.archive( - * 'agent_011CZkYpogX7uDKUyvBTophP', - * ); - * ``` - */ - archive(agentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/agents/${agentID}/archive?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } -}; -Agents.Versions = Versions$1; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/utils/abort.mjs -/** -* Chain an external {@link AbortSignal} into a local {@link AbortController}: -* the controller aborts whenever `external` aborts (synchronously if it is -* already aborted). -* -* Returns a cleanup function that detaches the listener. Callers MUST invoke it -* on their normal teardown path — `{ once: true }` only removes the listener if -* abort actually fires, so a long-lived `external` signal (e.g. a daemon-wide -* signal reused across many short-lived controllers) would otherwise leak one -* listener per controller. -*/ -function linkAbort(external, controller) { - if (!external) return () => {}; - if (external.aborted) { - controller.abort(); - return () => {}; - } - const onAbort = () => controller.abort(); - external.addEventListener("abort", onAbort); - return () => external.removeEventListener("abort", onAbort); -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/utils/backoff.mjs -/** True when `e` is an {@link APIError} whose HTTP status equals `code`. */ -function isStatus(e, code) { - return e instanceof APIError && e.status === code; -} -/** True when `e` is an {@link APIError} with a 4xx status. */ -function is4xx(e) { - return e instanceof APIError && typeof e.status === "number" && e.status >= 400 && e.status < 500; -} -/** -* True for a 4xx that the core client's retry policy would *not* retry, i.e. a -* permanent client error. 408 (request timeout), 409 (lock timeout) and 429 -* (rate limit) are retryable for the base client (`Anthropic.shouldRetry`), so -* they are not treated as fatal here — keeping helper retry behaviour aligned -* with the rest of the SDK. -*/ -function isFatal4xx(e) { - return is4xx(e) && !isStatus(e, 408) && !isStatus(e, 409) && !isStatus(e, 429); -} -/** Exponential backoff: `baseMs * 2 ** attempt`, clamped to `capMs`. */ -function backoff$1(attempt, baseMs, capMs) { - return Math.min(baseMs * 2 ** attempt, capMs); -} -/** Uniform random delay in the half-open interval `[lowMs, highMs)`. */ -function jitter(lowMs, highMs) { - return lowMs + Math.random() * (highMs - lowMs); -} -/** -* Trim up to 25% off `ms` at random so a fleet of clients backing off after a -* shared outage does not retry in lockstep — mirrors the jitter the core client -* applies to its own retry timeout. -*/ -function applyJitter(ms) { - return ms * (1 - Math.random() * .25); -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/helper-client.mjs -/** -* Return a `withOptions()` clone of `client` set up for use *by* one of the -* runner helpers: authenticated with `authToken` as Bearer credentials, with -* the parent's `X-Api-Key` cleared, and tagged with the helper's -* `x-stainless-helper` value on every outgoing request. -* -* The returned sub-client inherits the parent's full configuration -* (`baseURL`, `timeout`, `maxRetries`, `fetch`, `fetchOptions`, custom -* `defaultHeaders`, `defaultQuery`). Overrides applied: -* -* - `authToken: authToken` — the new credential. -* - `apiKey: null` — the parent's `X-Api-Key` is cleared. `withOptions` -* inherits the parent's `apiKey` by default; without this, both -* `X-Api-Key` *and* `Authorization: Bearer …` would land on the wire. -* `client.ts` only triggers the env-var fallback when `apiKey === undefined`, -* so explicit `null` is honored. -* - `credentials: undefined` — opts the clone out of any inherited -* credentials/config/profile so the explicit bearer is the unambiguous auth. -* - `baseURL: client.baseURL` — pins the parent's resolved host (auth override otherwise resets it). -* - `defaultHeaders` is rebuilt as `parent._authState.extraHeaders ⊕ parent.defaultHeaders ⊕ -* {'x-stainless-helper': helper}`. `withOptions` *replaces* (does not -* merge) `defaultHeaders`, so we merge here so any custom headers the -* caller set on the parent client survive on the sub-client. -*/ -function copyClientForHelper(client, { authToken, helper }) { - if (!authToken) throw new AnthropicError(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(authToken)}`); - const internal = client; - const parentDefaults = internal._options.defaultHeaders; - const parentAuthExtraHeaders = internal._authState?.extraHeaders; - const defaultHeaders = buildHeaders([ - parentAuthExtraHeaders ? Object.fromEntries(Object.entries(parentAuthExtraHeaders).filter(([name]) => { - const lower = name.toLowerCase(); - return lower !== "authorization" && lower !== "x-api-key"; - })) : void 0, - parentDefaults, - { [STAINLESS_HELPER_HEADER]: helper } - ]); - return client.withOptions({ - apiKey: null, - authToken, - baseURL: client.baseURL, - credentials: void 0, - defaultHeaders - }); -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/environments/poller.mjs -var _WorkPoller_runnerClient; -var _WorkPoller_consumed; -var _WorkPoller_controller; -var _WorkPoller_detachExternal; -var _WorkPoller_autoStop; -var _WorkPoller_drain; -var _WorkPoller_blockMs; -var _WorkPoller_reclaimOlderThanMs; -var _WorkPoller_requestOpts; -var POLL_BACKOFF_BASE_MS = 1e3; -var POLL_BACKOFF_CAP_MS = 6e4; -/** -* Async-iterable that long-polls a self-hosted environment for work, ack's -* each item, yields the {@link BetaSelfHostedWork} item, and posts `stop` after -* the consumer's loop body returns (or when the consumer `break`s). -* -* @example -* ```ts -* for await (const work of client.beta.environments.work.poller({ -* environmentId, -* environmentKey, -* })) { -* // ...service the work... -* } -* ``` -*/ -var WorkPoller = class { - constructor(opts) { - _WorkPoller_runnerClient.set(this, void 0); - _WorkPoller_consumed.set(this, false); - _WorkPoller_controller.set(this, void 0); - _WorkPoller_detachExternal.set(this, void 0); - _WorkPoller_autoStop.set(this, void 0); - _WorkPoller_drain.set(this, void 0); - _WorkPoller_blockMs.set(this, void 0); - _WorkPoller_reclaimOlderThanMs.set(this, void 0); - _WorkPoller_requestOpts.set(this, void 0); - this.client = opts.client; - this.environmentId = opts.environmentId; - this.environmentKey = opts.environmentKey; - this.workerId = opts.workerId ?? defaultWorkerId(); - __classPrivateFieldSet(this, _WorkPoller_runnerClient, copyClientForHelper(opts.client, { - authToken: opts.environmentKey, - helper: "environments-work-poller" - }), "f"); - __classPrivateFieldSet(this, _WorkPoller_autoStop, opts.autoStop ?? true, "f"); - __classPrivateFieldSet(this, _WorkPoller_drain, opts.drain ?? false, "f"); - __classPrivateFieldSet(this, _WorkPoller_blockMs, opts.blockMs === void 0 ? 999 : opts.blockMs, "f"); - __classPrivateFieldSet(this, _WorkPoller_reclaimOlderThanMs, opts.reclaimOlderThanMs ?? null, "f"); - __classPrivateFieldSet(this, _WorkPoller_requestOpts, opts.requestOptions, "f"); - __classPrivateFieldSet(this, _WorkPoller_controller, new AbortController(), "f"); - __classPrivateFieldSet(this, _WorkPoller_detachExternal, linkAbort(opts.signal, __classPrivateFieldGet(this, _WorkPoller_controller, "f")), "f"); - } - /** Read-only view of this iterator's abort signal. */ - get signal() { - return __classPrivateFieldGet(this, _WorkPoller_controller, "f").signal; - } - /** Abort the iterator. The current `for await` will exit cleanly. */ - abort() { - __classPrivateFieldGet(this, _WorkPoller_controller, "f").abort(); - } - async *[(_WorkPoller_runnerClient = /* @__PURE__ */ new WeakMap(), _WorkPoller_consumed = /* @__PURE__ */ new WeakMap(), _WorkPoller_controller = /* @__PURE__ */ new WeakMap(), _WorkPoller_detachExternal = /* @__PURE__ */ new WeakMap(), _WorkPoller_autoStop = /* @__PURE__ */ new WeakMap(), _WorkPoller_drain = /* @__PURE__ */ new WeakMap(), _WorkPoller_blockMs = /* @__PURE__ */ new WeakMap(), _WorkPoller_reclaimOlderThanMs = /* @__PURE__ */ new WeakMap(), _WorkPoller_requestOpts = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { - if (__classPrivateFieldGet(this, _WorkPoller_consumed, "f")) throw new AnthropicError("Cannot iterate over a consumed WorkPoller"); - __classPrivateFieldSet(this, _WorkPoller_consumed, true, "f"); - const log = loggerFor(this.client); - log.info("poller starting", { - component: "work-poller", - environment_id: this.environmentId - }); - try { - let attempt = 0; - while (!__classPrivateFieldGet(this, _WorkPoller_controller, "f").signal.aborted) { - let work; - try { - work = await __classPrivateFieldGet(this, _WorkPoller_runnerClient, "f").beta.environments.work.poll(this.environmentId, { - "Anthropic-Worker-ID": this.workerId, - ...__classPrivateFieldGet(this, _WorkPoller_blockMs, "f") !== null ? { block_ms: __classPrivateFieldGet(this, _WorkPoller_blockMs, "f") } : {}, - ...__classPrivateFieldGet(this, _WorkPoller_reclaimOlderThanMs, "f") !== null ? { reclaim_older_than_ms: __classPrivateFieldGet(this, _WorkPoller_reclaimOlderThanMs, "f") } : {} - }, { - headers: buildHeaders([__classPrivateFieldGet(this, _WorkPoller_requestOpts, "f")?.headers]), - signal: __classPrivateFieldGet(this, _WorkPoller_controller, "f").signal - }); - } catch (e) { - if (__classPrivateFieldGet(this, _WorkPoller_controller, "f").signal.aborted) return; - if (isFatal4xx(e)) { - log.error("poll failed permanently, stopping poller", { error: String(e) }); - throw e; - } - const wait = applyJitter(backoff(attempt)); - log.warn("poll failed, backing off", { - error: String(e), - backoff_ms: wait - }); - attempt++; - await sleep(wait, __classPrivateFieldGet(this, _WorkPoller_controller, "f").signal); - continue; - } - attempt = 0; - if (work == null) { - if (__classPrivateFieldGet(this, _WorkPoller_drain, "f")) return; - await sleep(jitter(1e3, 3e3), __classPrivateFieldGet(this, _WorkPoller_controller, "f").signal); - continue; - } - log.info("claimed work", { - component: "work-poller", - environment_id: this.environmentId, - work_id: work.id, - work_type: work.data.type - }); - try { - await __classPrivateFieldGet(this, _WorkPoller_runnerClient, "f").beta.environments.work.ack(work.id, { environment_id: work.environment_id }, { - headers: buildHeaders([__classPrivateFieldGet(this, _WorkPoller_requestOpts, "f")?.headers]), - signal: __classPrivateFieldGet(this, _WorkPoller_controller, "f").signal - }); - } catch (e) { - log.error("ack failed", { - work_id: work.id, - error: String(e) - }); - continue; - } - try { - yield work; - } finally { - if (__classPrivateFieldGet(this, _WorkPoller_autoStop, "f")) try { - await __classPrivateFieldGet(this, _WorkPoller_runnerClient, "f").beta.environments.work.stop(work.id, { environment_id: work.environment_id }, { headers: buildHeaders([__classPrivateFieldGet(this, _WorkPoller_requestOpts, "f")?.headers]) }); - } catch (e) { - if (!isStatus(e, 409)) log.warn("stop failed", { - work_id: work.id, - error: String(e) - }); - } - } - } - } finally { - __classPrivateFieldGet(this, _WorkPoller_detachExternal, "f").call(this); - } - } -}; -/** Exponential poll backoff: 1s, 2s, 4s … clamped to a 60s cap. */ -function backoff(attempt) { - return backoff$1(attempt, POLL_BACKOFF_BASE_MS, POLL_BACKOFF_CAP_MS); -} -function defaultWorkerId() { - const host = (globalThis.process?.env)?.["HOSTNAME"]; - return host ? `${host}-${uuid4()}` : uuid4(); -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/utils/async-queue.mjs -var _AsyncQueue_items; -var _AsyncQueue_waiters; -var _AsyncQueue_closed; -/** -* Single-consumer async queue that bridges background producers to an -* `AsyncIterator`-style reader. Producers `push()` items; the consumer awaits -* `next()`. `close()` is idempotent and wakes any pending `next()` with -* `done: true`. `tryShift()` synchronously drains remaining items after -* iteration has been signalled to stop. -*/ -var AsyncQueue = class { - constructor() { - _AsyncQueue_items.set(this, []); - _AsyncQueue_waiters.set(this, []); - _AsyncQueue_closed.set(this, false); - } - /** Enqueue an item, or hand it directly to a waiting reader. Returns `false` once closed. */ - push(item) { - if (__classPrivateFieldGet(this, _AsyncQueue_closed, "f")) return false; - const w = __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").shift(); - if (w) w({ - done: false, - value: item - }); - else __classPrivateFieldGet(this, _AsyncQueue_items, "f").push(item); - return true; - } - /** Mark the queue done. Idempotent; wakes every pending reader with `done: true`. */ - close() { - if (__classPrivateFieldGet(this, _AsyncQueue_closed, "f")) return; - __classPrivateFieldSet(this, _AsyncQueue_closed, true, "f"); - while (__classPrivateFieldGet(this, _AsyncQueue_waiters, "f").length > 0) __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").shift()({ - done: true, - value: void 0 - }); - } - /** - * Resolve with the next item, or `done: true` once the queue is closed and - * drained. When `signal` is supplied, aborting it resolves a pending read - * with `done: true` (cancellation is pushed down here rather than handled by - * an outer `Promise.race`). - */ - next(signal) { - if (__classPrivateFieldGet(this, _AsyncQueue_items, "f").length > 0) return Promise.resolve({ - done: false, - value: __classPrivateFieldGet(this, _AsyncQueue_items, "f").shift() - }); - if (__classPrivateFieldGet(this, _AsyncQueue_closed, "f") || signal?.aborted) return Promise.resolve({ - done: true, - value: void 0 - }); - return new Promise((resolve) => { - const waiter = (r) => { - signal?.removeEventListener("abort", onAbort); - resolve(r); - }; - const onAbort = () => { - const idx = __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").indexOf(waiter); - if (idx >= 0) __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").splice(idx, 1); - resolve({ - done: true, - value: void 0 - }); - }; - __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").push(waiter); - signal?.addEventListener("abort", onAbort, { once: true }); - }); - } - /** Synchronously remove and return the next buffered item, or `undefined` if empty. */ - tryShift() { - return __classPrivateFieldGet(this, _AsyncQueue_items, "f").shift(); - } -}; -_AsyncQueue_items = /* @__PURE__ */ new WeakMap(), _AsyncQueue_waiters = /* @__PURE__ */ new WeakMap(), _AsyncQueue_closed = /* @__PURE__ */ new WeakMap(); -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/tools/BetaRunnableTool.mjs -/** -* Resolve the registry key for a tool — the name the model addresses it by. -* MCP toolsets are keyed on `mcp_server_name`; every other tool on `name`. -* Shared so the tool-name lookup is identical across `toolRunner()` surfaces. -*/ -function toolName(tool) { - return "name" in tool ? tool.name : tool.mcp_server_name; -} -/** -* Format a thrown value into tool-result content: a {@link ToolError} carries -* its own structured content, anything else becomes an `Error: ` -* string. Shared so every `toolRunner()` surface reports tool failures the -* same way to the model. -*/ -function toolErrorContent(e) { - return e instanceof ToolError ? e.content : `Error: ${e instanceof Error ? e.message : String(e)}`; -} -/** -* Run a {@link BetaRunnableTool} end-to-end: parse the raw input, invoke `run`, -* and format any thrown value via {@link toolErrorContent}. Shared so the -* parse → run → catch → format pipeline is identical across `toolRunner()` -* surfaces. -*/ -async function runRunnableTool(tool, rawInput, context) { - try { - const input = tool.parse ? tool.parse(rawInput) : rawInput; - return { - content: await tool.run(input, context), - isError: false - }; - } catch (e) { - return { - content: toolErrorContent(e), - isError: true - }; - } -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/tools/SessionToolRunner.mjs -var _IdleClock_maxIdleMs; -var _IdleClock_onExpire; -var _IdleClock_blockers; -var _IdleClock_armPending; -var _IdleClock_timer; -var _SessionToolRunner_instances; -var _SessionToolRunner_consumed; -var _SessionToolRunner_controller; -var _SessionToolRunner_detachExternal; -var _SessionToolRunner_requestOpts; -var _SessionToolRunner_toolByName; -var _SessionToolRunner_logger; -var _SessionToolRunner_seen; -var _SessionToolRunner_answered; -var _SessionToolRunner_confirmationVerdicts; -var _SessionToolRunner_awaitingConfirmation; -var _SessionToolRunner_results; -var _SessionToolRunner_inFlightCount; -var _SessionToolRunner_onIdle; -var _SessionToolRunner_idleClock; -var _SessionToolRunner_requestOptions; -var _SessionToolRunner_streamLoop; -var _SessionToolRunner_reconcile; -var _SessionToolRunner_ingestHistory; -var _SessionToolRunner_handleStreamEvent; -var _SessionToolRunner_routeToolEvent; -var _SessionToolRunner_noteConfirmation; -var _SessionToolRunner_applyVerdict; -var _SessionToolRunner_surfaceCall; -var _SessionToolRunner_execute; -var _SessionToolRunner_sendResult; -var _SessionToolRunner_drain; -var STREAM_BACKOFF_START_MS = 500; -var STREAM_BACKOFF_CAP_MS = 1e4; -var TOOL_TIMEOUT_MS = 12e4; -var DRAIN_TIMEOUT_MS = 3e4; -var SEND_RETRIES = 3; -/** Returns true if `ev` is a `session.status_idle` with `stop_reason` `end_turn`. */ -function isEndTurnIdle(ev) { - return ev.type === "session.status_idle" && ev.stop_reason?.type === "end_turn"; -} -/** -* The `maxIdleMs` stop-countdown, including its deferral. {@link noteEvent} -* arms on `session.status_idle` with `stop_reason: end_turn` and disarms on -* anything else. Gated tool work registered via {@link block} — a call held for -* user confirmation, or a user-approved call still dispatching — keeps -* {@link arm} pending until {@link unblock} retires the last blocker, at which -* point the countdown starts. Event-driven — there is no polling watchdog. -*/ -var IdleClock = class { - constructor(maxIdleMs, onExpire) { - _IdleClock_maxIdleMs.set(this, void 0); - _IdleClock_onExpire.set(this, void 0); - _IdleClock_blockers.set(this, /* @__PURE__ */ new Set()); - _IdleClock_armPending.set(this, false); - _IdleClock_timer.set(this, void 0); - __classPrivateFieldSet(this, _IdleClock_maxIdleMs, maxIdleMs, "f"); - __classPrivateFieldSet(this, _IdleClock_onExpire, onExpire, "f"); - } - /** - * Arm on `status_idle{end_turn}`; disarm otherwise. `user.tool_confirmation` - * is neutral: it signals neither agent activity nor an idle, and its effect - * on the clock flows through {@link block} / {@link unblock} instead — - * disarming here would discard the pending arm the verdict is about to - * settle. - */ - noteEvent(ev) { - if (ev.type === "user.tool_confirmation") return; - if (isEndTurnIdle(ev)) this.arm(); - else this.disarm(); - } - /** Register gated work that must resolve before an idle countdown starts. */ - block(toolUseId) { - __classPrivateFieldGet(this, _IdleClock_blockers, "f").add(toolUseId); - if (__classPrivateFieldGet(this, _IdleClock_timer, "f") !== void 0) { - __classPrivateFieldSet(this, _IdleClock_armPending, true, "f"); - clearTimeout(__classPrivateFieldGet(this, _IdleClock_timer, "f")); - __classPrivateFieldSet(this, _IdleClock_timer, void 0, "f"); - } - } - /** - * Retire gated work (a no-op for ids never blocked); applies a pending arm — - * with a fresh full `maxIdleMs` window — once the last blocker retires. - */ - unblock(toolUseId) { - __classPrivateFieldGet(this, _IdleClock_blockers, "f").delete(toolUseId); - if (__classPrivateFieldGet(this, _IdleClock_blockers, "f").size === 0 && __classPrivateFieldGet(this, _IdleClock_armPending, "f")) this.arm(); - } - /** - * (Re)start the idle countdown — or, while blockers are outstanding, hold - * the arm pending instead. Stopping then would drop a held call when its - * verdict later arrives, or cut the runner off before a released call's - * result can drive the next turn. - */ - arm() { - if (__classPrivateFieldGet(this, _IdleClock_maxIdleMs, "f") <= 0) return; - if (__classPrivateFieldGet(this, _IdleClock_blockers, "f").size > 0) { - __classPrivateFieldSet(this, _IdleClock_armPending, true, "f"); - return; - } - __classPrivateFieldSet(this, _IdleClock_armPending, false, "f"); - if (__classPrivateFieldGet(this, _IdleClock_timer, "f") !== void 0) clearTimeout(__classPrivateFieldGet(this, _IdleClock_timer, "f")); - __classPrivateFieldSet(this, _IdleClock_timer, setTimeout(__classPrivateFieldGet(this, _IdleClock_onExpire, "f"), __classPrivateFieldGet(this, _IdleClock_maxIdleMs, "f")), "f"); - } - /** - * Cancel the idle countdown and any pending arm. Blockers persist — they - * track real outstanding work, retired only by {@link unblock}. - */ - disarm() { - __classPrivateFieldSet(this, _IdleClock_armPending, false, "f"); - if (__classPrivateFieldGet(this, _IdleClock_timer, "f") !== void 0) { - clearTimeout(__classPrivateFieldGet(this, _IdleClock_timer, "f")); - __classPrivateFieldSet(this, _IdleClock_timer, void 0, "f"); - } - } -}; -_IdleClock_maxIdleMs = /* @__PURE__ */ new WeakMap(), _IdleClock_onExpire = /* @__PURE__ */ new WeakMap(), _IdleClock_blockers = /* @__PURE__ */ new WeakMap(), _IdleClock_armPending = /* @__PURE__ */ new WeakMap(), _IdleClock_timer = /* @__PURE__ */ new WeakMap(); -/** -* The sessions-side counterpart to `client.beta.messages.toolRunner`: an -* async-iterable that attaches to a managed-agents session, executes every -* incoming `agent.tool_use` and `agent.custom_tool_use` event against a local -* tool registry, posts the matching result back (`user.tool_result` for the -* former, `user.custom_tool_result` for the latter), and yields one -* {@link DispatchedToolCall} per completed call. Server-side `agent.mcp_tool_use` -* calls are not dispatched. Internally drives event-stream reconnect and result -* posting. -* -* A call the server gated with `evaluated_permission: "ask"` (the `always_ask` -* policy — or any value this SDK doesn't recognize, which fails closed) is held -* until its `user.tool_confirmation` arrives: only an explicit `allow` runs it; -* `deny` — or any verdict this SDK doesn't recognize, failing closed — is never -* executed and posts nothing (the denial resolves the call server-side), but is -* still yielded (`confirmation="deny"`, `posted=false`, `result=undefined`) so -* the consumer can observe it. A held call — and a user-approved one still -* dispatching — defers the `maxIdleMs` countdown, so an `end_turn` idle -* observed in the meantime cannot stop the runner: it waits until the verdict -* arrives, the session terminates, or the abort signal fires — pass -* `AbortSignal.timeout(...)` for a wall-clock bound. -* -* Iteration ends when the session terminates (`session.status_terminated` / -* `session.deleted`), when the consumer `break`s out of the loop or aborts the -* supplied signal, or — once the session has gone idle with -* `stop_reason.type === "end_turn"` — when `maxIdleMs` elapses with no new -* event (any new event resets that countdown; it re-arms on the next `end_turn` -* idle; `maxIdleMs <= 0` disables it). The `finally` branch drains any in-flight -* tool calls and runs each tool's `close()` cleanup hook. It does *not* touch -* the work-item lease — wrap it in an `EnvironmentWorker` if you need -* heartbeating / force-stop. -* -* @example -* ```ts -* import { betaAgentToolset20260401 } from '@anthropic-ai/sdk/tools/agent-toolset/node'; -* -* for await (const call of client.beta.sessions.events.toolRunner(work.data.id, { -* tools: [...betaAgentToolset20260401({ workdir }), myTool], -* })) { -* console.log(`${call.name} -> ${call.isError ? 'error' : 'ok'}`); -* } -* ``` -*/ -var SessionToolRunner = class { - constructor(sessionId, opts) { - _SessionToolRunner_instances.add(this); - _SessionToolRunner_consumed.set(this, false); - _SessionToolRunner_controller.set(this, void 0); - _SessionToolRunner_detachExternal.set(this, void 0); - _SessionToolRunner_requestOpts.set(this, void 0); - _SessionToolRunner_toolByName.set(this, void 0); - _SessionToolRunner_logger.set(this, void 0); - _SessionToolRunner_seen.set(this, /* @__PURE__ */ new Set()); - _SessionToolRunner_answered.set(this, /* @__PURE__ */ new Set()); - _SessionToolRunner_confirmationVerdicts.set(this, /* @__PURE__ */ new Map()); - _SessionToolRunner_awaitingConfirmation.set(this, /* @__PURE__ */ new Map()); - _SessionToolRunner_results.set(this, new AsyncQueue()); - _SessionToolRunner_inFlightCount.set(this, 0); - _SessionToolRunner_onIdle.set(this, null); - _SessionToolRunner_idleClock.set(this, void 0); - this.client = opts.client; - this.sessionId = sessionId; - this.tools = opts.tools; - this.maxIdleMs = opts.maxIdleMs ?? 6e4; - __classPrivateFieldSet(this, _SessionToolRunner_logger, loggerFor(opts.client), "f"); - __classPrivateFieldSet(this, _SessionToolRunner_toolByName, new Map(opts.tools.map((t) => [toolName(t), t])), "f"); - __classPrivateFieldSet(this, _SessionToolRunner_controller, new AbortController(), "f"); - __classPrivateFieldSet(this, _SessionToolRunner_detachExternal, linkAbort(opts.signal, __classPrivateFieldGet(this, _SessionToolRunner_controller, "f")), "f"); - __classPrivateFieldSet(this, _SessionToolRunner_requestOpts, opts.requestOptions, "f"); - __classPrivateFieldSet(this, _SessionToolRunner_idleClock, new IdleClock(this.maxIdleMs, () => { - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("session idle after end_turn; stopping", { - component: "session-tool-runner", - session_id: this.sessionId, - max_idle_ms: this.maxIdleMs - }); - __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").abort(); - }), "f"); - } - /** Read-only view of this runner's abort signal. */ - get signal() { - return __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").signal; - } - /** Abort the runner. Background tasks will wind down and `for await` will exit cleanly. */ - abort() { - __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").abort(); - } - async *[(_SessionToolRunner_consumed = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_controller = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_detachExternal = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_requestOpts = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_toolByName = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_logger = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_seen = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_answered = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_confirmationVerdicts = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_awaitingConfirmation = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_results = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_inFlightCount = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_onIdle = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_idleClock = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() { - if (__classPrivateFieldGet(this, _SessionToolRunner_consumed, "f")) throw new AnthropicError("Cannot iterate over a consumed SessionToolRunner"); - __classPrivateFieldSet(this, _SessionToolRunner_consumed, true, "f"); - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("session tool runner starting", { - component: "session-tool-runner", - session_id: this.sessionId - }); - const streamPromise = __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_streamLoop).call(this).catch((e) => { - if (!__classPrivateFieldGet(this, _SessionToolRunner_controller, "f").signal.aborted) __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").error("stream loop failed", { error: String(e) }); - __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").abort(); - }); - try { - while (true) { - const next = await __classPrivateFieldGet(this, _SessionToolRunner_results, "f").next(__classPrivateFieldGet(this, _SessionToolRunner_controller, "f").signal); - if (next.done) break; - yield next.value; - } - await streamPromise; - let pending; - while ((pending = __classPrivateFieldGet(this, _SessionToolRunner_results, "f").tryShift()) !== void 0) yield pending; - } finally { - __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").abort(); - __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").disarm(); - await streamPromise; - try { - await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_drain).call(this); - } catch (e) { - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").warn("drain failed", { error: String(e) }); - } - __classPrivateFieldGet(this, _SessionToolRunner_results, "f").close(); - for (const t of this.tools) try { - await t.close?.(); - } catch (e) { - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").warn("tool.close failed", { - tool: toolName(t), - error: String(e) - }); - } - __classPrivateFieldGet(this, _SessionToolRunner_detachExternal, "f").call(this); - } - } -}; -_SessionToolRunner_requestOptions = function _SessionToolRunner_requestOptions() { - return { - ...__classPrivateFieldGet(this, _SessionToolRunner_requestOpts, "f"), - headers: buildHeaders([helperHeader("session-tool-runner"), __classPrivateFieldGet(this, _SessionToolRunner_requestOpts, "f")?.headers]), - signal: __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").signal - }; -}, _SessionToolRunner_streamLoop = async function _SessionToolRunner_streamLoop() { - const ctrl = __classPrivateFieldGet(this, _SessionToolRunner_controller, "f"); - let backoff = STREAM_BACKOFF_START_MS; - while (!ctrl.signal.aborted) { - try { - const stream = await this.client.beta.sessions.events.stream(this.sessionId, {}, __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_requestOptions).call(this)); - await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_reconcile).call(this); - for await (const ev of stream) { - backoff = STREAM_BACKOFF_START_MS; - if (await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_handleStreamEvent).call(this, ev)) return; - } - } catch (e) { - ctrl.signal.throwIfAborted(); - if (isFatal4xx(e)) { - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").error("permanent stream failure, shutting down", { error: String(e) }); - ctrl.abort(); - throw e; - } - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").warn("stream disconnected, reconnecting", { - error: String(e), - backoff_ms: backoff - }); - } - ctrl.signal.throwIfAborted(); - await sleep(backoff, ctrl.signal); - backoff = Math.min(backoff * 2, STREAM_BACKOFF_CAP_MS); - } -}, _SessionToolRunner_reconcile = async function _SessionToolRunner_reconcile() { - const ctrl = __classPrivateFieldGet(this, _SessionToolRunner_controller, "f"); - const pending = []; - let lastWasEndTurn = false; - try { - for await (const ev of this.client.beta.sessions.events.list(this.sessionId, { limit: 1e3 }, __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_requestOptions).call(this))) { - __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_ingestHistory).call(this, ev, pending); - lastWasEndTurn = isEndTurnIdle(ev); - } - } catch (e) { - ctrl.signal.throwIfAborted(); - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").warn("reconcile list failed", { error: String(e) }); - for (const ev of pending) __classPrivateFieldGet(this, _SessionToolRunner_seen, "f").delete(ev.id); - return; - } - const unanswered = pending.filter((ev) => !__classPrivateFieldGet(this, _SessionToolRunner_answered, "f").has(ev.id)); - __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").disarm(); - for (const ev of unanswered) await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_routeToolEvent).call(this, ev); - for (const held of [...__classPrivateFieldGet(this, _SessionToolRunner_awaitingConfirmation, "f").values()]) { - const verdict = __classPrivateFieldGet(this, _SessionToolRunner_confirmationVerdicts, "f").get(held.id); - if (verdict !== void 0) await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_applyVerdict).call(this, held, verdict); - } - const outstanding = unanswered.filter((ev) => !__classPrivateFieldGet(this, _SessionToolRunner_answered, "f").has(ev.id) && !__classPrivateFieldGet(this, _SessionToolRunner_awaitingConfirmation, "f").has(ev.id)); - if (lastWasEndTurn && outstanding.length === 0) __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").arm(); - else __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").disarm(); -}, _SessionToolRunner_ingestHistory = function _SessionToolRunner_ingestHistory(ev, pending) { - if (ev.type === "agent.tool_use" || ev.type === "agent.custom_tool_use") { - __classPrivateFieldGet(this, _SessionToolRunner_seen, "f").add(ev.id); - if (!__classPrivateFieldGet(this, _SessionToolRunner_answered, "f").has(ev.id)) pending.push(ev); - } else if (ev.type === "user.tool_result") __classPrivateFieldGet(this, _SessionToolRunner_answered, "f").add(ev.tool_use_id); - else if (ev.type === "user.custom_tool_result") __classPrivateFieldGet(this, _SessionToolRunner_answered, "f").add(ev.custom_tool_use_id); - else if (ev.type === "user.tool_confirmation") { - if (!__classPrivateFieldGet(this, _SessionToolRunner_answered, "f").has(ev.tool_use_id)) __classPrivateFieldGet(this, _SessionToolRunner_confirmationVerdicts, "f").set(ev.tool_use_id, ev.result); - } -}, _SessionToolRunner_handleStreamEvent = async function _SessionToolRunner_handleStreamEvent(ev) { - __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").noteEvent(ev); - switch (ev.type) { - case "agent.tool_use": - case "agent.custom_tool_use": - if (!__classPrivateFieldGet(this, _SessionToolRunner_seen, "f").has(ev.id)) { - __classPrivateFieldGet(this, _SessionToolRunner_seen, "f").add(ev.id); - await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_routeToolEvent).call(this, ev); - } - return false; - case "user.tool_confirmation": - await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_noteConfirmation).call(this, ev); - return false; - case "user.tool_result": - __classPrivateFieldGet(this, _SessionToolRunner_answered, "f").add(ev.tool_use_id); - return false; - case "user.custom_tool_result": - __classPrivateFieldGet(this, _SessionToolRunner_answered, "f").add(ev.custom_tool_use_id); - return false; - case "session.status_terminated": - case "session.deleted": - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("session terminated", { - component: "session-tool-runner", - session_id: this.sessionId - }); - __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").abort(); - return true; - default: return false; - } -}, _SessionToolRunner_routeToolEvent = async function _SessionToolRunner_routeToolEvent(ev) { - const permission = ev.evaluated_permission; - const verdict = permission === "deny" ? "deny" : __classPrivateFieldGet(this, _SessionToolRunner_confirmationVerdicts, "f").get(ev.id); - if (verdict === void 0) { - if (permission === void 0 || permission === "allow") await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_execute).call(this, ev, void 0); - else if (!__classPrivateFieldGet(this, _SessionToolRunner_awaitingConfirmation, "f").has(ev.id)) { - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("tool call awaiting confirmation; holding", { - component: "session-tool-runner", - session_id: this.sessionId, - tool: ev.name, - tool_use_id: ev.id - }); - __classPrivateFieldGet(this, _SessionToolRunner_awaitingConfirmation, "f").set(ev.id, ev); - __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").block(ev.id); - } - return; - } - await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_applyVerdict).call(this, ev, verdict); -}, _SessionToolRunner_noteConfirmation = async function _SessionToolRunner_noteConfirmation(ev) { - __classPrivateFieldGet(this, _SessionToolRunner_confirmationVerdicts, "f").set(ev.tool_use_id, ev.result); - const held = __classPrivateFieldGet(this, _SessionToolRunner_awaitingConfirmation, "f").get(ev.tool_use_id); - if (held === void 0) return; - await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_applyVerdict).call(this, held, ev.result); -}, _SessionToolRunner_applyVerdict = async function _SessionToolRunner_applyVerdict(ev, verdict) { - const wasHeld = __classPrivateFieldGet(this, _SessionToolRunner_awaitingConfirmation, "f").delete(ev.id); - if (verdict === "allow") { - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("tool call confirmed", { - component: "session-tool-runner", - session_id: this.sessionId, - tool: ev.name, - tool_use_id: ev.id - }); - if (!wasHeld) __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").block(ev.id); - try { - await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_execute).call(this, ev, "allow"); - } finally { - __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").unblock(ev.id); - } - return; - } - if (wasHeld) __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").unblock(ev.id); - __classPrivateFieldGet(this, _SessionToolRunner_answered, "f").add(ev.id); - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("tool call denied; not executing", { - component: "session-tool-runner", - session_id: this.sessionId, - tool: ev.name, - tool_use_id: ev.id - }); - __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_surfaceCall).call(this, { - event: ev, - toolUseId: ev.id, - name: ev.name, - isError: false, - posted: false, - confirmation: "deny" - }); -}, _SessionToolRunner_surfaceCall = function _SessionToolRunner_surfaceCall(call) { - __classPrivateFieldGet(this, _SessionToolRunner_results, "f").push(call); -}, _SessionToolRunner_execute = async function _SessionToolRunner_execute(ev, confirmation) { - var _a, _b; - if (__classPrivateFieldGet(this, _SessionToolRunner_answered, "f").has(ev.id)) return; - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("executing tool", { - component: "session-tool-runner", - session_id: this.sessionId, - tool: ev.name, - tool_use_id: ev.id - }); - __classPrivateFieldSet(this, _SessionToolRunner_inFlightCount, (_a = __classPrivateFieldGet(this, _SessionToolRunner_inFlightCount, "f"), _a++, _a), "f"); - try { - const tool = __classPrivateFieldGet(this, _SessionToolRunner_toolByName, "f").get(ev.name); - if (!tool) { - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("tool not owned by this runner; leaving the tool_use_id pending for its owner", { - component: "session-tool-runner", - session_id: this.sessionId, - tool: ev.name, - tool_use_id: ev.id - }); - __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_surfaceCall).call(this, { - event: ev, - toolUseId: ev.id, - name: ev.name, - isError: false, - posted: false, - confirmation - }); - return; - } - let content; - let isError; - const toolCtrl = new AbortController(); - const detachTool = linkAbort(__classPrivateFieldGet(this, _SessionToolRunner_controller, "f").signal, toolCtrl); - const timer = setTimeout(() => toolCtrl.abort(), TOOL_TIMEOUT_MS); - try { - const outcome = await runRunnableTool(tool, ev.input, { - toolUse: ev, - toolUseBlock: ev, - signal: toolCtrl.signal - }); - content = outcome.content; - isError = outcome.isError; - } finally { - clearTimeout(timer); - detachTool(); - } - const result = buildResultEvent(ev, isError, toSessionContent(content)); - const posted = await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_sendResult).call(this, result, ev.id); - __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_surfaceCall).call(this, { - event: ev, - result, - toolUseId: ev.id, - name: ev.name, - isError, - posted, - confirmation - }); - } finally { - __classPrivateFieldSet(this, _SessionToolRunner_inFlightCount, (_b = __classPrivateFieldGet(this, _SessionToolRunner_inFlightCount, "f"), _b--, _b), "f"); - if (__classPrivateFieldGet(this, _SessionToolRunner_inFlightCount, "f") === 0) __classPrivateFieldGet(this, _SessionToolRunner_onIdle, "f")?.call(this); - } -}, _SessionToolRunner_sendResult = async function _SessionToolRunner_sendResult(result, toolUseId) { - const ctrl = __classPrivateFieldGet(this, _SessionToolRunner_controller, "f"); - let lastErr; - for (let i = 0; i < SEND_RETRIES; i++) { - ctrl.signal.throwIfAborted(); - try { - await this.client.beta.sessions.events.send(this.sessionId, { events: [result] }, __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_requestOptions).call(this)); - __classPrivateFieldGet(this, _SessionToolRunner_answered, "f").add(toolUseId); - return true; - } catch (e) { - lastErr = e; - if (isFatal4xx(e)) break; - if (i < SEND_RETRIES - 1) await sleep((i + 1) * 1e3, ctrl.signal); - } - } - __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").error("failed to send tool result", { - tool_use_id: toolUseId, - error: String(lastErr) - }); - return false; -}, _SessionToolRunner_drain = async function _SessionToolRunner_drain() { - if (__classPrivateFieldGet(this, _SessionToolRunner_inFlightCount, "f") === 0) return; - await Promise.race([new Promise((r) => __classPrivateFieldSet(this, _SessionToolRunner_onIdle, r, "f")), sleep(DRAIN_TIMEOUT_MS)]); - __classPrivateFieldSet(this, _SessionToolRunner_onIdle, null, "f"); - if (__classPrivateFieldGet(this, _SessionToolRunner_inFlightCount, "f") > 0) __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").warn("drain timeout exceeded"); -}; -/** -* Build the result event that answers `ev`: a `user.tool_result` for a builtin -* `agent.tool_use`, a `user.custom_tool_result` for a custom -* `agent.custom_tool_use`. The two `(use, result)` pairs are distinct API event -* types and must be matched exactly — a `user.tool_result` does not answer a -* custom tool call. -*/ -function buildResultEvent(ev, isError, content) { - if (ev.type === "agent.custom_tool_use") return { - type: "user.custom_tool_result", - custom_tool_use_id: ev.id, - is_error: isError, - content - }; - return { - type: "user.tool_result", - tool_use_id: ev.id, - is_error: isError, - content - }; -} -function toSessionContent(content) { - if (typeof content === "string") return [{ - type: "text", - text: content || "(no output)" - }]; - const out = content.map((b) => { - if (b.type === "text") return { - type: "text", - text: b.text || "(no output)" - }; - if (b.type === "image" || b.type === "document") return b; - if (b.type === "search_result") return { - type: "search_result", - source: b.source, - title: b.title, - content: b.content.map((c) => ({ - type: "text", - text: c.text - })), - citations: { enabled: b.citations?.enabled ?? false } - }; - return { - type: "text", - text: JSON.stringify(b) - }; - }); - return out.length > 0 ? out : [{ - type: "text", - text: "(no output)" - }]; -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/environments/worker.mjs -var _EnvironmentWorker_instances; -var _EnvironmentWorker_signal; -var _EnvironmentWorker_handleItem; -var HEARTBEAT_DEFAULT_MS = 3e4; -var NO_HEARTBEAT_SENTINEL = "NO_HEARTBEAT"; -/** -* The self-hosted environment runner, composed from the control-plane -* {@link WorkPoller} and the per-session {@link SessionToolRunner}. -* -* For each claimed `session` work item it: builds the per-session -* {@link AgentToolContext}, downloads the session agent's skills -* (`setupSkills`), then runs a {@link SessionToolRunner} for the session -* *while* heartbeating the work-item lease in parallel; on exit it force-stops -* the work item, cleans up the downloaded skills, and loops to the next one. The -* lease heartbeat reports `state === "stopping"` / a lost lease back into the run -* by aborting the session runner. -* -* Use {@link EnvironmentWorker.handleItem} if you already hold a claimed work -* item (e.g. a `worker poll --on-work` script handed one to a fresh process) and -* just want the per-item flow without the poll loop — with no arguments it reads -* the `ANTHROPIC_*` env vars that command sets. -* -* Construct it via `client.beta.environments.work.worker({ ... })` (or -* `new EnvironmentWorker({ client, ... })` directly). -* -* @example -* ```ts -* // Long-running daemon: poll for work, serve each session, loop. -* await client.beta.environments.work -* .worker({ environmentId, environmentKey, workdir: '/workspace' }) -* .run(AbortSignal.timeout(60 * 60_000)); -* -* // Already-claimed item (e.g. inside `ant worker poll --on-work ...`): -* await client.beta.environments.work.worker({ workdir: '/workspace' }).handleItem(); -* ``` -*/ -var EnvironmentWorker = class { - constructor(opts) { - _EnvironmentWorker_instances.add(this); - _EnvironmentWorker_signal.set(this, void 0); - this.client = opts.client; - this.environmentId = opts.environmentId; - this.environmentKey = opts.environmentKey; - this.tools = opts.tools; - this.workdir = opts.workdir ?? process.cwd(); - this.unrestrictedPaths = opts.unrestrictedPaths; - this.maxFileBytes = opts.maxFileBytes; - this.maxIdleMs = opts.maxIdleMs; - this.workerId = opts.workerId; - this.requestOptions = opts.requestOptions; - __classPrivateFieldSet(this, _EnvironmentWorker_signal, opts.signal, "f"); - } - /** - * Poll the environment and service each claimed session until the supplied - * signal (or the one passed to the constructor) aborts. Throws if - * `environmentId` / `environmentKey` were not provided to the constructor. - */ - async run(signal) { - const { environmentId, environmentKey } = this; - if (environmentId === void 0 || environmentKey === void 0) throw new AnthropicError("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work"); - const externalSignal = signal ?? __classPrivateFieldGet(this, _EnvironmentWorker_signal, "f"); - const poller = new WorkPoller({ - client: this.client, - environmentId, - environmentKey, - ...this.workerId !== void 0 ? { workerId: this.workerId } : {}, - ...externalSignal ? { signal: externalSignal } : {}, - ...this.requestOptions !== void 0 ? { requestOptions: this.requestOptions } : {}, - autoStop: false - }); - for await (const work of poller) await __classPrivateFieldGet(this, _EnvironmentWorker_instances, "m", _EnvironmentWorker_handleItem).call(this, work, environmentKey, poller.signal); - } - /** - * Service a single, already-claimed work item without the poll loop: build the - * per-session {@link AgentToolContext} (workdir from this worker's options), - * download the session agent's skills (`setupSkills`), run a - * {@link SessionToolRunner} for the session while heartbeating the work-item - * lease in parallel, and force-stop the work item on exit (whether the runner - * finishes normally, throws, or the heartbeat loop signals shutdown). - * - * Use this when something else does the claiming — e.g. a `worker poll - * --on-work` script that hands an already-claimed item to a fresh process. The - * work id / environment id / session id each fall back to `ANTHROPIC_WORK_ID` / - * `ANTHROPIC_ENVIRONMENT_ID` / `ANTHROPIC_SESSION_ID` (the env vars that - * command sets) when not passed; the environment key resolves from this - * option, then the worker's own `environmentKey`, then - * `ANTHROPIC_ENVIRONMENT_KEY`. With no arguments inside that command it just - * works. Throws a clear error naming the first of the four required values - * still missing after resolution. - */ - async handleItem(opts) { - const workId = opts?.workId ?? readEnv("ANTHROPIC_WORK_ID"); - const environmentId = opts?.environmentId ?? readEnv("ANTHROPIC_ENVIRONMENT_ID"); - const sessionId = opts?.sessionId ?? readEnv("ANTHROPIC_SESSION_ID"); - const environmentKey = opts?.environmentKey ?? this.environmentKey ?? readEnv("ANTHROPIC_ENVIRONMENT_KEY"); - if (!workId) throw new AnthropicError("handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID"); - if (!environmentId) throw new AnthropicError("handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID"); - if (!sessionId) throw new AnthropicError("handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID"); - if (!environmentKey) throw new AnthropicError("handleItem: environmentKey is required — pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY"); - const work = { - id: workId, - environment_id: environmentId, - data: { - type: "session", - id: sessionId - } - }; - await __classPrivateFieldGet(this, _EnvironmentWorker_instances, "m", _EnvironmentWorker_handleItem).call(this, work, environmentKey, opts?.signal ?? __classPrivateFieldGet(this, _EnvironmentWorker_signal, "f")); - } -}; -_EnvironmentWorker_signal = /* @__PURE__ */ new WeakMap(), _EnvironmentWorker_instances = /* @__PURE__ */ new WeakSet(), _EnvironmentWorker_handleItem = async function _EnvironmentWorker_handleItem(work, environmentKey, externalSignal) { - const log = loggerFor(this.client); - const sessionClient = copyClientForHelper(this.client, { - authToken: environmentKey, - helper: "environments-worker" - }); - const sessionId = work.data.id; - const ctx = { - workdir: this.workdir, - client: this.client, - sessionId, - ...this.unrestrictedPaths !== void 0 ? { unrestrictedPaths: this.unrestrictedPaths } : {}, - ...this.maxFileBytes !== void 0 ? { maxFileBytes: this.maxFileBytes } : {} - }; - const agentToolset = await Promise.resolve().then(() => node_exports); - let cleanupSkills = async () => {}; - try { - cleanupSkills = await agentToolset.setupSkills(ctx); - } catch (e) { - log.warn("skill setup failed", { - session_id: sessionId, - work_id: work.id, - error: String(e) - }); - } - const tools = typeof this.tools === "function" ? this.tools(ctx) : this.tools ?? agentToolset.betaAgentToolset20260401(ctx); - const ctrl = new AbortController(); - const detachExternal = linkAbort(externalSignal, ctrl); - const heartbeatPromise = heartbeatLoop(sessionClient, work, ctrl, log, this.requestOptions).catch((e) => { - if (!ctrl.signal.aborted) log.error("heartbeat loop failed", { - work_id: work.id, - error: String(e) - }); - ctrl.abort(); - }); - try { - const runner = new SessionToolRunner(sessionId, { - client: sessionClient, - tools, - ...this.maxIdleMs !== void 0 ? { maxIdleMs: this.maxIdleMs } : {}, - ...this.requestOptions !== void 0 ? { requestOptions: this.requestOptions } : {}, - signal: ctrl.signal - }); - for await (const _ of runner); - } finally { - ctrl.abort(); - detachExternal(); - await heartbeatPromise; - await cleanupSkills().catch((e) => { - log.warn("skill cleanup failed", { - session_id: sessionId, - work_id: work.id, - error: String(e) - }); - }); - await forceStop(sessionClient, work, log, this.requestOptions); - } -}; -/** Force-stop a claimed work item, swallowing the 409 that means it's already stopped. */ -async function forceStop(client, work, log, requestOptions) { - try { - await client.beta.environments.work.stop(work.id, { - environment_id: work.environment_id, - force: true - }, { - ...requestOptions, - headers: buildHeaders([requestOptions?.headers]) - }); - } catch (e) { - if (!isStatus(e, 409)) log.error("force-stop on exit failed", { - work_id: work.id, - error: String(e) - }); - } -} -/** -* Keep the work-item lease alive while a session is being served. Aborts `ctrl` -* when the control plane reports the work is `stopping`/`stopped`, when the -* lease is no longer extended, or on a permanent heartbeat failure. -*/ -async function heartbeatLoop(client, work, ctrl, logger, requestOptions) { - let intervalMs = HEARTBEAT_DEFAULT_MS; - let last = NO_HEARTBEAT_SENTINEL; - const beat = async () => { - try { - const resp = await client.beta.environments.work.heartbeat(work.id, { - environment_id: work.environment_id, - expected_last_heartbeat: last - }, { - ...requestOptions, - headers: buildHeaders([requestOptions?.headers]), - signal: ctrl.signal - }); - last = resp.last_heartbeat; - if (resp.ttl_seconds > 0) intervalMs = Math.max(1e3, Math.min(resp.ttl_seconds * 1e3 / 2, HEARTBEAT_DEFAULT_MS)); - if (resp.state === "stopping" || resp.state === "stopped") { - logger.info("heartbeat signals shutdown", { - work_id: work.id, - state: resp.state - }); - ctrl.abort(); - } - if (!resp.lease_extended) { - logger.warn("lease not extended, shutting down", { work_id: work.id }); - ctrl.abort(); - } - } catch (e) { - ctrl.signal.throwIfAborted(); - if (isFatal4xx(e)) { - logger.error("permanent heartbeat failure", { - work_id: work.id, - error: String(e) - }); - ctrl.abort(); - throw e; - } - logger.warn("transient heartbeat failure", { - work_id: work.id, - error: String(e) - }); - } - }; - await beat(); - while (!ctrl.signal.aborted) { - await sleep(intervalMs, ctrl.signal); - ctrl.signal.throwIfAborted(); - await beat(); - } -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/environments/work.mjs -var Work = class extends APIResource { - /** - * Note: these endpoints are called automatically by the pre-built environment - * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted - * sandbox environments. They are included here as a reference; you do not need to - * invoke them directly. - * - * Retrieve detailed information about a specific work item. - * - * @example - * ```ts - * const betaSelfHostedWork = - * await client.beta.environments.work.retrieve('work_id', { - * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * }); - * ``` - */ - retrieve(workID, params, options) { - const { environment_id, betas } = params; - return this._client.get(path$2`/v1/environments/${environment_id}/work/${workID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Note: these endpoints are called automatically by the pre-built environment - * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted - * sandbox environments. They are included here as a reference; you do not need to - * invoke them directly. - * - * Update work item metadata with merge semantics. - * - * @example - * ```ts - * const betaSelfHostedWork = - * await client.beta.environments.work.update('work_id', { - * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * metadata: { foo: 'string' }, - * }); - * ``` - */ - update(workID, params, options) { - const { environment_id, betas, ...body } = params; - return this._client.post(path$2`/v1/environments/${environment_id}/work/${workID}?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Note: these endpoints are called automatically by the pre-built environment - * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted - * sandbox environments. They are included here as a reference; you do not need to - * invoke them directly. - * - * List work items in an environment. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaSelfHostedWork of client.beta.environments.work.list( - * 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * )) { - * // ... - * } - * ``` - */ - list(environmentID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList(path$2`/v1/environments/${environmentID}/work?beta=true`, PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Note: these endpoints are called automatically by the pre-built environment - * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted - * sandbox environments. They are included here as a reference; you do not need to - * invoke them directly. - * - * Acknowledge receipt of a work item, transitioning it from 'queued' to 'starting' - * and removing it from the queue. - * - * @example - * ```ts - * const betaSelfHostedWork = - * await client.beta.environments.work.ack('work_id', { - * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * }); - * ``` - */ - ack(workID, params, options) { - const { environment_id, betas } = params; - return this._client.post(path$2`/v1/environments/${environment_id}/work/${workID}/ack?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Note: these endpoints are called automatically by the pre-built environment - * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted - * sandbox environments. They are included here as a reference; you do not need to - * invoke them directly. - * - * Record a heartbeat for a work item to maintain the lease. - * - * @example - * ```ts - * const betaSelfHostedWorkHeartbeatResponse = - * await client.beta.environments.work.heartbeat('work_id', { - * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * }); - * ``` - */ - heartbeat(workID, params, options) { - const { environment_id, desired_ttl_seconds, expected_last_heartbeat, betas } = params; - return this._client.post(path$2`/v1/environments/${environment_id}/work/${workID}/heartbeat?beta=true`, { - query: { - desired_ttl_seconds, - expected_last_heartbeat - }, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Note: these endpoints are called automatically by the pre-built environment - * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted - * sandbox environments. They are included here as a reference; you do not need to - * invoke them directly. - * - * Long poll for work items in the queue. - * - * @example - * ```ts - * const betaSelfHostedWork = - * await client.beta.environments.work.poll( - * 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * ); - * ``` - */ - poll(environmentID, params = {}, options) { - const { betas, "Anthropic-Worker-ID": anthropicWorkerID, ...query } = params ?? {}; - return this._client.get(path$2`/v1/environments/${environmentID}/work/poll?beta=true`, { - query, - ...options, - headers: buildHeaders([{ - "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(), - ...anthropicWorkerID != null ? { "Anthropic-Worker-ID": anthropicWorkerID } : void 0 - }, options?.headers]) - }); - } - /** - * Get statistics about the work queue for an environment. - * - * @example - * ```ts - * const betaSelfHostedWorkQueueStats = - * await client.beta.environments.work.stats( - * 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * ); - * ``` - */ - stats(environmentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/environments/${environmentID}/work/stats?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Note: these endpoints are called automatically by the pre-built environment - * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted - * sandbox environments. They are included here as a reference; you do not need to - * invoke them directly. - * - * Stop a work item, initiating graceful or forced shutdown. - * - * @example - * ```ts - * const betaSelfHostedWork = - * await client.beta.environments.work.stop('work_id', { - * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * }); - * ``` - */ - stop(workID, params, options) { - const { environment_id, betas, ...body } = params; - return this._client.post(path$2`/v1/environments/${environment_id}/work/${workID}/stop?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Continuously claim work from a self-hosted environment, ack each item, - * and yield it. Posts `stop` automatically when the consumer's loop body - * returns or when iteration ends. - * - * @example - * ```ts - * for await (const work of client.beta.environments.work.poller({ - * environmentId, - * environmentKey, - * })) { - * if (work.data.type !== 'session') continue; - * // ...service the work... - * } - * ``` - */ - poller(opts) { - return new WorkPoller({ - ...opts, - client: this._client - }); - } - /** - * The self-hosted environment runner: poll for work, and for each claimed - * session set up the workdir, download the agent's skills, run the tools while - * heartbeating the lease, and force-stop on exit. - * - * @example - * ```ts - * // Long-running daemon — poll, serve each session, loop: - * await client.beta.environments.work - * .worker({ environmentId, environmentKey, workdir: '/workspace' }) - * .run(); - * - * // Or service one already-claimed work item (e.g. inside a sandbox spawned - * // by `ant worker poll --on-work`) — handleItem() reads the ANTHROPIC_* env vars: - * await client.beta.environments.work.worker({ workdir: '/workspace' }).handleItem(); - * ``` - */ - worker(opts) { - return new EnvironmentWorker({ - ...opts, - client: this._client - }); - } -}; -Work.WorkPoller = WorkPoller; -Work.EnvironmentWorker = EnvironmentWorker; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/environments/environments.mjs -var Environments = class extends APIResource { - constructor() { - super(...arguments); - this.work = new Work(this._client); - } - /** - * Create a new environment with the specified configuration. - * - * @example - * ```ts - * const betaEnvironment = - * await client.beta.environments.create({ - * name: 'python-data-analysis', - * }); - * ``` - */ - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/environments?beta=true", { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Retrieve a specific environment by ID. - * - * @example - * ```ts - * const betaEnvironment = - * await client.beta.environments.retrieve( - * 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * ); - * ``` - */ - retrieve(environmentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/environments/${environmentID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Update an existing environment's configuration. - * - * @example - * ```ts - * const betaEnvironment = - * await client.beta.environments.update( - * 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * ); - * ``` - */ - update(environmentID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/environments/${environmentID}?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * List environments with pagination support. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaEnvironment of client.beta.environments.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/environments?beta=true", PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Delete an environment by ID. Returns a confirmation of the deletion. - * - * @example - * ```ts - * const betaEnvironmentDeleteResponse = - * await client.beta.environments.delete( - * 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * ); - * ``` - */ - delete(environmentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path$2`/v1/environments/${environmentID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Archive an environment by ID. Archived environments cannot be used to create new - * sessions. - * - * @example - * ```ts - * const betaEnvironment = - * await client.beta.environments.archive( - * 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * ); - * ``` - */ - archive(environmentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/environments/${environmentID}/archive?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } -}; -Environments.Work = Work; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memories.mjs -var Memories = class extends APIResource { - /** - * Create a memory - * - * @example - * ```ts - * const betaManagedAgentsMemory = - * await client.beta.memoryStores.memories.create( - * 'memory_store_id', - * { content: 'content', path: 'xx' }, - * ); - * ``` - */ - create(memoryStoreID, params, options) { - const { view, betas, ...body } = params; - return this._client.post(path$2`/v1/memory_stores/${memoryStoreID}/memories?beta=true`, { - query: { view }, - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } - /** - * Retrieve a memory - * - * @example - * ```ts - * const betaManagedAgentsMemory = - * await client.beta.memoryStores.memories.retrieve( - * 'memory_id', - * { memory_store_id: 'memory_store_id' }, - * ); - * ``` - */ - retrieve(memoryID, params, options) { - const { memory_store_id, betas, ...query } = params; - return this._client.get(path$2`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } - /** - * Update a memory - * - * @example - * ```ts - * const betaManagedAgentsMemory = - * await client.beta.memoryStores.memories.update( - * 'memory_id', - * { memory_store_id: 'memory_store_id' }, - * ); - * ``` - */ - update(memoryID, params, options) { - const { memory_store_id, view, betas, ...body } = params; - return this._client.post(path$2`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, { - query: { view }, - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } - /** - * List memories - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsMemoryListItem of client.beta.memoryStores.memories.list( - * 'memory_store_id', - * )) { - * // ... - * } - * ``` - */ - list(memoryStoreID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList(path$2`/v1/memory_stores/${memoryStoreID}/memories?beta=true`, PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } - /** - * Delete a memory - * - * @example - * ```ts - * const betaManagedAgentsDeletedMemory = - * await client.beta.memoryStores.memories.delete( - * 'memory_id', - * { memory_store_id: 'memory_store_id' }, - * ); - * ``` - */ - delete(memoryID, params, options) { - const { memory_store_id, expected_content_sha256, betas } = params; - return this._client.delete(path$2`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, { - query: { expected_content_sha256 }, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memory-versions.mjs -var MemoryVersions = class extends APIResource { - /** - * Retrieve a memory version - * - * @example - * ```ts - * const betaManagedAgentsMemoryVersion = - * await client.beta.memoryStores.memoryVersions.retrieve( - * 'memory_version_id', - * { memory_store_id: 'memory_store_id' }, - * ); - * ``` - */ - retrieve(memoryVersionID, params, options) { - const { memory_store_id, betas, ...query } = params; - return this._client.get(path$2`/v1/memory_stores/${memory_store_id}/memory_versions/${memoryVersionID}?beta=true`, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } - /** - * List memory versions - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsMemoryVersion of client.beta.memoryStores.memoryVersions.list( - * 'memory_store_id', - * )) { - * // ... - * } - * ``` - */ - list(memoryStoreID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList(path$2`/v1/memory_stores/${memoryStoreID}/memory_versions?beta=true`, PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } - /** - * Redact a memory version - * - * @example - * ```ts - * const betaManagedAgentsMemoryVersion = - * await client.beta.memoryStores.memoryVersions.redact( - * 'memory_version_id', - * { memory_store_id: 'memory_store_id' }, - * ); - * ``` - */ - redact(memoryVersionID, params, options) { - const { memory_store_id, betas } = params; - return this._client.post(path$2`/v1/memory_stores/${memory_store_id}/memory_versions/${memoryVersionID}/redact?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memory-stores.mjs -var MemoryStores = class extends APIResource { - constructor() { - super(...arguments); - this.memories = new Memories(this._client); - this.memoryVersions = new MemoryVersions(this._client); - } - /** - * Create a memory store - * - * @example - * ```ts - * const betaManagedAgentsMemoryStore = - * await client.beta.memoryStores.create({ name: 'x' }); - * ``` - */ - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/memory_stores?beta=true", { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } - /** - * Retrieve a memory store - * - * @example - * ```ts - * const betaManagedAgentsMemoryStore = - * await client.beta.memoryStores.retrieve( - * 'memory_store_id', - * ); - * ``` - */ - retrieve(memoryStoreID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/memory_stores/${memoryStoreID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } - /** - * Update a memory store - * - * @example - * ```ts - * const betaManagedAgentsMemoryStore = - * await client.beta.memoryStores.update('memory_store_id'); - * ``` - */ - update(memoryStoreID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/memory_stores/${memoryStoreID}?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } - /** - * List memory stores - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsMemoryStore of client.beta.memoryStores.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/memory_stores?beta=true", PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } - /** - * Delete a memory store - * - * @example - * ```ts - * const betaManagedAgentsDeletedMemoryStore = - * await client.beta.memoryStores.delete('memory_store_id'); - * ``` - */ - delete(memoryStoreID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path$2`/v1/memory_stores/${memoryStoreID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } - /** - * Archive a memory store - * - * @example - * ```ts - * const betaManagedAgentsMemoryStore = - * await client.beta.memoryStores.archive('memory_store_id'); - * ``` - */ - archive(memoryStoreID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/memory_stores/${memoryStoreID}/archive?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) - }); - } -}; -MemoryStores.Memories = Memories; -MemoryStores.MemoryVersions = MemoryVersions; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs -var JSONLDecoder = class JSONLDecoder { - constructor(iterator, controller) { - this.iterator = iterator; - this.controller = controller; - } - async *decoder() { - const lineDecoder = new LineDecoder(); - for await (const chunk of this.iterator) for (const line of lineDecoder.decode(chunk)) yield JSON.parse(line); - for (const line of lineDecoder.flush()) yield JSON.parse(line); - } - [Symbol.asyncIterator]() { - return this.decoder(); - } - static fromResponse(response, controller) { - if (!response.body) { - controller.abort(); - if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") throw new AnthropicError(`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 AnthropicError(`Attempted to iterate over a response with no body`); - } - return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs -var Batches$1 = class extends APIResource { - /** - * Send a batch of Message creation requests. - * - * The Message Batches API can be used to process multiple Messages API requests at - * once. Once a Message Batch is created, it begins processing immediately. Batches - * can take up to 24 hours to complete. - * - * Learn more about the Message Batches API in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatch = - * await client.beta.messages.batches.create({ - * requests: [ - * { - * custom_id: 'my-custom-id-1', - * params: { - * max_tokens: 1024, - * messages: [ - * { content: 'Hello, world', role: 'user' }, - * ], - * model: 'claude-opus-4-6', - * }, - * }, - * ], - * }); - * ``` - */ - create(params, options) { - const { betas, user_profile_id, ...body } = params; - return this._client.post("/v1/messages/batches?beta=true", { - body, - ...options, - headers: buildHeaders([{ - "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(), - ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0 - }, options?.headers]) - }); - } - /** - * This endpoint is idempotent and can be used to poll for Message Batch - * completion. To access the results of a Message Batch, make a request to the - * `results_url` field in the response. - * - * Learn more about the Message Batches API in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatch = - * await client.beta.messages.batches.retrieve( - * 'message_batch_id', - * ); - * ``` - */ - retrieve(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/messages/batches/${messageBatchID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, options?.headers]) - }); - } - /** - * List all Message Batches within a Workspace. Most recently created batches are - * returned first. - * - * Learn more about the Message Batches API in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaMessageBatch of client.beta.messages.batches.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/messages/batches?beta=true", Page, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, options?.headers]) - }); - } - /** - * Delete a Message Batch. - * - * Message Batches can only be deleted once they've finished processing. If you'd - * like to delete an in-progress batch, you must first cancel it. - * - * Learn more about the Message Batches API in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaDeletedMessageBatch = - * await client.beta.messages.batches.delete( - * 'message_batch_id', - * ); - * ``` - */ - delete(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path$2`/v1/messages/batches/${messageBatchID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, options?.headers]) - }); - } - /** - * Batches may be canceled any time before processing ends. Once cancellation is - * initiated, the batch enters a `canceling` state, at which time the system may - * complete any in-progress, non-interruptible requests before finalizing - * cancellation. - * - * The number of canceled requests is specified in `request_counts`. To determine - * which requests were canceled, check the individual results within the batch. - * Note that cancellation may not result in any canceled requests if they were - * non-interruptible. - * - * Learn more about the Message Batches API in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatch = - * await client.beta.messages.batches.cancel( - * 'message_batch_id', - * ); - * ``` - */ - cancel(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, options?.headers]) - }); - } - /** - * Streams the results of a Message Batch as a `.jsonl` file. - * - * Each line in the file is a JSON object containing the result of a single request - * in the Message Batch. Results are not guaranteed to be in the same order as - * requests. Use the `custom_id` field to match results to requests. - * - * Learn more about the Message Batches API in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatchIndividualResponse = - * await client.beta.messages.batches.results( - * 'message_batch_id', - * ); - * ``` - */ - async results(messageBatchID, params = {}, options) { - const batch = await this.retrieve(messageBatchID); - if (!batch.results_url) throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); - const { betas } = params ?? {}; - return this._client.get(batch.results_url, { - ...options, - headers: buildHeaders([{ - "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(), - Accept: "application/binary" - }, options?.headers]), - stream: true, - __binaryResponse: true - })._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/constants.mjs -/** -* Model-specific timeout constraints for non-streaming requests -*/ -var MODEL_NONSTREAMING_TOKENS = { - "claude-opus-4-20250514": 8192, - "claude-opus-4-0": 8192, - "claude-4-opus-20250514": 8192, - "anthropic.claude-opus-4-20250514-v1:0": 8192, - "claude-opus-4@20250514": 8192, - "claude-opus-4-1-20250805": 8192, - "anthropic.claude-opus-4-1-20250805-v1:0": 8192, - "claude-opus-4-1@20250805": 8192 -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs -function getOutputFormat$1(params) { - return params?.output_format ?? params?.output_config?.format; -} -function maybeParseBetaMessage(message, params, opts) { - const outputFormat = getOutputFormat$1(params); - if (!params || !("parse" in (outputFormat ?? {}))) return { - ...message, - content: message.content.map((block) => { - if (block.type === "text") { - const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { - value: null, - enumerable: false - }); - return Object.defineProperty(parsedBlock, "parsed", { - get() { - opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."); - return null; - }, - enumerable: false - }); - } - return block; - }), - parsed_output: null - }; - return parseBetaMessage(message, params, opts); -} -function parseBetaMessage(message, params, opts) { - let firstParsedOutput = null; - const content = message.content.map((block) => { - if (block.type === "text") { - const parsedOutput = parseBetaOutputFormat(params, block.text); - if (firstParsedOutput === null) firstParsedOutput = parsedOutput; - const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { - value: parsedOutput, - enumerable: false - }); - return Object.defineProperty(parsedBlock, "parsed", { - get() { - opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."); - return parsedOutput; - }, - enumerable: false - }); - } - return block; - }); - return { - ...message, - content, - parsed_output: firstParsedOutput - }; -} -function parseBetaOutputFormat(params, content) { - const outputFormat = getOutputFormat$1(params); - if (outputFormat?.type !== "json_schema") return null; - try { - if ("parse" in outputFormat) return outputFormat.parse(content); - return JSON.parse(content); - } catch (error) { - throw new AnthropicError(`Failed to parse structured output: ${error}`); - } -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs -var tokenize = (input) => { - let current = 0; - let tokens = []; - while (current < input.length) { - let char = input[current]; - if (char === "\\") { - current++; - continue; - } - if (char === "{") { - tokens.push({ - type: "brace", - value: "{" - }); - current++; - continue; - } - if (char === "}") { - tokens.push({ - type: "brace", - value: "}" - }); - current++; - continue; - } - if (char === "[") { - tokens.push({ - type: "paren", - value: "[" - }); - current++; - continue; - } - if (char === "]") { - tokens.push({ - type: "paren", - value: "]" - }); - current++; - continue; - } - if (char === ":") { - tokens.push({ - type: "separator", - value: ":" - }); - current++; - continue; - } - if (char === ",") { - tokens.push({ - type: "delimiter", - value: "," - }); - current++; - continue; - } - if (char === "\"") { - let value = ""; - let danglingQuote = false; - char = input[++current]; - while (char !== "\"") { - if (current === input.length) { - danglingQuote = true; - break; - } - if (char === "\\") { - current++; - if (current === input.length) { - danglingQuote = true; - break; - } - value += char + input[current]; - char = input[++current]; - } else { - value += char; - char = input[++current]; - } - } - char = input[++current]; - if (!danglingQuote) tokens.push({ - type: "string", - value - }); - continue; - } - if (char && /\s/.test(char)) { - current++; - continue; - } - let NUMBERS = /[0-9]/; - if (char && NUMBERS.test(char) || char === "-" || char === ".") { - let value = ""; - if (char === "-") { - value += char; - char = input[++current]; - } - while (char && (NUMBERS.test(char) || char === "." || char === "e" || char === "E" || (char === "-" || char === "+") && (value[value.length - 1] === "e" || value[value.length - 1] === "E"))) { - value += char; - char = input[++current]; - } - tokens.push({ - type: "number", - value - }); - continue; - } - let LETTERS = /[a-z]/i; - if (char && LETTERS.test(char)) { - let value = ""; - while (char && LETTERS.test(char)) { - if (current === input.length) break; - value += char; - char = input[++current]; - } - if (value == "true" || value == "false" || value === "null") tokens.push({ - type: "name", - value - }); - else { - current++; - continue; - } - continue; - } - current++; - } - return tokens; -}; -var strip = (tokens) => { - if (tokens.length === 0) return tokens; - let lastToken = tokens[tokens.length - 1]; - switch (lastToken.type) { - case "separator": - tokens = tokens.slice(0, tokens.length - 1); - return strip(tokens); - case "number": - let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1]; - if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-" || lastCharacterOfLastToken === "+" || lastCharacterOfLastToken === "e" || lastCharacterOfLastToken === "E") { - tokens = tokens.slice(0, tokens.length - 1); - return strip(tokens); - } - case "string": - let tokenBeforeTheLastToken = tokens[tokens.length - 2]; - if (tokenBeforeTheLastToken?.type === "delimiter") { - tokens = tokens.slice(0, tokens.length - 1); - return strip(tokens); - } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") { - tokens = tokens.slice(0, tokens.length - 1); - return strip(tokens); - } - break; - case "delimiter": - tokens = tokens.slice(0, tokens.length - 1); - return strip(tokens); - } - return tokens; -}; -var unstrip = (tokens) => { - let tail = []; - tokens.map((token) => { - if (token.type === "brace") if (token.value === "{") tail.push("}"); - else tail.splice(tail.lastIndexOf("}"), 1); - if (token.type === "paren") if (token.value === "[") tail.push("]"); - else tail.splice(tail.lastIndexOf("]"), 1); - }); - if (tail.length > 0) tail.reverse().map((item) => { - if (item === "}") tokens.push({ - type: "brace", - value: "}" - }); - else if (item === "]") tokens.push({ - type: "paren", - value: "]" - }); - }); - return tokens; -}; -var generate = (tokens) => { - let output = ""; - tokens.map((token) => { - switch (token.type) { - case "string": - output += "\"" + token.value + "\""; - break; - default: - output += token.value; - break; - } - }); - return output; -}; -var partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input))))); -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/message-stream-utils.mjs -var JSON_BUF_PROPERTY = "__json_buf"; -/** -* Copies a tool-use block with an updated `__json_buf`, installing `.input` as -* a memoized getter so the partial-JSON parse happens on first read instead of -* on every delta. -*/ -function withLazyInput(prev, jsonBuf) { - const next = {}; - for (const key of Object.keys(prev)) if (key !== "input") next[key] = prev[key]; - Object.defineProperty(next, JSON_BUF_PROPERTY, { - value: jsonBuf, - enumerable: false, - writable: true - }); - let input; - let parsed = false; - Object.defineProperty(next, "input", { - enumerable: true, - configurable: true, - get() { - if (!parsed) { - input = jsonBuf ? partialParse(jsonBuf) : {}; - parsed = true; - } - return input; - } - }); - return next; -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs -var _BetaMessageStream_instances; -var _BetaMessageStream_currentMessageSnapshot; -var _BetaMessageStream_params; -var _BetaMessageStream_connectedPromise; -var _BetaMessageStream_resolveConnectedPromise; -var _BetaMessageStream_rejectConnectedPromise; -var _BetaMessageStream_endPromise; -var _BetaMessageStream_resolveEndPromise; -var _BetaMessageStream_rejectEndPromise; -var _BetaMessageStream_listeners; -var _BetaMessageStream_ended; -var _BetaMessageStream_errored; -var _BetaMessageStream_aborted; -var _BetaMessageStream_catchingPromiseCreated; -var _BetaMessageStream_response; -var _BetaMessageStream_request_id; -var _BetaMessageStream_logger; -var _BetaMessageStream_getFinalMessage; -var _BetaMessageStream_getFinalText; -var _BetaMessageStream_handleError; -var _BetaMessageStream_beginRequest; -var _BetaMessageStream_addStreamEvent; -var _BetaMessageStream_endRequest; -var _BetaMessageStream_accumulateMessage; -var _BetaMessageStream_toolInputParseError; -function tracksToolInput$1(content) { - return content.type === "tool_use" || content.type === "server_tool_use" || content.type === "mcp_tool_use"; -} -var BetaMessageStream = class BetaMessageStream { - constructor(params, opts) { - _BetaMessageStream_instances.add(this); - this.messages = []; - this.receivedMessages = []; - _BetaMessageStream_currentMessageSnapshot.set(this, void 0); - _BetaMessageStream_params.set(this, null); - this.controller = new AbortController(); - _BetaMessageStream_connectedPromise.set(this, void 0); - _BetaMessageStream_resolveConnectedPromise.set(this, () => {}); - _BetaMessageStream_rejectConnectedPromise.set(this, () => {}); - _BetaMessageStream_endPromise.set(this, void 0); - _BetaMessageStream_resolveEndPromise.set(this, () => {}); - _BetaMessageStream_rejectEndPromise.set(this, () => {}); - _BetaMessageStream_listeners.set(this, {}); - _BetaMessageStream_ended.set(this, false); - _BetaMessageStream_errored.set(this, false); - _BetaMessageStream_aborted.set(this, false); - _BetaMessageStream_catchingPromiseCreated.set(this, false); - _BetaMessageStream_response.set(this, void 0); - _BetaMessageStream_request_id.set(this, void 0); - _BetaMessageStream_logger.set(this, void 0); - _BetaMessageStream_handleError.set(this, (error) => { - __classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f"); - if (isAbortError(error)) error = new APIUserAbortError(); - if (error instanceof APIUserAbortError) { - __classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f"); - return this._emit("abort", error); - } - if (error instanceof AnthropicError) return this._emit("error", error); - if (error instanceof Error) { - const anthropicError = new AnthropicError(error.message); - anthropicError.cause = error; - return this._emit("error", anthropicError); - } - return this._emit("error", new AnthropicError(String(error))); - }); - __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f"); - }), "f"); - __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f"); - }), "f"); - __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => {}); - __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => {}); - __classPrivateFieldSet(this, _BetaMessageStream_params, params, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_logger, opts?.logger ?? console, "f"); - } - get response() { - return __classPrivateFieldGet(this, _BetaMessageStream_response, "f"); - } - get request_id() { - return __classPrivateFieldGet(this, _BetaMessageStream_request_id, "f"); - } - /** - * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, - * returned vie the `request-id` header which is useful for debugging requests and resporting - * issues to Anthropic. - * - * This is the same as the `APIPromise.withResponse()` method. - * - * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` - * as no `Response` is available. - */ - async withResponse() { - __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); - const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f"); - if (!response) throw new Error("Could not resolve a `Response` object"); - return { - data: this, - response, - request_id: response.headers.get("request-id") - }; - } - /** - * Intended for use on the frontend, consuming a stream produced with - * `.toReadableStream()` on the backend. - * - * Note that messages sent to the model do not appear in `.on('message')` - * in this context. - */ - static fromReadableStream(stream) { - const runner = new BetaMessageStream(null); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - static createMessage(messages, params, options, { logger } = {}) { - const runner = new BetaMessageStream(params, { logger }); - for (const message of params.messages) runner._addMessageParam(message); - __classPrivateFieldSet(runner, _BetaMessageStream_params, { - ...params, - stream: true - }, "f"); - runner._run(() => runner._createMessage(messages, { - ...params, - stream: true - }, { - ...options, - headers: { - ...options?.headers, - [STAINLESS_HELPER_METHOD_HEADER]: "stream" - } - })); - return runner; - } - _run(executor) { - executor().then(() => { - this._emitFinal(); - this._emit("end"); - }, __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f")); - } - _addMessageParam(message) { - this.messages.push(message); - } - _addMessage(message, emit = true) { - this.receivedMessages.push(message); - if (emit) this._emit("message", message); - } - async _createMessage(messages, params, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener("abort", abortHandler); - } - try { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); - const { response, data: stream } = await messages.create({ - ...params, - stream: true - }, { - ...options, - signal: this.controller.signal - }).withResponse(); - this._connected(response); - for await (const event of stream) __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); - if (stream.controller.signal?.aborted) throw new APIUserAbortError(); - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); - } finally { - if (signal && abortHandler) signal.removeEventListener("abort", abortHandler); - } - } - _connected(response) { - if (this.ended) return; - __classPrivateFieldSet(this, _BetaMessageStream_response, response, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get("request-id"), "f"); - __classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response); - this._emit("connect"); - } - get ended() { - return __classPrivateFieldGet(this, _BetaMessageStream_ended, "f"); - } - get errored() { - return __classPrivateFieldGet(this, _BetaMessageStream_errored, "f"); - } - get aborted() { - return __classPrivateFieldGet(this, _BetaMessageStream_aborted, "f"); - } - abort() { - this.controller.abort(); - } - /** - * Adds the listener function to the end of the listeners array for the event. - * No checks are made to see if the listener has already been added. Multiple calls passing - * the same combination of event and listener will result in the listener being added, and - * called, multiple times. - * @returns this MessageStream, so that calls can be chained - */ - on(event, listener) { - (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = [])).push({ listener }); - return this; - } - /** - * Removes the specified listener from the listener array for the event. - * off() will remove, at most, one instance of a listener from the listener array. If any single - * listener has been added multiple times to the listener array for the specified event, then - * off() must be called multiple times to remove each instance. - * @returns this MessageStream, so that calls can be chained - */ - off(event, listener) { - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; - if (!listeners) return this; - const index = listeners.findIndex((l) => l.listener === listener); - if (index >= 0) listeners.splice(index, 1); - return this; - } - /** - * Adds a one-time listener function for the event. The next time the event is triggered, - * this listener is removed and then invoked. - * @returns this MessageStream, so that calls can be chained - */ - once(event, listener) { - (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = [])).push({ - listener, - once: true - }); - return this; - } - /** - * This is similar to `.once()`, but returns a Promise that resolves the next time - * the event is triggered, instead of calling a listener callback. - * @returns a Promise that resolves the next time given event is triggered, - * or rejects if an error is emitted. (If you request the 'error' event, - * returns a promise that resolves with the error). - * - * Example: - * - * const message = await stream.emitted('message') // rejects if the stream errors - */ - emitted(event) { - return new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); - if (event !== "error") this.once("error", reject); - this.once(event, resolve); - }); - } - async done() { - __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); - await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f"); - } - get currentMessage() { - return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); - } - /** - * @returns a promise that resolves with the the final assistant Message response, - * or rejects if an error occurred or the stream ended prematurely without producing a Message. - * If structured outputs were used, this will be a ParsedMessage with a `parsed` field. - */ - async finalMessage() { - await this.done(); - return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this); - } - /** - * @returns a promise that resolves with the the final assistant Message's text response, concatenated - * together if there are more than one text blocks. - * Rejects if an error occurred or the stream ended prematurely without producing a Message. - */ - async finalText() { - await this.done(); - return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this); - } - _emit(event, ...args) { - if (__classPrivateFieldGet(this, _BetaMessageStream_ended, "f")) return; - if (event === "end") { - __classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f"); - __classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this); - } - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; - if (listeners) { - __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); - listeners.forEach(({ listener }) => listener(...args)); - } - if (event === "abort") { - const error = args[0]; - if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) Promise.reject(error); - __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); - __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); - this._emit("end"); - return; - } - if (event === "error") { - const error = args[0]; - if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) Promise.reject(error); - __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); - __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); - this._emit("end"); - } - } - _emitFinal() { - if (this.receivedMessages.at(-1)) this._emit("finalMessage", __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this)); - } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener("abort", abortHandler); - } - try { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); - this._connected(null); - const stream = Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); - if (stream.controller.signal?.aborted) throw new APIUserAbortError(); - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); - } finally { - if (signal && abortHandler) signal.removeEventListener("abort", abortHandler); - } - } - [(_BetaMessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_params = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_listeners = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_ended = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_errored = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_aborted = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_response = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_request_id = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_logger = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_handleError = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_instances = /* @__PURE__ */ new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage() { - if (this.receivedMessages.length === 0) throw new AnthropicError("stream ended without producing a Message with role=assistant"); - return this.receivedMessages.at(-1); - }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText() { - if (this.receivedMessages.length === 0) throw new AnthropicError("stream ended without producing a Message with role=assistant"); - const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text); - if (textBlocks.length === 0) throw new AnthropicError("stream ended without producing a content block with type=text"); - return textBlocks.join(" "); - }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest() { - if (this.ended) return; - __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f"); - }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent(event) { - if (this.ended) return; - const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event); - this._emit("streamEvent", event, messageSnapshot); - switch (event.type) { - case "content_block_delta": { - const content = messageSnapshot.content.at(-1); - switch (event.delta.type) { - case "text_delta": - if (content.type === "text") this._emit("text", event.delta.text, content.text || ""); - break; - case "citations_delta": - if (content.type === "text") this._emit("citation", event.delta.citation, content.citations ?? []); - break; - case "input_json_delta": - if (tracksToolInput$1(content) && __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f").inputJson?.length) { - let jsonSnapshot; - try { - jsonSnapshot = content.input; - } catch (err) { - __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_toolInputParseError).call(this, content, err)); - break; - } - this._emit("inputJson", event.delta.partial_json, jsonSnapshot); - } - break; - case "thinking_delta": - if (content.type === "thinking") this._emit("thinking", event.delta.thinking, content.thinking); - break; - case "signature_delta": - if (content.type === "thinking") this._emit("signature", content.signature); - break; - case "compaction_delta": - if (content.type === "compaction" && content.content) this._emit("compaction", content.content); - break; - default: event.delta; - } - break; - } - case "message_stop": - this._addMessageParam(messageSnapshot); - this._addMessage(maybeParseBetaMessage(messageSnapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }), true); - break; - case "content_block_stop": - this._emit("contentBlock", messageSnapshot.content.at(-1)); - break; - case "message_start": - __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f"); - break; - case "content_block_start": - case "message_delta": break; - } - }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest() { - if (this.ended) throw new AnthropicError(`stream has ended, this shouldn't happen`); - const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); - if (!snapshot) throw new AnthropicError(`request ended without sending any chunks`); - __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f"); - return maybeParseBetaMessage(snapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }); - }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage(event) { - let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); - if (event.type === "message_start") { - if (snapshot) throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); - return event.message; - } - if (!snapshot) throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); - switch (event.type) { - case "message_stop": return snapshot; - case "message_delta": - snapshot.container = event.delta.container; - snapshot.stop_reason = event.delta.stop_reason; - snapshot.stop_sequence = event.delta.stop_sequence; - if (event.delta.stop_details != null) snapshot.stop_details = event.delta.stop_details; - snapshot.usage.output_tokens = event.usage.output_tokens; - snapshot.context_management = event.context_management; - if (event.usage.input_tokens != null) snapshot.usage.input_tokens = event.usage.input_tokens; - if (event.usage.cache_creation_input_tokens != null) snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; - if (event.usage.cache_read_input_tokens != null) snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; - if (event.usage.server_tool_use != null) snapshot.usage.server_tool_use = event.usage.server_tool_use; - if (event.usage.iterations != null) snapshot.usage.iterations = event.usage.iterations; - if (event.usage.fallback_credit != null) snapshot.usage.fallback_credit = event.usage.fallback_credit; - return snapshot; - case "content_block_start": - snapshot.content.push(event.content_block); - if (event.content_block.type === "fallback") snapshot.model = event.content_block.to.model; - return snapshot; - case "content_block_delta": { - const snapshotContent = snapshot.content.at(event.index); - switch (event.delta.type) { - case "text_delta": - if (snapshotContent?.type === "text") snapshot.content[event.index] = { - ...snapshotContent, - text: (snapshotContent.text || "") + event.delta.text - }; - break; - case "citations_delta": - if (snapshotContent?.type === "text") snapshot.content[event.index] = { - ...snapshotContent, - citations: [...snapshotContent.citations ?? [], event.delta.citation] - }; - break; - case "input_json_delta": - if (snapshotContent && tracksToolInput$1(snapshotContent)) { - const jsonBuf = (snapshotContent["__json_buf"] || "") + event.delta.partial_json; - snapshot.content[event.index] = withLazyInput(snapshotContent, jsonBuf); - } - break; - case "thinking_delta": - if (snapshotContent?.type === "thinking") snapshot.content[event.index] = { - ...snapshotContent, - thinking: snapshotContent.thinking + event.delta.thinking - }; - break; - case "signature_delta": - if (snapshotContent?.type === "thinking") snapshot.content[event.index] = { - ...snapshotContent, - signature: event.delta.signature - }; - break; - case "compaction_delta": - if (snapshotContent?.type === "compaction") snapshot.content[event.index] = { - ...snapshotContent, - content: (snapshotContent.content || "") + event.delta.content, - encrypted_content: event.delta.encrypted_content - }; - break; - default: event.delta; - } - return snapshot; - } - case "content_block_stop": { - const snapshotContent = snapshot.content.at(event.index); - if (snapshotContent && tracksToolInput$1(snapshotContent) && "__json_buf" in snapshotContent) { - let input; - try { - input = snapshotContent.input; - } catch (err) { - input = {}; - __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_toolInputParseError).call(this, snapshotContent, err)); - } - Object.defineProperty(snapshotContent, "input", { - value: input, - enumerable: true, - configurable: true, - writable: true - }); - } - return snapshot; - } - } - }, _BetaMessageStream_toolInputParseError = function _BetaMessageStream_toolInputParseError(block, err) { - const jsonBuf = block[JSON_BUF_PROPERTY]; - return new AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`); - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on("streamEvent", (event) => { - const reader = readQueue.shift(); - if (reader) reader.resolve(event); - else pushQueue.push(event); - }); - this.on("end", () => { - done = true; - for (const reader of readQueue) reader.resolve(void 0); - readQueue.length = 0; - }); - this.on("abort", (err) => { - done = true; - for (const reader of readQueue) reader.reject(err); - readQueue.length = 0; - }); - this.on("error", (err) => { - done = true; - for (const reader of readQueue) reader.reject(err); - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) return { - value: void 0, - done: true - }; - return new Promise((resolve, reject) => readQueue.push({ - resolve, - reject - })).then((chunk) => chunk ? { - value: chunk, - done: false - } : { - value: void 0, - done: true - }); - } - return { - value: pushQueue.shift(), - done: false - }; - }, - return: async () => { - this.abort(); - return { - value: void 0, - done: true - }; - } - }; - } - toReadableStream() { - return new Stream(this[Symbol.asyncIterator].bind(this), this.controller).toReadableStream(); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/internal/utils/promise.mjs -/** -* A deferred: a `Promise` together with its `resolve` / `reject` functions. -* This is `Promise.withResolvers()`, which is not available in all supported -* runtimes. -*/ -function promiseWithResolvers() { - let resolve; - let reject; - return { - promise: new Promise((res, rej) => { - resolve = res; - reject = rej; - }), - resolve, - reject - }; -} -var DEFAULT_SUMMARY_PROMPT = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include: -1. Task Overview -The user's core request and success criteria -Any clarifications or constraints they specified -2. Current State -What has been completed so far -Files created, modified, or analyzed (with paths if relevant) -Key outputs or artifacts produced -3. Important Discoveries -Technical constraints or requirements uncovered -Decisions made and their rationale -Errors encountered and how they were resolved -What approaches were tried that didn't work (and why) -4. Next Steps -Specific actions needed to complete the task -Any blockers or open questions to resolve -Priority order if multiple steps remain -5. Context to Preserve -User preferences or style requirements -Domain-specific details that aren't obvious -Any promises made to the user -Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task. -Wrap your summary in tags.`; -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs -var _BetaToolRunner_instances; -var _BetaToolRunner_consumed; -var _BetaToolRunner_mutated; -var _BetaToolRunner_state; -var _BetaToolRunner_options; -var _BetaToolRunner_message; -var _BetaToolRunner_toolResponse; -var _BetaToolRunner_completion; -var _BetaToolRunner_iterationCount; -var _BetaToolRunner_checkAndCompact; -var _BetaToolRunner_generateToolResponse; -/** -* A ToolRunner handles the automatic conversation loop between the assistant and tools. -* -* A ToolRunner is an async iterable that yields either BetaMessage or BetaMessageStream objects -* depending on the streaming configuration. -*/ -var BetaToolRunner = class { - constructor(client, params, options) { - _BetaToolRunner_instances.add(this); - this.client = client; - /** Whether the async iterator has been consumed */ - _BetaToolRunner_consumed.set(this, false); - /** Whether parameters have been mutated since the last API call */ - _BetaToolRunner_mutated.set(this, false); - /** Current state containing the request parameters */ - _BetaToolRunner_state.set(this, void 0); - _BetaToolRunner_options.set(this, void 0); - /** Promise for the last message received from the assistant */ - _BetaToolRunner_message.set(this, void 0); - /** Cached tool response to avoid redundant executions */ - _BetaToolRunner_toolResponse.set(this, void 0); - /** Promise resolvers for waiting on completion */ - _BetaToolRunner_completion.set(this, void 0); - /** Number of iterations (API requests) made so far */ - _BetaToolRunner_iterationCount.set(this, 0); - __classPrivateFieldSet(this, _BetaToolRunner_state, { params: { - ...params, - messages: structuredClone(params.messages) - } }, "f"); - const collected = collectStainlessHelpers(params.tools, params.messages); - __classPrivateFieldSet(this, _BetaToolRunner_options, { - ...options, - headers: buildHeaders([ - helperHeader("BetaToolRunner"), - collected.length ? { [STAINLESS_HELPER_HEADER]: collected.join(", ") } : void 0, - options?.headers - ]) - }, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); - if (params.compactionControl?.enabled) console.warn("Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: \"compact_20260112\" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction"); - } - async *[(_BetaToolRunner_consumed = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_mutated = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_state = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_options = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_message = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_toolResponse = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_completion = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_iterationCount = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_instances = /* @__PURE__ */ new WeakSet(), _BetaToolRunner_checkAndCompact = async function _BetaToolRunner_checkAndCompact() { - const compactionControl = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.compactionControl; - if (!compactionControl || !compactionControl.enabled) return false; - let tokensUsed = 0; - if (__classPrivateFieldGet(this, _BetaToolRunner_message, "f") !== void 0) try { - const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); - tokensUsed = message.usage.input_tokens + (message.usage.cache_creation_input_tokens ?? 0) + (message.usage.cache_read_input_tokens ?? 0) + message.usage.output_tokens; - } catch { - return false; - } - const threshold = compactionControl.contextTokenThreshold ?? 1e5; - if (tokensUsed < threshold) return false; - const model = compactionControl.model ?? __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.model; - const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT; - const messages = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages; - if (messages[messages.length - 1].role === "assistant") { - const lastMessage = messages[messages.length - 1]; - if (Array.isArray(lastMessage.content)) { - const nonToolBlocks = lastMessage.content.filter((block) => block.type !== "tool_use"); - if (nonToolBlocks.length === 0) messages.pop(); - else lastMessage.content = nonToolBlocks; - } - } - const response = await this.client.beta.messages.create({ - model, - messages: [...messages, { - role: "user", - content: [{ - type: "text", - text: summaryPrompt - }] - }], - max_tokens: __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_tokens - }, { - signal: __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal, - headers: buildHeaders([__classPrivateFieldGet(this, _BetaToolRunner_options, "f").headers, helperHeader("compaction")]) - }); - if (response.content[0]?.type !== "text") throw new AnthropicError("Expected text response for compaction"); - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages = [{ - role: "user", - content: response.content - }]; - return true; - }, Symbol.asyncIterator)]() { - var _a; - if (__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) throw new AnthropicError("Cannot iterate over a consumed stream"); - __classPrivateFieldSet(this, _BetaToolRunner_consumed, true, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, void 0, "f"); - try { - while (true) { - let stream; - try { - if (__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations && __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations) break; - __classPrivateFieldSet(this, _BetaToolRunner_mutated, false, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, void 0, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a = __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f"), _a++, _a), "f"); - __classPrivateFieldSet(this, _BetaToolRunner_message, void 0, "f"); - const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; - if (params.stream) { - stream = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")); - __classPrivateFieldSet(this, _BetaToolRunner_message, stream.finalMessage(), "f"); - __classPrivateFieldGet(this, _BetaToolRunner_message, "f").catch(() => {}); - yield stream; - } else { - __classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ - ...params, - stream: false - }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); - yield __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); - } - if (!await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_checkAndCompact).call(this)) { - if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { - const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push({ - role: message.role, - content: message.content - }); - if (message.stop_reason === "refusal") break; - } - const toolMessage = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.at(-1)); - if (toolMessage) __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage); - else if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) break; - } - } finally { - if (stream) stream.abort(); - } - } - if (!__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) throw new AnthropicError("ToolRunner concluded without a message from the server"); - __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")); - } catch (error) { - __classPrivateFieldSet(this, _BetaToolRunner_consumed, false, "f"); - __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise.catch(() => {}); - __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").reject(error); - __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); - throw error; - } - } - setMessagesParams(paramsOrMutator) { - if (typeof paramsOrMutator === "function") __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params); - else __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator; - __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, void 0, "f"); - } - setRequestOptions(optionsOrMutator) { - if (typeof optionsOrMutator === "function") __classPrivateFieldSet(this, _BetaToolRunner_options, optionsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); - else __classPrivateFieldSet(this, _BetaToolRunner_options, { - ...__classPrivateFieldGet(this, _BetaToolRunner_options, "f"), - ...optionsOrMutator - }, "f"); - } - /** - * Get the tool response for the last message from the assistant. - * Avoids redundant tool executions by caching results. - * - * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed - * - * @example - * const toolResponse = await runner.generateToolResponse(); - * if (toolResponse) { - * console.log('Tool results:', toolResponse.content); - * } - */ - async generateToolResponse(signal = __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal) { - const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f") ?? this.params.messages.at(-1); - if (!message) return null; - return __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message, signal); - } - /** - * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and - * will wait for an instance to start and go to completion. - * - * @returns A promise that resolves to the final BetaMessage when the iterator completes - * - * @example - * // Start consuming the iterator - * for await (const message of runner) { - * console.log('Message:', message.content); - * } - * - * // Meanwhile, wait for completion from another part of the code - * const finalMessage = await runner.done(); - * console.log('Final response:', finalMessage.content); - */ - done() { - return __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise; - } - /** - * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream: - * * If the iterator has not been consumed, consume the entire iterator and return the final message from the - * assistant. - * * If the iterator has been consumed, waits for it to complete and returns the final message. - * - * @returns A promise that resolves to the final BetaMessage from the conversation - * @throws {AnthropicError} If no messages were processed during the conversation - * - * @example - * const finalMessage = await runner.runUntilDone(); - * console.log('Final response:', finalMessage.content); - */ - async runUntilDone() { - if (!__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) for await (const _ of this); - return this.done(); - } - /** - * Get the current parameters being used by the ToolRunner. - * - * @returns A readonly view of the current ToolRunnerParams - * - * @example - * const currentParams = runner.params; - * console.log('Current model:', currentParams.model); - * console.log('Message count:', currentParams.messages.length); - */ - get params() { - return __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; - } - /** - * Add one or more messages to the conversation history. - * - * @param messages - One or more BetaMessageParam objects to add to the conversation - * - * @example - * runner.pushMessages( - * { role: 'user', content: 'Also, what about the weather in NYC?' } - * ); - * - * @example - * // Adding multiple messages - * runner.pushMessages( - * { role: 'user', content: 'What about NYC?' }, - * { role: 'user', content: 'And Boston?' } - * ); - */ - pushMessages(...messages) { - this.setMessagesParams((params) => ({ - ...params, - messages: [...params.messages, ...messages] - })); - } - /** - * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone() - * This allows using `await runner` instead of `await runner.runUntilDone()` - */ - then(onfulfilled, onrejected) { - return this.runUntilDone().then(onfulfilled, onrejected); - } -}; -_BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse(lastMessage, signal = __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal) { - if (__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f") !== void 0) return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params, lastMessage, { - ...__classPrivateFieldGet(this, _BetaToolRunner_options, "f"), - signal - }), "f"); - return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); -}; -async function generateToolResponse(params, lastMessage = params.messages.at(-1), requestOptions) { - if (!lastMessage || lastMessage.role !== "assistant" || !lastMessage.content || typeof lastMessage.content === "string") return null; - const toolUseBlocks = lastMessage.content.filter((content) => content.type === "tool_use"); - if (toolUseBlocks.length === 0) return null; - const available = availableToolNames(params); - return { - role: "user", - content: await Promise.all(toolUseBlocks.map(async (toolUse) => { - const tool = params.tools.find((t) => ("name" in t ? t.name : t.mcp_server_name) === toolUse.name); - if (!tool || !("run" in tool) || !available.has(toolUse.name)) return toolNotFoundResult(toolUse); - try { - let input = toolUse.input; - if ("parse" in tool && tool.parse) input = tool.parse(input); - const result = await tool.run(input, { - toolUse, - toolUseBlock: toolUse, - signal: requestOptions?.signal - }); - return { - type: "tool_result", - tool_use_id: toolUse.id, - content: result - }; - } catch (error) { - return { - type: "tool_result", - tool_use_id: toolUse.id, - content: error instanceof ToolError ? error.content : `Error: ${error instanceof Error ? error.message : String(error)}`, - is_error: true - }; - } - })) - }; -} -function toolNotFoundResult(toolUse) { - return { - type: "tool_result", - tool_use_id: toolUse.id, - content: `Error: Tool '${toolUse.name}' not found`, - is_error: true - }; -} -/** -* Computes the names of locally runnable tools that are still available for the assistant -* turn being answered, by folding `tool_removal` / `tool_addition` blocks from the -* `role: "system"` messages over the runnable tools. The assistant turn being answered is -* terminal-or-absent and only `system` messages are inspected, so folding the whole current -* history is exactly folding the messages preceding that turn — call this before appending -* anything after it. MCP references are ignored — those tools are executed server-side and -* never dispatched by this runner. -*/ -function availableToolNames(params) { - const available = /* @__PURE__ */ new Set(); - for (const tool of params.tools) if ("run" in tool) available.add(tool.name); - for (const message of params.messages) { - if (message.role !== "system" || typeof message.content === "string") continue; - for (const block of message.content) applyToolChange(block, available); - } - return available; -} -function applyToolChange(block, available) { - switch (block.type) { - case "tool_removal": - case "tool_addition": - applyToolReference(block, available); - break; - case "mid_conv_system": - for (const inner of block.content) if (inner.type === "tool_removal" || inner.type === "tool_addition") applyToolReference(inner, available); - break; - default: break; - } -} -function applyToolReference(block, available) { - const name = referencedToolName(block.tool); - if (name === void 0) return; - if (block.type === "tool_removal") available.delete(name); - else available.add(name); -} -function referencedToolName(ref) { - switch (ref.type) { - case "tool_reference": return ref.name; - default: return; - } -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs -var DEPRECATED_MODELS$1 = { - "claude-1.3": "November 6th, 2024", - "claude-1.3-100k": "November 6th, 2024", - "claude-instant-1.1": "November 6th, 2024", - "claude-instant-1.1-100k": "November 6th, 2024", - "claude-instant-1.2": "November 6th, 2024", - "claude-3-sonnet-20240229": "July 21st, 2025", - "claude-3-opus-20240229": "January 5th, 2026", - "claude-2.1": "July 21st, 2025", - "claude-2.0": "July 21st, 2025", - "claude-3-7-sonnet-latest": "February 19th, 2026", - "claude-3-7-sonnet-20250219": "February 19th, 2026", - "claude-3-5-haiku-latest": "February 19th, 2026", - "claude-3-5-haiku-20241022": "February 19th, 2026", - "claude-opus-4-0": "June 15th, 2026", - "claude-opus-4-20250514": "June 15th, 2026", - "claude-sonnet-4-0": "June 15th, 2026", - "claude-sonnet-4-20250514": "June 15th, 2026", - "claude-opus-4-1": "August 5th, 2026", - "claude-opus-4-1-20250805": "August 5th, 2026", - "claude-mythos-preview": "June 30th, 2026" -}; -var MODELS_TO_WARN_WITH_THINKING_ENABLED$1 = ["claude-mythos-preview", "claude-opus-4-6"]; -var Messages$1 = class extends APIResource { - constructor() { - super(...arguments); - this.batches = new Batches$1(this._client); - } - create(params, options) { - const modifiedParams = transformOutputFormat(params); - const { betas, user_profile_id, ...body } = modifiedParams; - if (body.model in DEPRECATED_MODELS$1) console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS$1[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); - if (MODELS_TO_WARN_WITH_THINKING_ENABLED$1.includes(body.model) && body.thinking && body.thinking.type === "enabled") console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`); - let timeout = this._client._options.timeout; - if (!body.stream && timeout == null) { - const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? void 0; - timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); - } - const helperHeader = stainlessHelperHeader(body.tools, body.messages); - return this._client.post("/v1/messages?beta=true", { - body, - timeout: timeout ?? 6e5, - ...options, - headers: buildHeaders([ - { - ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0, - ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0 - }, - helperHeader, - options?.headers - ]), - stream: modifiedParams.stream ?? false - }); - } - /** - * Send a structured list of input messages with text and/or image content, along with an expected `output_format` and - * the response will be automatically parsed and available in the `parsed_output` property of the message. - * - * @example - * ```ts - * const message = await client.beta.messages.parse({ - * model: 'claude-3-5-sonnet-20241022', - * max_tokens: 1024, - * messages: [{ role: 'user', content: 'What is 2+2?' }], - * output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'), - * }); - * - * console.log(message.parsed_output?.answer); // 4 - * ``` - */ - parse(params, options) { - options = { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...params.betas ?? [], "structured-outputs-2025-12-15"].toString() }, options?.headers]) - }; - return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console })); - } - /** - * Create a Message stream - */ - stream(body, options) { - return BetaMessageStream.createMessage(this, body, options); - } - /** - * Count the number of tokens in a Message. - * - * The Token Count API can be used to count the number of tokens in a Message, - * including tools, images, and documents, without creating it. - * - * Learn more about token counting in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting) - * - * @example - * ```ts - * const betaMessageTokensCount = - * await client.beta.messages.countTokens({ - * messages: [{ content: 'Hello, world', role: 'user' }], - * model: 'claude-opus-4-6', - * }); - * ``` - */ - countTokens(params, options) { - const { betas, user_profile_id, ...body } = transformOutputFormat(params); - return this._client.post("/v1/messages/count_tokens?beta=true", { - body, - ...options, - headers: buildHeaders([{ - "anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString(), - ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0 - }, options?.headers]) - }); - } - toolRunner(body, options) { - return new BetaToolRunner(this._client, body, options); - } -}; -/** -* Transform deprecated output_format to output_config.format -* Returns a modified copy of the params without mutating the original -*/ -function transformOutputFormat(params) { - if (!params.output_format) return params; - if (params.output_config?.format) throw new AnthropicError("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated)."); - const { output_format, ...rest } = params; - return { - ...rest, - output_config: { - ...params.output_config, - format: output_format - } - }; -} -Messages$1.Batches = Batches$1; -Messages$1.BetaToolRunner = BetaToolRunner; -Messages$1.ToolError = ToolError; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/sessions/events.mjs -var Events$1 = class extends APIResource { - /** - * List Events - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsSessionEvent of client.beta.sessions.events.list( - * 'sesn_011CZkZAtmR3yMPDzynEDxu7', - * )) { - * // ... - * } - * ``` - */ - list(sessionID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList(path$2`/v1/sessions/${sessionID}/events?beta=true`, PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Send Events - * - * @example - * ```ts - * const betaManagedAgentsSendSessionEvents = - * await client.beta.sessions.events.send( - * 'sesn_011CZkZAtmR3yMPDzynEDxu7', - * { - * events: [ - * { - * content: [ - * { - * text: 'Where is my order #1234?', - * type: 'text', - * }, - * ], - * type: 'user.message', - * }, - * ], - * }, - * ); - * ``` - */ - send(sessionID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/sessions/${sessionID}/events?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Stream Events - * - * @example - * ```ts - * const betaManagedAgentsStreamSessionEvents = - * await client.beta.sessions.events.stream( - * 'sesn_011CZkZAtmR3yMPDzynEDxu7', - * ); - * ``` - */ - stream(sessionID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.get(path$2`/v1/sessions/${sessionID}/events/stream?beta=true`, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]), - stream: true - }); - } - /** - * Attach to a session and dispatch every incoming `agent.tool_use` and - * `agent.custom_tool_use` event to a local tool registry, sending the matching - * result back (`user.tool_result` / `user.custom_tool_result`). The - * sessions-side counterpart to `client.beta.messages.toolRunner`: yields one - * entry per completed tool call so callers can observe each dispatch (and - * `break` to abort cleanly). - * - * @example - * ```ts - * import { betaAgentToolset20260401 } from '@anthropic-ai/sdk/tools/agent-toolset/node'; - * - * for await (const call of client.beta.sessions.events.toolRunner(work.data.id, { - * tools: [...betaAgentToolset20260401({ workdir }), myTool], - * })) { - * console.log(`${call.name} -> ${call.isError ? 'error' : 'ok'}`); - * } - * ``` - */ - toolRunner(sessionID, opts) { - return new SessionToolRunner(sessionID, { - ...opts, - client: this._client - }); - } -}; -Events$1.SessionToolRunner = SessionToolRunner; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/sessions/resources.mjs -var Resources = class extends APIResource { - /** - * Get Session Resource - * - * @example - * ```ts - * const resource = - * await client.beta.sessions.resources.retrieve( - * 'sesrsc_011CZkZBJq5dWxk9fVLNcPht', - * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' }, - * ); - * ``` - */ - retrieve(resourceID, params, options) { - const { session_id, betas } = params; - return this._client.get(path$2`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Update Session Resource - * - * @example - * ```ts - * const resource = - * await client.beta.sessions.resources.update( - * 'sesrsc_011CZkZBJq5dWxk9fVLNcPht', - * { - * session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7', - * authorization_token: 'ghp_exampletoken', - * }, - * ); - * ``` - */ - update(resourceID, params, options) { - const { session_id, betas, ...body } = params; - return this._client.post(path$2`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * List Session Resources - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsSessionResource of client.beta.sessions.resources.list( - * 'sesn_011CZkZAtmR3yMPDzynEDxu7', - * )) { - * // ... - * } - * ``` - */ - list(sessionID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList(path$2`/v1/sessions/${sessionID}/resources?beta=true`, PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Delete Session Resource - * - * @example - * ```ts - * const betaManagedAgentsDeleteSessionResource = - * await client.beta.sessions.resources.delete( - * 'sesrsc_011CZkZBJq5dWxk9fVLNcPht', - * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' }, - * ); - * ``` - */ - delete(resourceID, params, options) { - const { session_id, betas } = params; - return this._client.delete(path$2`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Add Session Resource - * - * @example - * ```ts - * const betaManagedAgentsFileResource = - * await client.beta.sessions.resources.add( - * 'sesn_011CZkZAtmR3yMPDzynEDxu7', - * { - * file_id: 'file_011CNha8iCJcU1wXNR6q4V8w', - * type: 'file', - * }, - * ); - * ``` - */ - add(sessionID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/sessions/${sessionID}/resources?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/sessions/threads/events.mjs -var Events = class extends APIResource { - /** - * List Session Thread Events - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsSessionEvent of client.beta.sessions.threads.events.list( - * 'sthr_011CZkZVWa6oIjw0rgXZpnBt', - * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' }, - * )) { - * // ... - * } - * ``` - */ - list(threadID, params, options) { - const { session_id, betas, ...query } = params; - return this._client.getAPIList(path$2`/v1/sessions/${session_id}/threads/${threadID}/events?beta=true`, PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Stream Session Thread Events - * - * @example - * ```ts - * const betaManagedAgentsStreamSessionThreadEvents = - * await client.beta.sessions.threads.events.stream( - * 'sthr_011CZkZVWa6oIjw0rgXZpnBt', - * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' }, - * ); - * ``` - */ - stream(threadID, params, options) { - const { session_id, betas, ...query } = params; - return this._client.get(path$2`/v1/sessions/${session_id}/threads/${threadID}/stream?beta=true`, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]), - stream: true - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/sessions/threads/threads.mjs -var Threads = class extends APIResource { - constructor() { - super(...arguments); - this.events = new Events(this._client); - } - /** - * Get Session Thread - * - * @example - * ```ts - * const betaManagedAgentsSessionThread = - * await client.beta.sessions.threads.retrieve( - * 'sthr_011CZkZVWa6oIjw0rgXZpnBt', - * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' }, - * ); - * ``` - */ - retrieve(threadID, params, options) { - const { session_id, betas } = params; - return this._client.get(path$2`/v1/sessions/${session_id}/threads/${threadID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * List Session Threads - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsSessionThread of client.beta.sessions.threads.list( - * 'sesn_011CZkZAtmR3yMPDzynEDxu7', - * )) { - * // ... - * } - * ``` - */ - list(sessionID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList(path$2`/v1/sessions/${sessionID}/threads?beta=true`, PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Archive Session Thread - * - * @example - * ```ts - * const betaManagedAgentsSessionThread = - * await client.beta.sessions.threads.archive( - * 'sthr_011CZkZVWa6oIjw0rgXZpnBt', - * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' }, - * ); - * ``` - */ - archive(threadID, params, options) { - const { session_id, betas } = params; - return this._client.post(path$2`/v1/sessions/${session_id}/threads/${threadID}/archive?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } -}; -Threads.Events = Events; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/sessions/sessions.mjs -var Sessions = class extends APIResource { - constructor() { - super(...arguments); - this.events = new Events$1(this._client); - this.resources = new Resources(this._client); - this.threads = new Threads(this._client); - } - /** - * Create Session - * - * @example - * ```ts - * const betaManagedAgentsSession = - * await client.beta.sessions.create({ - * agent: 'agent_011CZkYpogX7uDKUyvBTophP', - * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW', - * }); - * ``` - */ - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/sessions?beta=true", { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Get Session - * - * @example - * ```ts - * const betaManagedAgentsSession = - * await client.beta.sessions.retrieve( - * 'sesn_011CZkZAtmR3yMPDzynEDxu7', - * ); - * ``` - */ - retrieve(sessionID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/sessions/${sessionID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Update Session - * - * @example - * ```ts - * const betaManagedAgentsSession = - * await client.beta.sessions.update( - * 'sesn_011CZkZAtmR3yMPDzynEDxu7', - * ); - * ``` - */ - update(sessionID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/sessions/${sessionID}?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * List Sessions - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsSession of client.beta.sessions.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/sessions?beta=true", BidirectionalPageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Delete Session - * - * @example - * ```ts - * const betaManagedAgentsDeletedSession = - * await client.beta.sessions.delete( - * 'sesn_011CZkZAtmR3yMPDzynEDxu7', - * ); - * ``` - */ - delete(sessionID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path$2`/v1/sessions/${sessionID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Archive Session - * - * @example - * ```ts - * const betaManagedAgentsSession = - * await client.beta.sessions.archive( - * 'sesn_011CZkZAtmR3yMPDzynEDxu7', - * ); - * ``` - */ - archive(sessionID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/sessions/${sessionID}/archive?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } -}; -Sessions.Events = Events$1; -Sessions.Resources = Resources; -Sessions.Threads = Threads; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs -var Versions = class extends APIResource { - /** - * Create Skill Version - * - * @example - * ```ts - * const version = await client.beta.skills.versions.create( - * 'skill_id', - * { files: [fs.createReadStream('path/to/file')] }, - * ); - * ``` - */ - create(skillID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions({ - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) - }, this._client, false)); - } - /** - * Get Skill Version - * - * @example - * ```ts - * const version = await client.beta.skills.versions.retrieve( - * 'version', - * { skill_id: 'skill_id' }, - * ); - * ``` - */ - retrieve(version, params, options) { - const { skill_id, betas } = params; - return this._client.get(path$2`/v1/skills/${skill_id}/versions/${version}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) - }); - } - /** - * List Skill Versions - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const versionListResponse of client.beta.skills.versions.list( - * 'skill_id', - * )) { - * // ... - * } - * ``` - */ - list(skillID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList(path$2`/v1/skills/${skillID}/versions?beta=true`, PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) - }); - } - /** - * Delete Skill Version - * - * @example - * ```ts - * const version = await client.beta.skills.versions.delete( - * 'version', - * { skill_id: 'skill_id' }, - * ); - * ``` - */ - delete(version, params, options) { - const { skill_id, betas } = params; - return this._client.delete(path$2`/v1/skills/${skill_id}/versions/${version}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) - }); - } - /** - * Download a skill version's content as a zip archive. - * - * @example - * ```ts - * const response = await client.beta.skills.versions.download( - * 'version', - * { skill_id: 'skill_id' }, - * ); - * - * const content = await response.blob(); - * console.log(content); - * ``` - */ - download(version, params, options) { - const { skill_id, betas } = params; - return this._client.get(path$2`/v1/skills/${skill_id}/versions/${version}/content?beta=true`, { - ...options, - headers: buildHeaders([{ - "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString(), - Accept: "application/binary" - }, options?.headers]), - __binaryResponse: true - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs -var Skills = class extends APIResource { - constructor() { - super(...arguments); - this.versions = new Versions(this._client); - } - /** - * Create Skill - * - * @example - * ```ts - * const skill = await client.beta.skills.create({ - * files: [fs.createReadStream('path/to/file')], - * }); - * ``` - */ - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/skills?beta=true", multipartFormRequestOptions({ - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) - }, this._client, false)); - } - /** - * Get Skill - * - * @example - * ```ts - * const skill = await client.beta.skills.retrieve('skill_id'); - * ``` - */ - retrieve(skillID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/skills/${skillID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) - }); - } - /** - * List Skills - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const skillListResponse of client.beta.skills.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/skills?beta=true", PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) - }); - } - /** - * Delete Skill - * - * @example - * ```ts - * const skill = await client.beta.skills.delete('skill_id'); - * ``` - */ - delete(skillID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path$2`/v1/skills/${skillID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) - }); - } -}; -Skills.Versions = Versions; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/tunnels/certificates.mjs -var Certificates = class extends APIResource { - /** - * The Tunnels API is in research preview. It requires the - * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a - * deprecation period. It supersedes the Admin API endpoints at - * `/v1/organizations/tunnels`, which remain available during a migration window. - * - * Registers a public CA certificate on a tunnel. Anthropic verifies the gateway's - * server certificate against this CA when it terminates the inner TLS session. A - * tunnel holds at most two non-archived certificates. - * - * @example - * ```ts - * const betaTunnelCertificate = - * await client.beta.tunnels.certificates.create( - * 'tunnel_id', - * { ca_certificate_pem: 'ca_certificate_pem' }, - * ); - * ``` - */ - create(tunnelID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/tunnels/${tunnelID}/certificates?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) - }); - } - /** - * The Tunnels API is in research preview. It requires the - * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a - * deprecation period. It supersedes the Admin API endpoints at - * `/v1/organizations/tunnels`, which remain available during a migration window. - * - * Fetches a tunnel certificate by ID. - * - * @example - * ```ts - * const betaTunnelCertificate = - * await client.beta.tunnels.certificates.retrieve( - * 'certificate_id', - * { tunnel_id: 'tunnel_id' }, - * ); - * ``` - */ - retrieve(certificateID, params, options) { - const { tunnel_id, betas } = params; - return this._client.get(path$2`/v1/tunnels/${tunnel_id}/certificates/${certificateID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) - }); - } - /** - * The Tunnels API is in research preview. It requires the - * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a - * deprecation period. It supersedes the Admin API endpoints at - * `/v1/organizations/tunnels`, which remain available during a migration window. - * - * Lists the certificates registered on a tunnel. Archived certificates are - * excluded unless include_archived is set. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaTunnelCertificate of client.beta.tunnels.certificates.list( - * 'tunnel_id', - * )) { - * // ... - * } - * ``` - */ - list(tunnelID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList(path$2`/v1/tunnels/${tunnelID}/certificates?beta=true`, PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) - }); - } - /** - * The Tunnels API is in research preview. It requires the - * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a - * deprecation period. It supersedes the Admin API endpoints at - * `/v1/organizations/tunnels`, which remain available during a migration window. - * - * Archives a tunnel certificate, removing it from the set Anthropic trusts for the - * tunnel. The certificate record is retained. Archiving the last non-archived - * certificate is permitted; the tunnel rejects MCP traffic until a new certificate - * is added. - * - * @example - * ```ts - * const betaTunnelCertificate = - * await client.beta.tunnels.certificates.archive( - * 'certificate_id', - * { tunnel_id: 'tunnel_id' }, - * ); - * ``` - */ - archive(certificateID, params, options) { - const { tunnel_id, betas } = params; - return this._client.post(path$2`/v1/tunnels/${tunnel_id}/certificates/${certificateID}/archive?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/tunnels/tunnels.mjs -var Tunnels = class extends APIResource { - constructor() { - super(...arguments); - this.certificates = new Certificates(this._client); - } - /** - * The Tunnels API is in research preview. It requires the - * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a - * deprecation period. It supersedes the Admin API endpoints at - * `/v1/organizations/tunnels`, which remain available during a migration window. - * - * Creates a tunnel. Creation allocates a fresh hostname and provisions the tunnel; - * it is not idempotent. The new tunnel rejects MCP traffic until at least one CA - * certificate is added. - * - * @example - * ```ts - * const betaTunnel = await client.beta.tunnels.create(); - * ``` - */ - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/tunnels?beta=true", { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) - }); - } - /** - * The Tunnels API is in research preview. It requires the - * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a - * deprecation period. It supersedes the Admin API endpoints at - * `/v1/organizations/tunnels`, which remain available during a migration window. - * - * Fetches a tunnel by ID. - * - * @example - * ```ts - * const betaTunnel = await client.beta.tunnels.retrieve( - * 'tunnel_id', - * ); - * ``` - */ - retrieve(tunnelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/tunnels/${tunnelID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) - }); - } - /** - * The Tunnels API is in research preview. It requires the - * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a - * deprecation period. It supersedes the Admin API endpoints at - * `/v1/organizations/tunnels`, which remain available during a migration window. - * - * Lists tunnels. Results are ordered by creation time, newest first; archived - * tunnels are excluded unless include_archived is set. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaTunnel of client.beta.tunnels.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/tunnels?beta=true", PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) - }); - } - /** - * The Tunnels API is in research preview. It requires the - * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a - * deprecation period. It supersedes the Admin API endpoints at - * `/v1/organizations/tunnels`, which remain available during a migration window. - * - * Archives a tunnel. Archival is irreversible: every non-archived certificate on - * the tunnel is archived in the same operation, the hostname is retired and never - * re-allocated, and the tunnel token is invalidated. Retrying against an - * already-archived tunnel returns the existing record unchanged. - * - * @example - * ```ts - * const betaTunnel = await client.beta.tunnels.archive( - * 'tunnel_id', - * ); - * ``` - */ - archive(tunnelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/tunnels/${tunnelID}/archive?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) - }); - } - /** - * The Tunnels API is in research preview. It requires the - * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a - * deprecation period. It supersedes the Admin API endpoints at - * `/v1/organizations/tunnels`, which remain available during a migration window. - * - * Reveals a tunnel's connector token. The value is fetched live on each call; - * Anthropic does not store it. Repeated calls return the same value until the - * token is rotated. Exposed as POST so the token does not appear in intermediary - * access logs. - * - * @example - * ```ts - * const betaTunnelToken = - * await client.beta.tunnels.revealToken('tunnel_id'); - * ``` - */ - revealToken(tunnelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/tunnels/${tunnelID}/reveal_token?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) - }); - } - /** - * The Tunnels API is in research preview. It requires the - * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a - * deprecation period. It supersedes the Admin API endpoints at - * `/v1/organizations/tunnels`, which remain available during a migration window. - * - * Rotates a tunnel's connector token. Rotation invalidates the current token for - * new connections and returns a fresh value; established connections are not - * severed. A connector restarted after rotation must use the new value. - * - * @example - * ```ts - * const betaTunnelToken = - * await client.beta.tunnels.rotateToken('tunnel_id'); - * ``` - */ - rotateToken(tunnelID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/tunnels/${tunnelID}/rotate_token?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) - }); - } -}; -Tunnels.Certificates = Certificates; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/vaults/credentials.mjs -var Credentials = class extends APIResource { - /** - * Create Credential - * - * @example - * ```ts - * const betaManagedAgentsCredential = - * await client.beta.vaults.credentials.create( - * 'vlt_011CZkZDLs7fYzm1hXNPeRjv', - * { - * auth: { - * token: 'bearer_exampletoken', - * mcp_server_url: - * 'https://example-server.modelcontextprotocol.io/sse', - * type: 'static_bearer', - * }, - * }, - * ); - * ``` - */ - create(vaultID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/vaults/${vaultID}/credentials?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Get Credential - * - * @example - * ```ts - * const betaManagedAgentsCredential = - * await client.beta.vaults.credentials.retrieve( - * 'vcrd_011CZkZEMt8gZan2iYOQfSkw', - * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' }, - * ); - * ``` - */ - retrieve(credentialID, params, options) { - const { vault_id, betas } = params; - return this._client.get(path$2`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Update Credential - * - * @example - * ```ts - * const betaManagedAgentsCredential = - * await client.beta.vaults.credentials.update( - * 'vcrd_011CZkZEMt8gZan2iYOQfSkw', - * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' }, - * ); - * ``` - */ - update(credentialID, params, options) { - const { vault_id, betas, ...body } = params; - return this._client.post(path$2`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * List Credentials - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsCredential of client.beta.vaults.credentials.list( - * 'vlt_011CZkZDLs7fYzm1hXNPeRjv', - * )) { - * // ... - * } - * ``` - */ - list(vaultID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList(path$2`/v1/vaults/${vaultID}/credentials?beta=true`, PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Delete Credential - * - * @example - * ```ts - * const betaManagedAgentsDeletedCredential = - * await client.beta.vaults.credentials.delete( - * 'vcrd_011CZkZEMt8gZan2iYOQfSkw', - * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' }, - * ); - * ``` - */ - delete(credentialID, params, options) { - const { vault_id, betas } = params; - return this._client.delete(path$2`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Archive Credential - * - * @example - * ```ts - * const betaManagedAgentsCredential = - * await client.beta.vaults.credentials.archive( - * 'vcrd_011CZkZEMt8gZan2iYOQfSkw', - * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' }, - * ); - * ``` - */ - archive(credentialID, params, options) { - const { vault_id, betas } = params; - return this._client.post(path$2`/v1/vaults/${vault_id}/credentials/${credentialID}/archive?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Validate Credential - * - * @example - * ```ts - * const betaManagedAgentsCredentialValidation = - * await client.beta.vaults.credentials.mcpOAuthValidate( - * 'vcrd_011CZkZEMt8gZan2iYOQfSkw', - * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' }, - * ); - * ``` - */ - mcpOAuthValidate(credentialID, params, options) { - const { vault_id, betas } = params; - return this._client.post(path$2`/v1/vaults/${vault_id}/credentials/${credentialID}/mcp_oauth_validate?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/vaults/vaults.mjs -var Vaults = class extends APIResource { - constructor() { - super(...arguments); - this.credentials = new Credentials(this._client); - } - /** - * Create Vault - * - * @example - * ```ts - * const betaManagedAgentsVault = - * await client.beta.vaults.create({ - * display_name: 'Example vault', - * }); - * ``` - */ - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/vaults?beta=true", { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Get Vault - * - * @example - * ```ts - * const betaManagedAgentsVault = - * await client.beta.vaults.retrieve( - * 'vlt_011CZkZDLs7fYzm1hXNPeRjv', - * ); - * ``` - */ - retrieve(vaultID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/vaults/${vaultID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Update Vault - * - * @example - * ```ts - * const betaManagedAgentsVault = - * await client.beta.vaults.update( - * 'vlt_011CZkZDLs7fYzm1hXNPeRjv', - * ); - * ``` - */ - update(vaultID, params, options) { - const { betas, ...body } = params; - return this._client.post(path$2`/v1/vaults/${vaultID}?beta=true`, { - body, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * List Vaults - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaManagedAgentsVault of client.beta.vaults.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/vaults?beta=true", PageCursor, { - query, - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Delete Vault - * - * @example - * ```ts - * const betaManagedAgentsDeletedVault = - * await client.beta.vaults.delete( - * 'vlt_011CZkZDLs7fYzm1hXNPeRjv', - * ); - * ``` - */ - delete(vaultID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path$2`/v1/vaults/${vaultID}?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } - /** - * Archive Vault - * - * @example - * ```ts - * const betaManagedAgentsVault = - * await client.beta.vaults.archive( - * 'vlt_011CZkZDLs7fYzm1hXNPeRjv', - * ); - * ``` - */ - archive(vaultID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path$2`/v1/vaults/${vaultID}/archive?beta=true`, { - ...options, - headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) - }); - } -}; -Vaults.Credentials = Credentials; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs -var Beta = class extends APIResource { - constructor() { - super(...arguments); - this.models = new Models$1(this._client); - this.messages = new Messages$1(this._client); - this.agents = new Agents(this._client); - this.environments = new Environments(this._client); - this.sessions = new Sessions(this._client); - this.deployments = new Deployments(this._client); - this.deploymentRuns = new DeploymentRuns(this._client); - this.vaults = new Vaults(this._client); - this.memoryStores = new MemoryStores(this._client); - this.files = new Files(this._client); - this.skills = new Skills(this._client); - this.webhooks = new Webhooks(this._client); - this.userProfiles = new UserProfiles(this._client); - this.dreams = new Dreams(this._client); - this.tunnels = new Tunnels(this._client); - } -}; -Beta.Models = Models$1; -Beta.Messages = Messages$1; -Beta.Agents = Agents; -Beta.Environments = Environments; -Beta.Sessions = Sessions; -Beta.Deployments = Deployments; -Beta.DeploymentRuns = DeploymentRuns; -Beta.Vaults = Vaults; -Beta.MemoryStores = MemoryStores; -Beta.Files = Files; -Beta.Skills = Skills; -Beta.Webhooks = Webhooks; -Beta.UserProfiles = UserProfiles; -Beta.Dreams = Dreams; -Beta.Tunnels = Tunnels; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/completions.mjs -var Completions = class extends APIResource { - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/complete", { - body, - timeout: this._client._options.timeout ?? 6e5, - ...options, - headers: buildHeaders([{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, options?.headers]), - stream: params.stream ?? false - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/parser.mjs -function getOutputFormat(params) { - return params?.output_config?.format; -} -function maybeParseMessage(message, params, opts) { - const outputFormat = getOutputFormat(params); - if (!params || !("parse" in (outputFormat ?? {}))) return { - ...message, - content: message.content.map((block) => { - if (block.type === "text") return Object.defineProperty({ ...block }, "parsed_output", { - value: null, - enumerable: false - }); - return block; - }), - parsed_output: null - }; - return parseMessage(message, params, opts); -} -function parseMessage(message, params, opts) { - let firstParsedOutput = null; - const content = message.content.map((block) => { - if (block.type === "text") { - const parsedOutput = parseOutputFormat(params, block.text); - if (firstParsedOutput === null) firstParsedOutput = parsedOutput; - return Object.defineProperty({ ...block }, "parsed_output", { - value: parsedOutput, - enumerable: false - }); - } - return block; - }); - return { - ...message, - content, - parsed_output: firstParsedOutput - }; -} -function parseOutputFormat(params, content) { - const outputFormat = getOutputFormat(params); - if (outputFormat?.type !== "json_schema") return null; - try { - if ("parse" in outputFormat) return outputFormat.parse(content); - return JSON.parse(content); - } catch (error) { - throw new AnthropicError(`Failed to parse structured output: ${error}`); - } -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs -var _MessageStream_instances; -var _MessageStream_currentMessageSnapshot; -var _MessageStream_params; -var _MessageStream_connectedPromise; -var _MessageStream_resolveConnectedPromise; -var _MessageStream_rejectConnectedPromise; -var _MessageStream_endPromise; -var _MessageStream_resolveEndPromise; -var _MessageStream_rejectEndPromise; -var _MessageStream_listeners; -var _MessageStream_ended; -var _MessageStream_errored; -var _MessageStream_aborted; -var _MessageStream_catchingPromiseCreated; -var _MessageStream_response; -var _MessageStream_request_id; -var _MessageStream_logger; -var _MessageStream_getFinalMessage; -var _MessageStream_getFinalText; -var _MessageStream_handleError; -var _MessageStream_beginRequest; -var _MessageStream_addStreamEvent; -var _MessageStream_endRequest; -var _MessageStream_accumulateMessage; -function tracksToolInput(content) { - return content.type === "tool_use" || content.type === "server_tool_use"; -} -var MessageStream = class MessageStream { - constructor(params, opts) { - _MessageStream_instances.add(this); - this.messages = []; - this.receivedMessages = []; - _MessageStream_currentMessageSnapshot.set(this, void 0); - _MessageStream_params.set(this, null); - this.controller = new AbortController(); - _MessageStream_connectedPromise.set(this, void 0); - _MessageStream_resolveConnectedPromise.set(this, () => {}); - _MessageStream_rejectConnectedPromise.set(this, () => {}); - _MessageStream_endPromise.set(this, void 0); - _MessageStream_resolveEndPromise.set(this, () => {}); - _MessageStream_rejectEndPromise.set(this, () => {}); - _MessageStream_listeners.set(this, {}); - _MessageStream_ended.set(this, false); - _MessageStream_errored.set(this, false); - _MessageStream_aborted.set(this, false); - _MessageStream_catchingPromiseCreated.set(this, false); - _MessageStream_response.set(this, void 0); - _MessageStream_request_id.set(this, void 0); - _MessageStream_logger.set(this, void 0); - _MessageStream_handleError.set(this, (error) => { - __classPrivateFieldSet(this, _MessageStream_errored, true, "f"); - if (isAbortError(error)) error = new APIUserAbortError(); - if (error instanceof APIUserAbortError) { - __classPrivateFieldSet(this, _MessageStream_aborted, true, "f"); - return this._emit("abort", error); - } - if (error instanceof AnthropicError) return this._emit("error", error); - if (error instanceof Error) { - const anthropicError = new AnthropicError(error.message); - anthropicError.cause = error; - return this._emit("error", anthropicError); - } - return this._emit("error", new AnthropicError(String(error))); - }); - __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, "f"); - __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f"); - }), "f"); - __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, "f"); - __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f"); - }), "f"); - __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => {}); - __classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => {}); - __classPrivateFieldSet(this, _MessageStream_params, params, "f"); - __classPrivateFieldSet(this, _MessageStream_logger, opts?.logger ?? console, "f"); - } - get response() { - return __classPrivateFieldGet(this, _MessageStream_response, "f"); - } - get request_id() { - return __classPrivateFieldGet(this, _MessageStream_request_id, "f"); - } - /** - * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, - * returned vie the `request-id` header which is useful for debugging requests and resporting - * issues to Anthropic. - * - * This is the same as the `APIPromise.withResponse()` method. - * - * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` - * as no `Response` is available. - */ - async withResponse() { - __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f"); - if (!response) throw new Error("Could not resolve a `Response` object"); - return { - data: this, - response, - request_id: response.headers.get("request-id") - }; - } - /** - * Intended for use on the frontend, consuming a stream produced with - * `.toReadableStream()` on the backend. - * - * Note that messages sent to the model do not appear in `.on('message')` - * in this context. - */ - static fromReadableStream(stream) { - const runner = new MessageStream(null); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - static createMessage(messages, params, options, { logger } = {}) { - const runner = new MessageStream(params, { logger }); - for (const message of params.messages) runner._addMessageParam(message); - __classPrivateFieldSet(runner, _MessageStream_params, { - ...params, - stream: true - }, "f"); - runner._run(() => runner._createMessage(messages, { - ...params, - stream: true - }, { - ...options, - headers: { - ...options?.headers, - [STAINLESS_HELPER_METHOD_HEADER]: "stream" - } - })); - return runner; - } - _run(executor) { - executor().then(() => { - this._emitFinal(); - this._emit("end"); - }, __classPrivateFieldGet(this, _MessageStream_handleError, "f")); - } - _addMessageParam(message) { - this.messages.push(message); - } - _addMessage(message, emit = true) { - this.receivedMessages.push(message); - if (emit) this._emit("message", message); - } - async _createMessage(messages, params, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener("abort", abortHandler); - } - try { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); - const { response, data: stream } = await messages.create({ - ...params, - stream: true - }, { - ...options, - signal: this.controller.signal - }).withResponse(); - this._connected(response); - for await (const event of stream) __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); - if (stream.controller.signal?.aborted) throw new APIUserAbortError(); - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); - } finally { - if (signal && abortHandler) signal.removeEventListener("abort", abortHandler); - } - } - _connected(response) { - if (this.ended) return; - __classPrivateFieldSet(this, _MessageStream_response, response, "f"); - __classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get("request-id"), "f"); - __classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response); - this._emit("connect"); - } - get ended() { - return __classPrivateFieldGet(this, _MessageStream_ended, "f"); - } - get errored() { - return __classPrivateFieldGet(this, _MessageStream_errored, "f"); - } - get aborted() { - return __classPrivateFieldGet(this, _MessageStream_aborted, "f"); - } - abort() { - this.controller.abort(); - } - /** - * Adds the listener function to the end of the listeners array for the event. - * No checks are made to see if the listener has already been added. Multiple calls passing - * the same combination of event and listener will result in the listener being added, and - * called, multiple times. - * @returns this MessageStream, so that calls can be chained - */ - on(event, listener) { - (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = [])).push({ listener }); - return this; - } - /** - * Removes the specified listener from the listener array for the event. - * off() will remove, at most, one instance of a listener from the listener array. If any single - * listener has been added multiple times to the listener array for the specified event, then - * off() must be called multiple times to remove each instance. - * @returns this MessageStream, so that calls can be chained - */ - off(event, listener) { - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; - if (!listeners) return this; - const index = listeners.findIndex((l) => l.listener === listener); - if (index >= 0) listeners.splice(index, 1); - return this; - } - /** - * Adds a one-time listener function for the event. The next time the event is triggered, - * this listener is removed and then invoked. - * @returns this MessageStream, so that calls can be chained - */ - once(event, listener) { - (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = [])).push({ - listener, - once: true - }); - return this; - } - /** - * This is similar to `.once()`, but returns a Promise that resolves the next time - * the event is triggered, instead of calling a listener callback. - * @returns a Promise that resolves the next time given event is triggered, - * or rejects if an error is emitted. (If you request the 'error' event, - * returns a promise that resolves with the error). - * - * Example: - * - * const message = await stream.emitted('message') // rejects if the stream errors - */ - emitted(event) { - return new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - if (event !== "error") this.once("error", reject); - this.once(event, resolve); - }); - } - async done() { - __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - await __classPrivateFieldGet(this, _MessageStream_endPromise, "f"); - } - get currentMessage() { - return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - } - /** - * @returns a promise that resolves with the the final assistant Message response, - * or rejects if an error occurred or the stream ended prematurely without producing a Message. - * If structured outputs were used, this will be a ParsedMessage with a `parsed_output` field. - */ - async finalMessage() { - await this.done(); - return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this); - } - /** - * @returns a promise that resolves with the the final assistant Message's text response, concatenated - * together if there are more than one text blocks. - * Rejects if an error occurred or the stream ended prematurely without producing a Message. - */ - async finalText() { - await this.done(); - return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this); - } - _emit(event, ...args) { - if (__classPrivateFieldGet(this, _MessageStream_ended, "f")) return; - if (event === "end") { - __classPrivateFieldSet(this, _MessageStream_ended, true, "f"); - __classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this); - } - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; - if (listeners) { - __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); - listeners.forEach(({ listener }) => listener(...args)); - } - if (event === "abort") { - const error = args[0]; - if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) Promise.reject(error); - __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); - __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); - this._emit("end"); - return; - } - if (event === "error") { - const error = args[0]; - if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) Promise.reject(error); - __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); - __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); - this._emit("end"); - } - } - _emitFinal() { - if (this.receivedMessages.at(-1)) this._emit("finalMessage", __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this)); - } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener("abort", abortHandler); - } - try { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); - this._connected(null); - const stream = Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); - if (stream.controller.signal?.aborted) throw new APIUserAbortError(); - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); - } finally { - if (signal && abortHandler) signal.removeEventListener("abort", abortHandler); - } - } - [(_MessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _MessageStream_params = /* @__PURE__ */ new WeakMap(), _MessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_listeners = /* @__PURE__ */ new WeakMap(), _MessageStream_ended = /* @__PURE__ */ new WeakMap(), _MessageStream_errored = /* @__PURE__ */ new WeakMap(), _MessageStream_aborted = /* @__PURE__ */ new WeakMap(), _MessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _MessageStream_response = /* @__PURE__ */ new WeakMap(), _MessageStream_request_id = /* @__PURE__ */ new WeakMap(), _MessageStream_logger = /* @__PURE__ */ new WeakMap(), _MessageStream_handleError = /* @__PURE__ */ new WeakMap(), _MessageStream_instances = /* @__PURE__ */ new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() { - if (this.receivedMessages.length === 0) throw new AnthropicError("stream ended without producing a Message with role=assistant"); - return this.receivedMessages.at(-1); - }, _MessageStream_getFinalText = function _MessageStream_getFinalText() { - if (this.receivedMessages.length === 0) throw new AnthropicError("stream ended without producing a Message with role=assistant"); - const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text); - if (textBlocks.length === 0) throw new AnthropicError("stream ended without producing a content block with type=text"); - return textBlocks.join(" "); - }, _MessageStream_beginRequest = function _MessageStream_beginRequest() { - if (this.ended) return; - __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, void 0, "f"); - }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) { - if (this.ended) return; - const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event); - this._emit("streamEvent", event, messageSnapshot); - switch (event.type) { - case "content_block_delta": { - const content = messageSnapshot.content.at(-1); - switch (event.delta.type) { - case "text_delta": - if (content.type === "text") this._emit("text", event.delta.text, content.text || ""); - break; - case "citations_delta": - if (content.type === "text") this._emit("citation", event.delta.citation, content.citations ?? []); - break; - case "input_json_delta": - if (tracksToolInput(content) && __classPrivateFieldGet(this, _MessageStream_listeners, "f").inputJson?.length) this._emit("inputJson", event.delta.partial_json, content.input); - break; - case "thinking_delta": - if (content.type === "thinking") this._emit("thinking", event.delta.thinking, content.thinking); - break; - case "signature_delta": - if (content.type === "thinking") this._emit("signature", content.signature); - break; - default: event.delta; - } - break; - } - case "message_stop": - this._addMessageParam(messageSnapshot); - this._addMessage(maybeParseMessage(messageSnapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }), true); - break; - case "content_block_stop": - this._emit("contentBlock", messageSnapshot.content.at(-1)); - break; - case "message_start": - __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f"); - break; - case "content_block_start": - case "message_delta": break; - } - }, _MessageStream_endRequest = function _MessageStream_endRequest() { - if (this.ended) throw new AnthropicError(`stream has ended, this shouldn't happen`); - const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - if (!snapshot) throw new AnthropicError(`request ended without sending any chunks`); - __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, void 0, "f"); - return maybeParseMessage(snapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }); - }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) { - let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - if (event.type === "message_start") { - if (snapshot) throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); - return event.message; - } - if (!snapshot) throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); - switch (event.type) { - case "message_stop": return snapshot; - case "message_delta": - snapshot.stop_reason = event.delta.stop_reason; - snapshot.stop_sequence = event.delta.stop_sequence; - if (event.delta.stop_details != null) snapshot.stop_details = event.delta.stop_details; - snapshot.usage.output_tokens = event.usage.output_tokens; - if (event.usage.input_tokens != null) snapshot.usage.input_tokens = event.usage.input_tokens; - if (event.usage.cache_creation_input_tokens != null) snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; - if (event.usage.cache_read_input_tokens != null) snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; - if (event.usage.server_tool_use != null) snapshot.usage.server_tool_use = event.usage.server_tool_use; - return snapshot; - case "content_block_start": - snapshot.content.push({ ...event.content_block }); - return snapshot; - case "content_block_delta": { - const snapshotContent = snapshot.content.at(event.index); - switch (event.delta.type) { - case "text_delta": - if (snapshotContent?.type === "text") snapshot.content[event.index] = { - ...snapshotContent, - text: (snapshotContent.text || "") + event.delta.text - }; - break; - case "citations_delta": - if (snapshotContent?.type === "text") snapshot.content[event.index] = { - ...snapshotContent, - citations: [...snapshotContent.citations ?? [], event.delta.citation] - }; - break; - case "input_json_delta": - if (snapshotContent && tracksToolInput(snapshotContent)) { - const jsonBuf = (snapshotContent["__json_buf"] || "") + event.delta.partial_json; - snapshot.content[event.index] = withLazyInput(snapshotContent, jsonBuf); - } - break; - case "thinking_delta": - if (snapshotContent?.type === "thinking") snapshot.content[event.index] = { - ...snapshotContent, - thinking: snapshotContent.thinking + event.delta.thinking - }; - break; - case "signature_delta": - if (snapshotContent?.type === "thinking") snapshot.content[event.index] = { - ...snapshotContent, - signature: event.delta.signature - }; - break; - default: event.delta; - } - return snapshot; - } - case "content_block_stop": { - const snapshotContent = snapshot.content.at(event.index); - if (snapshotContent && tracksToolInput(snapshotContent) && "__json_buf" in snapshotContent) Object.defineProperty(snapshotContent, "input", { - value: snapshotContent.input, - enumerable: true, - configurable: true, - writable: true - }); - return snapshot; - } - } - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on("streamEvent", (event) => { - const reader = readQueue.shift(); - if (reader) reader.resolve(event); - else pushQueue.push(event); - }); - this.on("end", () => { - done = true; - for (const reader of readQueue) reader.resolve(void 0); - readQueue.length = 0; - }); - this.on("abort", (err) => { - done = true; - for (const reader of readQueue) reader.reject(err); - readQueue.length = 0; - }); - this.on("error", (err) => { - done = true; - for (const reader of readQueue) reader.reject(err); - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) return { - value: void 0, - done: true - }; - return new Promise((resolve, reject) => readQueue.push({ - resolve, - reject - })).then((chunk) => chunk ? { - value: chunk, - done: false - } : { - value: void 0, - done: true - }); - } - return { - value: pushQueue.shift(), - done: false - }; - }, - return: async () => { - this.abort(); - return { - value: void 0, - done: true - }; - } - }; - } - toReadableStream() { - return new Stream(this[Symbol.asyncIterator].bind(this), this.controller).toReadableStream(); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs -var Batches = class extends APIResource { - /** - * Send a batch of Message creation requests. - * - * The Message Batches API can be used to process multiple Messages API requests at - * once. Once a Message Batch is created, it begins processing immediately. Batches - * can take up to 24 hours to complete. - * - * Learn more about the Message Batches API in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatch = await client.messages.batches.create({ - * requests: [ - * { - * custom_id: 'my-custom-id-1', - * params: { - * max_tokens: 1024, - * messages: [ - * { content: 'Hello, world', role: 'user' }, - * ], - * model: 'claude-opus-4-6', - * }, - * }, - * ], - * }); - * ``` - */ - create(params, options) { - const { user_profile_id, ...body } = params; - return this._client.post("/v1/messages/batches", { - body, - ...options, - headers: buildHeaders([{ ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0 }, options?.headers]) - }); - } - /** - * This endpoint is idempotent and can be used to poll for Message Batch - * completion. To access the results of a Message Batch, make a request to the - * `results_url` field in the response. - * - * Learn more about the Message Batches API in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatch = await client.messages.batches.retrieve( - * 'message_batch_id', - * ); - * ``` - */ - retrieve(messageBatchID, options) { - return this._client.get(path$2`/v1/messages/batches/${messageBatchID}`, options); - } - /** - * List all Message Batches within a Workspace. Most recently created batches are - * returned first. - * - * Learn more about the Message Batches API in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const messageBatch of client.messages.batches.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList("/v1/messages/batches", Page, { - query, - ...options - }); - } - /** - * Delete a Message Batch. - * - * Message Batches can only be deleted once they've finished processing. If you'd - * like to delete an in-progress batch, you must first cancel it. - * - * Learn more about the Message Batches API in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) - * - * @example - * ```ts - * const deletedMessageBatch = - * await client.messages.batches.delete('message_batch_id'); - * ``` - */ - delete(messageBatchID, options) { - return this._client.delete(path$2`/v1/messages/batches/${messageBatchID}`, options); - } - /** - * Batches may be canceled any time before processing ends. Once cancellation is - * initiated, the batch enters a `canceling` state, at which time the system may - * complete any in-progress, non-interruptible requests before finalizing - * cancellation. - * - * The number of canceled requests is specified in `request_counts`. To determine - * which requests were canceled, check the individual results within the batch. - * Note that cancellation may not result in any canceled requests if they were - * non-interruptible. - * - * Learn more about the Message Batches API in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatch = await client.messages.batches.cancel( - * 'message_batch_id', - * ); - * ``` - */ - cancel(messageBatchID, options) { - return this._client.post(path$2`/v1/messages/batches/${messageBatchID}/cancel`, options); - } - /** - * Streams the results of a Message Batch as a `.jsonl` file. - * - * Each line in the file is a JSON object containing the result of a single request - * in the Message Batch. Results are not guaranteed to be in the same order as - * requests. Use the `custom_id` field to match results to requests. - * - * Learn more about the Message Batches API in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatchIndividualResponse = - * await client.messages.batches.results('message_batch_id'); - * ``` - */ - async results(messageBatchID, options) { - const batch = await this.retrieve(messageBatchID); - if (!batch.results_url) throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); - return this._client.get(batch.results_url, { - ...options, - headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]), - stream: true, - __binaryResponse: true - })._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs -var Messages = class extends APIResource { - constructor() { - super(...arguments); - this.batches = new Batches(this._client); - } - create(params, options) { - const { user_profile_id, ...body } = params; - if (body.model in DEPRECATED_MODELS) console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); - if (MODELS_TO_WARN_WITH_THINKING_ENABLED.includes(body.model) && body.thinking && body.thinking.type === "enabled") console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`); - let timeout = this._client._options.timeout; - if (!body.stream && timeout == null) { - const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? void 0; - timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); - } - const helperHeader = stainlessHelperHeader(body.tools, body.messages); - return this._client.post("/v1/messages", { - body, - timeout: timeout ?? 6e5, - ...options, - headers: buildHeaders([ - { ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0 }, - helperHeader, - options?.headers - ]), - stream: params.stream ?? false - }); - } - /** - * Send a structured list of input messages with text and/or image content, along with an expected `output_config.format` and - * the response will be automatically parsed and available in the `parsed_output` property of the message. - * - * @example - * ```ts - * const message = await client.messages.parse({ - * model: 'claude-sonnet-4-5-20250929', - * max_tokens: 1024, - * messages: [{ role: 'user', content: 'What is 2+2?' }], - * output_config: { - * format: zodOutputFormat(z.object({ answer: z.number() })), - * }, - * }); - * - * console.log(message.parsed_output?.answer); // 4 - * ``` - */ - parse(params, options) { - return this.create(params, options).then((message) => parseMessage(message, params, { logger: this._client.logger ?? console })); - } - /** - * Create a Message stream. - * - * If `output_config.format` is provided with a parseable format (like `zodOutputFormat()`), - * the final message will include a `parsed_output` property with the parsed content. - * - * @example - * ```ts - * const stream = client.messages.stream({ - * model: 'claude-sonnet-4-5-20250929', - * max_tokens: 1024, - * messages: [{ role: 'user', content: 'What is 2+2?' }], - * output_config: { - * format: zodOutputFormat(z.object({ answer: z.number() })), - * }, - * }); - * - * const message = await stream.finalMessage(); - * console.log(message.parsed_output?.answer); // 4 - * ``` - */ - stream(body, options) { - return MessageStream.createMessage(this, body, options, { logger: this._client.logger ?? console }); - } - /** - * Count the number of tokens in a Message. - * - * The Token Count API can be used to count the number of tokens in a Message, - * including tools, images, and documents, without creating it. - * - * Learn more about token counting in our - * [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting) - * - * @example - * ```ts - * const messageTokensCount = - * await client.messages.countTokens({ - * messages: [{ content: 'Hello, world', role: 'user' }], - * model: 'claude-opus-4-6', - * }); - * ``` - */ - countTokens(params, options) { - const { user_profile_id, ...body } = params; - return this._client.post("/v1/messages/count_tokens", { - body, - ...options, - headers: buildHeaders([{ ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0 }, options?.headers]) - }); - } -}; -var DEPRECATED_MODELS = { - "claude-1.3": "November 6th, 2024", - "claude-1.3-100k": "November 6th, 2024", - "claude-instant-1.1": "November 6th, 2024", - "claude-instant-1.1-100k": "November 6th, 2024", - "claude-instant-1.2": "November 6th, 2024", - "claude-3-sonnet-20240229": "July 21st, 2025", - "claude-3-opus-20240229": "January 5th, 2026", - "claude-2.1": "July 21st, 2025", - "claude-2.0": "July 21st, 2025", - "claude-3-7-sonnet-latest": "February 19th, 2026", - "claude-3-7-sonnet-20250219": "February 19th, 2026", - "claude-3-5-haiku-latest": "February 19th, 2026", - "claude-3-5-haiku-20241022": "February 19th, 2026", - "claude-opus-4-0": "June 15th, 2026", - "claude-opus-4-20250514": "June 15th, 2026", - "claude-sonnet-4-0": "June 15th, 2026", - "claude-sonnet-4-20250514": "June 15th, 2026", - "claude-opus-4-1": "August 5th, 2026", - "claude-opus-4-1-20250805": "August 5th, 2026", - "claude-mythos-preview": "June 30th, 2026" -}; -var MODELS_TO_WARN_WITH_THINKING_ENABLED = ["claude-mythos-preview", "claude-opus-4-6"]; -Messages.Batches = Batches; -//#endregion -//#region node_modules/@anthropic-ai/sdk/resources/models.mjs -var Models = class extends APIResource { - /** - * Get a specific model. - * - * The Models API response can be used to determine information about a specific - * model or resolve a model alias to a model ID. - */ - retrieve(modelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path$2`/v1/models/${modelID}`, { - ...options, - headers: buildHeaders([{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, options?.headers]) - }); - } - /** - * List available models. - * - * The Models API response can be used to determine which models are available for - * use in the API. More recently released models are listed first. - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList("/v1/models", Page, { - query, - ...options, - headers: buildHeaders([{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, options?.headers]) - }); - } -}; -//#endregion -//#region node_modules/@anthropic-ai/sdk/client.mjs -var _BaseAnthropic_instances; -var _a; -var _BaseAnthropic_encoder; -var _BaseAnthropic_baseURLOverridden; -var HUMAN_PROMPT = "\\n\\nHuman:"; -var AI_PROMPT = "\\n\\nAssistant:"; -/** -* Base class for Anthropic API clients. -*/ -var BaseAnthropic = class { - /** - * The active credential provider. Default credential resolution runs once - * at construction time. If it fails, the error is surfaced on every - * request and the client must be reconstructed — there is no retry path. - * - * Clones returned by {@link withOptions} share the parent's auth state - * (provider, token cache, pending resolution, and any resolution error) - * unless the caller passes an explicit `apiKey`, `authToken`, - * `credentials`, `config`, or `profile` override. - */ - get credentials() { - return this._authState.provider; - } - /** - * API Client for interfacing with the Anthropic API. - * - * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null] - * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null] - * @param {string | null | undefined} [opts.webhookKey=process.env['ANTHROPIC_WEBHOOK_SIGNING_KEY'] ?? null] - * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. - */ - constructor({ baseURL = readEnv("ANTHROPIC_BASE_URL"), apiKey, authToken, webhookKey = readEnv("ANTHROPIC_WEBHOOK_SIGNING_KEY") ?? null, ...opts } = {}) { - _BaseAnthropic_instances.add(this); - this._requestAuthFlags = /* @__PURE__ */ new WeakMap(); - _BaseAnthropic_encoder.set(this, void 0); - if (apiKey === void 0) apiKey = opts.profile != null ? null : readEnv("ANTHROPIC_API_KEY") ?? null; - if (authToken === void 0) authToken = opts.profile != null ? null : readEnv("ANTHROPIC_AUTH_TOKEN") ?? null; - if (opts.profile != null && (opts.credentials != null || opts.config != null)) throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`."); - const options = { - apiKey, - authToken, - webhookKey, - ...opts, - baseURL: baseURL || `https://api.anthropic.com` - }; - if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) throw new AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n"); - this.baseURL = options.baseURL; - this._baseURLIsExplicit = opts.__baseURLIsExplicit ?? !!baseURL; - this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT; - this.logger = options.logger ?? console; - this.logLevel = defaultLogLevel; - this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", loggerFor(this)) ?? parseLogLevel(readEnv("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", loggerFor(this)) ?? "warn"; - this.fetchOptions = options.fetchOptions; - this.maxRetries = options.maxRetries ?? 2; - this.fetch = options.fetch ?? getDefaultFetch(); - __classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder, "f"); - this.middleware = [...options.middleware ?? []]; - const customHeadersEnv = readEnv("ANTHROPIC_CUSTOM_HEADERS"); - if (customHeadersEnv) { - const parsed = {}; - for (const line of customHeadersEnv.split("\n")) { - const colon = line.indexOf(":"); - if (colon >= 0) parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim(); - } - options.defaultHeaders = { - ...parsed, - ...options.defaultHeaders - }; - } - const inherited = opts.__auth; - delete options.__auth; - delete options.__baseURLIsExplicit; - this._options = options; - this.apiKey = typeof apiKey === "string" ? apiKey : null; - this.authToken = authToken; - this.webhookKey = webhookKey; - if (inherited) { - this._authState = inherited; - if (!this._baseURLIsExplicit && inherited.baseURL) this.baseURL = inherited.baseURL; - } else { - this._authState = { - provider: null, - tokenCache: null, - resolution: null, - error: null, - extraHeaders: {} - }; - if (this.apiKey == null && this.authToken == null) { - const credentials = options.credentials ?? null; - if (credentials) { - this._authState.provider = credentials; - this._authState.tokenCache = this._makeTokenCache(credentials); - } else if (options.config != null) { - const result = resolveCredentialsFromConfig(options.config, this._credentialResolverOptions()); - this._authState.provider = result.provider; - this._authState.tokenCache = this._makeTokenCache(result.provider); - this._authState.extraHeaders = result.extraHeaders; - this._applyCredentialBaseURL(result.baseURL); - } else if (options.profile != null) this._authState.resolution = this._resolveDefaultCredentials(options.profile); - else if (this._shouldResolveDefaultCredentials()) this._authState.resolution = this._resolveDefaultCredentials(); - } - } - } - /** - * Whether to lazily resolve auth from the default credential chain when no - * explicit auth is configured. Called once from the constructor, so - * overrides must not depend on subclass instance state. Subclasses that - * bring their own auth scheme return false so unrelated local credentials - * are never resolved or allowed to supply a base URL. - */ - _shouldResolveDefaultCredentials() { - return true; - } - /** - * Stores a profile/config-supplied base URL on the shared auth state and, if - * the caller did not pin `baseURL` via constructor option or env, adopts it - * as this client's outbound API host. Precedence: ctor opt > env > profile > - * hardcoded default. - */ - _applyCredentialBaseURL(baseURL) { - if (!baseURL) return; - const normalized = baseURL.replace(/\/+$/, ""); - this._authState.baseURL = normalized; - if (!this._baseURLIsExplicit) this.baseURL = normalized; - } - /** - * Options bag passed into the credential chain. `baseURL` here is only the - * fallback host for the token-exchange POST when the config itself omits - * `base_url`; the chain returns the config's own `base_url` (if any) on - * {@link CredentialResult.baseURL}, which {@link _applyCredentialBaseURL} - * then adopts for outbound API requests. The two are deliberately decoupled - * so this fallback never round-trips into precedence. - */ - _credentialResolverOptions() { - return { - baseURL: this.baseURL, - fetch: this._credentialsFetch(), - userAgent: this.getUserAgent(), - onCacheWriteError: (err) => { - loggerFor(this).debug("credential cache write failed (best-effort)", err); - }, - onSafetyWarning: (msg) => { - loggerFor(this).warn(msg); - } - }; - } - /** - * A `Fetch` for first-party credential token-exchange requests (OIDC - * federation jwt-bearer grants, user-OAuth refresh grants) that routes - * through this client's middleware chain, so middleware observes token - * traffic like any other request. Only client-level middleware applies: - * a minted token is shared across requests, so attributing the exchange - * to any one request's per-request middleware would be arbitrary. For the - * same reason, `ctx.options` is undefined for these requests. - */ - _credentialsFetch() { - return wrapFetchWithMiddleware(this.fetch, this.middleware, void 0, this); - } - _makeTokenCache(provider) { - return new TokenCache(provider, (err) => { - loggerFor(this).debug("advisory token refresh failed; serving cached token", err); - }); - } - /** - * Create a new client instance re-using the same options given to the current client with optional overriding. - */ - withOptions(options) { - const overridesStructuredAuth = "credentials" in options || "config" in options || "profile" in options; - const overridesAuth = "apiKey" in options || "authToken" in options || overridesStructuredAuth; - const internal = { - ...this._options, - ...this._baseURLIsExplicit ? { baseURL: this.baseURL } : {}, - maxRetries: this.maxRetries, - timeout: this.timeout, - logger: this.logger, - logLevel: this.logLevel, - fetch: this.fetch, - fetchOptions: this.fetchOptions, - middleware: this.middleware, - apiKey: this.apiKey, - authToken: this.authToken, - webhookKey: this.webhookKey, - credentials: this.credentials, - ...overridesStructuredAuth ? { - credentials: void 0, - config: void 0, - profile: void 0 - } : {}, - ...options, - __auth: overridesAuth ? void 0 : this._authState, - __baseURLIsExplicit: "baseURL" in options ? true : this._baseURLIsExplicit - }; - return new this.constructor(internal); - } - /** - * Lazily resolves credentials from config files or environment variables. - * Called once from the constructor when no explicit auth is provided, or - * when an explicit `profile` was passed (in which case a missing/unresolved - * profile is surfaced as an error instead of falling through to "no auth"). - * The returned promise is stored and awaited on the first request. - */ - async _resolveDefaultCredentials(profile) { - try { - const result = await defaultCredentials(this._credentialResolverOptions(), profile); - if (result) { - this._authState.provider = result.provider; - this._authState.tokenCache = this._makeTokenCache(result.provider); - this._authState.extraHeaders = result.extraHeaders; - this._applyCredentialBaseURL(result.baseURL); - } else if (profile != null) throw new AnthropicError(`Profile "${profile}" could not be resolved (no /configs/${profile}.json found).`); - } catch (err) { - this._authState.error = err; - } finally { - this._authState.resolution = null; - } - } - defaultQuery() { - return this._options.defaultQuery; - } - validateHeaders({ values, nulls }) { - if (values.get("x-api-key") || values.get("authorization")) return; - if (this._authState.error) throw this._authState.error; - if (this._authState.tokenCache || this._authState.resolution) return; - if (this.apiKey && values.get("x-api-key")) return; - if (nulls.has("x-api-key")) return; - if (this.authToken && values.get("authorization")) return; - if (nulls.has("authorization")) return; - throw new Error("Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the \"X-Api-Key\" or \"Authorization\" headers to be explicitly omitted"); - } - _authFlags(opts) { - let flags = this._requestAuthFlags.get(opts); - if (!flags) { - flags = { - usedTokenCache: false, - didRefreshFor401: false - }; - this._requestAuthFlags.set(opts, flags); - } - return flags; - } - async authHeaders(opts) { - if (this._authState.resolution) await this._authState.resolution; - if (this._authState.error) return; - if (this._authState.tokenCache && this.apiKey == null) { - const token = await this._authState.tokenCache.getToken(); - this._authFlags(opts).usedTokenCache = true; - return buildHeaders([{ Authorization: `Bearer ${token}` }]); - } - return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]); - } - async apiKeyAuth(opts) { - if (this.apiKey == null) return; - return buildHeaders([{ "X-Api-Key": this.apiKey }]); - } - async bearerAuth(opts) { - if (this.authToken == null) return; - return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); - } - stringifyQuery(query) { - return stringifyQuery(query); - } - getUserAgent() { - return `${this.constructor.name}/JS ${VERSION}`; - } - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid4()}`; - } - makeStatusError(status, error, message, headers) { - return APIError.generate(status, error, message, headers); - } - buildURL(path, query, defaultBaseURL) { - const baseURL = !__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; - const url = isAbsoluteURL(path) ? new URL(path) : new URL(baseURL + (baseURL.endsWith("/") && path.startsWith("/") ? path.slice(1) : path)); - const defaultQuery = this.defaultQuery(); - const pathQuery = Object.fromEntries(url.searchParams); - if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) query = { - ...pathQuery, - ...defaultQuery, - ...query - }; - if (typeof query === "object" && query && !Array.isArray(query)) url.search = this.stringifyQuery(query); - return url.toString(); - } - _calculateNonstreamingTimeout(maxTokens) { - const defaultTimeout = 600; - if (3600 * maxTokens / 128e3 > defaultTimeout) throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details"); - return defaultTimeout * 1e3; - } - /** - * Used as a callback for mutating the given `FinalRequestOptions` object. - */ - async prepareOptions(options) {} - /** - * Used as a callback for mutating the given `RequestInit` object. - * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. - * - * Runs after all middleware (including {@link backendMiddleware}), - * immediately before each underlying fetch call, so it sees exactly what - * goes over the wire. Middleware may replay a request by calling `next()` - * more than once, so this hook can run multiple times per attempt: - * overrides must be idempotent and overwrite headers from a previous - * invocation rather than append to them. - */ - async prepareRequest(request, { url, options }) { - if (this._authState.tokenCache && this.apiKey == null) { - const headers = request.headers instanceof Headers ? request.headers : new Headers(request.headers); - for (const [k, v] of Object.entries(this._authState.extraHeaders)) if (!headers.has(k)) headers.set(k, v); - if (!(headers.get("anthropic-beta")?.split(",").map((s) => s.trim()))?.includes("oauth-2025-04-20")) headers.append("anthropic-beta", OAUTH_API_BETA_HEADER); - request.headers = headers; - } - } - /** - * Internal {@link Middleware} composed innermost in the chain — inside both - * client-level and per-request middleware, immediately around the underlying - * `fetch`. Subclasses for third-party backends override this to adapt the - * canonical Anthropic-shaped request to the backend's wire shape (URL/body - * rewriting, request signing) and to normalize the wire response back to the - * canonical shape (e.g. AWS EventStream to SSE). - * - * Running inside the user's middleware means user middleware always observes - * canonical Anthropic-shaped traffic, and the adaptation re-runs (e.g. - * re-signs) on every `next()` invocation, covering whatever the middleware - * mutated. - * - * Errors thrown here follow the middleware error policy: they propagate to - * the caller as-is — no retries, no `APIConnectionError` wrapping — unless - * retryable (see {@link Middleware}); throw a `RetryableError` to opt into - * the retry path. - */ - backendMiddleware() { - return []; - } - get(path, opts) { - return this.methodRequest("get", path, opts); - } - post(path, opts) { - return this.methodRequest("post", path, opts); - } - patch(path, opts) { - return this.methodRequest("patch", path, opts); - } - put(path, opts) { - return this.methodRequest("put", path, opts); - } - delete(path, opts) { - return this.methodRequest("delete", path, opts); - } - methodRequest(method, path, opts) { - return this.request(Promise.resolve(opts).then((opts) => { - return { - method, - path, - ...opts - }; - })); - } - request(options, remainingRetries = null) { - return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0)); - } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; - this._requestAuthFlags.delete(options); - } - await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); - /** Not an API request ID, just for correlating local log entries. */ - const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); - const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - if (options.signal?.aborted) throw new APIUserAbortError(); - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller, options, { - requestLogID, - retryOfRequestLogID - }).catch(castToError); - const headersTime = Date.now(); - if (response instanceof globalThis.Error) { - releaseRequestSignal(controller); - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) throw new APIUserAbortError(); - const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); - const hasMiddleware = this.middleware.length > 0 || !!options.middleware?.length || this.backendMiddleware().length > 0; - if (hasMiddleware && !isTimeout && !isRetryableError(response)) { - loggerFor(this).info(`[${requestLogID}] middleware error (not retryable)`); - loggerFor(this).debug(`[${requestLogID}] middleware error (not retryable)`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - throw response; - } - if (retriesRemaining) { - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); - } - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message - })); - if (isTimeout) throw new APIConnectionTimeoutError(); - if (hasMiddleware && !isFetchOriginError(response)) throw response; - throw new APIConnectionError({ cause: response }); - } - const responseInfo = `[${requestLogID}${retryLogStr}${[...response.headers.entries()].filter(([name]) => name === "request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("")}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = await this.shouldRetry(response, options); - if (retriesRemaining && shouldRetry) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - await CancelReadableStream(response.body); - releaseRequestSignal(controller); - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); - } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err) => castToError(err).message); - const errJSON = safeJSON(errText); - const errMessage = errJSON ? void 0 : errText; - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime - })); - releaseRequestSignal(controller); - throw this.makeStatusError(response.status, errJSON, errMessage, response.headers); - } - loggerFor(this).info(responseInfo); - loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - armAbandonmentBackstop(response.body ?? response, controller); - return { - response, - options, - controller, - requestLogID, - retryOfRequestLogID, - startTime - }; - } - getAPIList(path, Page, opts) { - return this.requestAPIList(Page, opts && "then" in opts ? opts.then((opts) => ({ - method: "get", - path, - ...opts - })) : { - method: "get", - path, - ...opts - }); - } - requestAPIList(Page, options) { - const request = this.makeRequest(options, null, void 0); - return new PagePromise(this, request, Page); - } - async fetchWithTimeout(url, init, ms, controller, requestOptions, logCtx) { - const { signal, method, ...options } = init || {}; - const abort = this._makeAbort(controller); - if (signal) { - signal.addEventListener("abort", abort, { once: true }); - registerRequestSignalCleanup(controller, signal, abort); - } - const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; - const fetchOptions = { - signal: controller.signal, - ...isReadableBody ? { duplex: "half" } : {}, - method: "GET", - ...options - }; - if (method) fetchOptions.method = method.toUpperCase(); - const baseFetch = this.fetch; - const timedFetch = async (innerUrl, innerInit) => { - const timeout = setTimeout(abort, ms); - try { - return await baseFetch.call(void 0, innerUrl, innerInit); - } finally { - clearTimeout(timeout); - } - }; - const innerFetch = requestOptions === void 0 ? timedFetch : (async (innerUrl, innerInit = {}) => { - const innerUrlStr = typeof innerUrl === "string" ? innerUrl : innerUrl instanceof URL ? innerUrl.href : innerUrl.url; - innerInit.headers = innerInit.headers instanceof Headers ? innerInit.headers : new Headers(innerInit.headers); - await this.prepareRequest(innerInit, { - url: innerUrlStr, - options: requestOptions - }); - if (logCtx) loggerFor(this).debug(`[${logCtx.requestLogID}] sending request`, formatRequestDetails({ - retryOfRequestLogID: logCtx.retryOfRequestLogID, - method: innerInit.method, - url: innerUrlStr, - options: requestOptions, - headers: innerInit.headers - })); - return timedFetch(innerUrl, innerInit); - }); - const requestMiddleware = requestOptions?.middleware; - const backendMiddleware = this.backendMiddleware(); - return await wrapFetchWithMiddleware(innerFetch, requestMiddleware?.length || backendMiddleware.length ? [ - ...this.middleware, - ...requestMiddleware ?? [], - ...backendMiddleware - ] : this.middleware, requestOptions, this)(url, fetchOptions); - } - async shouldRetry(response, options) { - const flags = this._authFlags(options); - if (response.status === 401 && this._authState.tokenCache && flags.usedTokenCache && !flags.didRefreshFor401) { - flags.didRefreshFor401 = true; - this._authState.tokenCache.invalidate(); - return true; - } - const shouldRetryHeader = response.headers.get("x-should-retry"); - if (shouldRetryHeader === "true") return true; - if (shouldRetryHeader === "false") return false; - if (response.status === 408) return true; - if (response.status === 409) return true; - if (response.status === 429) return true; - if (response.status >= 500) return true; - return false; - } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) timeoutMillis = timeoutMs; - } - const retryAfterHeader = responseHeaders?.get("retry-after"); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) timeoutMillis = timeoutSeconds * 1e3; - else timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } - if (timeoutMillis === void 0) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); - } - await sleep(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); - } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = .5; - const maxRetryDelay = 8; - const numRetries = maxRetries - retriesRemaining; - return Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay) * (1 - Math.random() * .25) * 1e3; - } - calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) { - const maxTime = 3600 * 1e3; - const defaultTime = 600 * 1e3; - if (maxTime * maxTokens / 128e3 > defaultTime || maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens) throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details"); - return defaultTime; - } - async buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path, query, defaultBaseURL } = options; - if (this._authState.resolution) await this._authState.resolution; - if (!this._baseURLIsExplicit && this._authState.baseURL && this.baseURL !== this._authState.baseURL) this.baseURL = this._authState.baseURL; - const url = this.buildURL(path, query, defaultBaseURL); - if ("timeout" in options) validatePositiveInteger("timeout", options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - return { - req: { - method, - headers: await this.buildHeaders({ - options: inputOptions, - method, - bodyHeaders, - retryCount - }), - ...options.signal && { signal: options.signal }, - ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, - ...body && { body }, - ...this.fetchOptions ?? {}, - ...options.fetchOptions ?? {} - }, - url, - timeout: options.timeout - }; - } - async buildHeaders({ options, method, bodyHeaders, retryCount }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== "get") { - if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; - } - const headers = buildHeaders([ - idempotencyHeaders, - { - Accept: "application/json", - "User-Agent": this.getUserAgent(), - "X-Stainless-Retry-Count": String(retryCount), - ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, - ...getPlatformHeaders(), - ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : void 0, - "anthropic-version": "2023-06-01" - }, - await this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers - ]); - this.validateHeaders(headers); - return headers.values; - } - _makeAbort(controller) { - return () => controller.abort(); - } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) return { - bodyHeaders: void 0, - body: void 0 - }; - const headers = buildHeaders([rawHeaders]); - if (ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && headers.values.has("content-type") || globalThis.Blob && body instanceof globalThis.Blob || body instanceof FormData || body instanceof URLSearchParams || globalThis.ReadableStream && body instanceof globalThis.ReadableStream) return { - bodyHeaders: void 0, - body - }; - else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) return { - bodyHeaders: void 0, - body: ReadableStreamFrom(body) - }; - else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") return { - bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, - body: this.stringifyQuery(body) - }; - else return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { - body, - headers - }); - } -}; -_a = BaseAnthropic, _BaseAnthropic_encoder = /* @__PURE__ */ new WeakMap(), _BaseAnthropic_instances = /* @__PURE__ */ new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() { - return this.baseURL !== "https://api.anthropic.com"; -}; -BaseAnthropic.Anthropic = _a; -BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT; -BaseAnthropic.AI_PROMPT = AI_PROMPT; -BaseAnthropic.DEFAULT_TIMEOUT = 6e5; -BaseAnthropic.AnthropicError = AnthropicError; -BaseAnthropic.APIError = APIError; -BaseAnthropic.APIConnectionError = APIConnectionError; -BaseAnthropic.APIConnectionTimeoutError = APIConnectionTimeoutError; -BaseAnthropic.APIUserAbortError = APIUserAbortError; -BaseAnthropic.NotFoundError = NotFoundError; -BaseAnthropic.ConflictError = ConflictError; -BaseAnthropic.RateLimitError = RateLimitError; -BaseAnthropic.BadRequestError = BadRequestError; -BaseAnthropic.AuthenticationError = AuthenticationError; -BaseAnthropic.InternalServerError = InternalServerError; -BaseAnthropic.PermissionDeniedError = PermissionDeniedError; -BaseAnthropic.UnprocessableEntityError = UnprocessableEntityError; -BaseAnthropic.toFile = toFile; -/** -* API Client for interfacing with the Anthropic API. -*/ -var Anthropic = class extends BaseAnthropic { - constructor() { - super(...arguments); - this.completions = new Completions(this); - this.messages = new Messages(this); - this.models = new Models(this); - this.beta = new Beta(this); - } -}; -Anthropic.Completions = Completions; -Anthropic.Messages = Messages; -Anthropic.Models = Models; -Anthropic.Beta = Beta; -new TextEncoder(); -//#endregion -//#region node_modules/@anthropic-ai/sdk/lib/transform-json-schema.mjs -var SUPPORTED_STRING_FORMATS = /* @__PURE__ */ new Set([ - "date-time", - "time", - "date", - "duration", - "email", - "hostname", - "uri", - "ipv4", - "ipv6", - "uuid" -]); -function deepClone(obj) { - return JSON.parse(JSON.stringify(obj)); -} -function transformJSONSchema(jsonSchema) { - return _transformJSONSchema(deepClone(jsonSchema)); -} -function _transformJSONSchema(jsonSchema) { - const strictSchema = {}; - const ref = pop(jsonSchema, "$ref"); - if (ref !== void 0) { - strictSchema["$ref"] = ref; - return strictSchema; - } - const defs = pop(jsonSchema, "$defs"); - if (defs !== void 0) { - const strictDefs = {}; - strictSchema["$defs"] = strictDefs; - for (const [name, defSchema] of Object.entries(defs)) strictDefs[name] = _transformJSONSchema(defSchema); - } - const type = pop(jsonSchema, "type"); - const anyOf = pop(jsonSchema, "anyOf"); - const oneOf = pop(jsonSchema, "oneOf"); - const allOf = pop(jsonSchema, "allOf"); - if (Array.isArray(anyOf)) strictSchema["anyOf"] = anyOf.map((variant) => _transformJSONSchema(variant)); - else if (Array.isArray(oneOf)) strictSchema["anyOf"] = oneOf.map((variant) => _transformJSONSchema(variant)); - else if (Array.isArray(allOf)) strictSchema["allOf"] = allOf.map((entry) => _transformJSONSchema(entry)); - else { - if (type === void 0) throw new Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used"); - strictSchema["type"] = type; - } - const description = pop(jsonSchema, "description"); - if (description !== void 0) strictSchema["description"] = description; - const title = pop(jsonSchema, "title"); - if (title !== void 0) strictSchema["title"] = title; - if (type === "object") { - const properties = pop(jsonSchema, "properties") || {}; - strictSchema["properties"] = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [key, _transformJSONSchema(propSchema)])); - pop(jsonSchema, "additionalProperties"); - strictSchema["additionalProperties"] = false; - const required = pop(jsonSchema, "required"); - if (required !== void 0) strictSchema["required"] = required; - } else if (type === "string") { - const format = pop(jsonSchema, "format"); - if (format !== void 0 && SUPPORTED_STRING_FORMATS.has(format)) strictSchema["format"] = format; - else if (format !== void 0) jsonSchema["format"] = format; - } else if (type === "array") { - const items = pop(jsonSchema, "items"); - if (items !== void 0) strictSchema["items"] = _transformJSONSchema(items); - const minItems = pop(jsonSchema, "minItems"); - if (minItems !== void 0 && (minItems === 0 || minItems === 1)) strictSchema["minItems"] = minItems; - else if (minItems !== void 0) jsonSchema["minItems"] = minItems; - } - if (Object.keys(jsonSchema).length > 0) { - const existingDescription = strictSchema["description"]; - strictSchema["description"] = (existingDescription ? existingDescription + "\n\n" : "") + "{" + Object.entries(jsonSchema).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(", ") + "}"; - } - return strictSchema; -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/helpers/beta/json-schema.mjs -/** -* Creates a Tool with a provided JSON schema that can be passed -* to the `.toolRunner()` method. The schema is used to automatically validate -* the input arguments for the tool. -*/ -function betaTool(options) { - if (options.inputSchema.type !== "object") throw new Error(`JSON schema for tool "${options.name}" must be an object, but got ${options.inputSchema.type}`); - return { - type: "custom", - name: options.name, - input_schema: options.inputSchema, - description: options.description, - run: options.run, - parse: (content) => content, - ...options.close ? { close: options.close } : {} - }; -} -/** `realpath` `p`, or return `p` unchanged when it cannot be resolved. */ -async function realpathOrSelf(p) { - try { - return await fs$2.realpath(p); - } catch { - return p; - } -} -/** -* Fully resolve `abs`: `realpath` the longest existing ancestor and re-append -* the rest, but never re-append a component that is itself a symlink — read the -* link and continue from its target instead. This handles paths being created -* (write/edit) without letting a symlink leaf (e.g. a dangling one pointing -* outside a confinement root) slip through unresolved. -*/ -async function canonicalize(abs) { - const tail = []; - let prefix = abs; - let hops = 0; - for (;;) { - let real; - try { - real = await fs$2.realpath(prefix); - } catch { - let isLink = false; - try { - isLink = (await fs$2.lstat(prefix)).isSymbolicLink(); - } catch {} - if (isLink) { - if (++hops > 40) throw new ToolError(`path ${JSON.stringify(abs)} has too many levels of symbolic links`); - prefix = path$1.resolve(path$1.dirname(prefix), await fs$2.readlink(prefix)); - continue; - } - const parent = path$1.dirname(prefix); - if (parent === prefix) return abs; - tail.push(path$1.basename(prefix)); - prefix = parent; - continue; - } - return tail.length ? path$1.join(real, ...tail.reverse()) : real; - } -} -/** -* Resolve `p` and confine it to `root`. -* -* Absolute and relative inputs go through the same canonicalise-then-contain -* check — an absolute path that lands inside `root` is permitted, only paths -* that resolve *outside* are rejected. Every symlink in `p` (including the -* leaf, even a dangling one) is resolved before the confinement check, and the -* resolved path is what the caller then operates on, so a symlink inside `root` -* that points outside it can neither pass the check nor be followed afterwards. -* -* Residual TOCTOU: a component could still be swapped for a symlink between this -* call and the eventual `fs` operation. Closing that fully needs per-component -* `O_NOFOLLOW`/`openat`, which Node does not expose ergonomically; this is why a -* sandbox is still recommended for the toolset as a whole. -*/ -async function confineToRoot(root, p, opts) { - const allowOutside = opts?.allowOutside ?? false; - const realRoot = await realpathOrSelf(path$1.resolve(root)); - const abs = path$1.resolve(realRoot, p); - if (allowOutside) return abs; - const real = await canonicalize(abs); - if (real !== realRoot && !real.startsWith(realRoot + path$1.sep)) throw new ToolError(`path ${JSON.stringify(p)} escapes workdir`); - return real; -} -/** -* Atomically write `content` to `targetPath`: write a sibling temp file, fsync -* it, then rename over the target. The rename is atomic on most filesystems, so -* a crash mid-write never leaves the target half-written. -*/ -async function atomicWriteFile(targetPath, content) { - const dir = path$1.dirname(targetPath); - const tempPath = path$1.join(dir, `.tmp-${process.pid}-${randomUUID()}`); - let handle; - try { - handle = await fs$2.open(tempPath, "wx", 420); - await handle.writeFile(content, "utf-8"); - await handle.sync(); - await handle.close(); - handle = void 0; - await fs$2.rename(tempPath, targetPath); - } catch (err) { - if (handle) await handle.close().catch(() => {}); - await fs$2.unlink(tempPath).catch(() => {}); - throw err; - } -} -/** -* Map a thrown filesystem error to a consistent, language-independent message, -* so the model sees the same wording regardless of the runtime (Node's raw -* `ENOENT: no such file...` text would otherwise leak through). Falls back to -* the raw error message for codes we don't special-case. -*/ -function fsErrorMessage(err, file) { - switch (err?.code) { - case "ENOENT": return `${file}: no such file or directory`; - case "EACCES": - case "EPERM": return `${file}: permission denied`; - case "ENOTDIR": return `${file}: not a directory`; - case "EISDIR": return `${file}: is a directory`; - case "ELOOP": return `${file}: too many levels of symbolic links`; - case "ENAMETOOLONG": return `${file}: file name too long`; - case "ENOSPC": return `${file}: no space left on device`; - case "EMFILE": - case "ENFILE": return `${file}: too many open files`; - default: return `${file}: ${err instanceof Error ? err.message : String(err)}`; - } -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/tools/agent-toolset/skills.mjs -/** -* Node-only skill plumbing for the agent toolset: downloading a session -* agent's skills into the workdir and extracting the archives. Kept in its own -* file because it is a distinct concern from the tool implementations in -* `node.ts` — distinct enough, and large enough, to review on its own. -*/ -var execFileAsync = promisify(execFile); -/** -* Download the session agent's skills into `{ctx.workdir}/skills//`. -* -* No-op (returns a no-op cleanup) unless both `ctx.client` and `ctx.sessionId` -* are set. Looks up the session's resolved agent and, for each skill, fetches -* its files via `client.beta.skills.versions.download` and extracts the archive -* (a zip or tar.* archive) into a directory named after the skill. A failure on -* one skill is logged and does not block the others. Call this before starting -* the session tool runner (e.g. right after the bash session / workdir is -* ready). -* -* Returns a cleanup function that removes the skill directories this call -* created — call it once the work item is done so downloaded skills do not -* accumulate in the workdir across sessions. -*/ -async function setupSkills(ctx) { - const { client, sessionId } = ctx; - if (!client || !sessionId) return async () => {}; - const log = loggerFor(client); - const session = await client.beta.sessions.retrieve(sessionId); - const skillsRoot = path$1.resolve(ctx.workdir, "skills"); - const created = []; - for (const skill of session.agent.skills) try { - const versionId = await resolveSkillVersion(client, skill.skill_id, skill.version); - const version = await client.beta.skills.versions.retrieve(versionId, { skill_id: skill.skill_id }); - let dirname = path$1.basename(version.name.trim()); - if (dirname === "" || dirname === "." || dirname === "..") dirname = skill.skill_id; - const dest = path$1.resolve(skillsRoot, dirname); - if (dest !== skillsRoot && !dest.startsWith(skillsRoot + path$1.sep)) { - log.warn("skill name escapes the skills dir; skipping", { - component: "agent-tool-context", - name: version.name - }); - continue; - } - const resp = await client.beta.skills.versions.download(versionId, { skill_id: skill.skill_id }); - await fs$2.rm(dest, { - recursive: true, - force: true - }); - await fs$2.mkdir(dest, { - recursive: true, - mode: 493 - }); - created.push(dest); - await extractSkillArchive(resp, dest); - log.info("downloaded skill", { - component: "agent-tool-context", - skill_id: skill.skill_id, - version: versionId, - dest - }); - } catch (e) { - log.warn("failed to download skill", { - component: "agent-tool-context", - skill_id: skill.skill_id, - error: String(e) - }); - } - return async () => { - for (const dest of created) await fs$2.rm(dest, { - recursive: true, - force: true - }).catch((e) => { - log.warn("failed to clean up skill", { - component: "agent-tool-context", - dest, - error: String(e) - }); - }); - }; -} -/** -* Resolve `version` to the concrete numeric timestamp the -* `/v1/skills/{id}/versions/{version}` endpoints require — `session.agent.skills[].version` -* can be an alias such as `"latest"`, which those endpoints reject. Numeric -* versions pass through unchanged. -*/ -async function resolveSkillVersion(client, skillId, version) { - if (/^\d+$/.test(version)) return version; - let newest; - for await (const v of client.beta.skills.versions.list(skillId)) if (/^\d+$/.test(v.version) && (newest === void 0 || BigInt(v.version) > BigInt(newest))) newest = v.version; - if (newest === void 0) throw new AnthropicError(`skill ${JSON.stringify(skillId)} has no concrete version to resolve ${JSON.stringify(version)} against`); - return newest; -} -/** Reject archive members that are absolute or contain a `..` component. */ -function assertSafeMemberNames(names) { - for (const raw of names.split("\n")) { - const entry = raw.trim(); - if (!entry) continue; - if (path$1.isAbsolute(entry) || entry.split(/[\\/]/).includes("..")) throw new AnthropicError(`refusing to extract unsafe archive member: ${entry}`); - } -} -/** -* Reject archives that contain anything other than regular files and -* directories. The type char is the first byte of each `ls`-style line emitted -* by `tar -tvf` / `unzip -Z`: `-` file, `d` dir, `l` symlink, `h` hardlink, -* `b`/`c` device, `p` fifo, `s` socket. A symlink/hardlink member is how an -* archive escapes its extraction dir even when no name contains `..`. -*/ -function assertNoSpecialMembers(verboseListing) { - for (const line of verboseListing.split("\n")) { - const type = line.trimStart()[0]; - if (type === "l" || type === "h" || type === "b" || type === "c" || type === "p" || type === "s") throw new AnthropicError("refusing to extract archive with symlink/hardlink/device member"); - } -} -/** -* Run an archive CLI (`unzip` for zip archives, `tar` for everything else), -* returning its stdout. Both binaries must be on `PATH`; a missing one would -* otherwise surface as an opaque `ENOENT` spawn failure, so it is turned into a -* clear, specific error naming the missing command. -*/ -async function runArchiveTool(cmd, args) { - try { - const { stdout } = await execFileAsync(cmd, args); - return stdout; - } catch (e) { - if (e != null && typeof e === "object" && e.code === "ENOENT") throw new AnthropicError(`skill extraction requires the \`${cmd}\` command, but it was not found on PATH`); - throw e; - } -} -/** -* The single top-level directory shared by every entry in a newline-separated -* archive listing, or `''` if entries don't all live under one common -* directory. Skill bundles are packaged wrapped in one directory named after -* the skill (e.g. `pdf/SKILL.md`, `pdf/scripts/...`); the extractor strips it -* so contents land directly in the skill's dir instead of a redundant nested -* `//` level. A flat or multi-root archive yields `''`. -*/ -function archiveTopDir(listing) { - let top; - let nested = false; - for (const raw of listing.split("\n")) { - const parts = raw.trim().split("/").filter((p) => p !== "" && p !== "."); - if (parts.length === 0) continue; - const first = parts[0]; - if (top === void 0) top = first; - else if (first !== top) return ""; - if (parts.length > 1) nested = true; - } - return top !== void 0 && nested ? top : ""; -} -/** -* Extract a skill download (a zip or tar.* archive) into `dest`. Streams the -* response body straight to a temp file beside `dest` (so the whole archive is -* never buffered in memory — skills can contain large binaries), then shells out -* to `unzip`/`tar` — consistent with the rest of the toolset, which already -* invokes `bash` and `rg`. Both `unzip` and `tar` must be available on `PATH`; a -* missing binary surfaces as a clear error (see {@link runArchiveTool}). Refuses -* any member that would escape `dest` (zip-slip / tar-slip), including -* symlink/hardlink members: skill archives come from the API, but skills can be -* third-party. -* -* The skill bundle's single wrapper directory is stripped: the archive is -* extracted into a staging dir and the wrapper's contents are promoted into -* `dest`, so files land at `dest/SKILL.md` rather than a doubled -* `dest//SKILL.md` (`unzip` has no `--strip-components`, so this is -* done uniformly by staging + promote rather than per-tool flags). -*/ -async function extractSkillArchive(resp, dest) { - const tmp = path$1.join(dest, `.skill-archive-${process.pid}-${Date.now()}`); - if (!resp.body) throw new AnthropicError("skill download response had no body"); - await pipeline(Readable.fromWeb(resp.body), fssync.createWriteStream(tmp)); - const stage = path$1.join(path$1.dirname(dest), `.skill-stage-${process.pid}-${Date.now()}`); - try { - const head = await readHead(tmp, 4); - const isZip = head.length >= 4 && head[0] === 80 && head[1] === 75 && head[2] === 3 && head[3] === 4; - const archiveCmd = isZip ? "unzip" : "tar"; - const listing = await runArchiveTool(archiveCmd, isZip ? ["-Z1", tmp] : ["-tf", tmp]); - assertSafeMemberNames(listing); - assertNoSpecialMembers(await runArchiveTool(archiveCmd, isZip ? ["-Z", tmp] : ["-tvf", tmp])); - const top = archiveTopDir(listing); - await fs$2.mkdir(stage, { - recursive: true, - mode: 493 - }); - await runArchiveTool(archiveCmd, isZip ? [ - "-oq", - tmp, - "-d", - stage - ] : [ - "-xf", - tmp, - "-C", - stage - ]); - const srcRoot = top ? path$1.join(stage, top) : stage; - for (const entry of await fs$2.readdir(srcRoot)) await fs$2.rename(path$1.join(srcRoot, entry), path$1.join(dest, entry)); - } finally { - await fs$2.rm(tmp, { force: true }); - await fs$2.rm(stage, { - recursive: true, - force: true - }); - } -} -/** Read the first `n` bytes of `file`. */ -async function readHead(file, n) { - const handle = await fs$2.open(file, "r"); - try { - const buf = Buffer.alloc(n); - const { bytesRead } = await handle.read(buf, 0, n, 0); - return buf.subarray(0, bytesRead); - } finally { - await handle.close(); - } -} -//#endregion -//#region node_modules/@anthropic-ai/sdk/tools/agent-toolset/node.mjs -var node_exports = /* @__PURE__ */ __exportAll({ - BashSession: () => BashSession, - betaAgentToolset20260401: () => betaAgentToolset20260401, - betaBashTool: () => betaBashTool, - betaEditTool: () => betaEditTool, - betaGlobTool: () => betaGlobTool, - betaGrepTool: () => betaGrepTool, - betaReadTool: () => betaReadTool, - betaWriteTool: () => betaWriteTool, - resolvePath: () => resolvePath, - setupSkills: () => setupSkills -}); -/** -* Node implementation of the `agent_toolset_20260401` tools — `bash`, `read`, -* `write`, `edit`, `glob`, `grep` — plus the workdir/skills -* {@link AgentToolContext}. -* -* This mirrors `@anthropic-ai/sdk/tools/memory/node`: it is the explicit, -* Node-only entry point for these implementations. Importing it pulls in -* `node:child_process`, `node:fs`, etc., so it is kept separate from the rest of -* the SDK — depending on it is an opt-in. -* -* **Node 22+ is required** for this module: the `glob` tool uses the native -* `fs.glob`, added in Node 22. The rest of the SDK still supports Node 18+; only -* the agent toolset has this requirement. -* -* The result of {@link betaAgentToolset20260401} is a plain `BetaRunnableTool[]`; -* hand it to any tool runner — `client.beta.messages.toolRunner({ …, tools })` -* for the Messages API, or `client.beta.sessions.events.toolRunner({ …, tools })` -* for a managed-agents session: -* -* ```ts -* import { betaAgentToolset20260401 } from '@anthropic-ai/sdk/tools/agent-toolset/node'; -* -* const tools = betaAgentToolset20260401({ workdir: '/work' }); -* const tools2 = betaAgentToolset20260401({ workdir: '/work' }).filter((t) => t.name !== 'bash'); -* ``` -* -* Trust model: the file tools confine to `workdir` (symlink-aware) and are safe -* without a sandbox; `bash` is unrestricted and should run inside one. See -* {@link AgentToolContext}. -*/ -var _BashSession_instances; -var _BashSession_proc; -var _BashSession_buf; -var _BashSession_truncated; -var _BashSession_closed; -var _BashSession_waiting; -var _BashSession_append; -var BASH_OUTPUT_LIMIT = 100 * 1024; -var BASH_DEFAULT_TIMEOUT_MS = 12e4; -var DEFAULT_MAX_FILE_BYTES = 256 * 1024; -var GREP_OUTPUT_LIMIT = 100 * 1024; -var GREP_MAX_LINE_LENGTH = 2e3; -var GLOB_RESULT_LIMIT = 200; -var ANSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]/g; -var fsGlob = fs$2.glob; -function resolveMaxBytes(configured) { - return configured === void 0 ? DEFAULT_MAX_FILE_BYTES : configured; -} -/** -* Returns the `agent_toolset_20260401` implementations bound to `ctx`. The -* result is a plain array of `BetaRunnableTool`; filter or extend it before -* handing it to a tool runner: -* -* ```ts -* const tools = [...betaAgentToolset20260401(ctx), myCustomTool]; -* const tools = betaAgentToolset20260401(ctx).filter((t) => t.name !== 'grep'); -* ``` -* -* Concurrency note: `client.beta.sessions.events.toolRunner` dispatches a -* session's tool calls serially (the sessions API delivers one `agent.tool_use` -* at a time). `client.beta.messages.toolRunner` runs a turn's `tool.run` calls -* via `Promise.all`. The toolset below is safe under either model — -* {@link betaBashTool} serializes its persistent shell internally and the FS -* tools are independent per call — but {@link betaEditTool}/{@link betaWriteTool} -* cannot synchronize concurrent writes to the *same* file across processes, so a -* multi-edit turn touching one path is still subject to inherent FS lost-update -* races. Custom tools that close over mutable state should do their own queueing. -*/ -function betaAgentToolset20260401(ctx) { - return [ - betaBashTool(ctx), - betaReadTool(ctx), - betaWriteTool(ctx), - betaEditTool(ctx), - betaGlobTool(ctx), - betaGrepTool(ctx) - ]; -} -/** -* Resolve `p` against `ctx.workdir`. Absolute and relative inputs go through -* the same canonicalise-then-contain check — an absolute path that lands inside -* the workdir is permitted, only paths that resolve *outside* are rejected. -* Every symlink in `p` (including the leaf, even a dangling one) is resolved -* before the workdir check, and the resolved path is what the tool then operates -* on, so a symlink inside the workdir that points outside it can neither pass -* the check nor be followed afterwards. See the trust model on -* {@link AgentToolContext}. -* -* Residual TOCTOU: a component could still be swapped for a symlink between this -* call and the eventual `fs` operation. Closing that fully needs per-component -* `O_NOFOLLOW`/`openat`, which Node does not expose ergonomically; the same -* residual exposure exists in `tools/memory/node` and is why a sandbox is still -* recommended for the toolset as a whole. -*/ -function resolvePath(ctx, p) { - return confineToRoot(ctx.workdir, p, { allowOutside: ctx.unrestrictedPaths ?? false }); -} -/** -* Build the environment for the spawned bash shell. The runner process holds -* Anthropic credentials in `ANTHROPIC_*` env vars — the API key, the auth token, -* and the per-work session token among them. `bash` runs an unrestricted shell, -* so any command the agent runs could read those straight out of `process.env`; -* strip the whole `ANTHROPIC_*` namespace from the child's environment. -* Everything else (PATH, HOME, locale, …) is passed through unchanged. -* -* Passing an explicit `env` to {@link AgentToolContext} does NOT add to this -* default — it FULLY REPLACES it. The provided mapping becomes the entire bash -* environment verbatim; nothing here is merged in, so callers who want the -* scrubbed process environment plus extras must build that mapping themselves. -*/ -function scrubbedShellEnv() { - const env = {}; - for (const [key, value] of Object.entries(process.env)) { - if (key.startsWith("ANTHROPIC_")) continue; - env[key] = value; - } - return env; -} -/** -* A persistent /bin/bash process. State (cwd, env, background jobs) survives -* across exec() calls. Uses pipes rather than a PTY so input is never echoed. -*/ -var BashSession = class { - constructor(dir, env = scrubbedShellEnv()) { - _BashSession_instances.add(this); - _BashSession_proc.set(this, void 0); - _BashSession_buf.set(this, ""); - _BashSession_truncated.set(this, false); - _BashSession_closed.set(this, false); - _BashSession_waiting.set(this, null); - __classPrivateFieldSet(this, _BashSession_proc, cp.spawn("/bin/bash", ["--noprofile", "--norc"], { - cwd: dir, - env: { - ...env, - PS1: "", - PS2: "", - TERM: "dumb" - }, - stdio: [ - "pipe", - "pipe", - "pipe" - ], - detached: true - }), "f"); - __classPrivateFieldGet(this, _BashSession_proc, "f").stdout.setEncoding("utf8"); - __classPrivateFieldGet(this, _BashSession_proc, "f").stderr.setEncoding("utf8"); - __classPrivateFieldGet(this, _BashSession_proc, "f").stdout.on("data", (d) => __classPrivateFieldGet(this, _BashSession_instances, "m", _BashSession_append).call(this, d)); - __classPrivateFieldGet(this, _BashSession_proc, "f").stderr.on("data", (d) => __classPrivateFieldGet(this, _BashSession_instances, "m", _BashSession_append).call(this, d)); - __classPrivateFieldGet(this, _BashSession_proc, "f").once("close", () => { - __classPrivateFieldSet(this, _BashSession_closed, true, "f"); - const w = __classPrivateFieldGet(this, _BashSession_waiting, "f"); - __classPrivateFieldSet(this, _BashSession_waiting, null, "f"); - w?.resolve(); - }); - } - /** Whether the underlying shell process has exited. */ - get closed() { - return __classPrivateFieldGet(this, _BashSession_closed, "f"); - } - async exec(command, opts = {}) { - if (__classPrivateFieldGet(this, _BashSession_closed, "f")) throw new AnthropicError("bash session terminated"); - const timeoutMs = opts.timeoutMs ?? BASH_DEFAULT_TIMEOUT_MS; - const signal = opts.signal; - if (signal?.aborted) throw new AnthropicError("bash command aborted"); - __classPrivateFieldSet(this, _BashSession_buf, "", "f"); - __classPrivateFieldSet(this, _BashSession_truncated, false, "f"); - const sentinel = `__ANT_CMD_${crypto.randomUUID()}_DONE__`; - const wrapped = `{ ${command}\n} &1; printf '\\n${`${sentinel.slice(0, 8)}''${sentinel.slice(8)}`}%d\\n' $?\n`; - __classPrivateFieldGet(this, _BashSession_proc, "f").stdin.write(wrapped); - if (__classPrivateFieldGet(this, _BashSession_buf, "f").indexOf(sentinel) < 0) { - const { promise: sentinelSeen, resolve } = promiseWithResolvers(); - __classPrivateFieldSet(this, _BashSession_waiting, { - sentinel, - resolve - }, "f"); - let timer; - let onAbort; - try { - await Promise.race([ - sentinelSeen, - new Promise((_, reject) => { - timer = setTimeout(() => reject(new AnthropicError(`bash command timed out after ${timeoutMs}ms`)), timeoutMs); - }), - new Promise((_, reject) => { - if (!signal) return; - onAbort = () => reject(new AnthropicError("bash command aborted")); - signal.addEventListener("abort", onAbort, { once: true }); - }) - ]); - } finally { - if (timer) clearTimeout(timer); - if (onAbort && signal) signal.removeEventListener("abort", onAbort); - __classPrivateFieldSet(this, _BashSession_waiting, null, "f"); - } - } - const idx = __classPrivateFieldGet(this, _BashSession_buf, "f").indexOf(sentinel); - if (idx < 0) throw new AnthropicError("bash session terminated"); - const m = __classPrivateFieldGet(this, _BashSession_buf, "f").slice(idx + sentinel.length).match(/^(-?\d+)/); - const exitCode = m ? parseInt(m[1], 10) : -1; - let out = __classPrivateFieldGet(this, _BashSession_buf, "f").slice(0, idx).replace(ANSI_RE, "").replace(/\n+$/, ""); - if (__classPrivateFieldGet(this, _BashSession_truncated, "f")) out = `[output truncated]\n${out}`; - return { - output: out, - exitCode - }; - } - close() { - if (__classPrivateFieldGet(this, _BashSession_closed, "f")) return; - __classPrivateFieldSet(this, _BashSession_closed, true, "f"); - const w = __classPrivateFieldGet(this, _BashSession_waiting, "f"); - __classPrivateFieldSet(this, _BashSession_waiting, null, "f"); - w?.resolve(); - __classPrivateFieldGet(this, _BashSession_proc, "f").stdout.destroy(); - __classPrivateFieldGet(this, _BashSession_proc, "f").stderr.destroy(); - __classPrivateFieldGet(this, _BashSession_proc, "f").stdin.destroy(); - try { - process.kill(-__classPrivateFieldGet(this, _BashSession_proc, "f").pid, "SIGKILL"); - } catch { - __classPrivateFieldGet(this, _BashSession_proc, "f").kill("SIGKILL"); - } - __classPrivateFieldGet(this, _BashSession_proc, "f").unref(); - } -}; -_BashSession_proc = /* @__PURE__ */ new WeakMap(), _BashSession_buf = /* @__PURE__ */ new WeakMap(), _BashSession_truncated = /* @__PURE__ */ new WeakMap(), _BashSession_closed = /* @__PURE__ */ new WeakMap(), _BashSession_waiting = /* @__PURE__ */ new WeakMap(), _BashSession_instances = /* @__PURE__ */ new WeakSet(), _BashSession_append = function _BashSession_append(d) { - __classPrivateFieldSet(this, _BashSession_buf, __classPrivateFieldGet(this, _BashSession_buf, "f") + d, "f"); - if (__classPrivateFieldGet(this, _BashSession_buf, "f").length > BASH_OUTPUT_LIMIT) { - __classPrivateFieldSet(this, _BashSession_buf, __classPrivateFieldGet(this, _BashSession_buf, "f").slice(__classPrivateFieldGet(this, _BashSession_buf, "f").length - BASH_OUTPUT_LIMIT), "f"); - __classPrivateFieldSet(this, _BashSession_truncated, true, "f"); - } - if (__classPrivateFieldGet(this, _BashSession_waiting, "f") && __classPrivateFieldGet(this, _BashSession_buf, "f").indexOf(__classPrivateFieldGet(this, _BashSession_waiting, "f").sentinel) >= 0) { - const w = __classPrivateFieldGet(this, _BashSession_waiting, "f"); - __classPrivateFieldSet(this, _BashSession_waiting, null, "f"); - w.resolve(); - } -}; -function betaBashTool(ctx) { - let session; - let tail = Promise.resolve(); - return betaTool({ - name: "bash", - description: "Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.", - inputSchema: { - type: "object", - properties: { - command: { - type: "string", - description: "The command to run" - }, - restart: { - type: "boolean", - description: "Restart the persistent shell before running" - }, - timeout_ms: { - type: "integer", - description: "Per-call timeout in milliseconds" - } - } - }, - run: async ({ command, restart, timeout_ms }, context) => { - const prev = tail; - const gate = promiseWithResolvers(); - tail = gate.promise; - try { - await prev; - } catch {} - try { - if (restart) { - session?.close(); - session = void 0; - } - if (!command) { - if (restart) return "bash session restarted"; - throw new ToolError("bash: command is required"); - } - session ?? (session = new BashSession(ctx.workdir, ctx.env)); - try { - const { output, exitCode } = await session.exec(command, { - timeoutMs: timeout_ms ?? BASH_DEFAULT_TIMEOUT_MS, - signal: context?.signal - }); - if (exitCode !== 0) throw new ToolError(output || `exit ${exitCode}`); - return output; - } catch (e) { - if (e instanceof ToolError) throw e; - session.close(); - session = void 0; - throw new ToolError(`bash: ${e instanceof Error ? e.message : String(e)}`); - } - } finally { - gate.resolve(); - } - }, - close: () => { - session?.close(); - session = void 0; - } - }); -} -function betaReadTool(ctx) { - return betaTool({ - name: "read", - description: "Read a UTF-8 text file relative to the workdir.", - inputSchema: { - type: "object", - properties: { - file_path: { type: "string" }, - view_range: { - type: "array", - items: { type: "integer" }, - description: "[start_line, end_line] 1-indexed inclusive" - } - }, - required: ["file_path"] - }, - run: async ({ file_path, view_range }) => { - if (!file_path) throw new ToolError("read: file_path is required"); - const abs = await resolvePath(ctx, file_path); - let data; - try { - const st = await fs$2.stat(abs); - if (!st.isFile()) throw new ToolError(`read: ${file_path} is not a regular file`); - const limit = resolveMaxBytes(ctx.maxFileBytes); - if (limit !== null && st.size > limit) throw new ToolError(`read: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. Use bash (head/tail/sed) to read a slice.`); - data = await fs$2.readFile(abs, "utf8"); - } catch (e) { - if (e instanceof ToolError) throw e; - throw new ToolError(`read: ${fsErrorMessage(e, file_path)}`); - } - if (!view_range) return data; - if (view_range.length !== 2) throw new ToolError("read: view_range must be [start_line, end_line]"); - const [startLine, endLine] = view_range; - const lines = data.split("\n"); - const start = Math.max(0, startLine - 1); - const end = endLine > 0 ? endLine : lines.length; - return lines.slice(start, end).join("\n"); - } - }); -} -function betaWriteTool(ctx) { - return betaTool({ - name: "write", - description: "Write a UTF-8 text file relative to the workdir, creating parent directories as needed.", - inputSchema: { - type: "object", - properties: { - file_path: { type: "string" }, - content: { type: "string" } - }, - required: ["file_path", "content"] - }, - run: async ({ file_path, content }) => { - if (!file_path) throw new ToolError("write: file_path is required"); - const abs = await resolvePath(ctx, file_path); - try { - await fs$2.mkdir(path$1.dirname(abs), { - recursive: true, - mode: 493 - }); - await atomicWriteFile(abs, content ?? ""); - } catch (e) { - throw new ToolError(`write: ${fsErrorMessage(e, file_path)}`); - } - return `wrote ${Buffer.byteLength(content ?? "")} bytes to ${file_path}`; - } - }); -} -function betaEditTool(ctx) { - return betaTool({ - name: "edit", - description: "Replace old_string with new_string in a file. old_string must be unique unless replace_all.", - inputSchema: { - type: "object", - properties: { - file_path: { type: "string" }, - old_string: { type: "string" }, - new_string: { type: "string" }, - replace_all: { type: "boolean" } - }, - required: [ - "file_path", - "old_string", - "new_string" - ] - }, - run: async ({ file_path, old_string, new_string, replace_all }) => { - if (!file_path) throw new ToolError("edit: file_path is required"); - if (!old_string) throw new ToolError("edit: old_string is required"); - const abs = await resolvePath(ctx, file_path); - let data; - try { - const st = await fs$2.stat(abs); - if (!st.isFile()) throw new ToolError(`edit: ${file_path} is not a regular file`); - const limit = resolveMaxBytes(ctx.maxFileBytes); - if (limit !== null && st.size > limit) throw new ToolError(`edit: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. Use bash (sed/awk) to edit a large file.`); - data = await fs$2.readFile(abs, "utf8"); - } catch (e) { - if (e instanceof ToolError) throw e; - throw new ToolError(`edit: ${fsErrorMessage(e, file_path)}`); - } - const count = data.split(old_string).length - 1; - if (count === 0) throw new ToolError(`edit: old_string not found in ${file_path}`); - let updated; - if (replace_all) updated = data.split(old_string).join(new_string); - else { - if (count > 1) throw new ToolError(`edit: old_string appears ${count} times in ${file_path} (must be unique)`); - updated = data.replace(old_string, () => new_string); - } - try { - await atomicWriteFile(abs, updated); - } catch (e) { - throw new ToolError(`edit: write: ${fsErrorMessage(e, file_path)}`); - } - return `edited ${file_path} (${replace_all ? count : 1} replacement(s))`; - } - }); -} -function betaGlobTool(ctx) { - return betaTool({ - name: "glob", - description: "Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.", - inputSchema: { - type: "object", - properties: { - pattern: { type: "string" }, - path: { - type: "string", - description: "Directory to search in. Defaults to the workdir." - } - }, - required: ["pattern"] - }, - run: async ({ pattern, path: searchPath }) => { - if (!pattern) throw new ToolError("glob: pattern is required"); - let root = path$1.resolve(ctx.workdir); - let pat = pattern; - if (path$1.isAbsolute(pattern)) { - if (!ctx.unrestrictedPaths) throw new ToolError("glob: absolute pattern not permitted"); - root = path$1.parse(pattern).root; - pat = path$1.relative(root, pattern); - } else if (searchPath) root = await resolvePath(ctx, searchPath); - if (!ctx.unrestrictedPaths && pat.split(/[\\/]/).includes("..")) throw new ToolError("glob: \"..\" is not permitted in the pattern"); - const realRoot = ctx.unrestrictedPaths ? root : await fs$2.realpath(root).catch(() => root); - const matches = []; - try { - for await (const entry of fsGlob(pat, { - cwd: root, - withFileTypes: true, - exclude: (d) => d.name === ".git" || d.name === "node_modules" - })) { - if (!entry.isFile()) continue; - const full = path$1.join(entry.parentPath, entry.name); - if (!ctx.unrestrictedPaths) { - let real; - try { - real = await fs$2.realpath(full); - } catch { - continue; - } - if (!isWithin(realRoot, real)) continue; - } - let mtime = 0; - try { - mtime = (await fs$2.stat(full)).mtimeMs; - } catch {} - matches.push({ - path: full, - mtime - }); - } - } catch (e) { - throw new ToolError(`glob: ${e instanceof Error ? e.message : String(e)}`); - } - if (matches.length === 0) return "no matches"; - matches.sort((a, b) => b.mtime - a.mtime); - return matches.slice(0, GLOB_RESULT_LIMIT).map((m) => m.path).join("\n"); - } - }); -} -function betaGrepTool(ctx) { - return betaTool({ - name: "grep", - description: "Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.", - inputSchema: { - type: "object", - properties: { - pattern: { type: "string" }, - path: { type: "string" } - }, - required: ["pattern"] - }, - run: async ({ pattern, path: p }, context) => { - if (!pattern) throw new ToolError("grep: pattern is required"); - let searchPath = path$1.resolve(ctx.workdir); - if (p) searchPath = await resolvePath(ctx, p); - const rg = await findRg(); - return rg ? runRipgrep(rg, pattern, searchPath, context?.signal) : runWalkGrep(pattern, searchPath, context?.signal); - } - }); -} -function runRipgrep(rg, pattern, searchPath, signal) { - return new Promise((resolve, reject) => { - const proc = cp.spawn(rg, [ - "-n", - "--no-heading", - "-e", - pattern, - "--", - searchPath - ], { ...signal ? { signal } : {} }); - let out = ""; - let errOut = ""; - let truncated = false; - proc.stdout.on("data", (d) => { - if (truncated) return; - out += d; - if (out.length > GREP_OUTPUT_LIMIT) { - truncated = true; - out = out.slice(0, GREP_OUTPUT_LIMIT); - proc.kill("SIGKILL"); - } - }); - proc.stderr.on("data", (d) => errOut += d); - proc.on("close", (code) => { - if (signal?.aborted) return reject(new ToolError("grep: aborted")); - if (truncated) return resolve(out + `\n[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`); - if (code === 0) return resolve(out); - if (code === 1) return resolve("no matches"); - reject(new ToolError(`grep: rg failed: ${errOut || `exit ${code}`}`)); - }); - proc.on("error", (e) => { - if (signal?.aborted) return reject(new ToolError("grep: aborted")); - reject(new ToolError(`grep: rg failed: ${e.message}`)); - }); - }); -} -async function runWalkGrep(pattern, root, signal) { - let re; - try { - re = new RegExp(pattern); - } catch (e) { - throw new ToolError(`grep: invalid regex: ${e instanceof Error ? e.message : String(e)}`); - } - const hits = []; - let budget = GREP_OUTPUT_LIMIT; - const push = (line) => { - budget -= line.length + 1; - if (budget < 0) { - hits.push(`[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`); - return false; - } - hits.push(line); - return true; - }; - if ((await fs$2.stat(root).catch(() => null))?.isFile()) await grepFile(root, re, push); - else await walk(root, "", (rel) => grepFile(path$1.join(root, rel), re, push), signal); - if (signal?.aborted) throw new ToolError("grep: aborted"); - if (hits.length === 0) return "no matches"; - return hits.join("\n"); -} -async function grepFile(file, re, push) { - const stream = fssync.createReadStream(file, { encoding: "utf8" }); - const rl = readline.createInterface({ - input: stream, - crlfDelay: Infinity - }); - let i = 0; - try { - for await (const line of rl) { - i++; - if (line.length > GREP_MAX_LINE_LENGTH) continue; - if (re.test(line) && !push(`${file}:${i}:${line}`)) return false; - } - } catch {} finally { - stream.destroy(); - } - return true; -} -/** True when `p` is `root` itself or lexically contained within it. */ -function isWithin(root, p) { - const rel = path$1.relative(root, p); - return rel === "" || !rel.startsWith(".." + path$1.sep) && rel !== ".." && !path$1.isAbsolute(rel); -} -var WALK_MAX_DEPTH = 40; -var WALK_MAX_ENTRIES = 5e4; -/** -* Bounded recursive walk. `fn` may return `false` to abort. Only real -* directories are descended into and only real files are handed to `fn` — -* symlinks (and devices/fifos/sockets) are skipped entirely so a symlink inside -* the root cannot be followed out of it. -*/ -async function walk(root, rel, fn, signal) { - let remaining = WALK_MAX_ENTRIES; - async function inner(rel, depth) { - if (depth > WALK_MAX_DEPTH) return true; - if (signal?.aborted) return false; - let entries; - try { - entries = await fs$2.readdir(path$1.join(root, rel), { withFileTypes: true }); - } catch { - return true; - } - for (const e of entries) { - if (e.name === ".git" || e.name === "node_modules") continue; - if (remaining-- <= 0) return false; - if (signal?.aborted) return false; - const childRel = rel ? path$1.join(rel, e.name) : e.name; - if (e.isDirectory()) { - if (!await inner(childRel, depth + 1)) return false; - } else if (e.isFile()) { - if (await fn(childRel) === false) return false; - } - } - return true; - } - await inner(rel, 0); -} -async function findRg() { - const dirs = (process.env["PATH"] ?? "").split(path$1.delimiter); - for (const d of dirs) { - const candidate = path$1.join(d, "rg"); - try { - await fs$2.access(candidate, fssync.constants.X_OK); - return candidate; - } catch {} - } - return null; -} -//#endregion -export { Anthropic as n, transformJSONSchema as t }; diff --git a/.vercel/output/functions/__server.func/_libs/@better-auth/core+[...].mjs b/.vercel/output/functions/__server.func/_libs/@better-auth/core+[...].mjs deleted file mode 100644 index 61ba37b..0000000 --- a/.vercel/output/functions/__server.func/_libs/@better-auth/core+[...].mjs +++ /dev/null @@ -1,19462 +0,0 @@ -import { t as __commonJSMin } from "../../_runtime.mjs"; -//#region node_modules/@better-auth/core/dist/utils/error-codes.mjs -function defineErrorCodes(codes) { - return Object.fromEntries(Object.entries(codes).map(([key, value]) => [key, { - code: key, - message: value, - toString: () => key - }])); -} -//#endregion -//#region node_modules/@better-auth/core/dist/error/codes.mjs -var BASE_ERROR_CODES = defineErrorCodes({ - USER_NOT_FOUND: "User not found", - FAILED_TO_CREATE_USER: "Failed to create user", - FAILED_TO_CREATE_SESSION: "Failed to create session", - FAILED_TO_UPDATE_USER: "Failed to update user", - FAILED_TO_GET_SESSION: "Failed to get session", - INVALID_PASSWORD: "Invalid password", - INVALID_EMAIL: "Invalid email", - INVALID_EMAIL_OR_PASSWORD: "Invalid email or password", - INVALID_USER: "Invalid user", - SOCIAL_ACCOUNT_ALREADY_LINKED: "Social account already linked", - PROVIDER_NOT_FOUND: "Provider not found", - INVALID_TOKEN: "Invalid token", - TOKEN_EXPIRED: "Token expired", - ID_TOKEN_NOT_SUPPORTED: "id_token not supported", - FAILED_TO_GET_USER_INFO: "Failed to get user info", - USER_EMAIL_NOT_FOUND: "User email not found", - EMAIL_NOT_VERIFIED: "Email not verified", - PASSWORD_TOO_SHORT: "Password too short", - PASSWORD_TOO_LONG: "Password too long", - USER_ALREADY_EXISTS: "User already exists.", - USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: "User already exists. Use another email.", - EMAIL_CAN_NOT_BE_UPDATED: "Email can not be updated", - CHANGE_EMAIL_DISABLED: "Change email is disabled", - CREDENTIAL_ACCOUNT_NOT_FOUND: "Credential account not found", - SESSION_EXPIRED: "Session expired. Re-authenticate to perform this action.", - FAILED_TO_UNLINK_LAST_ACCOUNT: "You can't unlink your last account", - ACCOUNT_NOT_FOUND: "Account not found", - USER_ALREADY_HAS_PASSWORD: "User already has a password. Provide that to delete the account.", - CROSS_SITE_NAVIGATION_LOGIN_BLOCKED: "Cross-site navigation login blocked. This request appears to be a CSRF attack.", - VERIFICATION_EMAIL_NOT_ENABLED: "Verification email isn't enabled", - EMAIL_ALREADY_VERIFIED: "Email is already verified", - EMAIL_MISMATCH: "Email mismatch", - SESSION_NOT_FRESH: "Session is not fresh", - LINKED_ACCOUNT_ALREADY_EXISTS: "Linked account already exists", - INVALID_ORIGIN: "Invalid origin", - INVALID_CALLBACK_URL: "Invalid callbackURL", - INVALID_REDIRECT_URL: "Invalid redirectURL", - INVALID_ERROR_CALLBACK_URL: "Invalid errorCallbackURL", - INVALID_NEW_USER_CALLBACK_URL: "Invalid newUserCallbackURL", - MISSING_OR_NULL_ORIGIN: "Missing or null Origin", - CALLBACK_URL_REQUIRED: "callbackURL is required", - FAILED_TO_CREATE_VERIFICATION: "Unable to create verification", - FIELD_NOT_ALLOWED: "Field not allowed to be set", - ASYNC_VALIDATION_NOT_SUPPORTED: "Async validation is not supported", - VALIDATION_ERROR: "Validation Error", - MISSING_FIELD: "Field is required", - METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED: "POST method requires deferSessionRefresh to be enabled in session config", - BODY_MUST_BE_AN_OBJECT: "Body must be an object", - PASSWORD_ALREADY_SET: "User already has a password set" -}); -//#endregion -//#region node_modules/better-call/dist/error.mjs -function isErrorStackTraceLimitWritable() { - const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); - if (desc === void 0) return Object.isExtensible(Error); - return Object.prototype.hasOwnProperty.call(desc, "writable") ? desc.writable : desc.set !== void 0; -} -/** -* Hide internal stack frames from the error stack trace. -*/ -function hideInternalStackFrames(stack) { - const lines = stack.split("\n at "); - if (lines.length <= 1) return stack; - lines.splice(1, 1); - return lines.join("\n at "); -} -/** -* Creates a custom error class that hides stack frames. -*/ -function makeErrorForHideStackFrame(Base, clazz) { - class HideStackFramesError extends Base { - #hiddenStack; - constructor(...args) { - if (isErrorStackTraceLimitWritable()) { - const limit = Error.stackTraceLimit; - Error.stackTraceLimit = 0; - super(...args); - Error.stackTraceLimit = limit; - } else super(...args); - const stack = (/* @__PURE__ */ new Error()).stack; - if (stack) this.#hiddenStack = hideInternalStackFrames(stack.replace(/^Error/, this.name)); - } - get errorStack() { - return this.#hiddenStack; - } - } - Object.defineProperty(HideStackFramesError.prototype, "constructor", { - get() { - return clazz; - }, - enumerable: false, - configurable: true - }); - return HideStackFramesError; -} -var statusCodes = { - OK: 200, - CREATED: 201, - ACCEPTED: 202, - NO_CONTENT: 204, - MULTIPLE_CHOICES: 300, - MOVED_PERMANENTLY: 301, - FOUND: 302, - SEE_OTHER: 303, - NOT_MODIFIED: 304, - TEMPORARY_REDIRECT: 307, - BAD_REQUEST: 400, - UNAUTHORIZED: 401, - PAYMENT_REQUIRED: 402, - FORBIDDEN: 403, - NOT_FOUND: 404, - METHOD_NOT_ALLOWED: 405, - NOT_ACCEPTABLE: 406, - PROXY_AUTHENTICATION_REQUIRED: 407, - REQUEST_TIMEOUT: 408, - CONFLICT: 409, - GONE: 410, - LENGTH_REQUIRED: 411, - PRECONDITION_FAILED: 412, - PAYLOAD_TOO_LARGE: 413, - URI_TOO_LONG: 414, - UNSUPPORTED_MEDIA_TYPE: 415, - RANGE_NOT_SATISFIABLE: 416, - EXPECTATION_FAILED: 417, - "I'M_A_TEAPOT": 418, - MISDIRECTED_REQUEST: 421, - UNPROCESSABLE_ENTITY: 422, - LOCKED: 423, - FAILED_DEPENDENCY: 424, - TOO_EARLY: 425, - UPGRADE_REQUIRED: 426, - PRECONDITION_REQUIRED: 428, - TOO_MANY_REQUESTS: 429, - REQUEST_HEADER_FIELDS_TOO_LARGE: 431, - UNAVAILABLE_FOR_LEGAL_REASONS: 451, - INTERNAL_SERVER_ERROR: 500, - NOT_IMPLEMENTED: 501, - BAD_GATEWAY: 502, - SERVICE_UNAVAILABLE: 503, - GATEWAY_TIMEOUT: 504, - HTTP_VERSION_NOT_SUPPORTED: 505, - VARIANT_ALSO_NEGOTIATES: 506, - INSUFFICIENT_STORAGE: 507, - LOOP_DETECTED: 508, - NOT_EXTENDED: 510, - NETWORK_AUTHENTICATION_REQUIRED: 511 -}; -var InternalAPIError = class extends Error { - constructor(status = "INTERNAL_SERVER_ERROR", body = void 0, headers = {}, statusCode = typeof status === "number" ? status : statusCodes[status]) { - super(body?.message, body?.cause ? { cause: body.cause } : void 0); - this.status = status; - this.body = body; - this.headers = headers; - this.statusCode = statusCode; - this.name = "APIError"; - this.status = status; - this.headers = headers; - this.statusCode = statusCode; - this.body = body; - } -}; -var ValidationError$1 = class extends InternalAPIError { - constructor(message, issues) { - super(400, { - message, - code: "VALIDATION_ERROR" - }); - this.message = message; - this.issues = issues; - this.issues = issues; - } -}; -var BetterCallError = class extends Error { - constructor(message) { - super(message); - this.name = "BetterCallError"; - } -}; -var kAPIErrorHeaderSymbol = Symbol.for("better-call:api-error-headers"); -var APIError$1 = makeErrorForHideStackFrame(InternalAPIError, Error); -//#endregion -//#region node_modules/@better-auth/core/dist/error/index.mjs -var BetterAuthError = class extends Error { - constructor(message, options) { - super(message, options); - this.name = "BetterAuthError"; - this.message = message; - this.stack = ""; - } -}; -var APIError = class APIError extends APIError$1 { - constructor(...args) { - super(...args); - } - static fromStatus(status, body) { - return new APIError(status, body); - } - static from(status, error) { - return new APIError(status, { - message: error.message, - code: error.code - }); - } -}; -//#endregion -//#region node_modules/@better-auth/core/dist/env/env-impl.mjs -var _envShim = Object.create(null); -var _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis); -var env = new Proxy(_envShim, { - get(_, prop) { - return _getEnv()[prop] ?? _envShim[prop]; - }, - has(_, prop) { - return prop in _getEnv() || prop in _envShim; - }, - set(_, prop, value) { - const env = _getEnv(true); - env[prop] = value; - return true; - }, - deleteProperty(_, prop) { - if (!prop) return false; - const env = _getEnv(true); - delete env[prop]; - return true; - }, - ownKeys() { - const env = _getEnv(true); - return Object.keys(env); - } -}); -function toBoolean(val) { - return val ? val !== "false" : false; -} -var nodeENV = env.NODE_ENV ?? ""; -/** Detect if `NODE_ENV` environment variable is `production` */ -var isProduction = nodeENV === "production"; -/** Detect if `NODE_ENV` environment variable is `dev` or `development` */ -var isDevelopment = () => nodeENV === "dev" || nodeENV === "development"; -/** Detect if `NODE_ENV` environment variable is `test` */ -var isTest = () => nodeENV === "test" || toBoolean(env.TEST); -/** -* Get environment variable with fallback -*/ -function getEnvVar(key, fallback) { - if (typeof process !== "undefined" && process.env) return process.env[key] ?? fallback; - if (typeof Deno !== "undefined") return Deno.env.get(key) ?? fallback; - if (typeof Bun !== "undefined") return Bun.env[key] ?? fallback; - return fallback; -} -/** -* Get boolean environment variable -*/ -function getBooleanEnvVar(key, fallback = true) { - const value = getEnvVar(key); - if (!value) return fallback; - return value !== "0" && value.toLowerCase() !== "false" && value !== ""; -} -/** -* Common environment variables used in Better Auth -*/ -var ENV = Object.freeze({ - get BETTER_AUTH_SECRET() { - return getEnvVar("BETTER_AUTH_SECRET"); - }, - get AUTH_SECRET() { - return getEnvVar("AUTH_SECRET"); - }, - get BETTER_AUTH_TELEMETRY() { - return getEnvVar("BETTER_AUTH_TELEMETRY"); - }, - get BETTER_AUTH_TELEMETRY_ID() { - return getEnvVar("BETTER_AUTH_TELEMETRY_ID"); - }, - get NODE_ENV() { - return getEnvVar("NODE_ENV", "development"); - }, - get PACKAGE_VERSION() { - return getEnvVar("PACKAGE_VERSION", "0.0.0"); - }, - get BETTER_AUTH_TELEMETRY_ENDPOINT() { - return getEnvVar("BETTER_AUTH_TELEMETRY_ENDPOINT", ""); - } -}); -//#endregion -//#region node_modules/@better-auth/core/dist/env/color-depth.mjs -var COLORS_2 = 1; -var COLORS_16 = 4; -var COLORS_256 = 8; -var COLORS_16m = 24; -var TERM_ENVS = { - eterm: COLORS_16, - cons25: COLORS_16, - console: COLORS_16, - cygwin: COLORS_16, - dtterm: COLORS_16, - gnome: COLORS_16, - hurd: COLORS_16, - jfbterm: COLORS_16, - konsole: COLORS_16, - kterm: COLORS_16, - mlterm: COLORS_16, - mosh: COLORS_16m, - putty: COLORS_16, - st: COLORS_16, - "rxvt-unicode-24bit": COLORS_16m, - terminator: COLORS_16m, - "xterm-kitty": COLORS_16m -}; -var CI_ENVS_MAP = new Map(Object.entries({ - APPVEYOR: COLORS_256, - BUILDKITE: COLORS_256, - CIRCLECI: COLORS_16m, - DRONE: COLORS_256, - GITEA_ACTIONS: COLORS_16m, - GITHUB_ACTIONS: COLORS_16m, - GITLAB_CI: COLORS_256, - TRAVIS: COLORS_256 -})); -var TERM_ENVS_REG_EXP = [ - /ansi/, - /color/, - /linux/, - /direct/, - /^con[0-9]*x[0-9]/, - /^rxvt/, - /^screen/, - /^xterm/, - /^vt100/, - /^vt220/ -]; -function getColorDepth() { - if (getEnvVar("FORCE_COLOR") !== void 0) switch (getEnvVar("FORCE_COLOR")) { - case "": - case "1": - case "true": return COLORS_16; - case "2": return COLORS_256; - case "3": return COLORS_16m; - default: return COLORS_2; - } - if (getEnvVar("NODE_DISABLE_COLORS") !== void 0 && getEnvVar("NODE_DISABLE_COLORS") !== "" || getEnvVar("NO_COLOR") !== void 0 && getEnvVar("NO_COLOR") !== "" || getEnvVar("TERM") === "dumb") return COLORS_2; - if (getEnvVar("TMUX")) return COLORS_16m; - if ("TF_BUILD" in env && "AGENT_NAME" in env) return COLORS_16; - if ("CI" in env) { - for (const { 0: envName, 1: colors } of CI_ENVS_MAP) if (envName in env) return colors; - if (getEnvVar("CI_NAME") === "codeship") return COLORS_256; - return COLORS_2; - } - if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(getEnvVar("TEAMCITY_VERSION")) !== null ? COLORS_16 : COLORS_2; - switch (getEnvVar("TERM_PROGRAM")) { - case "iTerm.app": - if (!getEnvVar("TERM_PROGRAM_VERSION") || /^[0-2]\./.exec(getEnvVar("TERM_PROGRAM_VERSION")) !== null) return COLORS_256; - return COLORS_16m; - case "HyperTerm": - case "MacTerm": return COLORS_16m; - case "Apple_Terminal": return COLORS_256; - } - if (getEnvVar("COLORTERM") === "truecolor" || getEnvVar("COLORTERM") === "24bit") return COLORS_16m; - if (getEnvVar("TERM")) { - if (/truecolor/.exec(getEnvVar("TERM")) !== null) return COLORS_16m; - if (/^xterm-256/.exec(getEnvVar("TERM")) !== null) return COLORS_256; - const termEnv = getEnvVar("TERM").toLowerCase(); - if (TERM_ENVS[termEnv]) return TERM_ENVS[termEnv]; - if (TERM_ENVS_REG_EXP.some((term) => term.exec(termEnv) !== null)) return COLORS_16; - } - if (getEnvVar("COLORTERM")) return COLORS_16; - return COLORS_2; -} -//#endregion -//#region node_modules/@better-auth/core/dist/env/logger.mjs -var TTY_COLORS = { - reset: "\x1B[0m", - bright: "\x1B[1m", - dim: "\x1B[2m", - undim: "\x1B[22m", - underscore: "\x1B[4m", - blink: "\x1B[5m", - reverse: "\x1B[7m", - hidden: "\x1B[8m", - fg: { - black: "\x1B[30m", - red: "\x1B[31m", - green: "\x1B[32m", - yellow: "\x1B[33m", - blue: "\x1B[34m", - magenta: "\x1B[35m", - cyan: "\x1B[36m", - white: "\x1B[37m" - }, - bg: { - black: "\x1B[40m", - red: "\x1B[41m", - green: "\x1B[42m", - yellow: "\x1B[43m", - blue: "\x1B[44m", - magenta: "\x1B[45m", - cyan: "\x1B[46m", - white: "\x1B[47m" - } -}; -var levels = [ - "debug", - "info", - "success", - "warn", - "error" -]; -function shouldPublishLog(currentLogLevel, logLevel) { - return levels.indexOf(logLevel) >= levels.indexOf(currentLogLevel); -} -var levelColors = { - info: TTY_COLORS.fg.blue, - success: TTY_COLORS.fg.green, - warn: TTY_COLORS.fg.yellow, - error: TTY_COLORS.fg.red, - debug: TTY_COLORS.fg.magenta -}; -var formatMessage = (level, message, colorsEnabled) => { - const timestamp = (/* @__PURE__ */ new Date()).toISOString(); - if (colorsEnabled) return `${TTY_COLORS.dim}${timestamp}${TTY_COLORS.reset} ${levelColors[level]}${level.toUpperCase()}${TTY_COLORS.reset} ${TTY_COLORS.bright}[Better Auth]:${TTY_COLORS.reset} ${message}`; - return `${timestamp} ${level.toUpperCase()} [Better Auth]: ${message}`; -}; -var createLogger = (options) => { - const enabled = options?.disabled !== true; - const logLevel = options?.level ?? "warn"; - const colorsEnabled = options?.disableColors !== void 0 ? !options.disableColors : getColorDepth() !== 1; - const LogFunc = (level, message, args = []) => { - if (!enabled || !shouldPublishLog(logLevel, level)) return; - const formattedMessage = formatMessage(level, message, colorsEnabled); - if (!options || typeof options.log !== "function") { - if (level === "error") console.error(formattedMessage, ...args); - else if (level === "warn") console.warn(formattedMessage, ...args); - else console.log(formattedMessage, ...args); - return; - } - options.log(level === "success" ? "info" : level, message, ...args); - }; - return { - ...Object.fromEntries(levels.map((level) => [level, (...[message, ...args]) => LogFunc(level, message, args)])), - get level() { - return logLevel; - } - }; -}; -var logger = createLogger(); -//#endregion -//#region node_modules/@better-auth/core/dist/utils/url.mjs -/** -* Normalizes a request pathname by removing the basePath prefix and trailing slashes. -* This is useful for matching paths against configured path lists. -* -* @param requestUrl - The full request URL -* @param basePath - The base path of the auth API (e.g., "/api/auth") -* @returns The normalized path without basePath prefix or trailing slashes, -* or "/" if URL parsing fails -* -* @example -* normalizePathname("http://localhost:3000/api/auth/sso/saml2/callback/provider1", "/api/auth") -* // Returns: "/sso/saml2/callback/provider1" -* -* normalizePathname("http://localhost:3000/sso/saml2/callback/provider1/", "/") -* // Returns: "/sso/saml2/callback/provider1" -*/ -function normalizePathname(requestUrl, basePath) { - let pathname; - try { - pathname = new URL(requestUrl).pathname.replace(/\/+$/, "") || "/"; - } catch { - return "/"; - } - const normalizedBasePath = basePath.replace(/\/+$/, ""); - if (normalizedBasePath === "") return pathname; - if (pathname === normalizedBasePath) return "/"; - if (pathname.startsWith(normalizedBasePath + "/")) return pathname.slice(normalizedBasePath.length).replace(/\/+$/, "") || "/"; - return pathname; -} -/** -* Schemes that execute or embed code when navigated to or accepted as a -* redirect target. These are never safe as an OAuth `redirect_uri` or as a -* client-side navigation target (`window.location.href`, `location.assign`, ...). -*/ -var DANGEROUS_URL_SCHEMES = [ - "javascript:", - "data:", - "vbscript:" -]; -/** -* Returns `false` only when `value` is an absolute URL using a dangerous scheme -* (`javascript:`, `data:`, `vbscript:`). Relative URLs (e.g. `/dashboard`) and -* safe absolute schemes (`http`, `https`, custom app schemes such as -* `myapp://`) return `true`. -* -* Use this to guard browser navigation sinks and any redirect target that may -* originate from untrusted input. It is intentionally narrow: it blocks code -* execution schemes without rejecting relative paths or mobile deep links. -*/ -function isSafeUrlScheme(value) { - let parsed; - try { - parsed = new URL(value); - } catch { - return true; - } - return !DANGEROUS_URL_SCHEMES.includes(parsed.protocol); -} -//#endregion -//#region node_modules/@better-fetch/fetch/dist/index.js -var __defProp = Object.defineProperty; -var __defProps = Object.defineProperties; -var __getOwnPropDescs = Object.getOwnPropertyDescriptors; -var __getOwnPropSymbols = Object.getOwnPropertySymbols; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __propIsEnum = Object.prototype.propertyIsEnumerable; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { - enumerable: true, - configurable: true, - writable: true, - value -}) : obj[key] = value; -var __spreadValues = (a, b) => { - for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); - if (__getOwnPropSymbols) { - for (var prop of __getOwnPropSymbols(b)) if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); - } - return a; -}; -var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); -var BetterFetchError = class extends Error { - constructor(status, statusText, error) { - super(statusText || status.toString(), { cause: error }); - this.status = status; - this.statusText = statusText; - this.error = error; - Error.captureStackTrace(this, this.constructor); - } -}; -var initializePlugins = async (url, options) => { - var _a, _b, _c, _d, _e, _f; - let opts = options || {}; - const hooks = { - onRequest: [options == null ? void 0 : options.onRequest], - onResponse: [options == null ? void 0 : options.onResponse], - onSuccess: [options == null ? void 0 : options.onSuccess], - onError: [options == null ? void 0 : options.onError], - onRetry: [options == null ? void 0 : options.onRetry] - }; - if (!options || !(options == null ? void 0 : options.plugins)) return { - url, - options: opts, - hooks - }; - for (const plugin of (options == null ? void 0 : options.plugins) || []) { - if (plugin.init) { - const pluginRes = await ((_a = plugin.init) == null ? void 0 : _a.call(plugin, url.toString(), options)); - opts = pluginRes.options || opts; - url = pluginRes.url; - } - hooks.onRequest.push((_b = plugin.hooks) == null ? void 0 : _b.onRequest); - hooks.onResponse.push((_c = plugin.hooks) == null ? void 0 : _c.onResponse); - hooks.onSuccess.push((_d = plugin.hooks) == null ? void 0 : _d.onSuccess); - hooks.onError.push((_e = plugin.hooks) == null ? void 0 : _e.onError); - hooks.onRetry.push((_f = plugin.hooks) == null ? void 0 : _f.onRetry); - } - return { - url, - options: opts, - hooks - }; -}; -var LinearRetryStrategy = class { - constructor(options) { - this.options = options; - } - shouldAttemptRetry(attempt, response) { - if (this.options.shouldRetry) return Promise.resolve(attempt < this.options.attempts && this.options.shouldRetry(response)); - return Promise.resolve(attempt < this.options.attempts); - } - getDelay() { - return this.options.delay; - } -}; -var ExponentialRetryStrategy = class { - constructor(options) { - this.options = options; - } - shouldAttemptRetry(attempt, response) { - if (this.options.shouldRetry) return Promise.resolve(attempt < this.options.attempts && this.options.shouldRetry(response)); - return Promise.resolve(attempt < this.options.attempts); - } - getDelay(attempt) { - return Math.min(this.options.maxDelay, this.options.baseDelay * 2 ** attempt); - } -}; -function createRetryStrategy(options) { - if (typeof options === "number") return new LinearRetryStrategy({ - type: "linear", - attempts: options, - delay: 1e3 - }); - switch (options.type) { - case "linear": return new LinearRetryStrategy(options); - case "exponential": return new ExponentialRetryStrategy(options); - default: throw new Error("Invalid retry strategy"); - } -} -var getAuthHeader = async (options) => { - const headers = {}; - const getValue = async (value) => typeof value === "function" ? await value() : value; - if (options == null ? void 0 : options.auth) { - if (options.auth.type === "Bearer") { - const token = await getValue(options.auth.token); - if (!token) return headers; - headers["authorization"] = `Bearer ${token}`; - } else if (options.auth.type === "Basic") { - const [username, password] = await Promise.all([getValue(options.auth.username), getValue(options.auth.password)]); - if (!username || !password) return headers; - headers["authorization"] = `Basic ${btoa(`${username}:${password}`)}`; - } else if (options.auth.type === "Custom") { - const [prefix, value] = await Promise.all([getValue(options.auth.prefix), getValue(options.auth.value)]); - if (!value) return headers; - headers["authorization"] = `${prefix != null ? prefix : ""} ${value}`; - } - } - return headers; -}; -var JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i; -function detectResponseType(request) { - const _contentType = request.headers.get("content-type"); - const textTypes = /* @__PURE__ */ new Set([ - "image/svg", - "application/xml", - "application/xhtml", - "application/html" - ]); - if (!_contentType) return "json"; - const contentType = _contentType.split(";").shift() || ""; - if (JSON_RE.test(contentType)) return "json"; - if (textTypes.has(contentType) || contentType.startsWith("text/")) return "text"; - return "blob"; -} -function isJSONParsable(value) { - try { - JSON.parse(value); - return true; - } catch (error) { - return false; - } -} -function isJSONSerializable$1(value) { - if (value === void 0) return false; - const t = typeof value; - if (t === "string" || t === "number" || t === "boolean" || t === null) return true; - if (t !== "object") return false; - if (Array.isArray(value)) return true; - if (value.buffer) return false; - return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function"; -} -function jsonParse(text) { - try { - return JSON.parse(text); - } catch (error) { - return text; - } -} -function isFunction(value) { - return typeof value === "function"; -} -function getFetch(options) { - if (options == null ? void 0 : options.customFetchImpl) return options.customFetchImpl; - if (typeof globalThis !== "undefined" && isFunction(globalThis.fetch)) return globalThis.fetch; - if (typeof window !== "undefined" && isFunction(window.fetch)) return window.fetch; - throw new Error("No fetch implementation found"); -} -function mergeHeaders(...sources) { - const merged = {}; - for (const source of sources) { - if (!source) continue; - if (source instanceof Headers) source.forEach((value, key) => { - merged[key] = value; - }); - else { - const entries = Array.isArray(source) ? source : Object.entries(source); - for (const [key, value] of entries) if (value !== null && value !== void 0) merged[key] = value; - } - } - return merged; -} -async function getHeaders(opts) { - const headers = new Headers(mergeHeaders(opts == null ? void 0 : opts.headers, await getAuthHeader(opts))); - if (!headers.has("content-type")) { - const contentType = detectContentType(opts == null ? void 0 : opts.body); - if (contentType) headers.set("content-type", contentType); - } - return headers; -} -function detectContentType(body) { - if (isJSONSerializable$1(body)) return "application/json"; - return null; -} -function getMediaType(headers) { - const contentType = headers.get("content-type"); - return contentType ? contentType.split(";")[0].trim().toLowerCase() : null; -} -function getBody$1(options, headers) { - const { body } = options; - if (!body) return null; - if (!isJSONSerializable$1(body)) return body; - if (typeof body === "string") return body; - if (getMediaType(headers) === "application/x-www-form-urlencoded") return new URLSearchParams(body).toString(); - return JSON.stringify(body); -} -function getMethod(url, options) { - var _a; - if (options == null ? void 0 : options.method) return options.method.toUpperCase(); - if (url.startsWith("@")) { - const pMethod = (_a = url.split("@")[1]) == null ? void 0 : _a.split("/")[0]; - if (!methods.includes(pMethod)) return (options == null ? void 0 : options.body) ? "POST" : "GET"; - return pMethod.toUpperCase(); - } - return (options == null ? void 0 : options.body) ? "POST" : "GET"; -} -function getTimeout(options, controller) { - let abortTimeout; - if (!(options == null ? void 0 : options.signal) && (options == null ? void 0 : options.timeout)) abortTimeout = setTimeout(() => controller == null ? void 0 : controller.abort(), options == null ? void 0 : options.timeout); - return { - abortTimeout, - clearTimeout: () => { - if (abortTimeout) clearTimeout(abortTimeout); - } - }; -} -var ValidationError = class _ValidationError extends Error { - constructor(issues, message) { - super(message || JSON.stringify(issues, null, 2)); - this.issues = issues; - Object.setPrototypeOf(this, _ValidationError.prototype); - } -}; -async function parseStandardSchema(schema, input) { - const result = await schema["~standard"].validate(input); - if (result.issues) throw new ValidationError(result.issues); - return result.value; -} -var methods = [ - "get", - "post", - "put", - "patch", - "delete" -]; -var applySchemaPlugin = (config) => ({ - id: "apply-schema", - name: "Apply Schema", - version: "1.0.0", - async init(url, options) { - var _a, _b, _c, _d; - const schema = ((_b = (_a = config.plugins) == null ? void 0 : _a.find((plugin) => { - var _a2; - return ((_a2 = plugin.schema) == null ? void 0 : _a2.config) ? url.startsWith(plugin.schema.config.baseURL || "") || url.startsWith(plugin.schema.config.prefix || "") : false; - })) == null ? void 0 : _b.schema) || config.schema; - if (schema) { - let urlKey = url; - if ((_c = schema.config) == null ? void 0 : _c.prefix) { - if (urlKey.startsWith(schema.config.prefix)) { - urlKey = urlKey.replace(schema.config.prefix, ""); - if (schema.config.baseURL) url = url.replace(schema.config.prefix, schema.config.baseURL); - } - } - if ((_d = schema.config) == null ? void 0 : _d.baseURL) { - if (urlKey.startsWith(schema.config.baseURL)) urlKey = urlKey.replace(schema.config.baseURL, ""); - } - if (urlKey.startsWith("/") && urlKey.charAt(1) === "@") urlKey = urlKey.substring(1); - const keySchema = schema.schema[urlKey]; - if (keySchema) { - let validatedHeaders = options == null ? void 0 : options.headers; - if (keySchema.headers && !(options == null ? void 0 : options.disableValidation)) { - const normalizedHeaders = {}; - if (options == null ? void 0 : options.headers) { - if (options.headers instanceof Headers) options.headers.forEach((value, key) => { - normalizedHeaders[key.toLowerCase()] = value; - }); - else if (typeof options.headers === "object") { - for (const [key, value] of Object.entries(options.headers)) if (value !== null && value !== void 0) normalizedHeaders[key.toLowerCase()] = value; - } - } - const validated = await parseStandardSchema(keySchema.headers, normalizedHeaders); - const finalHeaders = {}; - for (const [key, value] of Object.entries(validated)) finalHeaders[key.toLowerCase()] = value; - validatedHeaders = finalHeaders; - } - let opts = __spreadProps(__spreadValues({}, options), { - method: keySchema.method, - output: keySchema.output, - headers: validatedHeaders - }); - if (!(options == null ? void 0 : options.disableValidation)) opts = __spreadProps(__spreadValues({}, opts), { - body: keySchema.input ? await parseStandardSchema(keySchema.input, options == null ? void 0 : options.body) : options == null ? void 0 : options.body, - params: keySchema.params ? await parseStandardSchema(keySchema.params, options == null ? void 0 : options.params) : options == null ? void 0 : options.params, - query: keySchema.query ? await parseStandardSchema(keySchema.query, options == null ? void 0 : options.query) : options == null ? void 0 : options.query - }); - return { - url, - options: opts - }; - } - } - return { - url, - options - }; - } -}); -var createFetch = (config) => { - async function $fetch(url, options) { - const opts = __spreadProps(__spreadValues(__spreadValues({}, config), options), { - headers: mergeHeaders(config == null ? void 0 : config.headers, options == null ? void 0 : options.headers), - plugins: [ - ...(config == null ? void 0 : config.plugins) || [], - applySchemaPlugin(config || {}), - ...(options == null ? void 0 : options.plugins) || [] - ] - }); - if (config == null ? void 0 : config.catchAllError) try { - return await betterFetch(url, opts); - } catch (error) { - return { - data: null, - error: { - status: 500, - statusText: "Fetch Error", - message: "Fetch related error. Captured by catchAllError option. See error property for more details.", - error - } - }; - } - return await betterFetch(url, opts); - } - return $fetch; -}; -var isReservedPathSegment = (value) => value === "." || value === ".."; -function encodePathSegment(segment, pathParams) { - let pathSegment = segment; - for (const [key, value] of pathParams) pathSegment = pathSegment.replace(key, value); - if (isReservedPathSegment(pathSegment)) throw new TypeError("Path parameters cannot be reserved path segments"); - return encodeURIComponent(pathSegment); -} -function getURL2(url, option) { - const { baseURL, params, query } = option || { - query: {}, - params: {}, - baseURL: "" - }; - let basePath = url.startsWith("http") ? url.split("/").slice(0, 3).join("/") : baseURL || ""; - if (url.startsWith("@")) { - const m = url.toString().split("@")[1].split("/")[0]; - if (methods.includes(m)) url = url.replace(`@${m}/`, "/"); - } - if (!basePath.endsWith("/")) basePath += "/"; - let [path, urlQuery] = url.replace(basePath, "").split("?"); - const queryParams = new URLSearchParams(urlQuery); - for (const [key, value] of Object.entries(query || {})) { - if (value == null) continue; - let serializedValue; - if (typeof value === "string") serializedValue = value; - else if (Array.isArray(value)) { - for (const val of value) queryParams.append(key, val); - continue; - } else serializedValue = JSON.stringify(value); - queryParams.set(key, serializedValue); - } - const pathParams = /* @__PURE__ */ new Map(); - if (params) if (Array.isArray(params)) { - const paramPaths = path.split("/").filter((p) => p.startsWith(":")); - for (const [index, key] of paramPaths.entries()) { - const value = params[index]; - pathParams.set(key, String(value)); - } - } else for (const [key, value] of Object.entries(params)) pathParams.set(`:${key}`, String(value)); - path = path.split("/").map((segment) => encodePathSegment(segment, pathParams)).join("/"); - path = path.replace(/^\/+/, ""); - let queryParamString = queryParams.toString(); - queryParamString = queryParamString.length > 0 ? `?${queryParamString}`.replace(/\+/g, "%20") : ""; - if (!basePath.startsWith("http")) return `${basePath}${path}${queryParamString}`; - return new URL(`${path}${queryParamString}`, basePath); -} -var betterFetch = async (url, options) => { - var _a, _b, _c, _d, _e, _f, _g, _h; - const { hooks, url: __url, options: opts } = await initializePlugins(url, options); - const fetch = getFetch(opts); - const controller = new AbortController(); - const signal = (_a = opts.signal) != null ? _a : controller.signal; - const _url = getURL2(__url, opts); - const headers = await getHeaders(opts); - const body = getBody$1(opts, headers); - const method = getMethod(__url, opts); - const context = __spreadProps(__spreadValues({}, opts), { - url: _url, - headers, - body, - method, - signal - }); - for (const onRequest of hooks.onRequest) if (onRequest) { - const res = await onRequest(context); - if (typeof res === "object" && res !== null) Object.assign(context, res); - } - if ("pipeTo" in context && typeof context.pipeTo === "function" || typeof ((_b = options == null ? void 0 : options.body) == null ? void 0 : _b.pipe) === "function") { - if (!("duplex" in context)) context.duplex = "half"; - } - const { clearTimeout: clearTimeout2 } = getTimeout(opts, controller); - let response = await fetch(context.url, context); - clearTimeout2(); - const responseContext = { - response, - request: context - }; - for (const onResponse of hooks.onResponse) if (onResponse) { - const r = await onResponse(__spreadProps(__spreadValues({}, responseContext), { response: ((_c = options == null ? void 0 : options.hookOptions) == null ? void 0 : _c.cloneResponse) ? response.clone() : response })); - if (r instanceof Response) response = r; - else if (typeof r === "object" && r !== null) response = r.response; - } - if (response.ok) { - if (!(context.method !== "HEAD")) return { - data: "", - error: null - }; - const responseType = detectResponseType(response); - const successContext = { - data: null, - response, - request: context - }; - if (responseType === "json" || responseType === "text") { - const text = await response.text(); - successContext.data = await ((_d = context.jsonParser) != null ? _d : jsonParse)(text); - } else successContext.data = await response[responseType](); - if (context == null ? void 0 : context.output) { - if (context.output && !context.disableValidation) successContext.data = await parseStandardSchema(context.output, successContext.data); - } - for (const onSuccess of hooks.onSuccess) if (onSuccess) await onSuccess(__spreadProps(__spreadValues({}, successContext), { response: ((_e = options == null ? void 0 : options.hookOptions) == null ? void 0 : _e.cloneResponse) ? response.clone() : response })); - if (options == null ? void 0 : options.throw) return successContext.data; - return { - data: successContext.data, - error: null - }; - } - const parser = (_f = options == null ? void 0 : options.jsonParser) != null ? _f : jsonParse; - const responseText = await response.text(); - const isJSONResponse = isJSONParsable(responseText); - const errorObject = isJSONResponse ? await parser(responseText) : null; - const errorContext = { - response, - responseText, - request: context, - error: __spreadProps(__spreadValues({}, errorObject), { - status: response.status, - statusText: response.statusText - }) - }; - for (const onError of hooks.onError) if (onError) await onError(__spreadProps(__spreadValues({}, errorContext), { response: ((_g = options == null ? void 0 : options.hookOptions) == null ? void 0 : _g.cloneResponse) ? response.clone() : response })); - if (options == null ? void 0 : options.retry) { - const retryStrategy = createRetryStrategy(options.retry); - const _retryAttempt = (_h = options.retryAttempt) != null ? _h : 0; - if (await retryStrategy.shouldAttemptRetry(_retryAttempt, response)) { - for (const onRetry of hooks.onRetry) if (onRetry) await onRetry(responseContext); - const delay = retryStrategy.getDelay(_retryAttempt); - await new Promise((resolve) => setTimeout(resolve, delay)); - return await betterFetch(url, __spreadProps(__spreadValues({}, options), { retryAttempt: _retryAttempt + 1 })); - } - } - if (options == null ? void 0 : options.throw) throw new BetterFetchError(response.status, response.statusText, isJSONResponse ? errorObject : responseText); - return { - data: null, - error: __spreadProps(__spreadValues({}, errorObject), { - status: response.status, - statusText: response.statusText - }) - }; -}; -//#endregion -//#region node_modules/@better-auth/core/dist/utils/string.mjs -function capitalizeFirstLetter(str) { - return str.charAt(0).toUpperCase() + str.slice(1); -} -var WORD_PATTERN = /[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu; -var APOSTROPHE_PATTERN = /['\u2019]/g; -function splitWords(input) { - return input.replace(APOSTROPHE_PATTERN, "").match(WORD_PATTERN) ?? []; -} -function toKebabCase(input) { - return splitWords(input).map((word) => word.toLowerCase()).join("-"); -} -//#endregion -//#region node_modules/zod/v4/core/core.js -var _a$1; -/** A special constant with type `never` */ -var NEVER = /*@__PURE__*/ Object.freeze({ status: "aborted" }); -function $constructor(name, initializer, params) { - function init(inst, def) { - if (!inst._zod) Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - if (inst._zod.traits.has(name)) return; - inst._zod.traits.add(name); - initializer(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) inst[k] = proto[k].bind(inst); - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent {} - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a = inst._zod).deferred ?? (_a.deferred = []); - for (const fn of inst._zod.deferred) fn(); - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) return true; - return inst?._zod?.traits?.has(name); - } }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -}; -(_a$1 = globalThis).__zod_globalConfig ?? (_a$1.__zod_globalConfig = {}); -var globalConfig = globalThis.__zod_globalConfig; -function config(newConfig) { - if (newConfig) Object.assign(globalConfig, newConfig); - return globalConfig; -} -//#endregion -//#region node_modules/zod/v4/core/util.js -function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") return value.toString(); - return value; -} -function cached(getter) { - return { get value() { - { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - } }; -} -function nullish(input) { - return input === null || input === void 0; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder(val, step) { - const ratio = val / step; - const roundedRatio = Math.round(ratio); - const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); - if (Math.abs(ratio - roundedRatio) < tolerance) return 0; - return ratio - roundedRatio; -} -var EVALUATING = /* @__PURE__*/ Symbol("evaluating"); -function defineLazy(object, key, getter) { - let value = void 0; - Object.defineProperty(object, key, { - get() { - if (value === EVALUATING) return; - if (value === void 0) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v) { - Object.defineProperty(object, key, { value: v }); - }, - configurable: true - }); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true - }); -} -function mergeDefs(...defs) { - const mergedDescriptors = {}; - for (const def of defs) { - const descriptors = Object.getOwnPropertyDescriptors(def); - Object.assign(mergedDescriptors, descriptors); - } - return Object.defineProperties({}, mergedDescriptors); -} -function esc(str) { - return JSON.stringify(str); -} -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); -} -var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {}; -function isObject$1(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -var allowsEval = /* @__PURE__*/ cached(() => { - if (globalConfig.jitless) return false; - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false; - try { - new Function(""); - return true; - } catch (_) { - return false; - } -}); -function isPlainObject(o) { - if (isObject$1(o) === false) return false; - const ctor = o.constructor; - if (ctor === void 0) return true; - if (typeof ctor !== "function") return true; - const prot = ctor.prototype; - if (isObject$1(prot) === false) return false; - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false; - return true; -} -function shallowClone(o) { - if (isPlainObject(o)) return { ...o }; - if (Array.isArray(o)) return [...o]; - if (o instanceof Map) return new Map(o); - if (o instanceof Set) return new Set(o); - return o; -} -var propertyKeyTypes = /* @__PURE__*/ new Set([ - "string", - "number", - "symbol" -]); -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -function clone(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) return {}; - if (typeof params === "string") return { error: () => params }; - if (params?.message !== void 0) { - if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") return { - ...params, - error: () => params.error - }; - return params; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; - }); -} -var NUMBER_FORMAT_RANGES = { - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-34028234663852886e22, 34028234663852886e22], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE] -}; -function pick(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements"); - return clone(schema, mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`); - if (!mask[key]) continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - })); -} -function omit(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements"); - return clone(schema, mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`); - if (!mask[key]) continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - })); -} -function extend(schema, shape) { - if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object"); - const checks = schema._zod.def.checks; - if (checks && checks.length > 0) { - const existingShape = schema._zod.def.shape; - for (const key in shape) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); - } - return clone(schema, mergeDefs(schema._zod.def, { get shape() { - const _shape = { - ...schema._zod.def.shape, - ...shape - }; - assignProp(this, "shape", _shape); - return _shape; - } })); -} -function safeExtend(schema, shape) { - if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object"); - return clone(schema, mergeDefs(schema._zod.def, { get shape() { - const _shape = { - ...schema._zod.def.shape, - ...shape - }; - assignProp(this, "shape", _shape); - return _shape; - } })); -} -function merge(a, b) { - if (a._zod.def.checks?.length) throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); - return clone(a, mergeDefs(a._zod.def, { - get shape() { - const _shape = { - ...a._zod.def.shape, - ...b._zod.def.shape - }; - assignProp(this, "shape", _shape); - return _shape; - }, - get catchall() { - return b._zod.def.catchall; - }, - checks: b._zod.def.checks ?? [] - })); -} -function partial(Class, schema, mask) { - const checks = schema._zod.def.checks; - if (checks && checks.length > 0) throw new Error(".partial() cannot be used on object schemas containing refinements"); - return clone(schema, mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) for (const key in mask) { - if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`); - if (!mask[key]) continue; - shape[key] = Class ? new Class({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - else for (const key in oldShape) shape[key] = Class ? new Class({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - })); -} -function required(Class, schema, mask) { - return clone(schema, mergeDefs(schema._zod.def, { get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) for (const key in mask) { - if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`); - if (!mask[key]) continue; - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - else for (const key in oldShape) shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key] - }); - assignProp(this, "shape", shape); - return shape; - } })); -} -function aborted(x, startIndex = 0) { - if (x.aborted === true) return true; - for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true; - return false; -} -function explicitlyAborted(x, startIndex = 0) { - if (x.aborted === true) return true; - for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue === false) return true; - return false; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a; - (_a = iss).path ?? (_a.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message) { - return typeof message === "string" ? message : message?.message; -} -function finalizeIssue(iss, ctx, config) { - const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input"; - const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message; - if (ctx?.reportInput) rest.input = _input; - return rest; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) return "array"; - if (typeof input === "string") return "string"; - return "unknown"; -} -function issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") return { - message: iss, - code: "custom", - input, - inst - }; - return { ...iss }; -} -//#endregion -//#region node_modules/zod/v4/core/errors.js -var initializer$1 = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false - }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false - }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false - }); -}; -var $ZodError = $constructor("$ZodError", initializer$1); -var $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error }); -function flattenError(error, mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error.issues) if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } else formErrors.push(mapper(sub)); - return { - formErrors, - fieldErrors - }; -} -function formatError(error, mapper = (issue) => issue.message) { - const fieldErrors = { _errors: [] }; - const processError = (error, path = []) => { - for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - else if (issue.code === "invalid_key") processError({ issues: issue.issues }, [...path, ...issue.path]); - else if (issue.code === "invalid_element") processError({ issues: issue.issues }, [...path, ...issue.path]); - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) fieldErrors._errors.push(mapper(issue)); - else { - let curr = fieldErrors; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - if (!(i === fullpath.length - 1)) curr[el] = curr[el] || { _errors: [] }; - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(error); - return fieldErrors; -} -/** Format a ZodError as a human-readable string in the following form. -* -* From -* -* ```ts -* ZodError { -* issues: [ -* { -* expected: 'string', -* code: 'invalid_type', -* path: [ 'username' ], -* message: 'Invalid input: expected string' -* }, -* { -* expected: 'number', -* code: 'invalid_type', -* path: [ 'favoriteNumbers', 1 ], -* message: 'Invalid input: expected number' -* } -* ]; -* } -* ``` -* -* to -* -* ``` -* username -* ✖ Expected number, received string at "username -* favoriteNumbers[0] -* ✖ Invalid input: expected number -* ``` -*/ -function toDotPath(_path) { - const segs = []; - const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg); - for (const seg of path) if (typeof seg === "number") segs.push(`[${seg}]`); - else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) segs.push("."); - segs.push(seg); - } - return segs.join(""); -} -function prettifyError(error) { - const lines = []; - const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); - for (const issue of issues) { - lines.push(`✖ ${issue.message}`); - if (issue.path?.length) lines.push(` → at ${toDotPath(issue.path)}`); - } - return lines.join("\n"); -} -//#endregion -//#region node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? { - ..._ctx, - async: false - } : { async: false }; - const result = schema._zod.run({ - value, - issues: [] - }, ctx); - if (result instanceof Promise) throw new $ZodAsyncError(); - if (result.issues.length) { - const e = new ((_params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; -}; -var parse$1 = /* @__PURE__*/ _parse($ZodRealError); -var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? { - ..._ctx, - async: true - } : { async: true }; - let result = schema._zod.run({ - value, - issues: [] - }, ctx); - if (result instanceof Promise) result = await result; - if (result.issues.length) { - const e = new ((params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; -}; -var parseAsync$1 = /* @__PURE__*/ _parseAsync($ZodRealError); -var _safeParse = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { - ..._ctx, - async: false - } : { async: false }; - const result = schema._zod.run({ - value, - issues: [] - }, ctx); - if (result instanceof Promise) throw new $ZodAsyncError(); - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { - success: true, - data: result.value - }; -}; -var safeParse$1 = /* @__PURE__*/ _safeParse($ZodRealError); -var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { - ..._ctx, - async: true - } : { async: true }; - let result = schema._zod.run({ - value, - issues: [] - }, ctx); - if (result instanceof Promise) result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { - success: true, - data: result.value - }; -}; -var safeParseAsync$1 = /* @__PURE__*/ _safeParseAsync($ZodRealError); -var _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { - ..._ctx, - direction: "backward" - } : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); -}; -var _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); -}; -var _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { - ..._ctx, - direction: "backward" - } : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); -}; -var _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); -}; -var _safeEncode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { - ..._ctx, - direction: "backward" - } : { direction: "backward" }; - return _safeParse(_Err)(schema, value, ctx); -}; -var _safeDecode = (_Err) => (schema, value, _ctx) => { - return _safeParse(_Err)(schema, value, _ctx); -}; -var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { - ..._ctx, - direction: "backward" - } : { direction: "backward" }; - return _safeParseAsync(_Err)(schema, value, ctx); -}; -var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { - return _safeParseAsync(_Err)(schema, value, _ctx); -}; -//#endregion -//#region node_modules/zod/v4/core/regexes.js -/** -* @deprecated CUID v1 is deprecated by its authors due to information leakage -* (timestamps embedded in the id). Use {@link cuid2} instead. -* See https://github.com/paralleldrive/cuid. -*/ -var cuid = /^[cC][0-9a-z]{6,}$/; -var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; -var xid = /^[0-9a-vA-V]{20}$/; -var ksuid = /^[A-Za-z0-9]{27}$/; -var nanoid = /^[a-zA-Z0-9_-]{21}$/; -/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ -var duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; -/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ -var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; -/** Returns a regex for validating an RFC 9562/4122 UUID. -* -* @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ -var uuid = (version) => { - if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); -}; -/** Practical email validation */ -var email$1 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; -var _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -function emoji() { - return new RegExp(_emoji$1, "u"); -} -var ipv4$1 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -var ipv6$1 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; -var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64$1 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; -var httpProtocol = /^https?$/; -var e164 = /^\+[1-9]\d{6,14}$/; -var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -var date$1 = /*@__PURE__*/ new RegExp(`^${dateSource}$`); -function timeSource(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; -} -function time$1(args) { - return new RegExp(`^${timeSource(args)}$`); -} -function datetime$1(args) { - const time = timeSource({ precision: args.precision }); - const opts = ["Z"]; - if (args.local) opts.push(""); - if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time}(?:${opts.join("|")})`; - return new RegExp(`^${dateSource}T(?:${timeRegex})$`); -} -var string$1 = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); -}; -var integer = /^-?\d+$/; -var number$1 = /^-?\d+(?:\.\d+)?$/; -var boolean$1 = /^(?:true|false)$/i; -var _null$2 = /^null$/i; -var lowercase = /^[^A-Z]*$/; -var uppercase = /^[^a-z]*$/; -//#endregion -//#region node_modules/zod/v4/core/checks.js -var $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { - var _a; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a = inst._zod).onattach ?? (_a.onattach = []); -}); -var numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date" -}; -var $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) if (def.inclusive) bag.maximum = def.value; - else bag.exclusiveMaximum = def.value; - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return; - payload.issues.push({ - origin, - code: "too_big", - maximum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) if (def.inclusive) bag.minimum = def.value; - else bag.exclusiveMinimum = def.value; - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return; - payload.issues.push({ - origin, - code: "too_small", - minimum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckMultipleOf = /*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - var _a; - (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); - }); - inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return; - payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) bag.pattern = integer; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (isInt) { - if (!Number.isInteger(input)) { - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst - }); - return; - } - if (!Number.isSafeInteger(input)) { - if (input > 0) payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort - }); - else payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort - }); - return; - } - } - if (input < minimum) payload.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort - }); - if (input > maximum) payload.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst) => { - const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input.length <= def.maximum) return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst) => { - const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input.length >= def.minimum) return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length === def.length) return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...tooBig ? { - code: "too_big", - maximum: def.length - } : { - code: "too_small", - minimum: def.length - }, - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...def.pattern ? { pattern: def.pattern.toString() } : {}, - inst, - continue: !def.abort - }); - }); - else (_b = inst._zod).check ?? (_b.check = () => {}); -}); -var $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); -}); -var $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); -}); -var $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; -}); -//#endregion -//#region node_modules/zod/v4/core/doc.js -var Doc = class { - constructor(args = []) { - this.content = []; - this.indent = 0; - if (this) this.args = args; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; - } - write(arg) { - if (typeof arg === "function") { - arg(this, { execution: "sync" }); - arg(this, { execution: "async" }); - return; - } - const lines = arg.split("\n").filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); - for (const line of dedented) this.content.push(line); - } - compile() { - const F = Function; - const args = this?.args; - const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); - } -}; -//#endregion -//#region node_modules/zod/v4/core/versions.js -var version = { - major: 4, - minor: 4, - patch: 3 -}; -//#endregion -//#region node_modules/zod/v4/core/schemas.js -var $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { - var _a; - inst ?? (inst = {}); - inst._zod.def = def; - inst._zod.bag = inst._zod.bag || {}; - inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst); - for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst); - if (checks.length === 0) { - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } else { - const runChecks = (payload, checks, ctx) => { - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks) { - if (ch._zod.def.when) { - if (explicitlyAborted(payload)) continue; - if (!ch._zod.def.when(payload)) continue; - } else if (isAborted) continue; - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError(); - if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - if (payload.issues.length === currLen) return; - if (!isAborted) isAborted = aborted(payload, currLen); - }); - else { - if (payload.issues.length === currLen) continue; - if (!isAborted) isAborted = aborted(payload, currLen); - } - } - if (asyncResult) return asyncResult.then(() => { - return payload; - }); - return payload; - }; - const handleCanaryResult = (canary, payload, ctx) => { - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - const checkResult = runChecks(payload, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) throw new $ZodAsyncError(); - return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); - } - return inst._zod.parse(checkResult, ctx); - }; - inst._zod.run = (payload, ctx) => { - if (ctx.skipChecks) return inst._zod.parse(payload, ctx); - if (ctx.direction === "backward") { - const canary = inst._zod.parse({ - value: payload.value, - issues: [] - }, { - ...ctx, - skipChecks: true - }); - if (canary instanceof Promise) return canary.then((canary) => { - return handleCanaryResult(canary, payload, ctx); - }); - return handleCanaryResult(canary, payload, ctx); - } - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) throw new $ZodAsyncError(); - return result.then((result) => runChecks(result, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } - defineLazy(inst, "~standard", () => ({ - validate: (value) => { - try { - const r = safeParse$1(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; - } catch (_) { - return safeParseAsync$1(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); - } - }, - vendor: "zod", - version: 1 - })); -}); -var $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) try { - payload.value = String(payload.value); - } catch (_) {} - if (typeof payload.value === "string") return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst - }); - return payload; - }; -}); -var $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); -}); -var $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); -}); -var $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const v = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8 - }[def.version]; - if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); - } else def.pattern ?? (def.pattern = uuid()); - $ZodStringFormat.init(inst, def); -}); -var $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email$1); - $ZodStringFormat.init(inst, def); -}); -var $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - const trimmed = payload.value.trim(); - if (!def.normalize && def.protocol?.source === httpProtocol.source) { - if (!/^https?:\/\//i.test(trimmed)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort - }); - return; - } - } - const url = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url.hostname)) payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } - if (def.normalize) payload.value = url.href; - else payload.value = trimmed; - return; - } catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; -}); -var $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); -}); -var $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); - $ZodStringFormat.init(inst, def); -}); -/** -* @deprecated CUID v1 is deprecated by its authors due to information leakage -* (timestamps embedded in the id). Use {@link $ZodCUID2} instead. -* See https://github.com/paralleldrive/cuid. -*/ -var $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); -}); -var $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); -}); -var $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); -}); -var $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); -}); -var $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); -}); -var $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime$1(def)); - $ZodStringFormat.init(inst, def); -}); -var $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = date$1); - $ZodStringFormat.init(inst, def); -}); -var $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = time$1(def)); - $ZodStringFormat.init(inst, def); -}); -var $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration$1); - $ZodStringFormat.init(inst, def); -}); -var $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4$1); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; -}); -var $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = ipv6$1); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; - inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; -}); -var $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); -}); -var $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6); - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) throw new Error(); - const [address, prefix] = parts; - if (!prefix) throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) throw new Error(); - if (prefixNum < 0 || prefixNum > 128) throw new Error(); - new URL(`http://[${address}]`); - } catch { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; -}); -function isValidBase64(data) { - if (data === "") return true; - if (/\s/.test(data)) return false; - if (data.length % 4 !== 0) return false; - try { - atob(data); - return true; - } catch { - return false; - } -} -var $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64$1); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -function isValidBase64URL(data) { - if (!base64url.test(data)) return false; - const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); - return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")); -} -var $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); -}); -function isValidJWT(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) return false; - const [header] = tokensParts; - if (!header) return false; - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false; - if (!parsedHeader.alg) return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; - return true; - } catch { - return false; - } -} -var $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT(payload.value, def.alg)) return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number$1; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) try { - payload.value = Number(payload.value); - } catch (_) {} - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload; - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...received ? { received } : {} - }); - return payload; - }; -}); -var $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); -}); -var $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = boolean$1; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) try { - payload.value = Boolean(payload.value); - } catch (_) {} - const input = payload.value; - if (typeof input === "boolean") return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst - }); - return payload; - }; -}); -var $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null$2; - inst._zod.values = /* @__PURE__ */ new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst - }); - return payload; - }; -}); -var $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -var $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -var $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst - }); - return payload; - }; -}); -function handleArrayResult(result, final, index) { - if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues)); - final.value[index] = result.value; -} -var $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst - }); - return payload; - } - payload.value = Array(input.length); - const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [] - }, ctx); - if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i))); - else handleArrayResult(result, payload, i); - } - if (proms.length) return Promise.all(proms).then(() => payload); - return payload; - }; -}); -function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { - const isPresent = key in input; - if (result.issues.length) { - if (isOptionalIn && isOptionalOut && !isPresent) return; - final.issues.push(...prefixIssues(key, result.issues)); - } - if (!isPresent && !isOptionalIn) { - if (!result.issues.length) final.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: void 0, - path: [key] - }); - return; - } - if (result.value === void 0) { - if (isPresent) final.value[key] = void 0; - } else final.value[key] = result.value; -} -function normalizeDef(def) { - const keys = Object.keys(def.shape); - for (const k of keys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${k}": expected a Zod schema`); - const okeys = optionalKeys(def.shape); - return { - ...def, - keys, - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys) - }; -} -function handleCatchall(proms, input, payload, ctx, def, inst) { - const unrecognized = []; - const keySet = def.keySet; - const _catchall = def.catchall._zod; - const t = _catchall.def.type; - const isOptionalIn = _catchall.optin === "optional"; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (key === "__proto__") continue; - if (keySet.has(key)) continue; - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ - value: input[key], - issues: [] - }, ctx); - if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut))); - else handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); - } - if (unrecognized.length) payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst - }); - if (!proms.length) return payload; - return Promise.all(proms).then(() => { - return payload; - }); -} -var $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { - $ZodType.init(inst, def); - if (!Object.getOwnPropertyDescriptor(def, "shape")?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { value: newSh }); - return newSh; - } }); - } - const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); - for (const v of field.values) propValues[key].add(v); - } - } - return propValues; - }); - const isObject = isObject$1; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst - }); - return payload; - } - payload.value = {}; - const proms = []; - const shape = value.shape; - for (const key of value.keys) { - const el = shape[key]; - const isOptionalIn = el._zod.optin === "optional"; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ - value: input[key], - issues: [] - }, ctx); - if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut))); - else handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); - } - if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload; - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); - }; -}); -var $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = cached(() => normalizeDef(def)); - const generateFastpass = (shape) => { - const doc = new Doc([ - "shape", - "payload", - "ctx" - ]); - const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; - doc.write(`const input = payload.value;`); - const ids = Object.create(null); - let counter = 0; - for (const key of normalized.keys) ids[key] = `key_${counter++}`; - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { - const id = ids[key]; - const k = esc(key); - const schema = shape[key]; - const isOptionalIn = schema?._zod?.optin === "optional"; - const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); - if (isOptionalIn && isOptionalOut) doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); - } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); - else if (!isOptionalIn) doc.write(` - const ${id}_present = ${k} in input; - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); - } - if (!${id}_present && !${id}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${k}] - }); - } - - if (${id}_present) { - if (${id}.value === undefined) { - newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } - } - - `); - else doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); - }; - let fastpass; - const isObject = isObject$1; - const jit = !globalConfig.jitless; - const fastEnabled = jit && allowsEval.value; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst - }); - return payload; - } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - if (!fastpass) fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - if (!catchall) return payload; - return handleCatchall([], input, payload, ctx, value, inst); - } - return superParse(payload, ctx); - }; -}); -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) if (result.issues.length === 0) { - final.value = result.value; - return final; - } - const nonaborted = results.filter((r) => !aborted(r)); - if (nonaborted.length === 1) { - final.value = nonaborted[0].value; - return nonaborted[0]; - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - }); - return final; -} -var $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); - }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - }); - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) return first(payload, ctx); - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [] - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } else { - if (result.issues.length === 0) return result; - results.push(result); - } - } - if (!async) return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleUnionResults(results, payload, inst, ctx); - }); - }; -}); -var $ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("$ZodDiscriminatedUnion", (inst, def) => { - def.inclusive = false; - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { - const propValues = {}; - for (const option of def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set(); - for (const val of v) propValues[k].add(val); - } - } - return propValues; - }); - const disc = cached(() => { - const opts = def.options; - const map = /* @__PURE__ */ new Map(); - for (const o of opts) { - const values = o._zod.propValues?.[def.discriminator]; - if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values) { - if (map.has(v)) throw new Error(`Duplicate discriminator value "${String(v)}"`); - map.set(v, o); - } - } - return map; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject$1(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) return opt._zod.run(payload, ctx); - if (def.unionFallback || ctx.direction === "backward") return _super(payload, ctx); - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, - path: [def.discriminator], - inst - }); - return payload; - }; -}); -var $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ - value: input, - issues: [] - }, ctx); - const right = def.right._zod.run({ - value: input, - issues: [] - }, ctx); - if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left, right]) => { - return handleIntersectionResults(payload, left, right); - }); - return handleIntersectionResults(payload, left, right); - }; -}); -function mergeValues(a, b) { - if (a === b) return { - valid: true, - data: a - }; - if (a instanceof Date && b instanceof Date && +a === +b) return { - valid: true, - data: a - }; - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { - ...a, - ...b - }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath] - }; - newObj[key] = sharedValue.data; - } - return { - valid: true, - data: newObj - }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) return { - valid: false, - mergeErrorPath: [] - }; - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) return { - valid: false, - mergeErrorPath: [index, ...sharedValue.mergeErrorPath] - }; - newArray.push(sharedValue.data); - } - return { - valid: true, - data: newArray - }; - } - return { - valid: false, - mergeErrorPath: [] - }; -} -function handleIntersectionResults(result, left, right) { - const unrecKeys = /* @__PURE__ */ new Map(); - let unrecIssue; - for (const iss of left.issues) if (iss.code === "unrecognized_keys") { - unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } - } else result.issues.push(iss); - for (const iss of right.issues) if (iss.code === "unrecognized_keys") for (const k of iss.keys) { - if (!unrecKeys.has(k)) unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - else result.issues.push(iss); - const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) result.issues.push({ - ...unrecIssue, - keys: bothKeys - }); - if (aborted(result)) return result; - const merged = mergeValues(left.value, right.value); - if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); - result.value = merged.data; - return result; -} -var $ZodTuple = /*@__PURE__*/ $constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type" - }); - return payload; - } - payload.value = []; - const proms = []; - const optinStart = getTupleOptStart(items, "optin"); - const optoutStart = getTupleOptStart(items, "optout"); - if (!def.rest) { - if (input.length < optinStart) { - payload.issues.push({ - code: "too_small", - minimum: optinStart, - inclusive: true, - input, - inst, - origin: "array" - }); - return payload; - } - if (input.length > items.length) payload.issues.push({ - code: "too_big", - maximum: items.length, - inclusive: true, - input, - inst, - origin: "array" - }); - } - const itemResults = new Array(items.length); - for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ - value: input[i], - issues: [] - }, ctx); - if (r instanceof Promise) proms.push(r.then((rr) => { - itemResults[i] = rr; - })); - else itemResults[i] = r; - } - if (def.rest) { - let i = items.length - 1; - const rest = input.slice(items.length); - for (const el of rest) { - i++; - const result = def.rest._zod.run({ - value: el, - issues: [] - }, ctx); - if (result instanceof Promise) proms.push(result.then((r) => handleTupleResult(r, payload, i))); - else handleTupleResult(result, payload, i); - } - } - if (proms.length) return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); - return handleTupleResults(itemResults, payload, items, input, optoutStart); - }; -}); -function getTupleOptStart(items, key) { - for (let i = items.length - 1; i >= 0; i--) if (items[i]._zod[key] !== "optional") return i + 1; - return 0; -} -function handleTupleResult(result, final, index) { - if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues)); - final.value[index] = result.value; -} -function handleTupleResults(itemResults, final, items, input, optoutStart) { - for (let i = 0; i < items.length; i++) { - const r = itemResults[i]; - const isPresent = i < input.length; - if (r.issues.length) { - if (!isPresent && i >= optoutStart) { - final.value.length = i; - break; - } - final.issues.push(...prefixIssues(i, r.issues)); - } - final.value[i] = r.value; - } - for (let i = final.value.length - 1; i >= input.length; i--) if (items[i]._zod.optout === "optional" && final.value[i] === void 0) final.value.length = i; - else break; - return final; -} -var $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst - }); - return payload; - } - const proms = []; - const values = def.keyType._zod.values; - if (values) { - payload.value = {}; - const recordKeys = /* @__PURE__ */ new Set(); - for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - recordKeys.add(typeof key === "number" ? key.toString() : key); - const keyResult = def.keyType._zod.run({ - value: key, - issues: [] - }, ctx); - if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); - if (keyResult.issues.length) { - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - input: key, - path: [key], - inst - }); - continue; - } - const outKey = keyResult.value; - const result = def.valueType._zod.run({ - value: input[key], - issues: [] - }, ctx); - if (result instanceof Promise) proms.push(result.then((result) => { - if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); - payload.value[outKey] = result.value; - })); - else { - if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); - payload.value[outKey] = result.value; - } - } - let unrecognized; - for (const key in input) if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - if (unrecognized && unrecognized.length > 0) payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized - }); - } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue; - let keyResult = def.keyType._zod.run({ - value: key, - issues: [] - }, ctx); - if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); - if (typeof key === "string" && number$1.test(key) && keyResult.issues.length) { - const retryResult = def.keyType._zod.run({ - value: Number(key), - issues: [] - }, ctx); - if (retryResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); - if (retryResult.issues.length === 0) keyResult = retryResult; - } - if (keyResult.issues.length) { - if (def.mode === "loose") payload.value[key] = input[key]; - else payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - input: key, - path: [key], - inst - }); - continue; - } - const result = def.valueType._zod.run({ - value: input[key], - issues: [] - }, ctx); - if (result instanceof Promise) proms.push(result.then((result) => { - if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); - payload.value[keyResult.value] = result.value; - })); - else { - if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); - payload.value[keyResult.value] = result.value; - } - } - } - if (proms.length) return Promise.all(proms).then(() => payload); - return payload; - }; -}); -var $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = getEnumValues(def.entries); - const valuesSet = new Set(values); - inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) return payload; - payload.issues.push({ - code: "invalid_value", - values, - input, - inst - }); - return payload; - }; -}); -var $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - if (def.values.length === 0) throw new Error("Cannot create literal schema with no valid values"); - const values = new Set(def.values); - inst._zod.values = values; - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values.has(input)) return payload; - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst - }); - return payload; - }; -}); -var $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name); - const _out = def.transform(payload.value, payload); - if (ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => { - payload.value = output; - payload.fallback = true; - return payload; - }); - if (_out instanceof Promise) throw new $ZodAsyncError(); - payload.value = _out; - payload.fallback = true; - return payload; - }; -}); -function handleOptionalResult(result, input) { - if (input === void 0 && (result.issues.length || result.fallback)) return { - issues: [], - value: void 0 - }; - return result; -} -var $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; - }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const input = payload.value; - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, input)); - return handleOptionalResult(result, input); - } - if (payload.value === void 0) return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -var $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { - $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); - inst._zod.parse = (payload, ctx) => { - return def.innerType._zod.run(payload, ctx); - }; -}); -var $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; - }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === null) return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -var $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); - if (payload.value === void 0) { - payload.value = def.defaultValue; - /** - * $ZodDefault returns the default value immediately in forward direction. - * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ - return payload; - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def)); - return handleDefaultResult(result, def); - }; -}); -function handleDefaultResult(payload, def) { - if (payload.value === void 0) payload.value = def.defaultValue; - return payload; -} -var $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); - if (payload.value === void 0) payload.value = def.defaultValue; - return def.innerType._zod.run(payload, ctx); - }; -}); -var $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) return result.then((result) => handleNonOptionalResult(result, inst)); - return handleNonOptionalResult(result, inst); - }; -}); -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === void 0) payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst - }); - return payload; -} -var $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) return result.then((result) => { - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }); - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }; -}); -var $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) return right.then((right) => handlePipeResult(right, def.in, ctx)); - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) return left.then((left) => handlePipeResult(left, def.out, ctx)); - return handlePipeResult(left, def.out, ctx); - }; -}); -function handlePipeResult(left, next, ctx) { - if (left.issues.length) { - left.aborted = true; - return left; - } - return next._zod.run({ - value: left.value, - issues: left.issues, - fallback: left.fallback - }, ctx); -} -var $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { - $ZodPipe.init(inst, def); -}); -var $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) return result.then(handleReadonlyResult); - return handleReadonlyResult(result); - }; -}); -function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); - return payload; -} -var $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) return r.then((r) => handleRefineResult(r, payload, input, inst)); - handleRefineResult(r, payload, input, inst); - }; -}); -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, - path: [...inst._zod.def.path ?? []], - continue: !inst._zod.def.abort - }; - if (inst._zod.def.params) _iss.params = inst._zod.def.params; - payload.issues.push(issue(_iss)); - } -} -//#endregion -//#region node_modules/zod/v4/core/registries.js -var _a; -var $ZodRegistry = class { - constructor() { - this._map = /* @__PURE__ */ new WeakMap(); - this._idmap = /* @__PURE__ */ new Map(); - } - add(schema, ..._meta) { - const meta = _meta[0]; - this._map.set(schema, meta); - if (meta && typeof meta === "object" && "id" in meta) this._idmap.set(meta.id, schema); - return this; - } - clear() { - this._map = /* @__PURE__ */ new WeakMap(); - this._idmap = /* @__PURE__ */ new Map(); - return this; - } - remove(schema) { - const meta = this._map.get(schema); - if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id); - this._map.delete(schema); - return this; - } - get(schema) { - const p = schema._zod.parent; - if (p) { - const pm = { ...this.get(p) ?? {} }; - delete pm.id; - const f = { - ...pm, - ...this._map.get(schema) - }; - return Object.keys(f).length ? f : void 0; - } - return this._map.get(schema); - } - has(schema) { - return this._map.has(schema); - } -}; -function registry() { - return new $ZodRegistry(); -} -(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry()); -var globalRegistry = globalThis.__zod_globalRegistry; -//#endregion -//#region node_modules/zod/v4/core/api.js -// @__NO_SIDE_EFFECTS__ -function _string(Class, params) { - return new Class({ - type: "string", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedString(Class, params) { - return new Class({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _email(Class, params) { - return new Class({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _guid(Class, params) { - return new Class({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuid(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv4(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv6(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv7(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _url(Class, params) { - return new Class({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _emoji(Class, params) { - return new Class({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _nanoid(Class, params) { - return new Class({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -/** -* @deprecated CUID v1 is deprecated by its authors due to information leakage -* (timestamps embedded in the id). Use {@link _cuid2} instead. -* See https://github.com/paralleldrive/cuid. -*/ -// @__NO_SIDE_EFFECTS__ -function _cuid(Class, params) { - return new Class({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid2(Class, params) { - return new Class({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ulid(Class, params) { - return new Class({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _xid(Class, params) { - return new Class({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ksuid(Class, params) { - return new Class({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv4(Class, params) { - return new Class({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv6(Class, params) { - return new Class({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv4(Class, params) { - return new Class({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv6(Class, params) { - return new Class({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64(Class, params) { - return new Class({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64url(Class, params) { - return new Class({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _e164(Class, params) { - return new Class({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _jwt(Class, params) { - return new Class({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDateTime(Class, params) { - return new Class({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDate(Class, params) { - return new Class({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoTime(Class, params) { - return new Class({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDuration(Class, params) { - return new Class({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _number(Class, params) { - return new Class({ - type: "number", - checks: [], - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedNumber(Class, params) { - return new Class({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _int(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _boolean(Class, params) { - return new Class({ - type: "boolean", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBoolean(Class, params) { - return new Class({ - type: "boolean", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _null$1(Class, params) { - return new Class({ - type: "null", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _any(Class) { - return new Class({ type: "any" }); -} -// @__NO_SIDE_EFFECTS__ -function _unknown(Class) { - return new Class({ type: "unknown" }); -} -// @__NO_SIDE_EFFECTS__ -function _never(Class, params) { - return new Class({ - type: "never", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false - }); -} -// @__NO_SIDE_EFFECTS__ -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true - }); -} -// @__NO_SIDE_EFFECTS__ -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false - }); -} -// @__NO_SIDE_EFFECTS__ -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true - }); -} -// @__NO_SIDE_EFFECTS__ -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxLength(maximum, params) { - return new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum - }); -} -// @__NO_SIDE_EFFECTS__ -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum - }); -} -// @__NO_SIDE_EFFECTS__ -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length - }); -} -// @__NO_SIDE_EFFECTS__ -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern - }); -} -// @__NO_SIDE_EFFECTS__ -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes - }); -} -// @__NO_SIDE_EFFECTS__ -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix - }); -} -// @__NO_SIDE_EFFECTS__ -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix - }); -} -// @__NO_SIDE_EFFECTS__ -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx - }); -} -// @__NO_SIDE_EFFECTS__ -function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); -} -// @__NO_SIDE_EFFECTS__ -function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); -} -// @__NO_SIDE_EFFECTS__ -function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); -} -// @__NO_SIDE_EFFECTS__ -function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); -} -// @__NO_SIDE_EFFECTS__ -function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); -} -// @__NO_SIDE_EFFECTS__ -function _array(Class, element, params) { - return new Class({ - type: "array", - element, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _custom(Class, fn, _params) { - const norm = normalizeParams(_params); - norm.abort ?? (norm.abort = true); - return new Class({ - type: "custom", - check: "custom", - fn, - ...norm - }); -} -// @__NO_SIDE_EFFECTS__ -function _refine(Class, fn, _params) { - return new Class({ - type: "custom", - check: "custom", - fn, - ...normalizeParams(_params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _superRefine(fn, params) { - const ch = /* @__PURE__ */ _check((payload) => { - payload.addIssue = (issue$2) => { - if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, ch._zod.def)); - else { - const _issue = issue$2; - if (_issue.fatal) _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); - payload.issues.push(issue(_issue)); - } - }; - return fn(payload.value, payload); - }, params); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _check(fn, params) { - const ch = new $ZodCheck({ - check: "custom", - ...normalizeParams(params) - }); - ch._zod.check = fn; - return ch; -} -//#endregion -//#region node_modules/zod/v4/core/to-json-schema.js -function initializeContext(params) { - let target = params?.target ?? "draft-2020-12"; - if (target === "draft-4") target = "draft-04"; - if (target === "draft-7") target = "draft-07"; - return { - processors: params.processors ?? {}, - metadataRegistry: params?.metadata ?? globalRegistry, - target, - unrepresentable: params?.unrepresentable ?? "throw", - override: params?.override ?? (() => {}), - io: params?.io ?? "output", - counter: 0, - seen: /* @__PURE__ */ new Map(), - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - external: params?.external ?? void 0 - }; -} -function process$1(schema, ctx, _params = { - path: [], - schemaPath: [] -}) { - var _a; - const def = schema._zod.def; - const seen = ctx.seen.get(schema); - if (seen) { - seen.count++; - if (_params.schemaPath.includes(schema)) seen.cycle = _params.path; - return seen.schema; - } - const result = { - schema: {}, - count: 1, - cycle: void 0, - path: _params.path - }; - ctx.seen.set(schema, result); - const overrideSchema = schema._zod.toJSONSchema?.(); - if (overrideSchema) result.schema = overrideSchema; - else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema], - path: _params.path - }; - if (schema._zod.processJSONSchema) schema._zod.processJSONSchema(ctx, result.schema, params); - else { - const _json = result.schema; - const processor = ctx.processors[def.type]; - if (!processor) throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); - processor(schema, ctx, _json, params); - } - const parent = schema._zod.parent; - if (parent) { - if (!result.ref) result.ref = parent; - process$1(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } - } - const meta = ctx.metadataRegistry.get(schema); - if (meta) Object.assign(result.schema, meta); - if (ctx.io === "input" && isTransforming(schema)) { - delete result.schema.examples; - delete result.schema.default; - } - if (ctx.io === "input" && "_prefault" in result.schema) (_a = result.schema).default ?? (_a.default = result.schema._prefault); - delete result.schema._prefault; - return ctx.seen.get(schema).schema; -} -function extractDefs(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); - const idToSchema = /* @__PURE__ */ new Map(); - for (const entry of ctx.seen.entries()) { - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - const existing = idToSchema.get(id); - if (existing && existing !== entry[0]) throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); - idToSchema.set(id, entry[0]); - } - } - const makeURI = (entry) => { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; - const uriGenerator = ctx.external.uri ?? ((id) => id); - if (externalId) return { ref: uriGenerator(externalId) }; - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; - return { - defId: id, - ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` - }; - } - if (entry[1] === root) return { ref: "#" }; - const defUriPrefix = `#/${defsSegment}/`; - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { - defId, - ref: defUriPrefix + defId - }; - }; - const extractToDef = (entry) => { - if (entry[1].schema.$ref) return; - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - if (defId) seen.defId = defId; - const schema = seen.schema; - for (const key in schema) delete schema[key]; - schema.$ref = ref; - }; - if (ctx.cycles === "throw") for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ - -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); - } - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (schema === entry[0]) { - extractToDef(entry); - continue; - } - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - if (ctx.metadataRegistry.get(entry[0])?.id) { - extractToDef(entry); - continue; - } - if (seen.cycle) { - extractToDef(entry); - continue; - } - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - continue; - } - } - } -} -function finalize(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - if (seen.ref === null) return; - const schema = seen.def ?? seen.schema; - const _cached = { ...schema }; - const ref = seen.ref; - seen.ref = null; - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); - const refSchema = refSeen.schema; - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - schema.allOf = schema.allOf ?? []; - schema.allOf.push(refSchema); - } else Object.assign(schema, refSchema); - Object.assign(schema, _cached); - if (zodSchema._zod.parent === ref) for (const key in schema) { - if (key === "$ref" || key === "allOf") continue; - if (!(key in _cached)) delete schema[key]; - } - if (refSchema.$ref && refSeen.def) for (const key in schema) { - if (key === "$ref" || key === "allOf") continue; - if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) delete schema[key]; - } - } - const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { - flattenRef(parent); - const parentSeen = ctx.seen.get(parent); - if (parentSeen?.schema.$ref) { - schema.$ref = parentSeen.schema.$ref; - if (parentSeen.def) for (const key in schema) { - if (key === "$ref" || key === "allOf") continue; - if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) delete schema[key]; - } - } - } - ctx.override({ - zodSchema, - jsonSchema: schema, - path: seen.path ?? [] - }); - }; - for (const entry of [...ctx.seen.entries()].reverse()) flattenRef(entry[0]); - const result = {}; - if (ctx.target === "draft-2020-12") result.$schema = "https://json-schema.org/draft/2020-12/schema"; - else if (ctx.target === "draft-07") result.$schema = "http://json-schema.org/draft-07/schema#"; - else if (ctx.target === "draft-04") result.$schema = "http://json-schema.org/draft-04/schema#"; - else if (ctx.target === "openapi-3.0") {} - if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema)?.id; - if (!id) throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); - } - Object.assign(result, root.def ?? root.schema); - const rootMetaId = ctx.metadataRegistry.get(schema)?.id; - if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; - const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) delete seen.def.id; - defs[seen.defId] = seen.def; - } - } - if (ctx.external) {} else if (Object.keys(defs).length > 0) if (ctx.target === "draft-2020-12") result.$defs = defs; - else result.definitions = defs; - try { - const finalized = JSON.parse(JSON.stringify(result)); - Object.defineProperty(finalized, "~standard", { - value: { - ...schema["~standard"], - jsonSchema: { - input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), - output: createStandardJSONSchemaMethod(schema, "output", ctx.processors) - } - }, - enumerable: false, - writable: false - }); - return finalized; - } catch (_err) { - throw new Error("Error converting schema to JSON."); - } -} -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; - if (ctx.seen.has(_schema)) return false; - ctx.seen.add(_schema); - const def = _schema._zod.def; - if (def.type === "transform") return true; - if (def.type === "array") return isTransforming(def.element, ctx); - if (def.type === "set") return isTransforming(def.valueType, ctx); - if (def.type === "lazy") return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") return isTransforming(def.innerType, ctx); - if (def.type === "intersection") return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - if (def.type === "record" || def.type === "map") return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - if (def.type === "pipe") { - if (_schema._zod.traits.has("$ZodCodec")) return true; - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - if (def.type === "object") { - for (const key in def.shape) if (isTransforming(def.shape[key], ctx)) return true; - return false; - } - if (def.type === "union") { - for (const option of def.options) if (isTransforming(option, ctx)) return true; - return false; - } - if (def.type === "tuple") { - for (const item of def.items) if (isTransforming(item, ctx)) return true; - if (def.rest && isTransforming(def.rest, ctx)) return true; - return false; - } - return false; -} -/** -* Creates a toJSONSchema method for a schema instance. -* This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. -*/ -var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { - const ctx = initializeContext({ - ...params, - processors - }); - process$1(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; -var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ - ...libraryOptions ?? {}, - target, - io, - processors - }); - process$1(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; -//#endregion -//#region node_modules/zod/v4/core/json-schema-processors.js -var formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "" -}; -var stringProcessor = (schema, ctx, _json, _params) => { - const json = _json; - json.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; - if (typeof minimum === "number") json.minLength = minimum; - if (typeof maximum === "number") json.maxLength = maximum; - if (format) { - json.format = formatMap[format] ?? format; - if (json.format === "") delete json.format; - if (format === "time") delete json.format; - } - if (contentEncoding) json.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) json.pattern = regexes[0].source; - else if (regexes.length > 1) json.allOf = [...regexes.map((regex) => ({ - ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, - pattern: regex.source - }))]; - } -}; -var numberProcessor = (schema, ctx, _json, _params) => { - const json = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) json.type = "integer"; - else json.type = "number"; - const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); - const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); - const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; - if (exMin) if (legacy) { - json.minimum = exclusiveMinimum; - json.exclusiveMinimum = true; - } else json.exclusiveMinimum = exclusiveMinimum; - else if (typeof minimum === "number") json.minimum = minimum; - if (exMax) if (legacy) { - json.maximum = exclusiveMaximum; - json.exclusiveMaximum = true; - } else json.exclusiveMaximum = exclusiveMaximum; - else if (typeof maximum === "number") json.maximum = maximum; - if (typeof multipleOf === "number") json.multipleOf = multipleOf; -}; -var booleanProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -var bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema"); -}; -var symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema"); -}; -var nullProcessor = (_schema, ctx, json, _params) => { - if (ctx.target === "openapi-3.0") { - json.type = "string"; - json.nullable = true; - json.enum = [null]; - } else json.type = "null"; -}; -var undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema"); -}; -var voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema"); -}; -var neverProcessor = (_schema, _ctx, json, _params) => { - json.not = {}; -}; -var anyProcessor = (_schema, _ctx, _json, _params) => {}; -var unknownProcessor = (_schema, _ctx, _json, _params) => {}; -var dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema"); -}; -var enumProcessor = (schema, _ctx, json, _params) => { - const def = schema._zod.def; - const values = getEnumValues(def.entries); - if (values.every((v) => typeof v === "number")) json.type = "number"; - if (values.every((v) => typeof v === "string")) json.type = "string"; - json.enum = values; -}; -var literalProcessor = (schema, ctx, json, _params) => { - const def = schema._zod.def; - const vals = []; - for (const val of def.values) if (val === void 0) { - if (ctx.unrepresentable === "throw") throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else if (typeof val === "bigint") if (ctx.unrepresentable === "throw") throw new Error("BigInt literals cannot be represented in JSON Schema"); - else vals.push(Number(val)); - else vals.push(val); - if (vals.length === 0) {} else if (vals.length === 1) { - const val = vals[0]; - json.type = val === null ? "null" : typeof val; - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") json.enum = [val]; - else json.const = val; - } else { - if (vals.every((v) => typeof v === "number")) json.type = "number"; - if (vals.every((v) => typeof v === "string")) json.type = "string"; - if (vals.every((v) => typeof v === "boolean")) json.type = "boolean"; - if (vals.every((v) => v === null)) json.type = "null"; - json.enum = vals; - } -}; -var nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema"); -}; -var templateLiteralProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const pattern = schema._zod.pattern; - if (!pattern) throw new Error("Pattern not found in template literal"); - _json.type = "string"; - _json.pattern = pattern.source; -}; -var fileProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const file = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; - if (minimum !== void 0) file.minLength = minimum; - if (maximum !== void 0) file.maxLength = maximum; - if (mime) if (mime.length === 1) { - file.contentMediaType = mime[0]; - Object.assign(_json, file); - } else { - Object.assign(_json, file); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - else Object.assign(_json, file); -}; -var successProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -var customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema"); -}; -var functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema"); -}; -var transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema"); -}; -var mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema"); -}; -var setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema"); -}; -var arrayProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") json.minItems = minimum; - if (typeof maximum === "number") json.maxItems = maximum; - json.type = "array"; - json.items = process$1(def.element, ctx, { - ...params, - path: [...params.path, "items"] - }); -}; -var objectProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - json.properties = {}; - const shape = def.shape; - for (const key in shape) json.properties[key] = process$1(shape[key], ctx, { - ...params, - path: [ - ...params.path, - "properties", - key - ] - }); - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") return v.optin === void 0; - else return v.optout === void 0; - })); - if (requiredKeys.size > 0) json.required = Array.from(requiredKeys); - if (def.catchall?._zod.def.type === "never") json.additionalProperties = false; - else if (!def.catchall) { - if (ctx.io === "output") json.additionalProperties = false; - } else if (def.catchall) json.additionalProperties = process$1(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"] - }); -}; -var unionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process$1(x, ctx, { - ...params, - path: [ - ...params.path, - isExclusive ? "oneOf" : "anyOf", - i - ] - })); - if (isExclusive) json.oneOf = options; - else json.anyOf = options; -}; -var intersectionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const a = process$1(def.left, ctx, { - ...params, - path: [ - ...params.path, - "allOf", - 0 - ] - }); - const b = process$1(def.right, ctx, { - ...params, - path: [ - ...params.path, - "allOf", - 1 - ] - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]]; -}; -var tupleProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "array"; - const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; - const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process$1(x, ctx, { - ...params, - path: [ - ...params.path, - prefixPath, - i - ] - })); - const rest = def.rest ? process$1(def.rest, ctx, { - ...params, - path: [ - ...params.path, - restPath, - ...ctx.target === "openapi-3.0" ? [def.items.length] : [] - ] - }) : null; - if (ctx.target === "draft-2020-12") { - json.prefixItems = prefixItems; - if (rest) json.items = rest; - } else if (ctx.target === "openapi-3.0") { - json.items = { anyOf: prefixItems }; - if (rest) json.items.anyOf.push(rest); - json.minItems = prefixItems.length; - if (!rest) json.maxItems = prefixItems.length; - } else { - json.items = prefixItems; - if (rest) json.additionalItems = rest; - } - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") json.minItems = minimum; - if (typeof maximum === "number") json.maxItems = maximum; -}; -var recordProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - const keyType = def.keyType; - const patterns = keyType._zod.bag?.patterns; - if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process$1(def.valueType, ctx, { - ...params, - path: [ - ...params.path, - "patternProperties", - "*" - ] - }); - json.patternProperties = {}; - for (const pattern of patterns) json.patternProperties[pattern.source] = valueSchema; - } else { - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process$1(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"] - }); - json.additionalProperties = process$1(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"] - }); - } - const keyValues = keyType._zod.values; - if (keyValues) { - const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); - if (validKeyValues.length > 0) json.required = validKeyValues; - } -}; -var nullableProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const inner = process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json.nullable = true; - } else json.anyOf = [inner, { type: "null" }]; -}; -var nonoptionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -var defaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.default = JSON.parse(JSON.stringify(def.defaultValue)); -}; -var prefaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); -}; -var catchProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(void 0); - } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); - } - json.default = catchValue; -}; -var pipeProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - const inIsTransform = def.in._zod.traits.has("$ZodTransform"); - const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; - process$1(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -var readonlyProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.readOnly = true; -}; -var promiseProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -var optionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -var lazyProcessor = (schema, ctx, _json, params) => { - const innerType = schema._zod.innerType; - process$1(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -var allProcessors = { - string: stringProcessor, - number: numberProcessor, - boolean: booleanProcessor, - bigint: bigintProcessor, - symbol: symbolProcessor, - null: nullProcessor, - undefined: undefinedProcessor, - void: voidProcessor, - never: neverProcessor, - any: anyProcessor, - unknown: unknownProcessor, - date: dateProcessor, - enum: enumProcessor, - literal: literalProcessor, - nan: nanProcessor, - template_literal: templateLiteralProcessor, - file: fileProcessor, - success: successProcessor, - custom: customProcessor, - function: functionProcessor, - transform: transformProcessor, - map: mapProcessor, - set: setProcessor, - array: arrayProcessor, - object: objectProcessor, - union: unionProcessor, - intersection: intersectionProcessor, - tuple: tupleProcessor, - record: recordProcessor, - nullable: nullableProcessor, - nonoptional: nonoptionalProcessor, - default: defaultProcessor, - prefault: prefaultProcessor, - catch: catchProcessor, - pipe: pipeProcessor, - readonly: readonlyProcessor, - promise: promiseProcessor, - optional: optionalProcessor, - lazy: lazyProcessor -}; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry = input; - const ctx = initializeContext({ - ...params, - processors: allProcessors - }); - const defs = {}; - for (const entry of registry._idmap.entries()) { - const [_, schema] = entry; - process$1(schema, ctx); - } - const schemas = {}; - ctx.external = { - registry, - uri: params?.uri, - defs - }; - for (const entry of registry._idmap.entries()) { - const [key, schema] = entry; - extractDefs(ctx, schema); - schemas[key] = finalize(ctx, schema); - } - if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs }; - return { schemas }; - } - const ctx = initializeContext({ - ...params, - processors: allProcessors - }); - process$1(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); -} -//#endregion -//#region node_modules/zod/v4/classic/iso.js -var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime(params) { - return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params); -} -var ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date(params) { - return /* @__PURE__ */ _isoDate(ZodISODate, params); -} -var ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time(params) { - return /* @__PURE__ */ _isoTime(ZodISOTime, params); -} -var ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration(params) { - return /* @__PURE__ */ _isoDuration(ZodISODuration, params); -} -//#endregion -//#region node_modules/zod/v4/classic/errors.js -var initializer = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { value: (mapper) => formatError(inst, mapper) }, - flatten: { value: (mapper) => flattenError(inst, mapper) }, - addIssue: { value: (issue) => { - inst.issues.push(issue); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } }, - addIssues: { value: (issues) => { - inst.issues.push(...issues); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } }, - isEmpty: { get() { - return inst.issues.length === 0; - } } - }); -}; -var ZodError = /*@__PURE__*/ $constructor("ZodError", initializer); -var ZodRealError = /*@__PURE__*/ $constructor("ZodError", initializer, { Parent: Error }); -//#endregion -//#region node_modules/zod/v4/classic/parse.js -var parse = /* @__PURE__ */ _parse(ZodRealError); -var parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError); -var safeParse = /* @__PURE__ */ _safeParse(ZodRealError); -var safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); -var encode$2 = /* @__PURE__ */ _encode(ZodRealError); -var decode$1 = /* @__PURE__ */ _decode(ZodRealError); -var encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError); -var decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError); -var safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); -var safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); -var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); -var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); -//#endregion -//#region node_modules/zod/v4/classic/schemas.js -var _installedGroups = /* @__PURE__ */ new WeakMap(); -function _installLazyMethods(inst, group, methods) { - const proto = Object.getPrototypeOf(inst); - let installed = _installedGroups.get(proto); - if (!installed) { - installed = /* @__PURE__ */ new Set(); - _installedGroups.set(proto, installed); - } - if (installed.has(group)) return; - installed.add(group); - for (const key in methods) { - const fn = methods[key]; - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const bound = fn.bind(this); - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: bound - }); - return bound; - }, - set(v) { - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: v - }); - } - }); - } -} -var ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { - $ZodType.init(inst, def); - Object.assign(inst["~standard"], { jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); - inst.def = def; - inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode$2(inst, data, params); - inst.decode = (data, params) => decode$1(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params); - inst.safeEncode = (data, params) => safeEncode(inst, data, params); - inst.safeDecode = (data, params) => safeDecode(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params); - _installLazyMethods(inst, "ZodType", { - check(...chks) { - const def = this.def; - return this.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...chks.map((ch) => typeof ch === "function" ? { _zod: { - check: ch, - def: { check: "custom" }, - onattach: [] - } } : ch)] }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def, params) { - return clone(this, def, params); - }, - brand() { - return this; - }, - register(reg, meta) { - reg.add(this, meta); - return this; - }, - refine(check, params) { - return this.check(refine(check, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(/* @__PURE__ */ _overwrite(fn)); - }, - optional() { - return optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return array(this); - }, - or(arg) { - return union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return _default(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return _catch(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - if (args.length === 0) return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(void 0).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn) { - return fn(this); - } - }); - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); - return inst; -}); -/** @internal */ -var _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - _installLazyMethods(inst, "_ZodString", { - regex(...args) { - return this.check(/* @__PURE__ */ _regex(...args)); - }, - includes(...args) { - return this.check(/* @__PURE__ */ _includes(...args)); - }, - startsWith(...args) { - return this.check(/* @__PURE__ */ _startsWith(...args)); - }, - endsWith(...args) { - return this.check(/* @__PURE__ */ _endsWith(...args)); - }, - min(...args) { - return this.check(/* @__PURE__ */ _minLength(...args)); - }, - max(...args) { - return this.check(/* @__PURE__ */ _maxLength(...args)); - }, - length(...args) { - return this.check(/* @__PURE__ */ _length(...args)); - }, - nonempty(...args) { - return this.check(/* @__PURE__ */ _minLength(1, ...args)); - }, - lowercase(params) { - return this.check(/* @__PURE__ */ _lowercase(params)); - }, - uppercase(params) { - return this.check(/* @__PURE__ */ _uppercase(params)); - }, - trim() { - return this.check(/* @__PURE__ */ _trim()); - }, - normalize(...args) { - return this.check(/* @__PURE__ */ _normalize(...args)); - }, - toLowerCase() { - return this.check(/* @__PURE__ */ _toLowerCase()); - }, - toUpperCase() { - return this.check(/* @__PURE__ */ _toUpperCase()); - }, - slugify() { - return this.check(/* @__PURE__ */ _slugify()); - } - }); -}); -var ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); - inst.email = (params) => inst.check(/* @__PURE__ */ _email(ZodEmail, params)); - inst.url = (params) => inst.check(/* @__PURE__ */ _url(ZodURL, params)); - inst.jwt = (params) => inst.check(/* @__PURE__ */ _jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(/* @__PURE__ */ _emoji(ZodEmoji, params)); - inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(/* @__PURE__ */ _uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(/* @__PURE__ */ _uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(/* @__PURE__ */ _uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(/* @__PURE__ */ _uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(/* @__PURE__ */ _nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(/* @__PURE__ */ _cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(/* @__PURE__ */ _cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(/* @__PURE__ */ _ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(/* @__PURE__ */ _base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(/* @__PURE__ */ _base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(/* @__PURE__ */ _xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(/* @__PURE__ */ _ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(/* @__PURE__ */ _ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(/* @__PURE__ */ _ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(/* @__PURE__ */ _cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(/* @__PURE__ */ _cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(/* @__PURE__ */ _e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime(params)); - inst.date = (params) => inst.check(date(params)); - inst.time = (params) => inst.check(time(params)); - inst.duration = (params) => inst.check(duration(params)); -}); -function string(params) { - return /* @__PURE__ */ _string(ZodString, params); -} -var ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); -}); -var ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function email(params) { - return /* @__PURE__ */ _email(ZodEmail, params); -} -var ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function url(params) { - return /* @__PURE__ */ _url(ZodURL, params); -} -var ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -/** -* @deprecated CUID v1 is deprecated by its authors due to information leakage -* (timestamps embedded in the id). Use {@link ZodCUID2} instead. -* See https://github.com/paralleldrive/cuid. -*/ -var ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function ipv4(params) { - return /* @__PURE__ */ _ipv4(ZodIPv4, params); -} -var ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function ipv6(params) { - return /* @__PURE__ */ _ipv6(ZodIPv6, params); -} -var ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); - _installLazyMethods(inst, "ZodNumber", { - gt(value, params) { - return this.check(/* @__PURE__ */ _gt(value, params)); - }, - gte(value, params) { - return this.check(/* @__PURE__ */ _gte(value, params)); - }, - min(value, params) { - return this.check(/* @__PURE__ */ _gte(value, params)); - }, - lt(value, params) { - return this.check(/* @__PURE__ */ _lt(value, params)); - }, - lte(value, params) { - return this.check(/* @__PURE__ */ _lte(value, params)); - }, - max(value, params) { - return this.check(/* @__PURE__ */ _lte(value, params)); - }, - int(params) { - return this.check(int(params)); - }, - safe(params) { - return this.check(int(params)); - }, - positive(params) { - return this.check(/* @__PURE__ */ _gt(0, params)); - }, - nonnegative(params) { - return this.check(/* @__PURE__ */ _gte(0, params)); - }, - negative(params) { - return this.check(/* @__PURE__ */ _lt(0, params)); - }, - nonpositive(params) { - return this.check(/* @__PURE__ */ _lte(0, params)); - }, - multipleOf(value, params) { - return this.check(/* @__PURE__ */ _multipleOf(value, params)); - }, - step(value, params) { - return this.check(/* @__PURE__ */ _multipleOf(value, params)); - }, - finite() { - return this; - } - }); - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); -function number(params) { - return /* @__PURE__ */ _number(ZodNumber, params); -} -var ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber.init(inst, def); -}); -function int(params) { - return /* @__PURE__ */ _int(ZodNumberFormat, params); -} -var ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); -}); -function boolean(params) { - return /* @__PURE__ */ _boolean(ZodBoolean, params); -} -var ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); -}); -function _null(params) { - return /* @__PURE__ */ _null$1(ZodNull, params); -} -var ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => void 0; -}); -function any() { - return /* @__PURE__ */ _any(ZodAny); -} -var ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => void 0; -}); -function unknown() { - return /* @__PURE__ */ _unknown(ZodUnknown); -} -var ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); -}); -function never(params) { - return /* @__PURE__ */ _never(ZodNever, params); -} -var ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { - $ZodArray.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); - inst.element = def.element; - _installLazyMethods(inst, "ZodArray", { - min(n, params) { - return this.check(/* @__PURE__ */ _minLength(n, params)); - }, - nonempty(params) { - return this.check(/* @__PURE__ */ _minLength(1, params)); - }, - max(n, params) { - return this.check(/* @__PURE__ */ _maxLength(n, params)); - }, - length(n, params) { - return this.check(/* @__PURE__ */ _length(n, params)); - }, - unwrap() { - return this.element; - } - }); -}); -function array(element, params) { - return /* @__PURE__ */ _array(ZodArray, element, params); -} -var ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { - $ZodObjectJIT.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); - defineLazy(inst, "shape", () => { - return def.shape; - }); - _installLazyMethods(inst, "ZodObject", { - keyof() { - return _enum(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ - ...this._zod.def, - catchall - }); - }, - passthrough() { - return this.clone({ - ...this._zod.def, - catchall: unknown() - }); - }, - loose() { - return this.clone({ - ...this._zod.def, - catchall: unknown() - }); - }, - strict() { - return this.clone({ - ...this._zod.def, - catchall: never() - }); - }, - strip() { - return this.clone({ - ...this._zod.def, - catchall: void 0 - }); - }, - extend(incoming) { - return extend(this, incoming); - }, - safeExtend(incoming) { - return safeExtend(this, incoming); - }, - merge(other) { - return merge(this, other); - }, - pick(mask) { - return pick(this, mask); - }, - omit(mask) { - return omit(this, mask); - }, - partial(...args) { - return partial(ZodOptional, this, args[0]); - }, - required(...args) { - return required(ZodNonOptional, this, args[0]); - } - }); -}); -function object(shape, params) { - return new ZodObject({ - type: "object", - shape: shape ?? {}, - ...normalizeParams(params) - }); -} -function looseObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: unknown(), - ...normalizeParams(params) - }); -} -var ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}); -function union(options, params) { - return new ZodUnion({ - type: "union", - options, - ...normalizeParams(params) - }); -} -var ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); -}); -function discriminatedUnion(discriminator, options, params) { - return new ZodDiscriminatedUnion({ - type: "union", - options, - discriminator, - ...normalizeParams(params) - }); -} -var ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); -}); -function intersection(left, right) { - return new ZodIntersection({ - type: "intersection", - left, - right - }); -} -var ZodTuple = /*@__PURE__*/ $constructor("ZodTuple", (inst, def) => { - $ZodTuple.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => tupleProcessor(inst, ctx, json, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); -}); -function tuple(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof $ZodType; - return new ZodTuple({ - type: "tuple", - items, - rest: hasRest ? _paramsOrRest : null, - ...normalizeParams(hasRest ? _params : _paramsOrRest) - }); -} -var ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { - $ZodRecord.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}); -function record(keyType, valueType, params) { - if (!valueType || !valueType._zod) return new ZodRecord({ - type: "record", - keyType: string(), - valueType: keyType, - ...normalizeParams(valueType) - }); - return new ZodRecord({ - type: "record", - keyType, - valueType, - ...normalizeParams(params) - }); -} -var ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value]; - else throw new Error(`Key ${value} not found in enum`); - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries - }); - }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) if (keys.has(value)) delete newEntries[value]; - else throw new Error(`Key ${value} not found in enum`); - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries - }); - }; -}); -function _enum(values, params) { - return new ZodEnum({ - type: "enum", - entries: Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values, - ...normalizeParams(params) - }); -} -var ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { get() { - if (def.values.length > 1) throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - return def.values[0]; - } }); -}); -function literal(value, params) { - return new ZodLiteral({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params) - }); -} -var ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { - $ZodTransform.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); - inst._zod.parse = (payload, _ctx) => { - if (_ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name); - payload.addIssue = (issue$1) => { - if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, def)); - else { - const _issue = issue$1; - if (_issue.fatal) _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = inst); - payload.issues.push(issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) return output.then((output) => { - payload.value = output; - payload.fallback = true; - return payload; - }); - payload.value = output; - payload.fallback = true; - return payload; - }; -}); -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn - }); -} -var ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function optional(innerType) { - return new ZodOptional({ - type: "optional", - innerType - }); -} -var ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function exactOptional(innerType) { - return new ZodExactOptional({ - type: "optional", - innerType - }); -} -var ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nullable(innerType) { - return new ZodNullable({ - type: "nullable", - innerType - }); -} -var ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; -}); -function _default(innerType, defaultValue) { - return new ZodDefault({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - } - }); -} -var ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - } - }); -} -var ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType, - ...normalizeParams(params) - }); -} -var ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; -}); -function _catch(innerType, catchValue) { - return new ZodCatch({ - type: "catch", - innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue - }); -} -var ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); - inst.in = def.in; - inst.out = def.out; -}); -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out - }); -} -var ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { - ZodPipe.init(inst, def); - $ZodPreprocess.init(inst, def); -}); -var ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function readonly(innerType) { - return new ZodReadonly({ - type: "readonly", - innerType - }); -} -var ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); -}); -function custom(fn, _params) { - return /* @__PURE__ */ _custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return /* @__PURE__ */ _refine(ZodCustom, fn, _params); -} -function superRefine(fn, params) { - return /* @__PURE__ */ _superRefine(fn, params); -} -function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...normalizeParams(params) - }); - inst._zod.bag.Class = cls; - inst._zod.check = (payload) => { - if (!(payload.value instanceof cls)) payload.issues.push({ - code: "invalid_type", - expected: cls.name, - input: payload.value, - inst, - path: [...inst._zod.def.path ?? []] - }); - }; - return inst; -} -function preprocess(fn, schema) { - return new ZodPreprocess({ - type: "pipe", - in: transform(fn), - out: schema - }); -} -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs -var initGetDefaultModelName = ({ usePlural, schema }) => { - /** - * This function helps us get the default model name from the schema defined by devs. - * Often times, the user will be using the `modelName` which could had been customized by the users. - * This function helps us get the actual model name useful to match against the schema. (eg: schema[model]) - * - * If it's still unclear what this does: - * - * 1. User can define a custom modelName. - * 2. When using a custom modelName, doing something like `schema[model]` will not work. - * 3. Using this function helps us get the actual model name based on the user's defined custom modelName. - */ - const getDefaultModelName = (model) => { - const resolve = (candidate) => { - if (schema[candidate]) return candidate; - return Object.entries(schema).find(([_, f]) => f.modelName === candidate)?.[0]; - }; - if (usePlural && model.charAt(model.length - 1) === "s") { - const m = resolve(model.slice(0, -1)); - if (m) return m; - } - const m = resolve(model); - if (!m) throw new BetterAuthError(`Model "${model}" not found in schema`); - return m; - }; - return getDefaultModelName; -}; -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs -var initGetDefaultFieldName = ({ schema, usePlural }) => { - const getDefaultModelName = initGetDefaultModelName({ - schema, - usePlural - }); - /** - * This function helps us get the default field name from the schema defined by devs. - * Often times, the user will be using the `fieldName` which could had been customized by the users. - * This function helps us get the actual field name useful to match against the schema. (eg: schema[model].fields[field]) - * - * If it's still unclear what this does: - * - * 1. User can define a custom fieldName. - * 2. When using a custom fieldName, doing something like `schema[model].fields[field]` will not work. - */ - const getDefaultFieldName = ({ field, model: unsafeModel }) => { - if (field === "id" || field === "_id") return "id"; - const model = getDefaultModelName(unsafeModel); - let f = schema[model]?.fields[field]; - if (!f) { - const result = Object.entries(schema[model].fields).find(([_, f]) => f.fieldName === field); - if (result) { - f = result[1]; - field = result[0]; - } - } - if (!f) throw new BetterAuthError(`Field ${field} not found in model ${model}`); - return field; - }; - return getDefaultFieldName; -}; -//#endregion -//#region node_modules/@better-auth/utils/dist/random.mjs -function expandAlphabet(alphabet) { - switch (alphabet) { - case "a-z": return "abcdefghijklmnopqrstuvwxyz"; - case "A-Z": return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - case "0-9": return "0123456789"; - case "-_": return "-_"; - default: throw new Error(`Unsupported alphabet: ${alphabet}`); - } -} -function createRandomStringGenerator(...baseAlphabets) { - const baseCharSet = baseAlphabets.map(expandAlphabet).join(""); - if (baseCharSet.length === 0) throw new Error("No valid characters provided for random string generation."); - const baseCharSetLength = baseCharSet.length; - return (length, ...alphabets) => { - if (length <= 0) throw new Error("Length must be a positive integer."); - let charSet = baseCharSet; - let charSetLength = baseCharSetLength; - if (alphabets.length > 0) { - charSet = alphabets.map(expandAlphabet).join(""); - charSetLength = charSet.length; - } - const maxValid = Math.floor(256 / charSetLength) * charSetLength; - const buf = new Uint8Array(length * 2); - const bufLength = buf.length; - let result = ""; - let bufIndex = bufLength; - let rand; - while (result.length < length) { - if (bufIndex >= bufLength) { - crypto.getRandomValues(buf); - bufIndex = 0; - } - rand = buf[bufIndex++]; - if (rand < maxValid) result += charSet[rand % charSetLength]; - } - return result; - }; -} -//#endregion -//#region node_modules/@better-auth/core/dist/utils/id.mjs -var generateId = (size) => { - return createRandomStringGenerator("a-z", "A-Z", "0-9")(size || 32); -}; -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs -var initGetIdField = ({ usePlural, schema, disableIdGeneration, options, customIdGenerator, supportsUUIDs }) => { - const getDefaultModelName = initGetDefaultModelName({ - usePlural, - schema - }); - const idField = ({ customModelName, forceAllowId }) => { - const useNumberId = options.advanced?.database?.generateId === "serial"; - const useUUIDs = options.advanced?.database?.generateId === "uuid"; - const shouldGenerateId = (() => { - if (disableIdGeneration) return false; - else if (useNumberId && !forceAllowId) return false; - else if (useUUIDs) return !supportsUUIDs; - else return true; - })(); - const model = getDefaultModelName(customModelName ?? "id"); - return { - type: useNumberId ? "number" : "string", - required: shouldGenerateId ? true : false, - ...shouldGenerateId ? { defaultValue() { - if (disableIdGeneration) return void 0; - const generateId$1 = options.advanced?.database?.generateId; - if (generateId$1 === false || generateId$1 === "serial") return void 0; - if (typeof generateId$1 === "function") return generateId$1({ model }); - if (generateId$1 === "uuid") return crypto.randomUUID(); - if (customIdGenerator) return customIdGenerator({ model }); - return generateId(); - } } : {}, - transform: { - input: (value) => { - if (!value) return void 0; - if (useNumberId) { - const numberValue = Number(value); - if (isNaN(numberValue)) return; - return numberValue; - } - if (useUUIDs) { - if (shouldGenerateId && !forceAllowId) return value; - if (disableIdGeneration) return void 0; - if (forceAllowId && typeof value === "string") if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) return value; - else { - const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", ""); - logger.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.", stack); - } - if (supportsUUIDs) return void 0; - if (typeof value !== "string" && !supportsUUIDs) return crypto.randomUUID(); - return; - } - return value; - }, - output: (value) => { - if (!value) return void 0; - return String(value); - } - } - }; - }; - return idField; -}; -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs -var initGetFieldAttributes = ({ usePlural, schema, options, customIdGenerator, disableIdGeneration }) => { - const getDefaultModelName = initGetDefaultModelName({ - usePlural, - schema - }); - const getDefaultFieldName = initGetDefaultFieldName({ - usePlural, - schema - }); - const idField = initGetIdField({ - usePlural, - schema, - options, - customIdGenerator, - disableIdGeneration - }); - const getFieldAttributes = ({ model, field }) => { - const defaultModelName = getDefaultModelName(model); - const defaultFieldName = getDefaultFieldName({ - field, - model: defaultModelName - }); - const fields = schema[defaultModelName].fields; - fields.id = idField({ customModelName: defaultModelName }); - const fieldAttributes = fields[defaultFieldName]; - if (!fieldAttributes) throw new BetterAuthError(`Field ${field} not found in model ${model}`); - return fieldAttributes; - }; - return getFieldAttributes; -}; -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs -var initGetFieldName = ({ schema, usePlural }) => { - const getDefaultModelName = initGetDefaultModelName({ - schema, - usePlural - }); - const getDefaultFieldName = initGetDefaultFieldName({ - schema, - usePlural - }); - /** - * Get the field name which is expected to be saved in the database based on the user's schema. - * - * This function is useful if you need to save the field name to the database. - * - * For example, if the user has defined a custom field name for the `user` model, then you can use this function to get the actual field name from the schema. - */ - function getFieldName({ model: modelName, field: fieldName }) { - const model = getDefaultModelName(modelName); - const field = getDefaultFieldName({ - model, - field: fieldName - }); - return schema[model]?.fields[field]?.fieldName || field; - } - return getFieldName; -}; -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs -var initGetModelName = ({ usePlural, schema }) => { - const getDefaultModelName = initGetDefaultModelName({ - schema, - usePlural - }); - /** - * Users can overwrite the default model of some tables. This function helps find the correct model name. - * Furthermore, if the user passes `usePlural` as true in their adapter config, - * then we should return the model name ending with an `s`. - */ - const getModelName = (model) => { - const defaultModelKey = getDefaultModelName(model); - if (schema && schema[defaultModelKey] && schema[defaultModelKey].modelName !== model) return usePlural ? `${schema[defaultModelKey].modelName}s` : schema[defaultModelKey].modelName; - return usePlural ? `${model}s` : model; - }; - return getModelName; -}; -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/utils.mjs -function withApplyDefault(value, field, action) { - if (action === "update") { - if (value === void 0 && field.onUpdate !== void 0) { - if (typeof field.onUpdate === "function") return field.onUpdate(); - return field.onUpdate; - } - return value; - } - if (action === "create") { - if (value === void 0 || field.required === true && value === null) { - if (field.defaultValue !== void 0) { - if (typeof field.defaultValue === "function") return field.defaultValue(); - return field.defaultValue; - } - } - } - return value; -} -//#endregion -//#region node_modules/@better-auth/core/dist/context/global.mjs -var symbol = Symbol.for("better-auth:global"); -var bind = null; -var __context = {}; -var __betterAuthVersion = "1.6.25"; -/** -* We store context instance in the globalThis. -* -* The reason we do this is that some bundlers, web framework, or package managers might -* create multiple copies of BetterAuth in the same process intentionally or unintentionally. -* -* For example, yarn v1, Next.js, SSR, Vite... -* -* @internal -*/ -function __getBetterAuthGlobal() { - if (!globalThis[symbol]) { - globalThis[symbol] = { - version: __betterAuthVersion, - epoch: 1, - context: __context - }; - bind = globalThis[symbol]; - } - bind = globalThis[symbol]; - if (bind.version !== __betterAuthVersion) { - bind.version = __betterAuthVersion; - bind.epoch++; - } - return globalThis[symbol]; -} -function getBetterAuthVersion() { - return __getBetterAuthGlobal().version; -} -//#endregion -//#region node_modules/@better-auth/core/dist/async_hooks/index.mjs -var AsyncLocalStoragePromise = import( - /* @vite-ignore */ - /* webpackIgnore: true */ - "node:async_hooks" -).then((mod) => mod.AsyncLocalStorage).catch((err) => { - if ("AsyncLocalStorage" in globalThis) return globalThis.AsyncLocalStorage; - if (typeof window !== "undefined") return null; - console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."); - console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"); - console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"); - throw err; -}); -async function getAsyncLocalStorage() { - const mod = await AsyncLocalStoragePromise; - if (mod === null) throw new Error("getAsyncLocalStorage is only available in server code"); - else return mod; -} -//#endregion -//#region node_modules/@better-auth/core/dist/context/transaction.mjs -var ensureAsyncStorage$2 = async () => { - const betterAuthGlobal = __getBetterAuthGlobal(); - if (!betterAuthGlobal.context.adapterAsyncStorage) { - const AsyncLocalStorage = await getAsyncLocalStorage(); - betterAuthGlobal.context.adapterAsyncStorage = new AsyncLocalStorage(); - } - return betterAuthGlobal.context.adapterAsyncStorage; -}; -var getCurrentAdapter = async (fallback) => { - return ensureAsyncStorage$2().then((als) => { - return als.getStore()?.adapter || fallback; - }).catch(() => { - return fallback; - }); -}; -var runWithAdapter = async (adapter, fn) => { - let called = false; - return ensureAsyncStorage$2().then(async (als) => { - called = true; - const pendingHooks = []; - let result; - let error; - let hasError = false; - try { - result = await als.run({ - adapter, - pendingHooks, - isTransactionActive: false - }, fn); - } catch (err) { - error = err; - hasError = true; - } - for (const hook of pendingHooks) await hook(); - if (hasError) throw error; - return result; - }).catch((err) => { - if (!called) return fn(); - throw err; - }); -}; -var runWithTransaction = async (adapter, fn) => { - let called = false; - return ensureAsyncStorage$2().then(async (als) => { - called = true; - if (als.getStore()?.isTransactionActive) return fn(); - const pendingHooks = []; - let result; - let error; - let hasError = false; - try { - result = await adapter.transaction(async (trx) => { - return als.run({ - adapter: trx, - pendingHooks, - isTransactionActive: true - }, fn); - }); - } catch (e) { - hasError = true; - error = e; - } - for (const hook of pendingHooks) await hook(); - if (hasError) throw error; - return result; - }).catch((err) => { - if (!called) return fn(); - throw err; - }); -}; -/** -* Queue a hook to be executed after the current transaction commits. -* If not in a transaction, the hook will execute immediately. -*/ -var queueAfterTransactionHook = async (hook) => { - return ensureAsyncStorage$2().then((als) => { - const store = als.getStore(); - if (store) store.pendingHooks.push(hook); - else return hook(); - }).catch(() => { - return hook(); - }); -}; -//#endregion -//#region node_modules/@better-auth/core/dist/db/get-tables.mjs -var getAuthTables = (options) => { - const pluginSchema = (options.plugins ?? []).reduce((acc, plugin) => { - const schema = plugin.schema; - if (!schema) return acc; - for (const [key, value] of Object.entries(schema)) acc[key] = { - fields: { - ...acc[key]?.fields, - ...value.fields - }, - modelName: value.modelName || key, - disableMigrations: value.disableMigration ?? acc[key]?.disableMigrations - }; - return acc; - }, {}); - const shouldAddRateLimitTable = options.rateLimit?.storage === "database"; - const rateLimitTable = { rateLimit: { - modelName: options.rateLimit?.modelName || "rateLimit", - fields: { - key: { - type: "string", - unique: true, - required: true, - fieldName: options.rateLimit?.fields?.key || "key" - }, - count: { - type: "number", - required: true, - fieldName: options.rateLimit?.fields?.count || "count" - }, - lastRequest: { - type: "number", - bigint: true, - required: true, - fieldName: options.rateLimit?.fields?.lastRequest || "lastRequest", - defaultValue: () => Date.now() - } - } - } }; - const { user, session, account, verification, ...pluginTables } = pluginSchema; - const verificationTable = { verification: { - modelName: options.verification?.modelName || "verification", - fields: { - identifier: { - type: "string", - required: true, - fieldName: options.verification?.fields?.identifier || "identifier", - index: true - }, - value: { - type: "string", - required: true, - fieldName: options.verification?.fields?.value || "value" - }, - expiresAt: { - type: "date", - required: true, - fieldName: options.verification?.fields?.expiresAt || "expiresAt" - }, - createdAt: { - type: "date", - required: true, - defaultValue: () => /* @__PURE__ */ new Date(), - fieldName: options.verification?.fields?.createdAt || "createdAt" - }, - updatedAt: { - type: "date", - required: true, - defaultValue: () => /* @__PURE__ */ new Date(), - onUpdate: () => /* @__PURE__ */ new Date(), - fieldName: options.verification?.fields?.updatedAt || "updatedAt" - }, - ...verification?.fields, - ...options.verification?.additionalFields - }, - order: 4 - } }; - const sessionTable = { session: { - modelName: options.session?.modelName || "session", - fields: { - expiresAt: { - type: "date", - required: true, - fieldName: options.session?.fields?.expiresAt || "expiresAt" - }, - token: { - type: "string", - required: true, - fieldName: options.session?.fields?.token || "token", - unique: true - }, - createdAt: { - type: "date", - required: true, - fieldName: options.session?.fields?.createdAt || "createdAt", - defaultValue: () => /* @__PURE__ */ new Date() - }, - updatedAt: { - type: "date", - required: true, - fieldName: options.session?.fields?.updatedAt || "updatedAt", - onUpdate: () => /* @__PURE__ */ new Date() - }, - ipAddress: { - type: "string", - required: false, - fieldName: options.session?.fields?.ipAddress || "ipAddress" - }, - userAgent: { - type: "string", - required: false, - fieldName: options.session?.fields?.userAgent || "userAgent" - }, - userId: { - type: "string", - fieldName: options.session?.fields?.userId || "userId", - references: { - model: "user", - field: "id", - onDelete: "cascade" - }, - required: true, - index: true - }, - ...session?.fields, - ...options.session?.additionalFields - }, - order: 2 - } }; - return { - user: { - modelName: options.user?.modelName || "user", - fields: { - name: { - type: "string", - required: true, - fieldName: options.user?.fields?.name || "name", - sortable: true - }, - email: { - type: "string", - unique: true, - required: true, - fieldName: options.user?.fields?.email || "email", - sortable: true - }, - emailVerified: { - type: "boolean", - defaultValue: false, - required: true, - fieldName: options.user?.fields?.emailVerified || "emailVerified", - input: false - }, - image: { - type: "string", - required: false, - fieldName: options.user?.fields?.image || "image" - }, - createdAt: { - type: "date", - defaultValue: () => /* @__PURE__ */ new Date(), - required: true, - fieldName: options.user?.fields?.createdAt || "createdAt" - }, - updatedAt: { - type: "date", - defaultValue: () => /* @__PURE__ */ new Date(), - onUpdate: () => /* @__PURE__ */ new Date(), - required: true, - fieldName: options.user?.fields?.updatedAt || "updatedAt" - }, - ...user?.fields, - ...options.user?.additionalFields - }, - order: 1 - }, - ...!options.secondaryStorage || options.session?.storeSessionInDatabase ? sessionTable : {}, - account: { - modelName: options.account?.modelName || "account", - fields: { - accountId: { - type: "string", - required: true, - fieldName: options.account?.fields?.accountId || "accountId" - }, - providerId: { - type: "string", - required: true, - fieldName: options.account?.fields?.providerId || "providerId" - }, - userId: { - type: "string", - references: { - model: "user", - field: "id", - onDelete: "cascade" - }, - required: true, - fieldName: options.account?.fields?.userId || "userId", - index: true - }, - accessToken: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.accessToken || "accessToken" - }, - refreshToken: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.refreshToken || "refreshToken" - }, - idToken: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.idToken || "idToken" - }, - accessTokenExpiresAt: { - type: "date", - required: false, - returned: false, - fieldName: options.account?.fields?.accessTokenExpiresAt || "accessTokenExpiresAt" - }, - refreshTokenExpiresAt: { - type: "date", - required: false, - returned: false, - fieldName: options.account?.fields?.refreshTokenExpiresAt || "refreshTokenExpiresAt" - }, - scope: { - type: "string", - required: false, - fieldName: options.account?.fields?.scope || "scope" - }, - password: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.password || "password" - }, - createdAt: { - type: "date", - required: true, - fieldName: options.account?.fields?.createdAt || "createdAt", - defaultValue: () => /* @__PURE__ */ new Date() - }, - updatedAt: { - type: "date", - required: true, - fieldName: options.account?.fields?.updatedAt || "updatedAt", - onUpdate: () => /* @__PURE__ */ new Date() - }, - ...account?.fields, - ...options.account?.additionalFields - }, - order: 3 - }, - ...!options.secondaryStorage || options.verification?.storeInDatabase ? verificationTable : {}, - ...pluginTables, - ...shouldAddRateLimitTable ? rateLimitTable : {} - }; -}; -//#endregion -//#region node_modules/@better-auth/core/dist/utils/json.mjs -var iso8601Regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/; -function reviveDate(value) { - if (typeof value === "string" && iso8601Regex.test(value)) { - const date = new Date(value); - if (!isNaN(date.getTime())) return date; - } - return value; -} -/** -* Recursively walk a pre-parsed object and convert ISO 8601 date strings -* to Date instances. This handles the case where a Redis client (or similar) -* returns already-parsed JSON objects whose date fields are still strings. -*/ -function reviveDates(value) { - if (value === null || value === void 0) return value; - if (typeof value === "string") return reviveDate(value); - if (value instanceof Date) return value; - if (Array.isArray(value)) return value.map(reviveDates); - if (typeof value === "object") { - const result = {}; - for (const key of Object.keys(value)) result[key] = reviveDates(value[key]); - return result; - } - return value; -} -function safeJSONParse(data) { - try { - if (typeof data !== "string") { - if (data === null || data === void 0) return null; - return reviveDates(data); - } - return JSON.parse(data, (_, value) => reviveDate(value)); - } catch (e) { - logger.error("Error parsing JSON", { error: e }); - return null; - } -} -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js -var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createConstMap = void 0; - /** - * Creates a const map from the given values - * @param values - An array of values to be used as keys and values in the map. - * @returns A populated version of the map with the values and keys derived from the values. - */ - /*#__NO_SIDE_EFFECTS__*/ - function createConstMap(values) { - let res = {}; - const len = values.length; - for (let lp = 0; lp < len; lp++) { - const val = values[lp]; - if (val) res[String(val).toUpperCase().replace(/[-.]/g, "_")] = val; - } - return res; - } - exports.createConstMap = createConstMap; -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js -var require_SemanticAttributes = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SEMATTRS_NET_HOST_CARRIER_ICC = exports.SEMATTRS_NET_HOST_CARRIER_MNC = exports.SEMATTRS_NET_HOST_CARRIER_MCC = exports.SEMATTRS_NET_HOST_CARRIER_NAME = exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = exports.SEMATTRS_NET_HOST_NAME = exports.SEMATTRS_NET_HOST_PORT = exports.SEMATTRS_NET_HOST_IP = exports.SEMATTRS_NET_PEER_NAME = exports.SEMATTRS_NET_PEER_PORT = exports.SEMATTRS_NET_PEER_IP = exports.SEMATTRS_NET_TRANSPORT = exports.SEMATTRS_FAAS_INVOKED_REGION = exports.SEMATTRS_FAAS_INVOKED_PROVIDER = exports.SEMATTRS_FAAS_INVOKED_NAME = exports.SEMATTRS_FAAS_COLDSTART = exports.SEMATTRS_FAAS_CRON = exports.SEMATTRS_FAAS_TIME = exports.SEMATTRS_FAAS_DOCUMENT_NAME = exports.SEMATTRS_FAAS_DOCUMENT_TIME = exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = exports.SEMATTRS_FAAS_EXECUTION = exports.SEMATTRS_FAAS_TRIGGER = exports.SEMATTRS_EXCEPTION_ESCAPED = exports.SEMATTRS_EXCEPTION_STACKTRACE = exports.SEMATTRS_EXCEPTION_MESSAGE = exports.SEMATTRS_EXCEPTION_TYPE = exports.SEMATTRS_DB_SQL_TABLE = exports.SEMATTRS_DB_MONGODB_COLLECTION = exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = exports.SEMATTRS_DB_HBASE_NAMESPACE = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = exports.SEMATTRS_DB_CASSANDRA_TABLE = exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = exports.SEMATTRS_DB_OPERATION = exports.SEMATTRS_DB_STATEMENT = exports.SEMATTRS_DB_NAME = exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = exports.SEMATTRS_DB_USER = exports.SEMATTRS_DB_CONNECTION_STRING = exports.SEMATTRS_DB_SYSTEM = exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = void 0; - exports.SEMATTRS_MESSAGING_DESTINATION_KIND = exports.SEMATTRS_MESSAGING_DESTINATION = exports.SEMATTRS_MESSAGING_SYSTEM = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = exports.SEMATTRS_AWS_DYNAMODB_COUNT = exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_SELECT = exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = exports.SEMATTRS_AWS_DYNAMODB_LIMIT = exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = exports.SEMATTRS_HTTP_CLIENT_IP = exports.SEMATTRS_HTTP_ROUTE = exports.SEMATTRS_HTTP_SERVER_NAME = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = exports.SEMATTRS_HTTP_USER_AGENT = exports.SEMATTRS_HTTP_FLAVOR = exports.SEMATTRS_HTTP_STATUS_CODE = exports.SEMATTRS_HTTP_SCHEME = exports.SEMATTRS_HTTP_HOST = exports.SEMATTRS_HTTP_TARGET = exports.SEMATTRS_HTTP_URL = exports.SEMATTRS_HTTP_METHOD = exports.SEMATTRS_CODE_LINENO = exports.SEMATTRS_CODE_FILEPATH = exports.SEMATTRS_CODE_NAMESPACE = exports.SEMATTRS_CODE_FUNCTION = exports.SEMATTRS_THREAD_NAME = exports.SEMATTRS_THREAD_ID = exports.SEMATTRS_ENDUSER_SCOPE = exports.SEMATTRS_ENDUSER_ROLE = exports.SEMATTRS_ENDUSER_ID = exports.SEMATTRS_PEER_SERVICE = void 0; - exports.DBSYSTEMVALUES_FILEMAKER = exports.DBSYSTEMVALUES_DERBY = exports.DBSYSTEMVALUES_FIREBIRD = exports.DBSYSTEMVALUES_ADABAS = exports.DBSYSTEMVALUES_CACHE = exports.DBSYSTEMVALUES_EDB = exports.DBSYSTEMVALUES_FIRSTSQL = exports.DBSYSTEMVALUES_INGRES = exports.DBSYSTEMVALUES_HANADB = exports.DBSYSTEMVALUES_MAXDB = exports.DBSYSTEMVALUES_PROGRESS = exports.DBSYSTEMVALUES_HSQLDB = exports.DBSYSTEMVALUES_CLOUDSCAPE = exports.DBSYSTEMVALUES_HIVE = exports.DBSYSTEMVALUES_REDSHIFT = exports.DBSYSTEMVALUES_POSTGRESQL = exports.DBSYSTEMVALUES_DB2 = exports.DBSYSTEMVALUES_ORACLE = exports.DBSYSTEMVALUES_MYSQL = exports.DBSYSTEMVALUES_MSSQL = exports.DBSYSTEMVALUES_OTHER_SQL = exports.SemanticAttributes = exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_ID = exports.SEMATTRS_MESSAGE_TYPE = exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = exports.SEMATTRS_RPC_JSONRPC_VERSION = exports.SEMATTRS_RPC_GRPC_STATUS_CODE = exports.SEMATTRS_RPC_METHOD = exports.SEMATTRS_RPC_SERVICE = exports.SEMATTRS_RPC_SYSTEM = exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = exports.SEMATTRS_MESSAGING_CONSUMER_ID = exports.SEMATTRS_MESSAGING_OPERATION = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = exports.SEMATTRS_MESSAGING_CONVERSATION_ID = exports.SEMATTRS_MESSAGING_MESSAGE_ID = exports.SEMATTRS_MESSAGING_URL = exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = exports.SEMATTRS_MESSAGING_PROTOCOL = exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = void 0; - exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = exports.FaasDocumentOperationValues = exports.FAASDOCUMENTOPERATIONVALUES_DELETE = exports.FAASDOCUMENTOPERATIONVALUES_EDIT = exports.FAASDOCUMENTOPERATIONVALUES_INSERT = exports.FaasTriggerValues = exports.FAASTRIGGERVALUES_OTHER = exports.FAASTRIGGERVALUES_TIMER = exports.FAASTRIGGERVALUES_PUBSUB = exports.FAASTRIGGERVALUES_HTTP = exports.FAASTRIGGERVALUES_DATASOURCE = exports.DbCassandraConsistencyLevelValues = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = exports.DbSystemValues = exports.DBSYSTEMVALUES_COCKROACHDB = exports.DBSYSTEMVALUES_MEMCACHED = exports.DBSYSTEMVALUES_ELASTICSEARCH = exports.DBSYSTEMVALUES_GEODE = exports.DBSYSTEMVALUES_NEO4J = exports.DBSYSTEMVALUES_DYNAMODB = exports.DBSYSTEMVALUES_COSMOSDB = exports.DBSYSTEMVALUES_COUCHDB = exports.DBSYSTEMVALUES_COUCHBASE = exports.DBSYSTEMVALUES_REDIS = exports.DBSYSTEMVALUES_MONGODB = exports.DBSYSTEMVALUES_HBASE = exports.DBSYSTEMVALUES_CASSANDRA = exports.DBSYSTEMVALUES_COLDFUSION = exports.DBSYSTEMVALUES_H2 = exports.DBSYSTEMVALUES_VERTICA = exports.DBSYSTEMVALUES_TERADATA = exports.DBSYSTEMVALUES_SYBASE = exports.DBSYSTEMVALUES_SQLITE = exports.DBSYSTEMVALUES_POINTBASE = exports.DBSYSTEMVALUES_PERVASIVE = exports.DBSYSTEMVALUES_NETEZZA = exports.DBSYSTEMVALUES_MARIADB = exports.DBSYSTEMVALUES_INTERBASE = exports.DBSYSTEMVALUES_INSTANTDB = exports.DBSYSTEMVALUES_INFORMIX = void 0; - exports.MESSAGINGOPERATIONVALUES_RECEIVE = exports.MessagingDestinationKindValues = exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = exports.HttpFlavorValues = exports.HTTPFLAVORVALUES_QUIC = exports.HTTPFLAVORVALUES_SPDY = exports.HTTPFLAVORVALUES_HTTP_2_0 = exports.HTTPFLAVORVALUES_HTTP_1_1 = exports.HTTPFLAVORVALUES_HTTP_1_0 = exports.NetHostConnectionSubtypeValues = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = exports.NetHostConnectionTypeValues = exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = exports.NETHOSTCONNECTIONTYPEVALUES_CELL = exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = exports.NetTransportValues = exports.NETTRANSPORTVALUES_OTHER = exports.NETTRANSPORTVALUES_INPROC = exports.NETTRANSPORTVALUES_PIPE = exports.NETTRANSPORTVALUES_UNIX = exports.NETTRANSPORTVALUES_IP = exports.NETTRANSPORTVALUES_IP_UDP = exports.NETTRANSPORTVALUES_IP_TCP = exports.FaasInvokedProviderValues = exports.FAASINVOKEDPROVIDERVALUES_GCP = exports.FAASINVOKEDPROVIDERVALUES_AZURE = exports.FAASINVOKEDPROVIDERVALUES_AWS = void 0; - exports.MessageTypeValues = exports.MESSAGETYPEVALUES_RECEIVED = exports.MESSAGETYPEVALUES_SENT = exports.RpcGrpcStatusCodeValues = exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = exports.RPCGRPCSTATUSCODEVALUES_ABORTED = exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = exports.RPCGRPCSTATUSCODEVALUES_OK = exports.MessagingOperationValues = exports.MESSAGINGOPERATIONVALUES_PROCESS = void 0; - var utils_1 = require_utils(); - var TMP_AWS_LAMBDA_INVOKED_ARN = "aws.lambda.invoked_arn"; - var TMP_DB_SYSTEM = "db.system"; - var TMP_DB_CONNECTION_STRING = "db.connection_string"; - var TMP_DB_USER = "db.user"; - var TMP_DB_JDBC_DRIVER_CLASSNAME = "db.jdbc.driver_classname"; - var TMP_DB_NAME = "db.name"; - var TMP_DB_STATEMENT = "db.statement"; - var TMP_DB_OPERATION = "db.operation"; - var TMP_DB_MSSQL_INSTANCE_NAME = "db.mssql.instance_name"; - var TMP_DB_CASSANDRA_KEYSPACE = "db.cassandra.keyspace"; - var TMP_DB_CASSANDRA_PAGE_SIZE = "db.cassandra.page_size"; - var TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = "db.cassandra.consistency_level"; - var TMP_DB_CASSANDRA_TABLE = "db.cassandra.table"; - var TMP_DB_CASSANDRA_IDEMPOTENCE = "db.cassandra.idempotence"; - var TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = "db.cassandra.speculative_execution_count"; - var TMP_DB_CASSANDRA_COORDINATOR_ID = "db.cassandra.coordinator.id"; - var TMP_DB_CASSANDRA_COORDINATOR_DC = "db.cassandra.coordinator.dc"; - var TMP_DB_HBASE_NAMESPACE = "db.hbase.namespace"; - var TMP_DB_REDIS_DATABASE_INDEX = "db.redis.database_index"; - var TMP_DB_MONGODB_COLLECTION = "db.mongodb.collection"; - var TMP_DB_SQL_TABLE = "db.sql.table"; - var TMP_EXCEPTION_TYPE = "exception.type"; - var TMP_EXCEPTION_MESSAGE = "exception.message"; - var TMP_EXCEPTION_STACKTRACE = "exception.stacktrace"; - var TMP_EXCEPTION_ESCAPED = "exception.escaped"; - var TMP_FAAS_TRIGGER = "faas.trigger"; - var TMP_FAAS_EXECUTION = "faas.execution"; - var TMP_FAAS_DOCUMENT_COLLECTION = "faas.document.collection"; - var TMP_FAAS_DOCUMENT_OPERATION = "faas.document.operation"; - var TMP_FAAS_DOCUMENT_TIME = "faas.document.time"; - var TMP_FAAS_DOCUMENT_NAME = "faas.document.name"; - var TMP_FAAS_TIME = "faas.time"; - var TMP_FAAS_CRON = "faas.cron"; - var TMP_FAAS_COLDSTART = "faas.coldstart"; - var TMP_FAAS_INVOKED_NAME = "faas.invoked_name"; - var TMP_FAAS_INVOKED_PROVIDER = "faas.invoked_provider"; - var TMP_FAAS_INVOKED_REGION = "faas.invoked_region"; - var TMP_NET_TRANSPORT = "net.transport"; - var TMP_NET_PEER_IP = "net.peer.ip"; - var TMP_NET_PEER_PORT = "net.peer.port"; - var TMP_NET_PEER_NAME = "net.peer.name"; - var TMP_NET_HOST_IP = "net.host.ip"; - var TMP_NET_HOST_PORT = "net.host.port"; - var TMP_NET_HOST_NAME = "net.host.name"; - var TMP_NET_HOST_CONNECTION_TYPE = "net.host.connection.type"; - var TMP_NET_HOST_CONNECTION_SUBTYPE = "net.host.connection.subtype"; - var TMP_NET_HOST_CARRIER_NAME = "net.host.carrier.name"; - var TMP_NET_HOST_CARRIER_MCC = "net.host.carrier.mcc"; - var TMP_NET_HOST_CARRIER_MNC = "net.host.carrier.mnc"; - var TMP_NET_HOST_CARRIER_ICC = "net.host.carrier.icc"; - var TMP_PEER_SERVICE = "peer.service"; - var TMP_ENDUSER_ID = "enduser.id"; - var TMP_ENDUSER_ROLE = "enduser.role"; - var TMP_ENDUSER_SCOPE = "enduser.scope"; - var TMP_THREAD_ID = "thread.id"; - var TMP_THREAD_NAME = "thread.name"; - var TMP_CODE_FUNCTION = "code.function"; - var TMP_CODE_NAMESPACE = "code.namespace"; - var TMP_CODE_FILEPATH = "code.filepath"; - var TMP_CODE_LINENO = "code.lineno"; - var TMP_HTTP_METHOD = "http.method"; - var TMP_HTTP_URL = "http.url"; - var TMP_HTTP_TARGET = "http.target"; - var TMP_HTTP_HOST = "http.host"; - var TMP_HTTP_SCHEME = "http.scheme"; - var TMP_HTTP_STATUS_CODE = "http.status_code"; - var TMP_HTTP_FLAVOR = "http.flavor"; - var TMP_HTTP_USER_AGENT = "http.user_agent"; - var TMP_HTTP_REQUEST_CONTENT_LENGTH = "http.request_content_length"; - var TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = "http.request_content_length_uncompressed"; - var TMP_HTTP_RESPONSE_CONTENT_LENGTH = "http.response_content_length"; - var TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = "http.response_content_length_uncompressed"; - var TMP_HTTP_SERVER_NAME = "http.server_name"; - var TMP_HTTP_ROUTE = "http.route"; - var TMP_HTTP_CLIENT_IP = "http.client_ip"; - var TMP_AWS_DYNAMODB_TABLE_NAMES = "aws.dynamodb.table_names"; - var TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = "aws.dynamodb.consumed_capacity"; - var TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = "aws.dynamodb.item_collection_metrics"; - var TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = "aws.dynamodb.provisioned_read_capacity"; - var TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = "aws.dynamodb.provisioned_write_capacity"; - var TMP_AWS_DYNAMODB_CONSISTENT_READ = "aws.dynamodb.consistent_read"; - var TMP_AWS_DYNAMODB_PROJECTION = "aws.dynamodb.projection"; - var TMP_AWS_DYNAMODB_LIMIT = "aws.dynamodb.limit"; - var TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = "aws.dynamodb.attributes_to_get"; - var TMP_AWS_DYNAMODB_INDEX_NAME = "aws.dynamodb.index_name"; - var TMP_AWS_DYNAMODB_SELECT = "aws.dynamodb.select"; - var TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = "aws.dynamodb.global_secondary_indexes"; - var TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = "aws.dynamodb.local_secondary_indexes"; - var TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = "aws.dynamodb.exclusive_start_table"; - var TMP_AWS_DYNAMODB_TABLE_COUNT = "aws.dynamodb.table_count"; - var TMP_AWS_DYNAMODB_SCAN_FORWARD = "aws.dynamodb.scan_forward"; - var TMP_AWS_DYNAMODB_SEGMENT = "aws.dynamodb.segment"; - var TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = "aws.dynamodb.total_segments"; - var TMP_AWS_DYNAMODB_COUNT = "aws.dynamodb.count"; - var TMP_AWS_DYNAMODB_SCANNED_COUNT = "aws.dynamodb.scanned_count"; - var TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = "aws.dynamodb.attribute_definitions"; - var TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = "aws.dynamodb.global_secondary_index_updates"; - var TMP_MESSAGING_SYSTEM = "messaging.system"; - var TMP_MESSAGING_DESTINATION = "messaging.destination"; - var TMP_MESSAGING_DESTINATION_KIND = "messaging.destination_kind"; - var TMP_MESSAGING_TEMP_DESTINATION = "messaging.temp_destination"; - var TMP_MESSAGING_PROTOCOL = "messaging.protocol"; - var TMP_MESSAGING_PROTOCOL_VERSION = "messaging.protocol_version"; - var TMP_MESSAGING_URL = "messaging.url"; - var TMP_MESSAGING_MESSAGE_ID = "messaging.message_id"; - var TMP_MESSAGING_CONVERSATION_ID = "messaging.conversation_id"; - var TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = "messaging.message_payload_size_bytes"; - var TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = "messaging.message_payload_compressed_size_bytes"; - var TMP_MESSAGING_OPERATION = "messaging.operation"; - var TMP_MESSAGING_CONSUMER_ID = "messaging.consumer_id"; - var TMP_MESSAGING_RABBITMQ_ROUTING_KEY = "messaging.rabbitmq.routing_key"; - var TMP_MESSAGING_KAFKA_MESSAGE_KEY = "messaging.kafka.message_key"; - var TMP_MESSAGING_KAFKA_CONSUMER_GROUP = "messaging.kafka.consumer_group"; - var TMP_MESSAGING_KAFKA_CLIENT_ID = "messaging.kafka.client_id"; - var TMP_MESSAGING_KAFKA_PARTITION = "messaging.kafka.partition"; - var TMP_MESSAGING_KAFKA_TOMBSTONE = "messaging.kafka.tombstone"; - var TMP_RPC_SYSTEM = "rpc.system"; - var TMP_RPC_SERVICE = "rpc.service"; - var TMP_RPC_METHOD = "rpc.method"; - var TMP_RPC_GRPC_STATUS_CODE = "rpc.grpc.status_code"; - var TMP_RPC_JSONRPC_VERSION = "rpc.jsonrpc.version"; - var TMP_RPC_JSONRPC_REQUEST_ID = "rpc.jsonrpc.request_id"; - var TMP_RPC_JSONRPC_ERROR_CODE = "rpc.jsonrpc.error_code"; - var TMP_RPC_JSONRPC_ERROR_MESSAGE = "rpc.jsonrpc.error_message"; - var TMP_MESSAGE_TYPE = "message.type"; - var TMP_MESSAGE_ID = "message.id"; - var TMP_MESSAGE_COMPRESSED_SIZE = "message.compressed_size"; - var TMP_MESSAGE_UNCOMPRESSED_SIZE = "message.uncompressed_size"; - /** - * The full invoked ARN as provided on the `Context` passed to the function (`Lambda-Runtime-Invoked-Function-Arn` header on the `/runtime/invocation/next` applicable). - * - * Note: This may be different from `faas.id` if an alias is involved. - * - * @deprecated Use ATTR_AWS_LAMBDA_INVOKED_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use ATTR_DB_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM; - /** - * The connection string used to connect to the database. It is recommended to remove embedded credentials. - * - * @deprecated Use ATTR_DB_CONNECTION_STRING in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING; - /** - * Username for accessing the database. - * - * @deprecated Use ATTR_DB_USER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_USER = TMP_DB_USER; - /** - * The fully-qualified class name of the [Java Database Connectivity (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver used to connect. - * - * @deprecated Use ATTR_DB_JDBC_DRIVER_CLASSNAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME; - /** - * If no [tech-specific attribute](#call-level-attributes-for-specific-technologies) is defined, this attribute is used to report the name of the database being accessed. For commands that switch the database, this should be set to the target database (even if the command fails). - * - * Note: In some SQL databases, the database name to be used is called "schema name". - * - * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_NAME = TMP_DB_NAME; - /** - * The database statement being executed. - * - * Note: The value may be sanitized to exclude sensitive information. - * - * @deprecated Use ATTR_DB_STATEMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT; - /** - * The name of the operation being executed, e.g. the [MongoDB command name](https://docs.mongodb.com/manual/reference/command/#database-operations) such as `findAndModify`, or the SQL keyword. - * - * Note: When setting this to an SQL keyword, it is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if the operation name is provided by the library being instrumented. If the SQL statement has an ambiguous operation, or performs more than one operation, this value may be omitted. - * - * @deprecated Use ATTR_DB_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_OPERATION = TMP_DB_OPERATION; - /** - * The Microsoft SQL Server [instance name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) connecting to. This name is used to determine the port of a named instance. - * - * Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no longer required (but still recommended if non-standard). - * - * @deprecated Use ATTR_DB_MSSQL_INSTANCE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME; - /** - * The name of the keyspace being accessed. To be used instead of the generic `db.name` attribute. - * - * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE; - /** - * The fetch size used for paging, i.e. how many rows will be returned at once. - * - * @deprecated Use ATTR_DB_CASSANDRA_PAGE_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use ATTR_DB_CASSANDRA_CONSISTENCY_LEVEL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL; - /** - * The name of the primary table that the operation is acting upon, including the schema name (if applicable). - * - * Note: This mirrors the db.sql.table attribute but references cassandra rather than sql. It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. - * - * @deprecated Use ATTR_DB_CASSANDRA_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE; - /** - * Whether or not the query is idempotent. - * - * @deprecated Use ATTR_DB_CASSANDRA_IDEMPOTENCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE; - /** - * The number of times a query was speculatively executed. Not set or `0` if the query was not executed speculatively. - * - * @deprecated Use ATTR_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT; - /** - * The ID of the coordinating node for a query. - * - * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID; - /** - * The data center of the coordinating node for a query. - * - * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_DC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = TMP_DB_CASSANDRA_COORDINATOR_DC; - /** - * The [HBase namespace](https://hbase.apache.org/book.html#_namespace) being accessed. To be used instead of the generic `db.name` attribute. - * - * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE; - /** - * The index of the database being accessed as used in the [`SELECT` command](https://redis.io/commands/select), provided as an integer. To be used instead of the generic `db.name` attribute. - * - * @deprecated Use ATTR_DB_REDIS_DATABASE_INDEX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX; - /** - * The collection being accessed within the database stated in `db.name`. - * - * @deprecated Use ATTR_DB_MONGODB_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION; - /** - * The name of the primary table that the operation is acting upon, including the schema name (if applicable). - * - * Note: It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. - * - * @deprecated Use ATTR_DB_SQL_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE; - /** - * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. - * - * @deprecated Use ATTR_EXCEPTION_TYPE. - */ - exports.SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE; - /** - * The exception message. - * - * @deprecated Use ATTR_EXCEPTION_MESSAGE. - */ - exports.SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE; - /** - * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. - * - * @deprecated Use ATTR_EXCEPTION_STACKTRACE. - */ - exports.SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE; - /** - * SHOULD be set to true if the exception event is recorded at a point where it is known that the exception is escaping the scope of the span. - * - * Note: An exception is considered to have escaped (or left) the scope of a span, - if that span is ended while the exception is still logically "in flight". - This may be actually "in flight" in some languages (e.g. if the exception - is passed to a Context manager's `__exit__` method in Python) but will - usually be caught at the point of recording the exception in most languages. - - It is usually not possible to determine at the point where an exception is thrown - whether it will escape the scope of a span. - However, it is trivial to know that an exception - will escape, if one checks for an active exception just before ending the span, - as done in the [example above](#exception-end-example). - - It follows that an exception may still escape the scope of the span - even if the `exception.escaped` attribute was not set or set to false, - since the event might have been recorded at a time where it was not - clear whether the exception will escape. - * - * @deprecated Use ATTR_EXCEPTION_ESCAPED. - */ - exports.SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use ATTR_FAAS_TRIGGER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER; - /** - * The execution ID of the current function execution. - * - * @deprecated Use ATTR_FAAS_INVOCATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION; - /** - * The name of the source on which the triggering operation was performed. For example, in Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the database name. - * - * @deprecated Use ATTR_FAAS_DOCUMENT_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION; - /** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use ATTR_FAAS_DOCUMENT_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION; - /** - * A string containing the time when the data was accessed in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - * - * @deprecated Use ATTR_FAAS_DOCUMENT_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME; - /** - * The document name/table subjected to the operation. For example, in Cloud Storage or S3 is the name of the file, and in Cosmos DB the table name. - * - * @deprecated Use ATTR_FAAS_DOCUMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME; - /** - * A string containing the function invocation time in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - * - * @deprecated Use ATTR_FAAS_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_TIME = TMP_FAAS_TIME; - /** - * A string containing the schedule period as [Cron Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). - * - * @deprecated Use ATTR_FAAS_CRON in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_CRON = TMP_FAAS_CRON; - /** - * A boolean that is true if the serverless function is executed for the first time (aka cold-start). - * - * @deprecated Use ATTR_FAAS_COLDSTART in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART; - /** - * The name of the invoked function. - * - * Note: SHOULD be equal to the `faas.name` resource attribute of the invoked function. - * - * @deprecated Use ATTR_FAAS_INVOKED_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use ATTR_FAAS_INVOKED_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER; - /** - * The cloud region of the invoked function. - * - * Note: SHOULD be equal to the `cloud.region` resource attribute of the invoked function. - * - * @deprecated Use ATTR_FAAS_INVOKED_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION; - /** - * Transport protocol used. See note below. - * - * @deprecated Use ATTR_NET_TRANSPORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT; - /** - * Remote address of the peer (dotted decimal for IPv4 or [RFC5952](https://tools.ietf.org/html/rfc5952) for IPv6). - * - * @deprecated Use ATTR_NET_PEER_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP; - /** - * Remote port number. - * - * @deprecated Use ATTR_NET_PEER_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT; - /** - * Remote hostname or similar, see note below. - * - * @deprecated Use ATTR_NET_PEER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME; - /** - * Like `net.peer.ip` but for the host IP. Useful in case of a multi-IP host. - * - * @deprecated Use ATTR_NET_HOST_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP; - /** - * Like `net.peer.port` but for the host port. - * - * @deprecated Use ATTR_NET_HOST_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT; - /** - * Local hostname or similar, see note below. - * - * @deprecated Use ATTR_NET_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use ATTR_NETWORK_CONNECTION_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use ATTR_NETWORK_CONNECTION_SUBTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = TMP_NET_HOST_CONNECTION_SUBTYPE; - /** - * The name of the mobile carrier. - * - * @deprecated Use ATTR_NETWORK_CARRIER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME; - /** - * The mobile carrier country code. - * - * @deprecated Use ATTR_NETWORK_CARRIER_MCC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC; - /** - * The mobile carrier network code. - * - * @deprecated Use ATTR_NETWORK_CARRIER_MNC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC; - /** - * The ISO 3166-1 alpha-2 2-character country code associated with the mobile carrier network. - * - * @deprecated Use ATTR_NETWORK_CARRIER_ICC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC; - /** - * The [`service.name`](../../resource/semantic_conventions/README.md#service) of the remote service. SHOULD be equal to the actual `service.name` resource attribute of the remote service if any. - * - * @deprecated Use ATTR_PEER_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE; - /** - * Username or client_id extracted from the access token or [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in the inbound request from outside the system. - * - * @deprecated Use ATTR_ENDUSER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID; - /** - * Actual/assumed role the client is making the request under extracted from token or application security context. - * - * @deprecated Use ATTR_ENDUSER_ROLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE; - /** - * Scopes or granted authorities the client currently possesses extracted from token or application security context. The value would come from the scope associated with an [OAuth 2.0 Access Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute value in a [SAML 2.0 Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). - * - * @deprecated Use ATTR_ENDUSER_SCOPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE; - /** - * Current "managed" thread ID (as opposed to OS thread ID). - * - * @deprecated Use ATTR_THREAD_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_THREAD_ID = TMP_THREAD_ID; - /** - * Current thread name. - * - * @deprecated Use ATTR_THREAD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_THREAD_NAME = TMP_THREAD_NAME; - /** - * The method or function name, or equivalent (usually rightmost part of the code unit's name). - * - * @deprecated Use ATTR_CODE_FUNCTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION; - /** - * The "namespace" within which `code.function` is defined. Usually the qualified class or module name, such that `code.namespace` + some separator + `code.function` form a unique identifier for the code unit. - * - * @deprecated Use ATTR_CODE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE; - /** - * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). - * - * @deprecated Use ATTR_CODE_FILEPATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH; - /** - * The line number in `code.filepath` best representing the operation. It SHOULD point within the code unit named in `code.function`. - * - * @deprecated Use ATTR_CODE_LINENO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_CODE_LINENO = TMP_CODE_LINENO; - /** - * HTTP request method. - * - * @deprecated Use ATTR_HTTP_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD; - /** - * Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is not transmitted over HTTP, but if it is known, it should be included nevertheless. - * - * Note: `http.url` MUST NOT contain credentials passed via URL in form of `https://username:password@www.example.com/`. In such case the attribute's value should be `https://www.example.com/`. - * - * @deprecated Use ATTR_HTTP_URL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_URL = TMP_HTTP_URL; - /** - * The full request target as passed in a HTTP request line or equivalent. - * - * @deprecated Use ATTR_HTTP_TARGET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET; - /** - * The value of the [HTTP host header](https://tools.ietf.org/html/rfc7230#section-5.4). An empty Host header should also be reported, see note. - * - * Note: When the header is present but empty the attribute SHOULD be set to the empty string. Note that this is a valid situation that is expected in certain cases, according the aforementioned [section of RFC 7230](https://tools.ietf.org/html/rfc7230#section-5.4). When the header is not set the attribute MUST NOT be set. - * - * @deprecated Use ATTR_HTTP_HOST in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_HOST = TMP_HTTP_HOST; - /** - * The URI scheme identifying the used protocol. - * - * @deprecated Use ATTR_HTTP_SCHEME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME; - /** - * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6). - * - * @deprecated Use ATTR_HTTP_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use ATTR_HTTP_FLAVOR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR; - /** - * Value of the [HTTP User-Agent](https://tools.ietf.org/html/rfc7231#section-5.5.3) header sent by the client. - * - * @deprecated Use ATTR_HTTP_USER_AGENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT; - /** - * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. - * - * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = TMP_HTTP_REQUEST_CONTENT_LENGTH; - /** - * The size of the uncompressed request payload body after transport decoding. Not set if transport encoding not used. - * - * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED; - /** - * The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. - * - * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH; - /** - * The size of the uncompressed response payload body after transport decoding. Not set if transport encoding not used. - * - * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED; - /** - * The primary server name of the matched virtual host. This should be obtained via configuration. If no such configuration can be obtained, this attribute MUST NOT be set ( `net.host.name` should be used instead). - * - * Note: `http.url` is usually not readily available on the server side but would have to be assembled in a cumbersome and sometimes lossy process from other information (see e.g. open-telemetry/opentelemetry-python/pull/148). It is thus preferred to supply the raw data that is available. - * - * @deprecated Use ATTR_HTTP_SERVER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME; - /** - * The matched route (path template). - * - * @deprecated Use ATTR_HTTP_ROUTE. - */ - exports.SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE; - /** - * The IP address of the original client behind all proxies, if known (e.g. from [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)). - * - * Note: This is not necessarily the same as `net.peer.ip`, which would - identify the network-level peer, which may be a proxy. - - This attribute should be set when a source of information different - from the one used for `net.peer.ip`, is available even if that other - source just confirms the same value as `net.peer.ip`. - Rationale: For `net.peer.ip`, one typically does not know if it - comes from a proxy, reverse proxy, or the actual client. Setting - `http.client_ip` when it's the same as `net.peer.ip` means that - one is at least somewhat confident that the address is not that of - the closest proxy. - * - * @deprecated Use ATTR_HTTP_CLIENT_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP; - /** - * The keys in the `RequestItems` object field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES; - /** - * The JSON-serialized value of each item in the `ConsumedCapacity` response field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_CONSUMED_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = TMP_AWS_DYNAMODB_CONSUMED_CAPACITY; - /** - * The JSON-serialized value of the `ItemCollectionMetrics` response field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_ITEM_COLLECTION_METRICS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS; - /** - * The value of the `ProvisionedThroughput.ReadCapacityUnits` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY; - /** - * The value of the `ProvisionedThroughput.WriteCapacityUnits` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY; - /** - * The value of the `ConsistentRead` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_CONSISTENT_READ in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = TMP_AWS_DYNAMODB_CONSISTENT_READ; - /** - * The value of the `ProjectionExpression` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_PROJECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION; - /** - * The value of the `Limit` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_LIMIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT; - /** - * The value of the `AttributesToGet` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTES_TO_GET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET; - /** - * The value of the `IndexName` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_INDEX_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME; - /** - * The value of the `Select` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_SELECT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT; - /** - * The JSON-serialized value of each item of the `GlobalSecondaryIndexes` request field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES; - /** - * The JSON-serialized value of each item of the `LocalSecondaryIndexes` request field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES; - /** - * The value of the `ExclusiveStartTableName` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_EXCLUSIVE_START_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE; - /** - * The the number of items in the `TableNames` response parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT; - /** - * The value of the `ScanIndexForward` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_SCAN_FORWARD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD; - /** - * The value of the `Segment` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_SEGMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT; - /** - * The value of the `TotalSegments` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_TOTAL_SEGMENTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = TMP_AWS_DYNAMODB_TOTAL_SEGMENTS; - /** - * The value of the `Count` response parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT; - /** - * The value of the `ScannedCount` response parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_SCANNED_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = TMP_AWS_DYNAMODB_SCANNED_COUNT; - /** - * The JSON-serialized value of each item in the `AttributeDefinitions` request field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS; - /** - * The JSON-serialized value of each item in the the `GlobalSecondaryIndexUpdates` request field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES; - /** - * A string identifying the messaging system. - * - * @deprecated Use ATTR_MESSAGING_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM; - /** - * The message destination name. This might be equal to the span name but is required nevertheless. - * - * @deprecated Use ATTR_MESSAGING_DESTINATION_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION; - /** - * The kind of message destination. - * - * @deprecated Removed in semconv v1.20.0. - */ - exports.SEMATTRS_MESSAGING_DESTINATION_KIND = TMP_MESSAGING_DESTINATION_KIND; - /** - * A boolean that is true if the message destination is temporary. - * - * @deprecated Use ATTR_MESSAGING_DESTINATION_TEMPORARY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = TMP_MESSAGING_TEMP_DESTINATION; - /** - * The name of the transport protocol. - * - * @deprecated Use ATTR_NETWORK_PROTOCOL_NAME. - */ - exports.SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL; - /** - * The version of the transport protocol. - * - * @deprecated Use ATTR_NETWORK_PROTOCOL_VERSION. - */ - exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = TMP_MESSAGING_PROTOCOL_VERSION; - /** - * Connection string. - * - * @deprecated Removed in semconv v1.17.0. - */ - exports.SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL; - /** - * A value used by the messaging system as an identifier for the message, represented as a string. - * - * @deprecated Use ATTR_MESSAGING_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID; - /** - * The [conversation ID](#conversations) identifying the conversation to which the message belongs, represented as a string. Sometimes called "Correlation ID". - * - * @deprecated Use ATTR_MESSAGING_MESSAGE_CONVERSATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID; - /** - * The (uncompressed) size of the message payload in bytes. Also use this attribute if it is unknown whether the compressed or uncompressed payload size is reported. - * - * @deprecated Use ATTR_MESSAGING_MESSAGE_BODY_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES; - /** - * The compressed size of the message payload in bytes. - * - * @deprecated Removed in semconv v1.22.0. - */ - exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES; - /** - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * - * @deprecated Use ATTR_MESSAGING_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION; - /** - * The identifier for the consumer receiving a message. For Kafka, set it to `{messaging.kafka.consumer_group} - {messaging.kafka.client_id}`, if both are present, or only `messaging.kafka.consumer_group`. For brokers, such as RabbitMQ and Artemis, set it to the `client_id` of the client consuming the message. - * - * @deprecated Removed in semconv v1.21.0. - */ - exports.SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID; - /** - * RabbitMQ message routing key. - * - * @deprecated Use ATTR_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = TMP_MESSAGING_RABBITMQ_ROUTING_KEY; - /** - * Message keys in Kafka are used for grouping alike messages to ensure they're processed on the same partition. They differ from `messaging.message_id` in that they're not unique. If the key is `null`, the attribute MUST NOT be set. - * - * Note: If the key type is not string, it's string representation has to be supplied for the attribute. If the key has no unambiguous, canonical string form, don't include its value. - * - * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = TMP_MESSAGING_KAFKA_MESSAGE_KEY; - /** - * Name of the Kafka Consumer Group that is handling the message. Only applies to consumers, not producers. - * - * @deprecated Use ATTR_MESSAGING_KAFKA_CONSUMER_GROUP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = TMP_MESSAGING_KAFKA_CONSUMER_GROUP; - /** - * Client Id for the Consumer or Producer that is handling the message. - * - * @deprecated Use ATTR_MESSAGING_CLIENT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID; - /** - * Partition the message is sent to. - * - * @deprecated Use ATTR_MESSAGING_KAFKA_DESTINATION_PARTITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION; - /** - * A boolean that is true if the message is a tombstone. - * - * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE; - /** - * A string identifying the remoting system. - * - * @deprecated Use ATTR_RPC_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM; - /** - * The full (logical) name of the service being called, including its package name, if applicable. - * - * Note: This is the logical name of the service from the RPC interface perspective, which can be different from the name of any implementing class. The `code.namespace` attribute may be used to store the latter (despite the attribute name, it may include a class name; e.g., class with method actually executing the call on the server side, RPC client stub class on the client side). - * - * @deprecated Use ATTR_RPC_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE; - /** - * The name of the (logical) method being called, must be equal to the $method part in the span name. - * - * Note: This is the logical name of the method from the RPC interface perspective, which can be different from the name of any implementing method/function. The `code.function` attribute may be used to store the latter (e.g., method actually executing the call on the server side, RPC client stub method on the client side). - * - * @deprecated Use ATTR_RPC_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_METHOD = TMP_RPC_METHOD; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use ATTR_RPC_GRPC_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE; - /** - * Protocol version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 does not specify this, the value can be omitted. - * - * @deprecated Use ATTR_RPC_JSONRPC_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION; - /** - * `id` property of request or response. Since protocol allows id to be int, string, `null` or missing (for notifications), value is expected to be cast to string for simplicity. Use empty string in case of `null` value. Omit entirely if this is a notification. - * - * @deprecated Use ATTR_RPC_JSONRPC_REQUEST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID; - /** - * `error.code` property of response if it is an error response. - * - * @deprecated Use ATTR_RPC_JSONRPC_ERROR_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE; - /** - * `error.message` property of response if it is an error response. - * - * @deprecated Use ATTR_RPC_JSONRPC_ERROR_MESSAGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE; - /** - * Whether this is a received or sent message. - * - * @deprecated Use ATTR_MESSAGE_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE; - /** - * MUST be calculated as two different counters starting from `1` one for sent messages and one for received message. - * - * Note: This way we guarantee that the values will be consistent between different implementations. - * - * @deprecated Use ATTR_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID; - /** - * Compressed size of the message in bytes. - * - * @deprecated Use ATTR_MESSAGE_COMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE; - /** - * Uncompressed size of the message in bytes. - * - * @deprecated Use ATTR_MESSAGE_UNCOMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE; - /** - * Create exported Value Map for SemanticAttributes values - * @deprecated Use the SEMATTRS_XXXXX constants rather than the SemanticAttributes.XXXXX for bundle minification - */ - exports.SemanticAttributes = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_AWS_LAMBDA_INVOKED_ARN, - TMP_DB_SYSTEM, - TMP_DB_CONNECTION_STRING, - TMP_DB_USER, - TMP_DB_JDBC_DRIVER_CLASSNAME, - TMP_DB_NAME, - TMP_DB_STATEMENT, - TMP_DB_OPERATION, - TMP_DB_MSSQL_INSTANCE_NAME, - TMP_DB_CASSANDRA_KEYSPACE, - TMP_DB_CASSANDRA_PAGE_SIZE, - TMP_DB_CASSANDRA_CONSISTENCY_LEVEL, - TMP_DB_CASSANDRA_TABLE, - TMP_DB_CASSANDRA_IDEMPOTENCE, - TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, - TMP_DB_CASSANDRA_COORDINATOR_ID, - TMP_DB_CASSANDRA_COORDINATOR_DC, - TMP_DB_HBASE_NAMESPACE, - TMP_DB_REDIS_DATABASE_INDEX, - TMP_DB_MONGODB_COLLECTION, - TMP_DB_SQL_TABLE, - TMP_EXCEPTION_TYPE, - TMP_EXCEPTION_MESSAGE, - TMP_EXCEPTION_STACKTRACE, - TMP_EXCEPTION_ESCAPED, - TMP_FAAS_TRIGGER, - TMP_FAAS_EXECUTION, - TMP_FAAS_DOCUMENT_COLLECTION, - TMP_FAAS_DOCUMENT_OPERATION, - TMP_FAAS_DOCUMENT_TIME, - TMP_FAAS_DOCUMENT_NAME, - TMP_FAAS_TIME, - TMP_FAAS_CRON, - TMP_FAAS_COLDSTART, - TMP_FAAS_INVOKED_NAME, - TMP_FAAS_INVOKED_PROVIDER, - TMP_FAAS_INVOKED_REGION, - TMP_NET_TRANSPORT, - TMP_NET_PEER_IP, - TMP_NET_PEER_PORT, - TMP_NET_PEER_NAME, - TMP_NET_HOST_IP, - TMP_NET_HOST_PORT, - TMP_NET_HOST_NAME, - TMP_NET_HOST_CONNECTION_TYPE, - TMP_NET_HOST_CONNECTION_SUBTYPE, - TMP_NET_HOST_CARRIER_NAME, - TMP_NET_HOST_CARRIER_MCC, - TMP_NET_HOST_CARRIER_MNC, - TMP_NET_HOST_CARRIER_ICC, - TMP_PEER_SERVICE, - TMP_ENDUSER_ID, - TMP_ENDUSER_ROLE, - TMP_ENDUSER_SCOPE, - TMP_THREAD_ID, - TMP_THREAD_NAME, - TMP_CODE_FUNCTION, - TMP_CODE_NAMESPACE, - TMP_CODE_FILEPATH, - TMP_CODE_LINENO, - TMP_HTTP_METHOD, - TMP_HTTP_URL, - TMP_HTTP_TARGET, - TMP_HTTP_HOST, - TMP_HTTP_SCHEME, - TMP_HTTP_STATUS_CODE, - TMP_HTTP_FLAVOR, - TMP_HTTP_USER_AGENT, - TMP_HTTP_REQUEST_CONTENT_LENGTH, - TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, - TMP_HTTP_RESPONSE_CONTENT_LENGTH, - TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, - TMP_HTTP_SERVER_NAME, - TMP_HTTP_ROUTE, - TMP_HTTP_CLIENT_IP, - TMP_AWS_DYNAMODB_TABLE_NAMES, - TMP_AWS_DYNAMODB_CONSUMED_CAPACITY, - TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, - TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, - TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, - TMP_AWS_DYNAMODB_CONSISTENT_READ, - TMP_AWS_DYNAMODB_PROJECTION, - TMP_AWS_DYNAMODB_LIMIT, - TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET, - TMP_AWS_DYNAMODB_INDEX_NAME, - TMP_AWS_DYNAMODB_SELECT, - TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, - TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, - TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, - TMP_AWS_DYNAMODB_TABLE_COUNT, - TMP_AWS_DYNAMODB_SCAN_FORWARD, - TMP_AWS_DYNAMODB_SEGMENT, - TMP_AWS_DYNAMODB_TOTAL_SEGMENTS, - TMP_AWS_DYNAMODB_COUNT, - TMP_AWS_DYNAMODB_SCANNED_COUNT, - TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, - TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, - TMP_MESSAGING_SYSTEM, - TMP_MESSAGING_DESTINATION, - TMP_MESSAGING_DESTINATION_KIND, - TMP_MESSAGING_TEMP_DESTINATION, - TMP_MESSAGING_PROTOCOL, - TMP_MESSAGING_PROTOCOL_VERSION, - TMP_MESSAGING_URL, - TMP_MESSAGING_MESSAGE_ID, - TMP_MESSAGING_CONVERSATION_ID, - TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, - TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, - TMP_MESSAGING_OPERATION, - TMP_MESSAGING_CONSUMER_ID, - TMP_MESSAGING_RABBITMQ_ROUTING_KEY, - TMP_MESSAGING_KAFKA_MESSAGE_KEY, - TMP_MESSAGING_KAFKA_CONSUMER_GROUP, - TMP_MESSAGING_KAFKA_CLIENT_ID, - TMP_MESSAGING_KAFKA_PARTITION, - TMP_MESSAGING_KAFKA_TOMBSTONE, - TMP_RPC_SYSTEM, - TMP_RPC_SERVICE, - TMP_RPC_METHOD, - TMP_RPC_GRPC_STATUS_CODE, - TMP_RPC_JSONRPC_VERSION, - TMP_RPC_JSONRPC_REQUEST_ID, - TMP_RPC_JSONRPC_ERROR_CODE, - TMP_RPC_JSONRPC_ERROR_MESSAGE, - TMP_MESSAGE_TYPE, - TMP_MESSAGE_ID, - TMP_MESSAGE_COMPRESSED_SIZE, - TMP_MESSAGE_UNCOMPRESSED_SIZE - ]); - var TMP_DBSYSTEMVALUES_OTHER_SQL = "other_sql"; - var TMP_DBSYSTEMVALUES_MSSQL = "mssql"; - var TMP_DBSYSTEMVALUES_MYSQL = "mysql"; - var TMP_DBSYSTEMVALUES_ORACLE = "oracle"; - var TMP_DBSYSTEMVALUES_DB2 = "db2"; - var TMP_DBSYSTEMVALUES_POSTGRESQL = "postgresql"; - var TMP_DBSYSTEMVALUES_REDSHIFT = "redshift"; - var TMP_DBSYSTEMVALUES_HIVE = "hive"; - var TMP_DBSYSTEMVALUES_CLOUDSCAPE = "cloudscape"; - var TMP_DBSYSTEMVALUES_HSQLDB = "hsqldb"; - var TMP_DBSYSTEMVALUES_PROGRESS = "progress"; - var TMP_DBSYSTEMVALUES_MAXDB = "maxdb"; - var TMP_DBSYSTEMVALUES_HANADB = "hanadb"; - var TMP_DBSYSTEMVALUES_INGRES = "ingres"; - var TMP_DBSYSTEMVALUES_FIRSTSQL = "firstsql"; - var TMP_DBSYSTEMVALUES_EDB = "edb"; - var TMP_DBSYSTEMVALUES_CACHE = "cache"; - var TMP_DBSYSTEMVALUES_ADABAS = "adabas"; - var TMP_DBSYSTEMVALUES_FIREBIRD = "firebird"; - var TMP_DBSYSTEMVALUES_DERBY = "derby"; - var TMP_DBSYSTEMVALUES_FILEMAKER = "filemaker"; - var TMP_DBSYSTEMVALUES_INFORMIX = "informix"; - var TMP_DBSYSTEMVALUES_INSTANTDB = "instantdb"; - var TMP_DBSYSTEMVALUES_INTERBASE = "interbase"; - var TMP_DBSYSTEMVALUES_MARIADB = "mariadb"; - var TMP_DBSYSTEMVALUES_NETEZZA = "netezza"; - var TMP_DBSYSTEMVALUES_PERVASIVE = "pervasive"; - var TMP_DBSYSTEMVALUES_POINTBASE = "pointbase"; - var TMP_DBSYSTEMVALUES_SQLITE = "sqlite"; - var TMP_DBSYSTEMVALUES_SYBASE = "sybase"; - var TMP_DBSYSTEMVALUES_TERADATA = "teradata"; - var TMP_DBSYSTEMVALUES_VERTICA = "vertica"; - var TMP_DBSYSTEMVALUES_H2 = "h2"; - var TMP_DBSYSTEMVALUES_COLDFUSION = "coldfusion"; - var TMP_DBSYSTEMVALUES_CASSANDRA = "cassandra"; - var TMP_DBSYSTEMVALUES_HBASE = "hbase"; - var TMP_DBSYSTEMVALUES_MONGODB = "mongodb"; - var TMP_DBSYSTEMVALUES_REDIS = "redis"; - var TMP_DBSYSTEMVALUES_COUCHBASE = "couchbase"; - var TMP_DBSYSTEMVALUES_COUCHDB = "couchdb"; - var TMP_DBSYSTEMVALUES_COSMOSDB = "cosmosdb"; - var TMP_DBSYSTEMVALUES_DYNAMODB = "dynamodb"; - var TMP_DBSYSTEMVALUES_NEO4J = "neo4j"; - var TMP_DBSYSTEMVALUES_GEODE = "geode"; - var TMP_DBSYSTEMVALUES_ELASTICSEARCH = "elasticsearch"; - var TMP_DBSYSTEMVALUES_MEMCACHED = "memcached"; - var TMP_DBSYSTEMVALUES_COCKROACHDB = "cockroachdb"; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_OTHER_SQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MSSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MYSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_ORACLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_DB2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_POSTGRESQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_REDSHIFT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_CLOUDSCAPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HSQLDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_PROGRESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MAXDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HANADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INGRES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_FIRSTSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_EDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_CACHE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_ADABAS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_FIREBIRD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_DERBY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_FILEMAKER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INFORMIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INSTANTDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INTERBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MARIADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_NETEZZA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_PERVASIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_POINTBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_SQLITE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_SYBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_TERADATA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_VERTICA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_H2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COLDFUSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_CASSANDRA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MONGODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_REDIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COUCHBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COUCHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COSMOSDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_DYNAMODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_NEO4J in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_GEODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_ELASTICSEARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MEMCACHED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COCKROACHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB; - /** - * The constant map of values for DbSystemValues. - * @deprecated Use the DBSYSTEMVALUES_XXXXX constants rather than the DbSystemValues.XXXXX for bundle minification. - */ - exports.DbSystemValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_DBSYSTEMVALUES_OTHER_SQL, - TMP_DBSYSTEMVALUES_MSSQL, - TMP_DBSYSTEMVALUES_MYSQL, - TMP_DBSYSTEMVALUES_ORACLE, - TMP_DBSYSTEMVALUES_DB2, - TMP_DBSYSTEMVALUES_POSTGRESQL, - TMP_DBSYSTEMVALUES_REDSHIFT, - TMP_DBSYSTEMVALUES_HIVE, - TMP_DBSYSTEMVALUES_CLOUDSCAPE, - TMP_DBSYSTEMVALUES_HSQLDB, - TMP_DBSYSTEMVALUES_PROGRESS, - TMP_DBSYSTEMVALUES_MAXDB, - TMP_DBSYSTEMVALUES_HANADB, - TMP_DBSYSTEMVALUES_INGRES, - TMP_DBSYSTEMVALUES_FIRSTSQL, - TMP_DBSYSTEMVALUES_EDB, - TMP_DBSYSTEMVALUES_CACHE, - TMP_DBSYSTEMVALUES_ADABAS, - TMP_DBSYSTEMVALUES_FIREBIRD, - TMP_DBSYSTEMVALUES_DERBY, - TMP_DBSYSTEMVALUES_FILEMAKER, - TMP_DBSYSTEMVALUES_INFORMIX, - TMP_DBSYSTEMVALUES_INSTANTDB, - TMP_DBSYSTEMVALUES_INTERBASE, - TMP_DBSYSTEMVALUES_MARIADB, - TMP_DBSYSTEMVALUES_NETEZZA, - TMP_DBSYSTEMVALUES_PERVASIVE, - TMP_DBSYSTEMVALUES_POINTBASE, - TMP_DBSYSTEMVALUES_SQLITE, - TMP_DBSYSTEMVALUES_SYBASE, - TMP_DBSYSTEMVALUES_TERADATA, - TMP_DBSYSTEMVALUES_VERTICA, - TMP_DBSYSTEMVALUES_H2, - TMP_DBSYSTEMVALUES_COLDFUSION, - TMP_DBSYSTEMVALUES_CASSANDRA, - TMP_DBSYSTEMVALUES_HBASE, - TMP_DBSYSTEMVALUES_MONGODB, - TMP_DBSYSTEMVALUES_REDIS, - TMP_DBSYSTEMVALUES_COUCHBASE, - TMP_DBSYSTEMVALUES_COUCHDB, - TMP_DBSYSTEMVALUES_COSMOSDB, - TMP_DBSYSTEMVALUES_DYNAMODB, - TMP_DBSYSTEMVALUES_NEO4J, - TMP_DBSYSTEMVALUES_GEODE, - TMP_DBSYSTEMVALUES_ELASTICSEARCH, - TMP_DBSYSTEMVALUES_MEMCACHED, - TMP_DBSYSTEMVALUES_COCKROACHDB - ]); - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = "all"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = "each_quorum"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = "quorum"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = "local_quorum"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = "one"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = "two"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = "three"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = "local_one"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = "any"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = "serial"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = "local_serial"; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ALL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_EACH_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_TWO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_THREE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ANY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL; - /** - * The constant map of values for DbCassandraConsistencyLevelValues. - * @deprecated Use the DBCASSANDRACONSISTENCYLEVELVALUES_XXXXX constants rather than the DbCassandraConsistencyLevelValues.XXXXX for bundle minification. - */ - exports.DbCassandraConsistencyLevelValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL - ]); - var TMP_FAASTRIGGERVALUES_DATASOURCE = "datasource"; - var TMP_FAASTRIGGERVALUES_HTTP = "http"; - var TMP_FAASTRIGGERVALUES_PUBSUB = "pubsub"; - var TMP_FAASTRIGGERVALUES_TIMER = "timer"; - var TMP_FAASTRIGGERVALUES_OTHER = "other"; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_DATASOURCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_HTTP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_PUBSUB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_TIMER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER; - /** - * The constant map of values for FaasTriggerValues. - * @deprecated Use the FAASTRIGGERVALUES_XXXXX constants rather than the FaasTriggerValues.XXXXX for bundle minification. - */ - exports.FaasTriggerValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_FAASTRIGGERVALUES_DATASOURCE, - TMP_FAASTRIGGERVALUES_HTTP, - TMP_FAASTRIGGERVALUES_PUBSUB, - TMP_FAASTRIGGERVALUES_TIMER, - TMP_FAASTRIGGERVALUES_OTHER - ]); - var TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = "insert"; - var TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = "edit"; - var TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = "delete"; - /** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_INSERT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASDOCUMENTOPERATIONVALUES_INSERT = TMP_FAASDOCUMENTOPERATIONVALUES_INSERT; - /** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_EDIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASDOCUMENTOPERATIONVALUES_EDIT = TMP_FAASDOCUMENTOPERATIONVALUES_EDIT; - /** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_DELETE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASDOCUMENTOPERATIONVALUES_DELETE = TMP_FAASDOCUMENTOPERATIONVALUES_DELETE; - /** - * The constant map of values for FaasDocumentOperationValues. - * @deprecated Use the FAASDOCUMENTOPERATIONVALUES_XXXXX constants rather than the FaasDocumentOperationValues.XXXXX for bundle minification. - */ - exports.FaasDocumentOperationValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_FAASDOCUMENTOPERATIONVALUES_INSERT, - TMP_FAASDOCUMENTOPERATIONVALUES_EDIT, - TMP_FAASDOCUMENTOPERATIONVALUES_DELETE - ]); - var TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; - var TMP_FAASINVOKEDPROVIDERVALUES_AWS = "aws"; - var TMP_FAASINVOKEDPROVIDERVALUES_AZURE = "azure"; - var TMP_FAASINVOKEDPROVIDERVALUES_GCP = "gcp"; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASINVOKEDPROVIDERVALUES_AZURE = TMP_FAASINVOKEDPROVIDERVALUES_AZURE; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP; - /** - * The constant map of values for FaasInvokedProviderValues. - * @deprecated Use the FAASINVOKEDPROVIDERVALUES_XXXXX constants rather than the FaasInvokedProviderValues.XXXXX for bundle minification. - */ - exports.FaasInvokedProviderValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, - TMP_FAASINVOKEDPROVIDERVALUES_AWS, - TMP_FAASINVOKEDPROVIDERVALUES_AZURE, - TMP_FAASINVOKEDPROVIDERVALUES_GCP - ]); - var TMP_NETTRANSPORTVALUES_IP_TCP = "ip_tcp"; - var TMP_NETTRANSPORTVALUES_IP_UDP = "ip_udp"; - var TMP_NETTRANSPORTVALUES_IP = "ip"; - var TMP_NETTRANSPORTVALUES_UNIX = "unix"; - var TMP_NETTRANSPORTVALUES_PIPE = "pipe"; - var TMP_NETTRANSPORTVALUES_INPROC = "inproc"; - var TMP_NETTRANSPORTVALUES_OTHER = "other"; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_IP_TCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_IP_UDP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP; - /** - * Transport protocol used. See note below. - * - * @deprecated Removed in v1.21.0. - */ - exports.NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP; - /** - * Transport protocol used. See note below. - * - * @deprecated Removed in v1.21.0. - */ - exports.NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_PIPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_INPROC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER; - /** - * The constant map of values for NetTransportValues. - * @deprecated Use the NETTRANSPORTVALUES_XXXXX constants rather than the NetTransportValues.XXXXX for bundle minification. - */ - exports.NetTransportValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_NETTRANSPORTVALUES_IP_TCP, - TMP_NETTRANSPORTVALUES_IP_UDP, - TMP_NETTRANSPORTVALUES_IP, - TMP_NETTRANSPORTVALUES_UNIX, - TMP_NETTRANSPORTVALUES_PIPE, - TMP_NETTRANSPORTVALUES_INPROC, - TMP_NETTRANSPORTVALUES_OTHER - ]); - var TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = "wifi"; - var TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = "wired"; - var TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = "cell"; - var TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = "unavailable"; - var TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = "unknown"; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIFI in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIRED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_CELL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONTYPEVALUES_CELL = TMP_NETHOSTCONNECTIONTYPEVALUES_CELL; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN; - /** - * The constant map of values for NetHostConnectionTypeValues. - * @deprecated Use the NETHOSTCONNECTIONTYPEVALUES_XXXXX constants rather than the NetHostConnectionTypeValues.XXXXX for bundle minification. - */ - exports.NetHostConnectionTypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI, - TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED, - TMP_NETHOSTCONNECTIONTYPEVALUES_CELL, - TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, - TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN - ]); - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = "gprs"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = "edge"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = "umts"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = "cdma"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = "evdo_0"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = "evdo_a"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = "cdma2000_1xrtt"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = "hsdpa"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = "hsupa"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = "hspa"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = "iden"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = "evdo_b"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = "lte"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = "ehrpd"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = "hspap"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = "gsm"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = "td_scdma"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = "iwlan"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = "nr"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = "nrnsa"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = "lte_ca"; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GPRS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EDGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_UMTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_A in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA2000_1XRTT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSDPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSUPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IDEN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_B in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EHRPD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPAP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GSM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_TD_SCDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IWLAN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NRNSA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE_CA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA; - /** - * The constant map of values for NetHostConnectionSubtypeValues. - * @deprecated Use the NETHOSTCONNECTIONSUBTYPEVALUES_XXXXX constants rather than the NetHostConnectionSubtypeValues.XXXXX for bundle minification. - */ - exports.NetHostConnectionSubtypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA - ]); - var TMP_HTTPFLAVORVALUES_HTTP_1_0 = "1.0"; - var TMP_HTTPFLAVORVALUES_HTTP_1_1 = "1.1"; - var TMP_HTTPFLAVORVALUES_HTTP_2_0 = "2.0"; - var TMP_HTTPFLAVORVALUES_SPDY = "SPDY"; - var TMP_HTTPFLAVORVALUES_QUIC = "QUIC"; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_1 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_2_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_SPDY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_QUIC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC; - /** - * The constant map of values for HttpFlavorValues. - * @deprecated Use the HTTPFLAVORVALUES_XXXXX constants rather than the HttpFlavorValues.XXXXX for bundle minification. - */ - exports.HttpFlavorValues = { - HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0, - HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1, - HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0, - SPDY: TMP_HTTPFLAVORVALUES_SPDY, - QUIC: TMP_HTTPFLAVORVALUES_QUIC - }; - var TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = "queue"; - var TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = "topic"; - /** - * The kind of message destination. - * - * @deprecated Removed in semconv v1.20.0. - */ - exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE; - /** - * The kind of message destination. - * - * @deprecated Removed in semconv v1.20.0. - */ - exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC; - /** - * The constant map of values for MessagingDestinationKindValues. - * @deprecated Use the MESSAGINGDESTINATIONKINDVALUES_XXXXX constants rather than the MessagingDestinationKindValues.XXXXX for bundle minification. - */ - exports.MessagingDestinationKindValues = /*#__PURE__*/ (0, utils_1.createConstMap)([TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE, TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC]); - var TMP_MESSAGINGOPERATIONVALUES_RECEIVE = "receive"; - var TMP_MESSAGINGOPERATIONVALUES_PROCESS = "process"; - /** - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * - * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_RECEIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.MESSAGINGOPERATIONVALUES_RECEIVE = TMP_MESSAGINGOPERATIONVALUES_RECEIVE; - /** - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * - * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_PROCESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.MESSAGINGOPERATIONVALUES_PROCESS = TMP_MESSAGINGOPERATIONVALUES_PROCESS; - /** - * The constant map of values for MessagingOperationValues. - * @deprecated Use the MESSAGINGOPERATIONVALUES_XXXXX constants rather than the MessagingOperationValues.XXXXX for bundle minification. - */ - exports.MessagingOperationValues = /*#__PURE__*/ (0, utils_1.createConstMap)([TMP_MESSAGINGOPERATIONVALUES_RECEIVE, TMP_MESSAGINGOPERATIONVALUES_PROCESS]); - var TMP_RPCGRPCSTATUSCODEVALUES_OK = 0; - var TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1; - var TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2; - var TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3; - var TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4; - var TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5; - var TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6; - var TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7; - var TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8; - var TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9; - var TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10; - var TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11; - var TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12; - var TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13; - var TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14; - var TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15; - var TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_CANCELLED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INVALID_ARGUMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DEADLINE_EXCEEDED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_NOT_FOUND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ALREADY_EXISTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_PERMISSION_DENIED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_RESOURCE_EXHAUSTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_FAILED_PRECONDITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ABORTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_ABORTED = TMP_RPCGRPCSTATUSCODEVALUES_ABORTED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OUT_OF_RANGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNIMPLEMENTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INTERNAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DATA_LOSS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAUTHENTICATED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED; - /** - * The constant map of values for RpcGrpcStatusCodeValues. - * @deprecated Use the RPCGRPCSTATUSCODEVALUES_XXXXX constants rather than the RpcGrpcStatusCodeValues.XXXXX for bundle minification. - */ - exports.RpcGrpcStatusCodeValues = { - OK: TMP_RPCGRPCSTATUSCODEVALUES_OK, - CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED, - UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN, - INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, - DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, - NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND, - ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, - PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, - RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, - FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, - ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED, - OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, - UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, - INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL, - UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, - DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS, - UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED - }; - var TMP_MESSAGETYPEVALUES_SENT = "SENT"; - var TMP_MESSAGETYPEVALUES_RECEIVED = "RECEIVED"; - /** - * Whether this is a received or sent message. - * - * @deprecated Use MESSAGE_TYPE_VALUE_SENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT; - /** - * Whether this is a received or sent message. - * - * @deprecated Use MESSAGE_TYPE_VALUE_RECEIVED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED; - /** - * The constant map of values for MessageTypeValues. - * @deprecated Use the MESSAGETYPEVALUES_XXXXX constants rather than the MessageTypeValues.XXXXX for bundle minification. - */ - exports.MessageTypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([TMP_MESSAGETYPEVALUES_SENT, TMP_MESSAGETYPEVALUES_RECEIVED]); -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js -var require_trace = /* @__PURE__ */ __commonJSMin(((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = { - enumerable: true, - get: function() { - return m[k]; - } - }; - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar = exports && exports.__exportStar || function(m, exports$3) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$3, p)) __createBinding(exports$3, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - __exportStar(require_SemanticAttributes(), exports); -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js -var require_SemanticResourceAttributes = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SEMRESATTRS_K8S_STATEFULSET_NAME = exports.SEMRESATTRS_K8S_STATEFULSET_UID = exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = exports.SEMRESATTRS_K8S_REPLICASET_NAME = exports.SEMRESATTRS_K8S_REPLICASET_UID = exports.SEMRESATTRS_K8S_CONTAINER_NAME = exports.SEMRESATTRS_K8S_POD_NAME = exports.SEMRESATTRS_K8S_POD_UID = exports.SEMRESATTRS_K8S_NAMESPACE_NAME = exports.SEMRESATTRS_K8S_NODE_UID = exports.SEMRESATTRS_K8S_NODE_NAME = exports.SEMRESATTRS_K8S_CLUSTER_NAME = exports.SEMRESATTRS_HOST_IMAGE_VERSION = exports.SEMRESATTRS_HOST_IMAGE_ID = exports.SEMRESATTRS_HOST_IMAGE_NAME = exports.SEMRESATTRS_HOST_ARCH = exports.SEMRESATTRS_HOST_TYPE = exports.SEMRESATTRS_HOST_NAME = exports.SEMRESATTRS_HOST_ID = exports.SEMRESATTRS_FAAS_MAX_MEMORY = exports.SEMRESATTRS_FAAS_INSTANCE = exports.SEMRESATTRS_FAAS_VERSION = exports.SEMRESATTRS_FAAS_ID = exports.SEMRESATTRS_FAAS_NAME = exports.SEMRESATTRS_DEVICE_MODEL_NAME = exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = exports.SEMRESATTRS_DEVICE_ID = exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = exports.SEMRESATTRS_CONTAINER_RUNTIME = exports.SEMRESATTRS_CONTAINER_ID = exports.SEMRESATTRS_CONTAINER_NAME = exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = exports.SEMRESATTRS_AWS_ECS_TASK_ARN = exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = exports.SEMRESATTRS_CLOUD_PLATFORM = exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = exports.SEMRESATTRS_CLOUD_REGION = exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = exports.SEMRESATTRS_CLOUD_PROVIDER = void 0; - exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = exports.CLOUDPLATFORMVALUES_AZURE_AKS = exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = exports.CLOUDPLATFORMVALUES_AZURE_VM = exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = exports.CLOUDPLATFORMVALUES_AWS_EKS = exports.CLOUDPLATFORMVALUES_AWS_ECS = exports.CLOUDPLATFORMVALUES_AWS_EC2 = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = exports.CloudProviderValues = exports.CLOUDPROVIDERVALUES_GCP = exports.CLOUDPROVIDERVALUES_AZURE = exports.CLOUDPROVIDERVALUES_AWS = exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = exports.SemanticResourceAttributes = exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = exports.SEMRESATTRS_WEBENGINE_VERSION = exports.SEMRESATTRS_WEBENGINE_NAME = exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = exports.SEMRESATTRS_TELEMETRY_SDK_NAME = exports.SEMRESATTRS_SERVICE_VERSION = exports.SEMRESATTRS_SERVICE_INSTANCE_ID = exports.SEMRESATTRS_SERVICE_NAMESPACE = exports.SEMRESATTRS_SERVICE_NAME = exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = exports.SEMRESATTRS_PROCESS_OWNER = exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = exports.SEMRESATTRS_PROCESS_COMMAND_LINE = exports.SEMRESATTRS_PROCESS_COMMAND = exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = exports.SEMRESATTRS_PROCESS_PID = exports.SEMRESATTRS_OS_VERSION = exports.SEMRESATTRS_OS_NAME = exports.SEMRESATTRS_OS_DESCRIPTION = exports.SEMRESATTRS_OS_TYPE = exports.SEMRESATTRS_K8S_CRONJOB_NAME = exports.SEMRESATTRS_K8S_CRONJOB_UID = exports.SEMRESATTRS_K8S_JOB_NAME = exports.SEMRESATTRS_K8S_JOB_UID = exports.SEMRESATTRS_K8S_DAEMONSET_NAME = exports.SEMRESATTRS_K8S_DAEMONSET_UID = void 0; - exports.TelemetrySdkLanguageValues = exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = exports.TELEMETRYSDKLANGUAGEVALUES_PHP = exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = exports.TELEMETRYSDKLANGUAGEVALUES_GO = exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = exports.TELEMETRYSDKLANGUAGEVALUES_CPP = exports.OsTypeValues = exports.OSTYPEVALUES_Z_OS = exports.OSTYPEVALUES_SOLARIS = exports.OSTYPEVALUES_AIX = exports.OSTYPEVALUES_HPUX = exports.OSTYPEVALUES_DRAGONFLYBSD = exports.OSTYPEVALUES_OPENBSD = exports.OSTYPEVALUES_NETBSD = exports.OSTYPEVALUES_FREEBSD = exports.OSTYPEVALUES_DARWIN = exports.OSTYPEVALUES_LINUX = exports.OSTYPEVALUES_WINDOWS = exports.HostArchValues = exports.HOSTARCHVALUES_X86 = exports.HOSTARCHVALUES_PPC64 = exports.HOSTARCHVALUES_PPC32 = exports.HOSTARCHVALUES_IA64 = exports.HOSTARCHVALUES_ARM64 = exports.HOSTARCHVALUES_ARM32 = exports.HOSTARCHVALUES_AMD64 = exports.AwsEcsLaunchtypeValues = exports.AWSECSLAUNCHTYPEVALUES_FARGATE = exports.AWSECSLAUNCHTYPEVALUES_EC2 = exports.CloudPlatformValues = exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = void 0; - var utils_1 = require_utils(); - var TMP_CLOUD_PROVIDER = "cloud.provider"; - var TMP_CLOUD_ACCOUNT_ID = "cloud.account.id"; - var TMP_CLOUD_REGION = "cloud.region"; - var TMP_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone"; - var TMP_CLOUD_PLATFORM = "cloud.platform"; - var TMP_AWS_ECS_CONTAINER_ARN = "aws.ecs.container.arn"; - var TMP_AWS_ECS_CLUSTER_ARN = "aws.ecs.cluster.arn"; - var TMP_AWS_ECS_LAUNCHTYPE = "aws.ecs.launchtype"; - var TMP_AWS_ECS_TASK_ARN = "aws.ecs.task.arn"; - var TMP_AWS_ECS_TASK_FAMILY = "aws.ecs.task.family"; - var TMP_AWS_ECS_TASK_REVISION = "aws.ecs.task.revision"; - var TMP_AWS_EKS_CLUSTER_ARN = "aws.eks.cluster.arn"; - var TMP_AWS_LOG_GROUP_NAMES = "aws.log.group.names"; - var TMP_AWS_LOG_GROUP_ARNS = "aws.log.group.arns"; - var TMP_AWS_LOG_STREAM_NAMES = "aws.log.stream.names"; - var TMP_AWS_LOG_STREAM_ARNS = "aws.log.stream.arns"; - var TMP_CONTAINER_NAME = "container.name"; - var TMP_CONTAINER_ID = "container.id"; - var TMP_CONTAINER_RUNTIME = "container.runtime"; - var TMP_CONTAINER_IMAGE_NAME = "container.image.name"; - var TMP_CONTAINER_IMAGE_TAG = "container.image.tag"; - var TMP_DEPLOYMENT_ENVIRONMENT = "deployment.environment"; - var TMP_DEVICE_ID = "device.id"; - var TMP_DEVICE_MODEL_IDENTIFIER = "device.model.identifier"; - var TMP_DEVICE_MODEL_NAME = "device.model.name"; - var TMP_FAAS_NAME = "faas.name"; - var TMP_FAAS_ID = "faas.id"; - var TMP_FAAS_VERSION = "faas.version"; - var TMP_FAAS_INSTANCE = "faas.instance"; - var TMP_FAAS_MAX_MEMORY = "faas.max_memory"; - var TMP_HOST_ID = "host.id"; - var TMP_HOST_NAME = "host.name"; - var TMP_HOST_TYPE = "host.type"; - var TMP_HOST_ARCH = "host.arch"; - var TMP_HOST_IMAGE_NAME = "host.image.name"; - var TMP_HOST_IMAGE_ID = "host.image.id"; - var TMP_HOST_IMAGE_VERSION = "host.image.version"; - var TMP_K8S_CLUSTER_NAME = "k8s.cluster.name"; - var TMP_K8S_NODE_NAME = "k8s.node.name"; - var TMP_K8S_NODE_UID = "k8s.node.uid"; - var TMP_K8S_NAMESPACE_NAME = "k8s.namespace.name"; - var TMP_K8S_POD_UID = "k8s.pod.uid"; - var TMP_K8S_POD_NAME = "k8s.pod.name"; - var TMP_K8S_CONTAINER_NAME = "k8s.container.name"; - var TMP_K8S_REPLICASET_UID = "k8s.replicaset.uid"; - var TMP_K8S_REPLICASET_NAME = "k8s.replicaset.name"; - var TMP_K8S_DEPLOYMENT_UID = "k8s.deployment.uid"; - var TMP_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; - var TMP_K8S_STATEFULSET_UID = "k8s.statefulset.uid"; - var TMP_K8S_STATEFULSET_NAME = "k8s.statefulset.name"; - var TMP_K8S_DAEMONSET_UID = "k8s.daemonset.uid"; - var TMP_K8S_DAEMONSET_NAME = "k8s.daemonset.name"; - var TMP_K8S_JOB_UID = "k8s.job.uid"; - var TMP_K8S_JOB_NAME = "k8s.job.name"; - var TMP_K8S_CRONJOB_UID = "k8s.cronjob.uid"; - var TMP_K8S_CRONJOB_NAME = "k8s.cronjob.name"; - var TMP_OS_TYPE = "os.type"; - var TMP_OS_DESCRIPTION = "os.description"; - var TMP_OS_NAME = "os.name"; - var TMP_OS_VERSION = "os.version"; - var TMP_PROCESS_PID = "process.pid"; - var TMP_PROCESS_EXECUTABLE_NAME = "process.executable.name"; - var TMP_PROCESS_EXECUTABLE_PATH = "process.executable.path"; - var TMP_PROCESS_COMMAND = "process.command"; - var TMP_PROCESS_COMMAND_LINE = "process.command_line"; - var TMP_PROCESS_COMMAND_ARGS = "process.command_args"; - var TMP_PROCESS_OWNER = "process.owner"; - var TMP_PROCESS_RUNTIME_NAME = "process.runtime.name"; - var TMP_PROCESS_RUNTIME_VERSION = "process.runtime.version"; - var TMP_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description"; - var TMP_SERVICE_NAME = "service.name"; - var TMP_SERVICE_NAMESPACE = "service.namespace"; - var TMP_SERVICE_INSTANCE_ID = "service.instance.id"; - var TMP_SERVICE_VERSION = "service.version"; - var TMP_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; - var TMP_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; - var TMP_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; - var TMP_TELEMETRY_AUTO_VERSION = "telemetry.auto.version"; - var TMP_WEBENGINE_NAME = "webengine.name"; - var TMP_WEBENGINE_VERSION = "webengine.version"; - var TMP_WEBENGINE_DESCRIPTION = "webengine.description"; - /** - * Name of the cloud provider. - * - * @deprecated Use ATTR_CLOUD_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER; - /** - * The cloud account ID the resource is assigned to. - * - * @deprecated Use ATTR_CLOUD_ACCOUNT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID; - /** - * The geographical region the resource is running. Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), or [Google Cloud regions](https://cloud.google.com/about/locations). - * - * @deprecated Use ATTR_CLOUD_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION; - /** - * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running. - * - * Note: Availability zones are called "zones" on Alibaba Cloud and Google Cloud. - * - * @deprecated Use ATTR_CLOUD_AVAILABILITY_ZONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use ATTR_CLOUD_PLATFORM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM; - /** - * The Amazon Resource Name (ARN) of an [ECS container instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). - * - * @deprecated Use ATTR_AWS_ECS_CONTAINER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN; - /** - * The ARN of an [ECS cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). - * - * @deprecated Use ATTR_AWS_ECS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN; - /** - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * - * @deprecated Use ATTR_AWS_ECS_LAUNCHTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE; - /** - * The ARN of an [ECS task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). - * - * @deprecated Use ATTR_AWS_ECS_TASK_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN; - /** - * The task definition family this task definition is a member of. - * - * @deprecated Use ATTR_AWS_ECS_TASK_FAMILY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY; - /** - * The revision for this task definition. - * - * @deprecated Use ATTR_AWS_ECS_TASK_REVISION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION; - /** - * The ARN of an EKS cluster. - * - * @deprecated Use ATTR_AWS_EKS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN; - /** - * The name(s) of the AWS log group(s) an application is writing to. - * - * Note: Multiple log groups must be supported for cases like multi-container applications, where a single application has sidecar containers, and each write to their own log group. - * - * @deprecated Use ATTR_AWS_LOG_GROUP_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES; - /** - * The Amazon Resource Name(s) (ARN) of the AWS log group(s). - * - * Note: See the [log group ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). - * - * @deprecated Use ATTR_AWS_LOG_GROUP_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS; - /** - * The name(s) of the AWS log stream(s) an application is writing to. - * - * @deprecated Use ATTR_AWS_LOG_STREAM_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES; - /** - * The ARN(s) of the AWS log stream(s). - * - * Note: See the [log stream ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). One log group can contain several log streams, so these ARNs necessarily identify both a log group and a log stream. - * - * @deprecated Use ATTR_AWS_LOG_STREAM_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS; - /** - * Container name. - * - * @deprecated Use ATTR_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME; - /** - * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/reference/run/#container-identification). The UUID might be abbreviated. - * - * @deprecated Use ATTR_CONTAINER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID; - /** - * The container runtime managing this container. - * - * @deprecated Use ATTR_CONTAINER_RUNTIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME; - /** - * Name of the image the container was built on. - * - * @deprecated Use ATTR_CONTAINER_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME; - /** - * Container image tag. - * - * @deprecated Use ATTR_CONTAINER_IMAGE_TAGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG; - /** - * Name of the [deployment environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka deployment tier). - * - * @deprecated Use ATTR_DEPLOYMENT_ENVIRONMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT; - /** - * A unique identifier representing the device. - * - * Note: The device identifier MUST only be defined using the values outlined below. This value is not an advertising identifier and MUST NOT be used as such. On iOS (Swift or Objective-C), this value MUST be equal to the [vendor identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). On Android (Java or Kotlin), this value MUST be equal to the Firebase Installation ID or a globally unique UUID which is persisted across sessions in your application. More information can be found [here](https://developer.android.com/training/articles/user-data-ids) on best practices and exact implementation details. Caution should be taken when storing personal data or anything which can identify a user. GDPR and data protection laws may apply, ensure you do your own due diligence. - * - * @deprecated Use ATTR_DEVICE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID; - /** - * The model identifier for the device. - * - * Note: It's recommended this value represents a machine readable version of the model identifier rather than the market or consumer-friendly name of the device. - * - * @deprecated Use ATTR_DEVICE_MODEL_IDENTIFIER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER; - /** - * The marketing name for the device model. - * - * Note: It's recommended this value represents a human readable version of the device model rather than a machine readable alternative. - * - * @deprecated Use ATTR_DEVICE_MODEL_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME; - /** - * The name of the single function that this runtime instance executes. - * - * Note: This is the name of the function as configured/deployed on the FaaS platform and is usually different from the name of the callback function (which may be stored in the [`code.namespace`/`code.function`](../../trace/semantic_conventions/span-general.md#source-code-attributes) span attributes). - * - * @deprecated Use ATTR_FAAS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME; - /** - * The unique ID of the single function that this runtime instance executes. - * - * Note: Depending on the cloud provider, use: - - * **AWS Lambda:** The function [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). - Take care not to use the "invoked ARN" directly but replace any - [alias suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) with the resolved function version, as the same runtime instance may be invokable with multiple - different aliases. - * **GCP:** The [URI of the resource](https://cloud.google.com/iam/docs/full-resource-names) - * **Azure:** The [Fully Qualified Resource ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id). - - On some providers, it may not be possible to determine the full ID at startup, - which is why this field cannot be made required. For example, on AWS the account ID - part of the ARN is not available without calling another AWS API - which may be deemed too slow for a short-running lambda function. - As an alternative, consider setting `faas.id` as a span attribute instead. - * - * @deprecated Use ATTR_CLOUD_RESOURCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_FAAS_ID = TMP_FAAS_ID; - /** - * The immutable version of the function being executed. - * - * Note: Depending on the cloud provider and platform, use: - - * **AWS Lambda:** The [function version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html) - (an integer represented as a decimal string). - * **Google Cloud Run:** The [revision](https://cloud.google.com/run/docs/managing/revisions) - (i.e., the function name plus the revision suffix). - * **Google Cloud Functions:** The value of the - [`K_REVISION` environment variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically). - * **Azure Functions:** Not applicable. Do not set this attribute. - * - * @deprecated Use ATTR_FAAS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION; - /** - * The execution environment ID as a string, that will be potentially reused for other invocations to the same function/function version. - * - * Note: * **AWS Lambda:** Use the (full) log stream name. - * - * @deprecated Use ATTR_FAAS_INSTANCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE; - /** - * The amount of memory available to the serverless function in MiB. - * - * Note: It's recommended to set this attribute since e.g. too little memory can easily stop a Java AWS Lambda function from working correctly. On AWS Lambda, the environment variable `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information. - * - * @deprecated Use ATTR_FAAS_MAX_MEMORY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY; - /** - * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider. - * - * @deprecated Use ATTR_HOST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_ID = TMP_HOST_ID; - /** - * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user. - * - * @deprecated Use ATTR_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_NAME = TMP_HOST_NAME; - /** - * Type of host. For Cloud, this must be the machine type. - * - * @deprecated Use ATTR_HOST_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use ATTR_HOST_ARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH; - /** - * Name of the VM image or OS install the host was instantiated from. - * - * @deprecated Use ATTR_HOST_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME; - /** - * VM image ID. For Cloud, this value is from the provider. - * - * @deprecated Use ATTR_HOST_IMAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID; - /** - * The version string of the VM image as defined in [Version Attributes](README.md#version-attributes). - * - * @deprecated Use ATTR_HOST_IMAGE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION; - /** - * The name of the cluster. - * - * @deprecated Use ATTR_K8S_CLUSTER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME; - /** - * The name of the Node. - * - * @deprecated Use ATTR_K8S_NODE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME; - /** - * The UID of the Node. - * - * @deprecated Use ATTR_K8S_NODE_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID; - /** - * The name of the namespace that the pod is running in. - * - * @deprecated Use ATTR_K8S_NAMESPACE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME; - /** - * The UID of the Pod. - * - * @deprecated Use ATTR_K8S_POD_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID; - /** - * The name of the Pod. - * - * @deprecated Use ATTR_K8S_POD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME; - /** - * The name of the Container in a Pod template. - * - * @deprecated Use ATTR_K8S_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME; - /** - * The UID of the ReplicaSet. - * - * @deprecated Use ATTR_K8S_REPLICASET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID; - /** - * The name of the ReplicaSet. - * - * @deprecated Use ATTR_K8S_REPLICASET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME; - /** - * The UID of the Deployment. - * - * @deprecated Use ATTR_K8S_DEPLOYMENT_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID; - /** - * The name of the Deployment. - * - * @deprecated Use ATTR_K8S_DEPLOYMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME; - /** - * The UID of the StatefulSet. - * - * @deprecated Use ATTR_K8S_STATEFULSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID; - /** - * The name of the StatefulSet. - * - * @deprecated Use ATTR_K8S_STATEFULSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME; - /** - * The UID of the DaemonSet. - * - * @deprecated Use ATTR_K8S_DAEMONSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID; - /** - * The name of the DaemonSet. - * - * @deprecated Use ATTR_K8S_DAEMONSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME; - /** - * The UID of the Job. - * - * @deprecated Use ATTR_K8S_JOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID; - /** - * The name of the Job. - * - * @deprecated Use ATTR_K8S_JOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME; - /** - * The UID of the CronJob. - * - * @deprecated Use ATTR_K8S_CRONJOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID; - /** - * The name of the CronJob. - * - * @deprecated Use ATTR_K8S_CRONJOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME; - /** - * The operating system type. - * - * @deprecated Use ATTR_OS_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_OS_TYPE = TMP_OS_TYPE; - /** - * Human readable (not intended to be parsed) OS version information, like e.g. reported by `ver` or `lsb_release -a` commands. - * - * @deprecated Use ATTR_OS_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION; - /** - * Human readable operating system name. - * - * @deprecated Use ATTR_OS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_OS_NAME = TMP_OS_NAME; - /** - * The version string of the operating system as defined in [Version Attributes](../../resource/semantic_conventions/README.md#version-attributes). - * - * @deprecated Use ATTR_OS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_OS_VERSION = TMP_OS_VERSION; - /** - * Process identifier (PID). - * - * @deprecated Use ATTR_PROCESS_PID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID; - /** - * The name of the process executable. On Linux based systems, can be set to the `Name` in `proc/[pid]/status`. On Windows, can be set to the base name of `GetProcessImageFileNameW`. - * - * @deprecated Use ATTR_PROCESS_EXECUTABLE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME; - /** - * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`. - * - * @deprecated Use ATTR_PROCESS_EXECUTABLE_PATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH; - /** - * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`. - * - * @deprecated Use ATTR_PROCESS_COMMAND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND; - /** - * The full command used to launch the process as a single string representing the full command. On Windows, can be set to the result of `GetCommandLineW`. Do not set this if you have to assemble it just for monitoring; use `process.command_args` instead. - * - * @deprecated Use ATTR_PROCESS_COMMAND_LINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE; - /** - * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`. - * - * @deprecated Use ATTR_PROCESS_COMMAND_ARGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS; - /** - * The username of the user that owns the process. - * - * @deprecated Use ATTR_PROCESS_OWNER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER; - /** - * The name of the runtime of this process. For compiled native binaries, this SHOULD be the name of the compiler. - * - * @deprecated Use ATTR_PROCESS_RUNTIME_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME; - /** - * The version of the runtime of this process, as returned by the runtime without modification. - * - * @deprecated Use ATTR_PROCESS_RUNTIME_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION; - /** - * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment. - * - * @deprecated Use ATTR_PROCESS_RUNTIME_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = TMP_PROCESS_RUNTIME_DESCRIPTION; - /** - * Logical name of the service. - * - * Note: MUST be the same for all instances of horizontally scaled services. If the value was not specified, SDKs MUST fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md#process), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value MUST be set to `unknown_service`. - * - * @deprecated Use ATTR_SERVICE_NAME. - */ - exports.SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME; - /** - * A namespace for `service.name`. - * - * Note: A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace. - * - * @deprecated Use ATTR_SERVICE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE; - /** - * The string ID of the service instance. - * - * Note: MUST be unique for each instance of the same `service.namespace,service.name` pair (in other words `service.namespace,service.name,service.instance.id` triplet MUST be globally unique). The ID helps to distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled service). It is preferable for the ID to be persistent and stay the same for the lifetime of the service instance, however it is acceptable that the ID is ephemeral and changes during important lifetime events for the service (e.g. service restarts). If the service has no inherent unique ID that can be used as the value of this attribute it is recommended to generate a random Version 1 or Version 4 RFC 4122 UUID (services aiming for reproducible UUIDs may also use Version 5, see RFC 4122 for more recommendations). - * - * @deprecated Use ATTR_SERVICE_INSTANCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID; - /** - * The version string of the service API or implementation. - * - * @deprecated Use ATTR_SERVICE_VERSION. - */ - exports.SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION; - /** - * The name of the telemetry SDK as defined above. - * - * @deprecated Use ATTR_TELEMETRY_SDK_NAME. - */ - exports.SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME; - /** - * The language of the telemetry SDK. - * - * @deprecated Use ATTR_TELEMETRY_SDK_LANGUAGE. - */ - exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE; - /** - * The version string of the telemetry SDK. - * - * @deprecated Use ATTR_TELEMETRY_SDK_VERSION. - */ - exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION; - /** - * The version string of the auto instrumentation agent, if used. - * - * @deprecated Use ATTR_TELEMETRY_DISTRO_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION; - /** - * The name of the web engine. - * - * @deprecated Use ATTR_WEBENGINE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME; - /** - * The version of the web engine. - * - * @deprecated Use ATTR_WEBENGINE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION; - /** - * Additional description of the web engine (e.g. detailed version and edition information). - * - * @deprecated Use ATTR_WEBENGINE_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION; - /** - * Create exported Value Map for SemanticResourceAttributes values - * @deprecated Use the SEMRESATTRS_XXXXX constants rather than the SemanticResourceAttributes.XXXXX for bundle minification - */ - exports.SemanticResourceAttributes = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_CLOUD_PROVIDER, - TMP_CLOUD_ACCOUNT_ID, - TMP_CLOUD_REGION, - TMP_CLOUD_AVAILABILITY_ZONE, - TMP_CLOUD_PLATFORM, - TMP_AWS_ECS_CONTAINER_ARN, - TMP_AWS_ECS_CLUSTER_ARN, - TMP_AWS_ECS_LAUNCHTYPE, - TMP_AWS_ECS_TASK_ARN, - TMP_AWS_ECS_TASK_FAMILY, - TMP_AWS_ECS_TASK_REVISION, - TMP_AWS_EKS_CLUSTER_ARN, - TMP_AWS_LOG_GROUP_NAMES, - TMP_AWS_LOG_GROUP_ARNS, - TMP_AWS_LOG_STREAM_NAMES, - TMP_AWS_LOG_STREAM_ARNS, - TMP_CONTAINER_NAME, - TMP_CONTAINER_ID, - TMP_CONTAINER_RUNTIME, - TMP_CONTAINER_IMAGE_NAME, - TMP_CONTAINER_IMAGE_TAG, - TMP_DEPLOYMENT_ENVIRONMENT, - TMP_DEVICE_ID, - TMP_DEVICE_MODEL_IDENTIFIER, - TMP_DEVICE_MODEL_NAME, - TMP_FAAS_NAME, - TMP_FAAS_ID, - TMP_FAAS_VERSION, - TMP_FAAS_INSTANCE, - TMP_FAAS_MAX_MEMORY, - TMP_HOST_ID, - TMP_HOST_NAME, - TMP_HOST_TYPE, - TMP_HOST_ARCH, - TMP_HOST_IMAGE_NAME, - TMP_HOST_IMAGE_ID, - TMP_HOST_IMAGE_VERSION, - TMP_K8S_CLUSTER_NAME, - TMP_K8S_NODE_NAME, - TMP_K8S_NODE_UID, - TMP_K8S_NAMESPACE_NAME, - TMP_K8S_POD_UID, - TMP_K8S_POD_NAME, - TMP_K8S_CONTAINER_NAME, - TMP_K8S_REPLICASET_UID, - TMP_K8S_REPLICASET_NAME, - TMP_K8S_DEPLOYMENT_UID, - TMP_K8S_DEPLOYMENT_NAME, - TMP_K8S_STATEFULSET_UID, - TMP_K8S_STATEFULSET_NAME, - TMP_K8S_DAEMONSET_UID, - TMP_K8S_DAEMONSET_NAME, - TMP_K8S_JOB_UID, - TMP_K8S_JOB_NAME, - TMP_K8S_CRONJOB_UID, - TMP_K8S_CRONJOB_NAME, - TMP_OS_TYPE, - TMP_OS_DESCRIPTION, - TMP_OS_NAME, - TMP_OS_VERSION, - TMP_PROCESS_PID, - TMP_PROCESS_EXECUTABLE_NAME, - TMP_PROCESS_EXECUTABLE_PATH, - TMP_PROCESS_COMMAND, - TMP_PROCESS_COMMAND_LINE, - TMP_PROCESS_COMMAND_ARGS, - TMP_PROCESS_OWNER, - TMP_PROCESS_RUNTIME_NAME, - TMP_PROCESS_RUNTIME_VERSION, - TMP_PROCESS_RUNTIME_DESCRIPTION, - TMP_SERVICE_NAME, - TMP_SERVICE_NAMESPACE, - TMP_SERVICE_INSTANCE_ID, - TMP_SERVICE_VERSION, - TMP_TELEMETRY_SDK_NAME, - TMP_TELEMETRY_SDK_LANGUAGE, - TMP_TELEMETRY_SDK_VERSION, - TMP_TELEMETRY_AUTO_VERSION, - TMP_WEBENGINE_NAME, - TMP_WEBENGINE_VERSION, - TMP_WEBENGINE_DESCRIPTION - ]); - var TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; - var TMP_CLOUDPROVIDERVALUES_AWS = "aws"; - var TMP_CLOUDPROVIDERVALUES_AZURE = "azure"; - var TMP_CLOUDPROVIDERVALUES_GCP = "gcp"; - /** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD; - /** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS; - /** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE; - /** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP; - /** - * The constant map of values for CloudProviderValues. - * @deprecated Use the CLOUDPROVIDERVALUES_XXXXX constants rather than the CloudProviderValues.XXXXX for bundle minification. - */ - exports.CloudProviderValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD, - TMP_CLOUDPROVIDERVALUES_AWS, - TMP_CLOUDPROVIDERVALUES_AZURE, - TMP_CLOUDPROVIDERVALUES_GCP - ]); - var TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = "alibaba_cloud_ecs"; - var TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = "alibaba_cloud_fc"; - var TMP_CLOUDPLATFORMVALUES_AWS_EC2 = "aws_ec2"; - var TMP_CLOUDPLATFORMVALUES_AWS_ECS = "aws_ecs"; - var TMP_CLOUDPLATFORMVALUES_AWS_EKS = "aws_eks"; - var TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = "aws_lambda"; - var TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = "aws_elastic_beanstalk"; - var TMP_CLOUDPLATFORMVALUES_AZURE_VM = "azure_vm"; - var TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = "azure_container_instances"; - var TMP_CLOUDPLATFORMVALUES_AZURE_AKS = "azure_aks"; - var TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = "azure_functions"; - var TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = "azure_app_service"; - var TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = "gcp_compute_engine"; - var TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = "gcp_cloud_run"; - var TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = "gcp_kubernetes_engine"; - var TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = "gcp_cloud_functions"; - var TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = "gcp_app_engine"; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_FC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_LAMBDA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ELASTIC_BEANSTALK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_VM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_CONTAINER_INSTANCES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_AKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_APP_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_COMPUTE_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_RUN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_KUBERNETES_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_APP_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE; - /** - * The constant map of values for CloudPlatformValues. - * @deprecated Use the CLOUDPLATFORMVALUES_XXXXX constants rather than the CloudPlatformValues.XXXXX for bundle minification. - */ - exports.CloudPlatformValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, - TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, - TMP_CLOUDPLATFORMVALUES_AWS_EC2, - TMP_CLOUDPLATFORMVALUES_AWS_ECS, - TMP_CLOUDPLATFORMVALUES_AWS_EKS, - TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA, - TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, - TMP_CLOUDPLATFORMVALUES_AZURE_VM, - TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, - TMP_CLOUDPLATFORMVALUES_AZURE_AKS, - TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, - TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, - TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, - TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, - TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, - TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, - TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE - ]); - var TMP_AWSECSLAUNCHTYPEVALUES_EC2 = "ec2"; - var TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = "fargate"; - /** - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * - * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2; - /** - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * - * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_FARGATE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.AWSECSLAUNCHTYPEVALUES_FARGATE = TMP_AWSECSLAUNCHTYPEVALUES_FARGATE; - /** - * The constant map of values for AwsEcsLaunchtypeValues. - * @deprecated Use the AWSECSLAUNCHTYPEVALUES_XXXXX constants rather than the AwsEcsLaunchtypeValues.XXXXX for bundle minification. - */ - exports.AwsEcsLaunchtypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([TMP_AWSECSLAUNCHTYPEVALUES_EC2, TMP_AWSECSLAUNCHTYPEVALUES_FARGATE]); - var TMP_HOSTARCHVALUES_AMD64 = "amd64"; - var TMP_HOSTARCHVALUES_ARM32 = "arm32"; - var TMP_HOSTARCHVALUES_ARM64 = "arm64"; - var TMP_HOSTARCHVALUES_IA64 = "ia64"; - var TMP_HOSTARCHVALUES_PPC32 = "ppc32"; - var TMP_HOSTARCHVALUES_PPC64 = "ppc64"; - var TMP_HOSTARCHVALUES_X86 = "x86"; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_AMD64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_ARM32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_ARM64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_IA64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_PPC32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_PPC64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_X86 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86; - /** - * The constant map of values for HostArchValues. - * @deprecated Use the HOSTARCHVALUES_XXXXX constants rather than the HostArchValues.XXXXX for bundle minification. - */ - exports.HostArchValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_HOSTARCHVALUES_AMD64, - TMP_HOSTARCHVALUES_ARM32, - TMP_HOSTARCHVALUES_ARM64, - TMP_HOSTARCHVALUES_IA64, - TMP_HOSTARCHVALUES_PPC32, - TMP_HOSTARCHVALUES_PPC64, - TMP_HOSTARCHVALUES_X86 - ]); - var TMP_OSTYPEVALUES_WINDOWS = "windows"; - var TMP_OSTYPEVALUES_LINUX = "linux"; - var TMP_OSTYPEVALUES_DARWIN = "darwin"; - var TMP_OSTYPEVALUES_FREEBSD = "freebsd"; - var TMP_OSTYPEVALUES_NETBSD = "netbsd"; - var TMP_OSTYPEVALUES_OPENBSD = "openbsd"; - var TMP_OSTYPEVALUES_DRAGONFLYBSD = "dragonflybsd"; - var TMP_OSTYPEVALUES_HPUX = "hpux"; - var TMP_OSTYPEVALUES_AIX = "aix"; - var TMP_OSTYPEVALUES_SOLARIS = "solaris"; - var TMP_OSTYPEVALUES_Z_OS = "z_os"; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_WINDOWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_LINUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_DARWIN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_FREEBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_NETBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_OPENBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_DRAGONFLYBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_HPUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_AIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_SOLARIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_Z_OS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS; - /** - * The constant map of values for OsTypeValues. - * @deprecated Use the OSTYPEVALUES_XXXXX constants rather than the OsTypeValues.XXXXX for bundle minification. - */ - exports.OsTypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_OSTYPEVALUES_WINDOWS, - TMP_OSTYPEVALUES_LINUX, - TMP_OSTYPEVALUES_DARWIN, - TMP_OSTYPEVALUES_FREEBSD, - TMP_OSTYPEVALUES_NETBSD, - TMP_OSTYPEVALUES_OPENBSD, - TMP_OSTYPEVALUES_DRAGONFLYBSD, - TMP_OSTYPEVALUES_HPUX, - TMP_OSTYPEVALUES_AIX, - TMP_OSTYPEVALUES_SOLARIS, - TMP_OSTYPEVALUES_Z_OS - ]); - var TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = "cpp"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = "dotnet"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = "erlang"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_GO = "go"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = "java"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = "nodejs"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = "php"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = "python"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = "ruby"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = "webjs"; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_CPP. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_CPP = TMP_TELEMETRYSDKLANGUAGEVALUES_CPP; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_GO. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_JAVA. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PHP. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_PHP = TMP_TELEMETRYSDKLANGUAGEVALUES_PHP; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_RUBY. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS; - /** - * The constant map of values for TelemetrySdkLanguageValues. - * @deprecated Use the TELEMETRYSDKLANGUAGEVALUES_XXXXX constants rather than the TelemetrySdkLanguageValues.XXXXX for bundle minification. - */ - exports.TelemetrySdkLanguageValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_TELEMETRYSDKLANGUAGEVALUES_CPP, - TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET, - TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG, - TMP_TELEMETRYSDKLANGUAGEVALUES_GO, - TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA, - TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS, - TMP_TELEMETRYSDKLANGUAGEVALUES_PHP, - TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON, - TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY, - TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS - ]); -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js -var require_resource = /* @__PURE__ */ __commonJSMin(((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = { - enumerable: true, - get: function() { - return m[k]; - } - }; - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar = exports && exports.__exportStar || function(m, exports$2) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$2, p)) __createBinding(exports$2, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - __exportStar(require_SemanticResourceAttributes(), exports); -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js -var require_stable_attributes = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = exports.ATTR_DOTNET_GC_HEAP_GENERATION = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT = exports.ATTR_DEPLOYMENT_ENVIRONMENT_NAME = exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = exports.DB_SYSTEM_NAME_VALUE_MYSQL = exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = exports.DB_SYSTEM_NAME_VALUE_MARIADB = exports.ATTR_DB_SYSTEM_NAME = exports.ATTR_DB_STORED_PROCEDURE_NAME = exports.ATTR_DB_RESPONSE_STATUS_CODE = exports.ATTR_DB_QUERY_TEXT = exports.ATTR_DB_QUERY_SUMMARY = exports.ATTR_DB_OPERATION_NAME = exports.ATTR_DB_OPERATION_BATCH_SIZE = exports.ATTR_DB_NAMESPACE = exports.ATTR_DB_COLLECTION_NAME = exports.ATTR_CONTAINER_IMAGE_TAGS = exports.ATTR_CONTAINER_IMAGE_REPO_DIGESTS = exports.ATTR_CONTAINER_IMAGE_NAME = exports.ATTR_CONTAINER_ID = exports.ATTR_CODE_STACKTRACE = exports.ATTR_CODE_LINE_NUMBER = exports.ATTR_CODE_FUNCTION_NAME = exports.ATTR_CODE_FILE_PATH = exports.ATTR_CODE_COLUMN_NUMBER = exports.ATTR_CLIENT_PORT = exports.ATTR_CLIENT_ADDRESS = exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = void 0; - exports.ATTR_K8S_DAEMONSET_LABEL = exports.ATTR_K8S_DAEMONSET_ANNOTATION = exports.ATTR_K8S_CRONJOB_UID = exports.ATTR_K8S_CRONJOB_NAME = exports.ATTR_K8S_CRONJOB_LABEL = exports.ATTR_K8S_CRONJOB_ANNOTATION = exports.ATTR_K8S_CONTAINER_RESTART_COUNT = exports.ATTR_K8S_CONTAINER_NAME = exports.ATTR_K8S_CLUSTER_UID = exports.ATTR_K8S_CLUSTER_NAME = exports.JVM_THREAD_STATE_VALUE_WAITING = exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = exports.JVM_THREAD_STATE_VALUE_TERMINATED = exports.JVM_THREAD_STATE_VALUE_RUNNABLE = exports.JVM_THREAD_STATE_VALUE_NEW = exports.JVM_THREAD_STATE_VALUE_BLOCKED = exports.ATTR_JVM_THREAD_STATE = exports.ATTR_JVM_THREAD_DAEMON = exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = exports.JVM_MEMORY_TYPE_VALUE_HEAP = exports.ATTR_JVM_MEMORY_TYPE = exports.ATTR_JVM_MEMORY_POOL_NAME = exports.ATTR_JVM_GC_NAME = exports.ATTR_JVM_GC_ACTION = exports.ATTR_HTTP_ROUTE = exports.ATTR_HTTP_RESPONSE_STATUS_CODE = exports.ATTR_HTTP_RESPONSE_HEADER = exports.ATTR_HTTP_REQUEST_RESEND_COUNT = exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = exports.HTTP_REQUEST_METHOD_VALUE_TRACE = exports.HTTP_REQUEST_METHOD_VALUE_PUT = exports.HTTP_REQUEST_METHOD_VALUE_POST = exports.HTTP_REQUEST_METHOD_VALUE_PATCH = exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = exports.HTTP_REQUEST_METHOD_VALUE_HEAD = exports.HTTP_REQUEST_METHOD_VALUE_GET = exports.HTTP_REQUEST_METHOD_VALUE_DELETE = exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = exports.HTTP_REQUEST_METHOD_VALUE_OTHER = exports.ATTR_HTTP_REQUEST_METHOD = exports.ATTR_HTTP_REQUEST_HEADER = exports.ATTR_EXCEPTION_TYPE = exports.ATTR_EXCEPTION_STACKTRACE = exports.ATTR_EXCEPTION_MESSAGE = exports.ATTR_EXCEPTION_ESCAPED = exports.ERROR_TYPE_VALUE_OTHER = exports.ATTR_ERROR_TYPE = exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = void 0; - exports.ATTR_OTEL_SCOPE_VERSION = exports.ATTR_OTEL_SCOPE_NAME = exports.ATTR_OTEL_EVENT_NAME = exports.NETWORK_TYPE_VALUE_IPV6 = exports.NETWORK_TYPE_VALUE_IPV4 = exports.ATTR_NETWORK_TYPE = exports.NETWORK_TRANSPORT_VALUE_UNIX = exports.NETWORK_TRANSPORT_VALUE_UDP = exports.NETWORK_TRANSPORT_VALUE_TCP = exports.NETWORK_TRANSPORT_VALUE_QUIC = exports.NETWORK_TRANSPORT_VALUE_PIPE = exports.ATTR_NETWORK_TRANSPORT = exports.ATTR_NETWORK_PROTOCOL_VERSION = exports.ATTR_NETWORK_PROTOCOL_NAME = exports.ATTR_NETWORK_PEER_PORT = exports.ATTR_NETWORK_PEER_ADDRESS = exports.ATTR_NETWORK_LOCAL_PORT = exports.ATTR_NETWORK_LOCAL_ADDRESS = exports.ATTR_K8S_STATEFULSET_UID = exports.ATTR_K8S_STATEFULSET_NAME = exports.ATTR_K8S_STATEFULSET_LABEL = exports.ATTR_K8S_STATEFULSET_ANNOTATION = exports.ATTR_K8S_REPLICASET_UID = exports.ATTR_K8S_REPLICASET_NAME = exports.ATTR_K8S_REPLICASET_LABEL = exports.ATTR_K8S_REPLICASET_ANNOTATION = exports.ATTR_K8S_POD_UID = exports.ATTR_K8S_POD_START_TIME = exports.ATTR_K8S_POD_NAME = exports.ATTR_K8S_POD_LABEL = exports.ATTR_K8S_POD_IP = exports.ATTR_K8S_POD_HOSTNAME = exports.ATTR_K8S_POD_ANNOTATION = exports.ATTR_K8S_NODE_UID = exports.ATTR_K8S_NODE_NAME = exports.ATTR_K8S_NODE_LABEL = exports.ATTR_K8S_NODE_ANNOTATION = exports.ATTR_K8S_NAMESPACE_NAME = exports.ATTR_K8S_NAMESPACE_LABEL = exports.ATTR_K8S_NAMESPACE_ANNOTATION = exports.ATTR_K8S_JOB_UID = exports.ATTR_K8S_JOB_NAME = exports.ATTR_K8S_JOB_LABEL = exports.ATTR_K8S_JOB_ANNOTATION = exports.ATTR_K8S_DEPLOYMENT_UID = exports.ATTR_K8S_DEPLOYMENT_NAME = exports.ATTR_K8S_DEPLOYMENT_LABEL = exports.ATTR_K8S_DEPLOYMENT_ANNOTATION = exports.ATTR_K8S_DAEMONSET_UID = exports.ATTR_K8S_DAEMONSET_NAME = void 0; - exports.ATTR_USER_AGENT_ORIGINAL = exports.ATTR_URL_SCHEME = exports.ATTR_URL_QUERY = exports.ATTR_URL_PATH = exports.ATTR_URL_FULL = exports.ATTR_URL_FRAGMENT = exports.ATTR_TELEMETRY_SDK_VERSION = exports.ATTR_TELEMETRY_SDK_NAME = exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_KOTLIN = exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = exports.ATTR_TELEMETRY_SDK_LANGUAGE = exports.ATTR_TELEMETRY_DISTRO_VERSION = exports.ATTR_TELEMETRY_DISTRO_NAME = exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = exports.ATTR_SIGNALR_TRANSPORT = exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = exports.ATTR_SIGNALR_CONNECTION_STATUS = exports.ATTR_SERVICE_VERSION = exports.ATTR_SERVICE_NAMESPACE = exports.ATTR_SERVICE_NAME = exports.ATTR_SERVICE_INSTANCE_ID = exports.ATTR_SERVER_PORT = exports.ATTR_SERVER_ADDRESS = exports.ATTR_OTEL_STATUS_DESCRIPTION = exports.OTEL_STATUS_CODE_VALUE_OK = exports.OTEL_STATUS_CODE_VALUE_ERROR = exports.ATTR_OTEL_STATUS_CODE = void 0; - /** - * ASP.NET Core exception middleware handling result. - * - * @example handled - * @example unhandled - */ - exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = "aspnetcore.diagnostics.exception.result"; - /** - * Enum value "aborted" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - * - * Exception handling didn't run because the request was aborted. - */ - exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = "aborted"; - /** - * Enum value "handled" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - * - * Exception was handled by the exception handling middleware. - */ - exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = "handled"; - /** - * Enum value "skipped" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - * - * Exception handling was skipped because the response had started. - */ - exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = "skipped"; - /** - * Enum value "unhandled" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - * - * Exception was not handled by the exception handling middleware. - */ - exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = "unhandled"; - /** - * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception. - * - * @example Contoso.MyHandler - */ - exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = "aspnetcore.diagnostics.handler.type"; - /** - * Rate limiting policy name. - * - * @example fixed - * @example sliding - * @example token - */ - exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = "aspnetcore.rate_limiting.policy"; - /** - * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason - * - * @example acquired - * @example request_canceled - */ - exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = "aspnetcore.rate_limiting.result"; - /** - * Enum value "acquired" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - * - * Lease was acquired - */ - exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = "acquired"; - /** - * Enum value "endpoint_limiter" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - * - * Lease request was rejected by the endpoint limiter - */ - exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = "endpoint_limiter"; - /** - * Enum value "global_limiter" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - * - * Lease request was rejected by the global limiter - */ - exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = "global_limiter"; - /** - * Enum value "request_canceled" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - * - * Lease request was canceled - */ - exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = "request_canceled"; - /** - * Flag indicating if request was handled by the application pipeline. - * - * @example true - */ - exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = "aspnetcore.request.is_unhandled"; - /** - * A value that indicates whether the matched route is a fallback route. - * - * @example true - */ - exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = "aspnetcore.routing.is_fallback"; - /** - * Match result - success or failure - * - * @example success - * @example failure - */ - exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = "aspnetcore.routing.match_status"; - /** - * Enum value "failure" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}. - * - * Match failed - */ - exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = "failure"; - /** - * Enum value "success" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}. - * - * Match succeeded - */ - exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = "success"; - /** - * A value that indicates whether the user is authenticated. - * - * @example true - */ - exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = "aspnetcore.user.is_authenticated"; - /** - * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name. - * - * @example client.example.com - * @example 10.1.2.80 - * @example /tmp/my.sock - * - * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available. - */ - exports.ATTR_CLIENT_ADDRESS = "client.address"; - /** - * Client port number. - * - * @example 65123 - * - * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available. - */ - exports.ATTR_CLIENT_PORT = "client.port"; - /** - * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example 16 - */ - exports.ATTR_CODE_COLUMN_NUMBER = "code.column.number"; - /** - * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example "/usr/local/MyApplication/content_root/app/index.php" - */ - exports.ATTR_CODE_FILE_PATH = "code.file.path"; - /** - * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example com.example.MyHttpService.serveRequest - * @example GuzzleHttp\\Client::transfer - * @example fopen - * - * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples. - * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in - * `code.stacktrace` without information on arguments. - * - * Examples: - * - * - Java method: `com.example.MyHttpService.serveRequest` - * - Java anonymous class method: `com.mycompany.Main$1.myMethod` - * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod` - * - PHP function: `GuzzleHttp\Client::transfer` - * - Go function: `github.com/my/repo/pkg.foo.func5` - * - Elixir: `OpenTelemetry.Ctx.new` - * - Erlang: `opentelemetry_ctx:new` - * - Rust: `playground::my_module::my_cool_func` - * - C function: `fopen` - */ - exports.ATTR_CODE_FUNCTION_NAME = "code.function.name"; - /** - * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example 42 - */ - exports.ATTR_CODE_LINE_NUMBER = "code.line.number"; - /** - * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example "at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\n" - */ - exports.ATTR_CODE_STACKTRACE = "code.stacktrace"; - /** - * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/containers/run/#container-identification). The UUID might be abbreviated. - * - * @example a3bf90e006b2 - */ - exports.ATTR_CONTAINER_ID = "container.id"; - /** - * Name of the image the container was built on. - * - * @example gcr.io/opentelemetry/operator - */ - exports.ATTR_CONTAINER_IMAGE_NAME = "container.image.name"; - /** - * Repo digests of the container image as provided by the container runtime. - * - * @example ["example@sha256:afcc7f1ac1b49db317a7196c902e61c6c3c4607d63599ee1a82d702d249a0ccb", "internal.registry.example.com:5000/example@sha256:b69959407d21e8a062e0416bf13405bb2b71ed7a84dde4158ebafacfa06f5578"] - * - * @note [Docker](https://docs.docker.com/reference/api/engine/version/v1.52/#tag/Image/operation/ImageInspect) and [CRI](https://github.com/kubernetes/cri-api/blob/c75ef5b473bbe2d0a4fc92f82235efd665ea8e9f/pkg/apis/runtime/v1/api.proto#L1237-L1238) report those under the `RepoDigests` field. - */ - exports.ATTR_CONTAINER_IMAGE_REPO_DIGESTS = "container.image.repo_digests"; - /** - * Container image tags. An example can be found in [Docker Image Inspect](https://docs.docker.com/reference/api/engine/version/v1.52/#tag/Image/operation/ImageInspect). Should be only the `` section of the full name for example from `registry.example.com/my-org/my-image:`. - * - * @example ["v1.27.1", "3.5.7-0"] - */ - exports.ATTR_CONTAINER_IMAGE_TAGS = "container.image.tags"; - /** - * The name of a collection (table, container) within the database. - * - * @example public.users - * @example customers - * - * @note It is **RECOMMENDED** to capture the value as provided by the application - * without attempting to do any case normalization. - * - * The collection name **SHOULD NOT** be extracted from `db.query.text`, - * when the database system supports query text with multiple collections - * in non-batch operations. - * - * For batch operations, if the individual operations are known to have the same - * collection name then that collection name **SHOULD** be used. - */ - exports.ATTR_DB_COLLECTION_NAME = "db.collection.name"; - /** - * The name of the database, fully qualified within the server address and port. - * - * @example customers - * @example test.users - * - * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted. - * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system. - * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization. - */ - exports.ATTR_DB_NAMESPACE = "db.namespace"; - /** - * The number of database operations included in a batch operation. - * - * @example 2 - * @example 3 - * @example 4 - * - * @note Except for empty batch requests described below, a batch operation contains two - * or more database operations explicitly submitted as separate operations in a single - * client call, protocol message, or database command. - * - * Requests to batch APIs that contain only one operation **SHOULD** be modeled as single - * operations, not as batch operations. - * - * A database call is not a batch operation solely because one operation accepts - * multiple operands, such as keys, rows, documents, points, or other data elements, - * including Redis [`MGET`](https://redis.io/docs/latest/commands/mget/) with - * multiple keys. - * - * In batch APIs that execute the same parameterized operation with parameter sets, - * each parameter set represents one database operation for determining whether the - * request is a batch operation. Requests with only one parameter set **SHOULD** be modeled - * as single operations, not as batch operations. - * - * `db.operation.batch.size` **SHOULD** be set to the number of operations in the batch. - * It **SHOULD NOT** be set for non-batch operations. - * - * A request to execute a batch operation with no operations **SHOULD** also be treated - * as a batch operation, and `db.operation.batch.size` **SHOULD** be set to `0`. - */ - exports.ATTR_DB_OPERATION_BATCH_SIZE = "db.operation.batch.size"; - /** - * The name of the operation or command being executed. - * - * @example findAndModify - * @example HMSET - * @example SELECT - * - * @note It is **RECOMMENDED** to capture the value as provided by the application - * without attempting to do any case normalization. - * - * The operation name **SHOULD NOT** be extracted from `db.query.text`, - * when the database system supports query text with multiple operations - * in non-batch operations. - * - * If spaces can occur in the operation name, multiple consecutive spaces - * **SHOULD** be normalized to a single space. - * - * For batch operations, if the individual operations are known to have the same operation name - * then that operation name **SHOULD** be used prepended by `BATCH `, - * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database - * system specific term if more applicable. - */ - exports.ATTR_DB_OPERATION_NAME = "db.operation.name"; - /** - * Low cardinality summary of a database query. - * - * @example SELECT wuser_table - * @example INSERT shipping_details SELECT orders - * @example get user by id - * - * @note The query summary describes a class of database queries and is useful - * as a grouping key, especially when analyzing telemetry for database - * calls involving complex queries. - * - * Summary may be available to the instrumentation through - * instrumentation hooks or other means. If it is not available, instrumentations - * that support query parsing **SHOULD** generate a summary following - * [Generating query summary](/docs/db/database-spans.md#generating-a-summary-of-the-query) - * section. - * - * For batch operations, if the individual operations are known to have the same query summary - * then that query summary **SHOULD** be used prepended by `BATCH `, - * otherwise `db.query.summary` **SHOULD** be `BATCH` or some other database - * system specific term if more applicable. - */ - exports.ATTR_DB_QUERY_SUMMARY = "db.query.summary"; - /** - * The database query being executed. - * - * @example SELECT * FROM wuser_table where username = ? - * @example SET mykey ? - * - * @note For sanitization see [Sanitization of `db.query.text`](/docs/db/database-spans.md#sanitization-of-dbquerytext). - * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable. - * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk. - */ - exports.ATTR_DB_QUERY_TEXT = "db.query.text"; - /** - * Database response status code. - * - * @example 102 - * @example ORA-17002 - * @example 08P01 - * @example 404 - * - * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes. - * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system. - */ - exports.ATTR_DB_RESPONSE_STATUS_CODE = "db.response.status_code"; - /** - * The name of a stored procedure within the database. - * - * @example GetCustomer - * - * @note It is **RECOMMENDED** to capture the value as provided by the application - * without attempting to do any case normalization. - * - * For batch operations, if the individual operations are known to have the same - * stored procedure name then that stored procedure name **SHOULD** be used. - */ - exports.ATTR_DB_STORED_PROCEDURE_NAME = "db.stored_procedure.name"; - /** - * The database management system (DBMS) product as identified by the client instrumentation. - * - * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge. - */ - exports.ATTR_DB_SYSTEM_NAME = "db.system.name"; - /** - * Enum value "mariadb" for attribute {@link ATTR_DB_SYSTEM_NAME}. - * - * [MariaDB](https://mariadb.org/) - */ - exports.DB_SYSTEM_NAME_VALUE_MARIADB = "mariadb"; - /** - * Enum value "microsoft.sql_server" for attribute {@link ATTR_DB_SYSTEM_NAME}. - * - * [Microsoft SQL Server](https://www.microsoft.com/sql-server) - */ - exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = "microsoft.sql_server"; - /** - * Enum value "mysql" for attribute {@link ATTR_DB_SYSTEM_NAME}. - * - * [MySQL](https://www.mysql.com/) - */ - exports.DB_SYSTEM_NAME_VALUE_MYSQL = "mysql"; - /** - * Enum value "postgresql" for attribute {@link ATTR_DB_SYSTEM_NAME}. - * - * [PostgreSQL](https://www.postgresql.org/) - */ - exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = "postgresql"; - /** - * Name of the [deployment environment](https://wikipedia.org/wiki/Deployment_environment) (aka deployment tier). - * - * @example staging - * @example production - * - * @note `deployment.environment.name` does not affect the uniqueness constraints defined through - * the `service.namespace`, `service.name` and `service.instance.id` resource attributes. - * This implies that resources carrying the following attribute combinations **MUST** be - * considered to be identifying the same service: - * - * - `service.name=frontend`, `deployment.environment.name=production` - * - `service.name=frontend`, `deployment.environment.name=staging`. - */ - exports.ATTR_DEPLOYMENT_ENVIRONMENT_NAME = "deployment.environment.name"; - /** - * Enum value "development" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}. - * - * Development environment - */ - exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT = "development"; - /** - * Enum value "production" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}. - * - * Production environment - */ - exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION = "production"; - /** - * Enum value "staging" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}. - * - * Staging environment - */ - exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING = "staging"; - /** - * Enum value "test" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}. - * - * Testing environment - */ - exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST = "test"; - /** - * Name of the garbage collector managed heap generation. - * - * @example gen0 - * @example gen1 - * @example gen2 - */ - exports.ATTR_DOTNET_GC_HEAP_GENERATION = "dotnet.gc.heap.generation"; - /** - * Enum value "gen0" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Generation 0 - */ - exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = "gen0"; - /** - * Enum value "gen1" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Generation 1 - */ - exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = "gen1"; - /** - * Enum value "gen2" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Generation 2 - */ - exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = "gen2"; - /** - * Enum value "loh" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Large Object Heap - */ - exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = "loh"; - /** - * Enum value "poh" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Pinned Object Heap - */ - exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = "poh"; - /** - * Describes a class of error the operation ended with. - * - * @example timeout - * @example java.net.UnknownHostException - * @example server_certificate_invalid - * @example 500 - * - * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality. - * - * When `error.type` is set to a type (e.g., an exception type), its - * canonical class name identifying the type within the artifact **SHOULD** be used. - * - * If the recorded error type is a wrapper that is not meaningful for - * failure classification, instrumentation **MAY** use the type of the inner - * error instead. For example, in Go, errors created with `fmt.Errorf` - * using `%w` **MAY** be unwrapped when the wrapper type does not help - * classify the failure. - * - * Instrumentations **SHOULD** document the list of errors they report. - * - * The cardinality of `error.type` within one instrumentation library **SHOULD** be low. - * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications - * should be prepared for `error.type` to have high cardinality at query time when no - * additional filters are applied. - * - * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`. - * - * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes), - * it's **RECOMMENDED** to: - * - * - Use a domain-specific attribute - * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not. - */ - exports.ATTR_ERROR_TYPE = "error.type"; - /** - * Enum value "_OTHER" for attribute {@link ATTR_ERROR_TYPE}. - * - * A fallback error value to be used when the instrumentation doesn't define a custom value. - */ - exports.ERROR_TYPE_VALUE_OTHER = "_OTHER"; - /** - * Indicates that the exception is escaping the scope of the span. - * - * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span. - */ - exports.ATTR_EXCEPTION_ESCAPED = "exception.escaped"; - /** - * The exception message. - * - * @example Division by zero - * @example Can't convert 'int' object to str implicitly - * - * @note > [!WARNING] - * - * > This attribute may contain sensitive information. - */ - exports.ATTR_EXCEPTION_MESSAGE = "exception.message"; - /** - * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. - * - * @example "Exception in thread "main" java.lang.RuntimeException: Test exception\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\n" - */ - exports.ATTR_EXCEPTION_STACKTRACE = "exception.stacktrace"; - /** - * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. - * - * @example java.net.ConnectException - * @example OSError - * - * @note If the recorded exception type is a wrapper that is not meaningful for - * failure classification, instrumentation **MAY** use the type of the inner - * exception instead. For example, in Go, errors created with `fmt.Errorf` - * using `%w` **MAY** be unwrapped when the wrapper type does not help - * classify the failure. - */ - exports.ATTR_EXCEPTION_TYPE = "exception.type"; - /** - * HTTP request headers, `` being the normalized HTTP Header name (lowercase), the value being the header values. - * - * @example ["application/json"] - * @example ["1.2.3.4", "1.2.3.5"] - * - * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured. - * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information. - * - * The `User-Agent` header is already captured in the `user_agent.original` attribute. - * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended. - * - * The attribute value **MUST** consist of either multiple header values as an array of strings - * or a single-item array containing a possibly comma-concatenated string, depending on the way - * the HTTP library provides access to headers. - * - * Examples: - * - * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type` - * attribute with value `["application/json"]`. - * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for` - * attribute with value `["1.2.3.4", "1.2.3.5"]` or `["1.2.3.4, 1.2.3.5"]` depending on the HTTP library. - */ - var ATTR_HTTP_REQUEST_HEADER = (key) => `http.request.header.${key}`; - exports.ATTR_HTTP_REQUEST_HEADER = ATTR_HTTP_REQUEST_HEADER; - /** - * HTTP request method. - * - * @example GET - * @example POST - * @example HEAD - * - * @note HTTP request method value **SHOULD** be "known" to the instrumentation. - * By default, this convention defines "known" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods), - * the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html) - * and the QUERY method defined in [httpbis-safe-method-w-body](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/?include_text=1). - * - * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`. - * - * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override - * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named - * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods. - * - * - * If this override is done via declarative configuration, then the list **MUST** be configurable via the `known_methods` property - * (an array of case-sensitive strings with minimum items 0) under `.instrumentation/development.general.http.client` and/or - * `.instrumentation/development.general.http.server`. - * - * In either case, this list **MUST** be a full override of the default known methods, - * it is not a list of known methods in addition to the defaults. - * - * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly. - * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent. - * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value. - */ - exports.ATTR_HTTP_REQUEST_METHOD = "http.request.method"; - /** - * Enum value "_OTHER" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * Any HTTP method that the instrumentation has no prior knowledge of. - */ - exports.HTTP_REQUEST_METHOD_VALUE_OTHER = "_OTHER"; - /** - * Enum value "CONNECT" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * CONNECT method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = "CONNECT"; - /** - * Enum value "DELETE" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * DELETE method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_DELETE = "DELETE"; - /** - * Enum value "GET" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * GET method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_GET = "GET"; - /** - * Enum value "HEAD" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * HEAD method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_HEAD = "HEAD"; - /** - * Enum value "OPTIONS" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * OPTIONS method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = "OPTIONS"; - /** - * Enum value "PATCH" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * PATCH method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_PATCH = "PATCH"; - /** - * Enum value "POST" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * POST method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_POST = "POST"; - /** - * Enum value "PUT" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * PUT method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_PUT = "PUT"; - /** - * Enum value "TRACE" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * TRACE method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_TRACE = "TRACE"; - /** - * Original HTTP method sent by the client in the request line. - * - * @example GeT - * @example ACL - * @example foo - */ - exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = "http.request.method_original"; - /** - * The ordinal number of request resending attempt (for any reason, including redirects). - * - * @example 3 - * - * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other). - */ - exports.ATTR_HTTP_REQUEST_RESEND_COUNT = "http.request.resend_count"; - /** - * HTTP response headers, `` being the normalized HTTP Header name (lowercase), the value being the header values. - * - * @example ["application/json"] - * @example ["abc", "def"] - * - * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured. - * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information. - * - * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended. - * - * The attribute value **MUST** consist of either multiple header values as an array of strings - * or a single-item array containing a possibly comma-concatenated string, depending on the way - * the HTTP library provides access to headers. - * - * Examples: - * - * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type` - * attribute with value `["application/json"]`. - * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header` - * attribute with value `["abc", "def"]` or `["abc, def"]` depending on the HTTP library. - */ - var ATTR_HTTP_RESPONSE_HEADER = (key) => `http.response.header.${key}`; - exports.ATTR_HTTP_RESPONSE_HEADER = ATTR_HTTP_RESPONSE_HEADER; - /** - * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6). - * - * @example 200 - */ - exports.ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code"; - /** - * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders. - * - * @example /users/:userID? - * @example my-controller/my-action/{id?} - * - * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it. - * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one. - * - * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that - * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`. - * - * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments. - * - * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY** - * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string. - */ - exports.ATTR_HTTP_ROUTE = "http.route"; - /** - * Name of the garbage collector action. - * - * @example end of minor GC - * @example end of major GC - * - * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()). - */ - exports.ATTR_JVM_GC_ACTION = "jvm.gc.action"; - /** - * Name of the garbage collector. - * - * @example G1 Young Generation - * @example G1 Old Generation - * - * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()). - */ - exports.ATTR_JVM_GC_NAME = "jvm.gc.name"; - /** - * Name of the memory pool. - * - * @example G1 Old Gen - * @example G1 Eden space - * @example G1 Survivor Space - * - * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()). - */ - exports.ATTR_JVM_MEMORY_POOL_NAME = "jvm.memory.pool.name"; - /** - * The type of memory. - * - * @example heap - * @example non_heap - */ - exports.ATTR_JVM_MEMORY_TYPE = "jvm.memory.type"; - /** - * Enum value "heap" for attribute {@link ATTR_JVM_MEMORY_TYPE}. - * - * Heap memory. - */ - exports.JVM_MEMORY_TYPE_VALUE_HEAP = "heap"; - /** - * Enum value "non_heap" for attribute {@link ATTR_JVM_MEMORY_TYPE}. - * - * Non-heap memory - */ - exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = "non_heap"; - /** - * Whether the thread is daemon or not. - */ - exports.ATTR_JVM_THREAD_DAEMON = "jvm.thread.daemon"; - /** - * State of the thread. - * - * @example runnable - * @example blocked - */ - exports.ATTR_JVM_THREAD_STATE = "jvm.thread.state"; - /** - * Enum value "blocked" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that is blocked waiting for a monitor lock is in this state. - */ - exports.JVM_THREAD_STATE_VALUE_BLOCKED = "blocked"; - /** - * Enum value "new" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that has not yet started is in this state. - */ - exports.JVM_THREAD_STATE_VALUE_NEW = "new"; - /** - * Enum value "runnable" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread executing in the Java virtual machine is in this state. - */ - exports.JVM_THREAD_STATE_VALUE_RUNNABLE = "runnable"; - /** - * Enum value "terminated" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that has exited is in this state. - */ - exports.JVM_THREAD_STATE_VALUE_TERMINATED = "terminated"; - /** - * Enum value "timed_waiting" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. - */ - exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = "timed_waiting"; - /** - * Enum value "waiting" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that is waiting indefinitely for another thread to perform a particular action is in this state. - */ - exports.JVM_THREAD_STATE_VALUE_WAITING = "waiting"; - /** - * The name of the cluster. - * - * @example opentelemetry-cluster - */ - exports.ATTR_K8S_CLUSTER_NAME = "k8s.cluster.name"; - /** - * A pseudo-ID for the cluster, set to the UID of the `kube-system` namespace. - * - * @example 218fc5a9-a5f1-4b54-aa05-46717d0ab26d - * - * @note K8s doesn't have support for obtaining a cluster ID. If this is ever - * added, we will recommend collecting the `k8s.cluster.uid` through the - * official APIs. In the meantime, we are able to use the `uid` of the - * `kube-system` namespace as a proxy for cluster ID. Read on for the - * rationale. - * - * Every object created in a K8s cluster is assigned a distinct UID. The - * `kube-system` namespace is used by Kubernetes itself and will exist - * for the lifetime of the cluster. Using the `uid` of the `kube-system` - * namespace is a reasonable proxy for the K8s ClusterID as it will only - * change if the cluster is rebuilt. Furthermore, Kubernetes UIDs are - * UUIDs as standardized by - * [ISO/IEC 9834-8 and ITU-T X.667](https://www.itu.int/ITU-T/studygroups/com17/oid.html). - * Which states: - * - * > If generated according to one of the mechanisms defined in Rec. - * > ITU-T X.667 | ISO/IEC 9834-8, a UUID is either guaranteed to be - * > different from all other UUIDs generated before 3603 A.D., or is - * > extremely likely to be different (depending on the mechanism chosen). - * - * Therefore, UIDs between clusters should be extremely unlikely to - * conflict. - */ - exports.ATTR_K8S_CLUSTER_UID = "k8s.cluster.uid"; - /** - * The name of the Container from Pod specification, must be unique within a Pod. Container runtime usually uses different globally unique name (`container.name`). - * - * @example redis - */ - exports.ATTR_K8S_CONTAINER_NAME = "k8s.container.name"; - /** - * Number of times the container was restarted. This attribute can be used to identify a particular container (running or stopped) within a container spec. - */ - exports.ATTR_K8S_CONTAINER_RESTART_COUNT = "k8s.container.restart_count"; - /** - * The cronjob annotation placed on the CronJob, the `` being the annotation name, the value being the annotation value. - * - * @example 4 - * @example - * - * @note Examples: - * - * - An annotation `retries` with value `4` **SHOULD** be recorded as the - * `k8s.cronjob.annotation.retries` attribute with value `"4"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.cronjob.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_CRONJOB_ANNOTATION = (key) => `k8s.cronjob.annotation.${key}`; - exports.ATTR_K8S_CRONJOB_ANNOTATION = ATTR_K8S_CRONJOB_ANNOTATION; - /** - * The label placed on the CronJob, the `` being the label name, the value being the label value. - * - * @example weekly - * @example - * - * @note Examples: - * - * - A label `type` with value `weekly` **SHOULD** be recorded as the - * `k8s.cronjob.label.type` attribute with value `"weekly"`. - * - A label `automated` with empty string value **SHOULD** be recorded as - * the `k8s.cronjob.label.automated` attribute with value `""`. - */ - var ATTR_K8S_CRONJOB_LABEL = (key) => `k8s.cronjob.label.${key}`; - exports.ATTR_K8S_CRONJOB_LABEL = ATTR_K8S_CRONJOB_LABEL; - /** - * The name of the CronJob. - * - * @example opentelemetry - */ - exports.ATTR_K8S_CRONJOB_NAME = "k8s.cronjob.name"; - /** - * The UID of the CronJob. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_CRONJOB_UID = "k8s.cronjob.uid"; - /** - * The annotation placed on the DaemonSet, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 1 - * @example - * - * @note - * Examples: - * - * - An annotation `replicas` with value `1` **SHOULD** be recorded - * as the `k8s.daemonset.annotation.replicas` attribute with value `"1"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.daemonset.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_DAEMONSET_ANNOTATION = (key) => `k8s.daemonset.annotation.${key}`; - exports.ATTR_K8S_DAEMONSET_ANNOTATION = ATTR_K8S_DAEMONSET_ANNOTATION; - /** - * The label placed on the DaemonSet, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example guestbook - * @example - * - * @note - * Examples: - * - * - A label `app` with value `guestbook` **SHOULD** be recorded - * as the `k8s.daemonset.label.app` attribute with value `"guestbook"`. - * - A label `injected` with empty string value **SHOULD** be recorded as - * the `k8s.daemonset.label.injected` attribute with value `""`. - */ - var ATTR_K8S_DAEMONSET_LABEL = (key) => `k8s.daemonset.label.${key}`; - exports.ATTR_K8S_DAEMONSET_LABEL = ATTR_K8S_DAEMONSET_LABEL; - /** - * The name of the DaemonSet. - * - * @example opentelemetry - */ - exports.ATTR_K8S_DAEMONSET_NAME = "k8s.daemonset.name"; - /** - * The UID of the DaemonSet. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_DAEMONSET_UID = "k8s.daemonset.uid"; - /** - * The annotation placed on the Deployment, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 1 - * @example - * - * @note - * Examples: - * - * - An annotation `replicas` with value `1` **SHOULD** be recorded - * as the `k8s.deployment.annotation.replicas` attribute with value `"1"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.deployment.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_DEPLOYMENT_ANNOTATION = (key) => `k8s.deployment.annotation.${key}`; - exports.ATTR_K8S_DEPLOYMENT_ANNOTATION = ATTR_K8S_DEPLOYMENT_ANNOTATION; - /** - * The label placed on the Deployment, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example guestbook - * @example - * - * @note - * Examples: - * - * - A label `app` with value `guestbook` **SHOULD** be recorded - * as the `k8s.deployment.label.app` attribute with value `"guestbook"`. - * - A label `injected` with empty string value **SHOULD** be recorded as - * the `k8s.deployment.label.injected` attribute with value `""`. - */ - var ATTR_K8S_DEPLOYMENT_LABEL = (key) => `k8s.deployment.label.${key}`; - exports.ATTR_K8S_DEPLOYMENT_LABEL = ATTR_K8S_DEPLOYMENT_LABEL; - /** - * The name of the Deployment. - * - * @example opentelemetry - */ - exports.ATTR_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; - /** - * The UID of the Deployment. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_DEPLOYMENT_UID = "k8s.deployment.uid"; - /** - * The annotation placed on the Job, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 1 - * @example - * - * @note - * Examples: - * - * - An annotation `number` with value `1` **SHOULD** be recorded - * as the `k8s.job.annotation.number` attribute with value `"1"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.job.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_JOB_ANNOTATION = (key) => `k8s.job.annotation.${key}`; - exports.ATTR_K8S_JOB_ANNOTATION = ATTR_K8S_JOB_ANNOTATION; - /** - * The label placed on the Job, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example ci - * @example - * - * @note - * Examples: - * - * - A label `jobtype` with value `ci` **SHOULD** be recorded - * as the `k8s.job.label.jobtype` attribute with value `"ci"`. - * - A label `automated` with empty string value **SHOULD** be recorded as - * the `k8s.job.label.automated` attribute with value `""`. - */ - var ATTR_K8S_JOB_LABEL = (key) => `k8s.job.label.${key}`; - exports.ATTR_K8S_JOB_LABEL = ATTR_K8S_JOB_LABEL; - /** - * The name of the Job. - * - * @example opentelemetry - */ - exports.ATTR_K8S_JOB_NAME = "k8s.job.name"; - /** - * The UID of the Job. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_JOB_UID = "k8s.job.uid"; - /** - * The annotation placed on the Namespace, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 0 - * @example - * - * @note - * Examples: - * - * - An annotation `ttl` with value `0` **SHOULD** be recorded - * as the `k8s.namespace.annotation.ttl` attribute with value `"0"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.namespace.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_NAMESPACE_ANNOTATION = (key) => `k8s.namespace.annotation.${key}`; - exports.ATTR_K8S_NAMESPACE_ANNOTATION = ATTR_K8S_NAMESPACE_ANNOTATION; - /** - * The label placed on the Namespace, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example default - * @example - * - * @note - * Examples: - * - * - A label `kubernetes.io/metadata.name` with value `default` **SHOULD** be recorded - * as the `k8s.namespace.label.kubernetes.io/metadata.name` attribute with value `"default"`. - * - A label `data` with empty string value **SHOULD** be recorded as - * the `k8s.namespace.label.data` attribute with value `""`. - */ - var ATTR_K8S_NAMESPACE_LABEL = (key) => `k8s.namespace.label.${key}`; - exports.ATTR_K8S_NAMESPACE_LABEL = ATTR_K8S_NAMESPACE_LABEL; - /** - * The name of the namespace that the pod is running in. - * - * @example default - */ - exports.ATTR_K8S_NAMESPACE_NAME = "k8s.namespace.name"; - /** - * The annotation placed on the Node, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 0 - * @example - * - * @note Examples: - * - * - An annotation `node.alpha.kubernetes.io/ttl` with value `0` **SHOULD** be recorded as - * the `k8s.node.annotation.node.alpha.kubernetes.io/ttl` attribute with value `"0"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.node.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_NODE_ANNOTATION = (key) => `k8s.node.annotation.${key}`; - exports.ATTR_K8S_NODE_ANNOTATION = ATTR_K8S_NODE_ANNOTATION; - /** - * The label placed on the Node, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example arm64 - * @example - * - * @note Examples: - * - * - A label `kubernetes.io/arch` with value `arm64` **SHOULD** be recorded - * as the `k8s.node.label.kubernetes.io/arch` attribute with value `"arm64"`. - * - A label `data` with empty string value **SHOULD** be recorded as - * the `k8s.node.label.data` attribute with value `""`. - */ - var ATTR_K8S_NODE_LABEL = (key) => `k8s.node.label.${key}`; - exports.ATTR_K8S_NODE_LABEL = ATTR_K8S_NODE_LABEL; - /** - * The name of the Node. - * - * @example node-1 - */ - exports.ATTR_K8S_NODE_NAME = "k8s.node.name"; - /** - * The UID of the Node. - * - * @example 1eb3a0c6-0477-4080-a9cb-0cb7db65c6a2 - */ - exports.ATTR_K8S_NODE_UID = "k8s.node.uid"; - /** - * The annotation placed on the Pod, the `` being the annotation name, the value being the annotation value. - * - * @example true - * @example x64 - * @example - * - * @note Examples: - * - * - An annotation `kubernetes.io/enforce-mountable-secrets` with value `true` **SHOULD** be recorded as - * the `k8s.pod.annotation.kubernetes.io/enforce-mountable-secrets` attribute with value `"true"`. - * - An annotation `mycompany.io/arch` with value `x64` **SHOULD** be recorded as - * the `k8s.pod.annotation.mycompany.io/arch` attribute with value `"x64"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.pod.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_POD_ANNOTATION = (key) => `k8s.pod.annotation.${key}`; - exports.ATTR_K8S_POD_ANNOTATION = ATTR_K8S_POD_ANNOTATION; - /** - * Specifies the hostname of the Pod. - * - * @example collector-gateway - * - * @note The K8s Pod spec has an optional hostname field, which can be used to specify a hostname. - * Refer to [K8s docs](https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-hostname-and-subdomain-field) - * for more information about this field. - * - * This attribute aligns with the `hostname` field of the - * [K8s PodSpec](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.34/#podspec-v1-core). - */ - exports.ATTR_K8S_POD_HOSTNAME = "k8s.pod.hostname"; - /** - * IP address allocated to the Pod. - * - * @example 172.18.0.2 - * - * @note This attribute aligns with the `podIP` field of the - * [K8s PodStatus](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.34/#podstatus-v1-core). - */ - exports.ATTR_K8S_POD_IP = "k8s.pod.ip"; - /** - * The label placed on the Pod, the `` being the label name, the value being the label value. - * - * @example my-app - * @example x64 - * @example - * - * @note Examples: - * - * - A label `app` with value `my-app` **SHOULD** be recorded as - * the `k8s.pod.label.app` attribute with value `"my-app"`. - * - A label `mycompany.io/arch` with value `x64` **SHOULD** be recorded as - * the `k8s.pod.label.mycompany.io/arch` attribute with value `"x64"`. - * - A label `data` with empty string value **SHOULD** be recorded as - * the `k8s.pod.label.data` attribute with value `""`. - */ - var ATTR_K8S_POD_LABEL = (key) => `k8s.pod.label.${key}`; - exports.ATTR_K8S_POD_LABEL = ATTR_K8S_POD_LABEL; - /** - * The name of the Pod. - * - * @example opentelemetry-pod-autoconf - */ - exports.ATTR_K8S_POD_NAME = "k8s.pod.name"; - /** - * The start timestamp of the Pod. - * - * @example 2025-12-04T08:41:03Z - * - * @note Date and time at which the object was acknowledged by the Kubelet. - * This is before the Kubelet pulled the container image(s) for the pod. - * - * This attribute aligns with the `startTime` field of the - * [K8s PodStatus](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.34/#podstatus-v1-core), - * in ISO 8601 (RFC 3339 compatible) format. - */ - exports.ATTR_K8S_POD_START_TIME = "k8s.pod.start_time"; - /** - * The UID of the Pod. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_POD_UID = "k8s.pod.uid"; - /** - * The annotation placed on the ReplicaSet, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 0 - * @example - * - * @note - * Examples: - * - * - An annotation `replicas` with value `0` **SHOULD** be recorded - * as the `k8s.replicaset.annotation.replicas` attribute with value `"0"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.replicaset.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_REPLICASET_ANNOTATION = (key) => `k8s.replicaset.annotation.${key}`; - exports.ATTR_K8S_REPLICASET_ANNOTATION = ATTR_K8S_REPLICASET_ANNOTATION; - /** - * The label placed on the ReplicaSet, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example guestbook - * @example - * - * @note - * Examples: - * - * - A label `app` with value `guestbook` **SHOULD** be recorded - * as the `k8s.replicaset.label.app` attribute with value `"guestbook"`. - * - A label `injected` with empty string value **SHOULD** be recorded as - * the `k8s.replicaset.label.injected` attribute with value `""`. - */ - var ATTR_K8S_REPLICASET_LABEL = (key) => `k8s.replicaset.label.${key}`; - exports.ATTR_K8S_REPLICASET_LABEL = ATTR_K8S_REPLICASET_LABEL; - /** - * The name of the ReplicaSet. - * - * @example opentelemetry - */ - exports.ATTR_K8S_REPLICASET_NAME = "k8s.replicaset.name"; - /** - * The UID of the ReplicaSet. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_REPLICASET_UID = "k8s.replicaset.uid"; - /** - * The annotation placed on the StatefulSet, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 1 - * @example - * - * @note - * Examples: - * - * - An annotation `replicas` with value `1` **SHOULD** be recorded - * as the `k8s.statefulset.annotation.replicas` attribute with value `"1"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.statefulset.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_STATEFULSET_ANNOTATION = (key) => `k8s.statefulset.annotation.${key}`; - exports.ATTR_K8S_STATEFULSET_ANNOTATION = ATTR_K8S_STATEFULSET_ANNOTATION; - /** - * The label placed on the StatefulSet, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example guestbook - * @example - * - * @note - * Examples: - * - * - A label `app` with value `guestbook` **SHOULD** be recorded - * as the `k8s.statefulset.label.app` attribute with value `"guestbook"`. - * - A label `injected` with empty string value **SHOULD** be recorded as - * the `k8s.statefulset.label.injected` attribute with value `""`. - */ - var ATTR_K8S_STATEFULSET_LABEL = (key) => `k8s.statefulset.label.${key}`; - exports.ATTR_K8S_STATEFULSET_LABEL = ATTR_K8S_STATEFULSET_LABEL; - /** - * The name of the StatefulSet. - * - * @example opentelemetry - */ - exports.ATTR_K8S_STATEFULSET_NAME = "k8s.statefulset.name"; - /** - * The UID of the StatefulSet. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_STATEFULSET_UID = "k8s.statefulset.uid"; - /** - * Local address of the network connection - IP address or Unix domain socket name. - * - * @example 10.1.2.80 - * @example /tmp/my.sock - */ - exports.ATTR_NETWORK_LOCAL_ADDRESS = "network.local.address"; - /** - * Local port number of the network connection. - * - * @example 65123 - */ - exports.ATTR_NETWORK_LOCAL_PORT = "network.local.port"; - /** - * Peer address of the network connection - IP address or Unix domain socket name. - * - * @example 10.1.2.80 - * @example /tmp/my.sock - */ - exports.ATTR_NETWORK_PEER_ADDRESS = "network.peer.address"; - /** - * Peer port number of the network connection. - * - * @example 65123 - */ - exports.ATTR_NETWORK_PEER_PORT = "network.peer.port"; - /** - * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent. - * - * @example amqp - * @example http - * @example mqtt - * - * @note The value **SHOULD** be normalized to lowercase. - */ - exports.ATTR_NETWORK_PROTOCOL_NAME = "network.protocol.name"; - /** - * The actual version of the protocol used for network communication. - * - * @example 1.1 - * @example 2 - * - * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set. - */ - exports.ATTR_NETWORK_PROTOCOL_VERSION = "network.protocol.version"; - /** - * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication). - * - * @example tcp - * @example udp - * - * @note The value **SHOULD** be normalized to lowercase. - * - * Consider always setting the transport when setting a port number, since - * a port number is ambiguous without knowing the transport. For example - * different processes could be listening on TCP port 12345 and UDP port 12345. - */ - exports.ATTR_NETWORK_TRANSPORT = "network.transport"; - /** - * Enum value "pipe" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * Named or anonymous pipe. - */ - exports.NETWORK_TRANSPORT_VALUE_PIPE = "pipe"; - /** - * Enum value "quic" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * QUIC - */ - exports.NETWORK_TRANSPORT_VALUE_QUIC = "quic"; - /** - * Enum value "tcp" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * TCP - */ - exports.NETWORK_TRANSPORT_VALUE_TCP = "tcp"; - /** - * Enum value "udp" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * UDP - */ - exports.NETWORK_TRANSPORT_VALUE_UDP = "udp"; - /** - * Enum value "unix" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * Unix domain socket - */ - exports.NETWORK_TRANSPORT_VALUE_UNIX = "unix"; - /** - * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent. - * - * @example ipv4 - * @example ipv6 - * - * @note The value **SHOULD** be normalized to lowercase. - */ - exports.ATTR_NETWORK_TYPE = "network.type"; - /** - * Enum value "ipv4" for attribute {@link ATTR_NETWORK_TYPE}. - * - * IPv4 - */ - exports.NETWORK_TYPE_VALUE_IPV4 = "ipv4"; - /** - * Enum value "ipv6" for attribute {@link ATTR_NETWORK_TYPE}. - * - * IPv6 - */ - exports.NETWORK_TYPE_VALUE_IPV6 = "ipv6"; - /** - * Identifies the class / type of event. - * - * @example browser.mouse.click - * @example device.app.lifecycle - * - * @note This attribute **SHOULD** be used by non-OTLP exporters when destination does not support `EventName` or equivalent field. This attribute **MAY** be used by applications using existing logging libraries so that it can be used to set the `EventName` field by Collector or SDK components. - */ - exports.ATTR_OTEL_EVENT_NAME = "otel.event.name"; - /** - * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP). - * - * @example io.opentelemetry.contrib.mongodb - */ - exports.ATTR_OTEL_SCOPE_NAME = "otel.scope.name"; - /** - * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP). - * - * @example 1.0.0 - */ - exports.ATTR_OTEL_SCOPE_VERSION = "otel.scope.version"; - /** - * Name of the code, either "OK" or "ERROR". **MUST NOT** be set if the status code is UNSET. - */ - exports.ATTR_OTEL_STATUS_CODE = "otel.status_code"; - /** - * Enum value "ERROR" for attribute {@link ATTR_OTEL_STATUS_CODE}. - * - * The operation contains an error. - */ - exports.OTEL_STATUS_CODE_VALUE_ERROR = "ERROR"; - /** - * Enum value "OK" for attribute {@link ATTR_OTEL_STATUS_CODE}. - * - * The operation has been validated by an Application developer or Operator to have completed successfully. - */ - exports.OTEL_STATUS_CODE_VALUE_OK = "OK"; - /** - * Description of the Status if it has a value, otherwise not set. - * - * @example resource not found - */ - exports.ATTR_OTEL_STATUS_DESCRIPTION = "otel.status_description"; - /** - * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name. - * - * @example example.com - * @example 10.1.2.80 - * @example /tmp/my.sock - * - * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available. - */ - exports.ATTR_SERVER_ADDRESS = "server.address"; - /** - * Server port number. - * - * @example 80 - * @example 8080 - * @example 443 - * - * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available. - */ - exports.ATTR_SERVER_PORT = "server.port"; - /** - * The string ID of the service instance. - * - * @example 627cc493-f310-47de-96bd-71410b7dec09 - * - * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words - * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to - * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled - * service). - * - * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC - * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of - * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and - * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`. - * - * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is - * needed. Similar to what can be seen in the man page for the - * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying - * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it - * or not via another resource attribute. - * - * For applications running behind an application server (like unicorn), we do not recommend using one identifier - * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker - * thread in unicorn) to have its own instance.id. - * - * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the - * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will - * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated. - * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance - * for that telemetry. This is typically the case for scraping receivers, as they know the target address and - * port. - */ - exports.ATTR_SERVICE_INSTANCE_ID = "service.instance.id"; - /** - * Logical name of the service. - * - * @example shoppingcart - * - * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with the process executable name, e.g. `unknown_service:bash`. If the process executable name is not available, the value **MUST** be set to `unknown_service`. - * The process executable name is the name of the process executable, the same value as described by the [`process.executable.name`](process.md) resource attribute. - */ - exports.ATTR_SERVICE_NAME = "service.name"; - /** - * A namespace for `service.name`. - * - * @example Shop - * - * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace. - */ - exports.ATTR_SERVICE_NAMESPACE = "service.namespace"; - /** - * The version string of the service component. The format is not defined by these conventions. - * - * @example 2.0.0 - * @example a01dbef8a - */ - exports.ATTR_SERVICE_VERSION = "service.version"; - /** - * SignalR HTTP connection closure status. - * - * @example app_shutdown - * @example timeout - */ - exports.ATTR_SIGNALR_CONNECTION_STATUS = "signalr.connection.status"; - /** - * Enum value "app_shutdown" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. - * - * The connection was closed because the app is shutting down. - */ - exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = "app_shutdown"; - /** - * Enum value "normal_closure" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. - * - * The connection was closed normally. - */ - exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = "normal_closure"; - /** - * Enum value "timeout" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. - * - * The connection was closed due to a timeout. - */ - exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = "timeout"; - /** - * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md) - * - * @example web_sockets - * @example long_polling - */ - exports.ATTR_SIGNALR_TRANSPORT = "signalr.transport"; - /** - * Enum value "long_polling" for attribute {@link ATTR_SIGNALR_TRANSPORT}. - * - * LongPolling protocol - */ - exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = "long_polling"; - /** - * Enum value "server_sent_events" for attribute {@link ATTR_SIGNALR_TRANSPORT}. - * - * ServerSentEvents protocol - */ - exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = "server_sent_events"; - /** - * Enum value "web_sockets" for attribute {@link ATTR_SIGNALR_TRANSPORT}. - * - * WebSockets protocol - */ - exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = "web_sockets"; - /** - * The name of the auto instrumentation agent or distribution, if used. - * - * @example parts-unlimited-java - * - * @note Official auto instrumentation agents and distributions **SHOULD** set the `telemetry.distro.name` attribute to - * a string starting with `opentelemetry-`, e.g. `opentelemetry-java-instrumentation`. - */ - exports.ATTR_TELEMETRY_DISTRO_NAME = "telemetry.distro.name"; - /** - * The version string of the auto instrumentation agent or distribution, if used. - * - * @example 1.2.3 - */ - exports.ATTR_TELEMETRY_DISTRO_VERSION = "telemetry.distro.version"; - /** - * The language of the telemetry SDK. - */ - exports.ATTR_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; - /** - * Enum value "cpp" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = "cpp"; - /** - * Enum value "dotnet" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = "dotnet"; - /** - * Enum value "erlang" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = "erlang"; - /** - * Enum value "go" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = "go"; - /** - * Enum value "java" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = "java"; - /** - * Enum value "kotlin" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_KOTLIN = "kotlin"; - /** - * Enum value "nodejs" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs"; - /** - * Enum value "php" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = "php"; - /** - * Enum value "python" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = "python"; - /** - * Enum value "ruby" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = "ruby"; - /** - * Enum value "rust" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = "rust"; - /** - * Enum value "swift" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = "swift"; - /** - * Enum value "webjs" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = "webjs"; - /** - * The name of the telemetry SDK as defined above. - * - * @example opentelemetry - * - * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`. - * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the - * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point - * or another suitable identifier depending on the language. - * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case. - * All custom identifiers **SHOULD** be stable across different versions of an implementation. - */ - exports.ATTR_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; - /** - * The version string of the telemetry SDK. - * - * @example 1.2.3 - */ - exports.ATTR_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; - /** - * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component - * - * @example SemConv - */ - exports.ATTR_URL_FRAGMENT = "url.fragment"; - /** - * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986) - * - * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv - * @example //localhost - * - * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment - * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless. - * - * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`. - * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`. - * - * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed). - * - * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it. - * - * - * Query string values for the following keys **SHOULD** be redacted by default and replaced by the - * value `REDACTED`: - * - * - [`X-Amz-Signature`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) - * - [`X-Amz-Credential`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) - * - [`X-Amz-Security-Token`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) - * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token) - * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls) - * - * This list is subject to change over time. - * - * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive. - * - * - * Instrumentation **MAY** provide a way to override this list via declarative configuration. - * If so, it **SHOULD** use the `sensitive_query_parameters` property - * (an array of case-sensitive strings with minimum items 0) under - * `.instrumentation/development.general.sanitization.url`. - * This list is a full override of the default sensitive query parameter keys, - * it is not a list of keys in addition to the defaults. - * - * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g. - * `https://www.example.com/path?color=blue&sig=REDACTED`. - */ - exports.ATTR_URL_FULL = "url.full"; - /** - * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component - * - * @example /search - * - * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it. - */ - exports.ATTR_URL_PATH = "url.path"; - /** - * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component - * - * @example q=OpenTelemetry - * - * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it. - * - * - * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`: - * - * - [`X-Amz-Signature`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) - * - [`X-Amz-Credential`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) - * - [`X-Amz-Security-Token`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) - * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token) - * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls) - * - * This list is subject to change over time. - * - * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive. - * - * Instrumentation **MAY** provide a way to override this list via declarative configuration. - * If so, it **SHOULD** use the `sensitive_query_parameters` property - * (an array of case-sensitive strings with minimum items 0) under - * `.instrumentation/development.general.sanitization.url`. - * This list is a full override of the default sensitive query parameter keys, - * it is not a list of keys in addition to the defaults. - * - * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g. - * `q=OpenTelemetry&sig=REDACTED`. - */ - exports.ATTR_URL_QUERY = "url.query"; - /** - * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol. - * - * @example https - * @example ftp - * @example telnet - */ - exports.ATTR_URL_SCHEME = "url.scheme"; - /** - * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client. - * - * @example CERN-LineMode/2.15 libwww/2.17b3 - * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1 - * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2 - */ - exports.ATTR_USER_AGENT_ORIGINAL = "user_agent.original"; -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js -var require_stable_metrics = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = exports.METRIC_KESTREL_REJECTED_CONNECTIONS = exports.METRIC_KESTREL_QUEUED_REQUESTS = exports.METRIC_KESTREL_QUEUED_CONNECTIONS = exports.METRIC_KESTREL_CONNECTION_DURATION = exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = exports.METRIC_JVM_THREAD_COUNT = exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = exports.METRIC_JVM_MEMORY_USED = exports.METRIC_JVM_MEMORY_LIMIT = exports.METRIC_JVM_MEMORY_COMMITTED = exports.METRIC_JVM_GC_DURATION = exports.METRIC_JVM_CPU_TIME = exports.METRIC_JVM_CPU_RECENT_UTILIZATION = exports.METRIC_JVM_CPU_COUNT = exports.METRIC_JVM_CLASS_UNLOADED = exports.METRIC_JVM_CLASS_LOADED = exports.METRIC_JVM_CLASS_COUNT = exports.METRIC_HTTP_SERVER_REQUEST_DURATION = exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = exports.METRIC_DOTNET_TIMER_COUNT = exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = exports.METRIC_DOTNET_PROCESS_CPU_TIME = exports.METRIC_DOTNET_PROCESS_CPU_COUNT = exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = exports.METRIC_DOTNET_JIT_COMPILED_METHODS = exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = exports.METRIC_DOTNET_JIT_COMPILATION_TIME = exports.METRIC_DOTNET_GC_PAUSE_TIME = exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = exports.METRIC_DOTNET_GC_COLLECTIONS = exports.METRIC_DOTNET_EXCEPTIONS = exports.METRIC_DOTNET_ASSEMBLY_COUNT = exports.METRIC_DB_CLIENT_OPERATION_DURATION = exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = void 0; - exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = void 0; - /** - * Number of exceptions caught by exception handling middleware. - * - * @note Meter name: `Microsoft.AspNetCore.Diagnostics`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = "aspnetcore.diagnostics.exceptions"; - /** - * Number of requests that are currently active on the server that hold a rate limiting lease. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = "aspnetcore.rate_limiting.active_request_leases"; - /** - * Number of requests that are currently queued, waiting to acquire a rate limiting lease. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = "aspnetcore.rate_limiting.queued_requests"; - /** - * The time the request spent in a queue waiting to acquire a rate limiting lease. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = "aspnetcore.rate_limiting.request.time_in_queue"; - /** - * The duration of rate limiting lease held by requests on the server. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = "aspnetcore.rate_limiting.request_lease.duration"; - /** - * Number of requests that tried to acquire a rate limiting lease. - * - * @note Requests could be: - * - * - Rejected by global or endpoint rate limiting policies - * - Canceled while waiting for the lease. - * - * Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = "aspnetcore.rate_limiting.requests"; - /** - * Number of requests that were attempted to be matched to an endpoint. - * - * @note Meter name: `Microsoft.AspNetCore.Routing`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = "aspnetcore.routing.match_attempts"; - /** - * Duration of database client operations. - * - * @note Batch operations **SHOULD** be recorded as a single operation. - */ - exports.METRIC_DB_CLIENT_OPERATION_DURATION = "db.client.operation.duration"; - /** - * The number of .NET assemblies that are currently loaded. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`AppDomain.CurrentDomain.GetAssemblies().Length`](https://learn.microsoft.com/dotnet/api/system.appdomain.getassemblies). - */ - exports.METRIC_DOTNET_ASSEMBLY_COUNT = "dotnet.assembly.count"; - /** - * The number of exceptions that have been thrown in managed code. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as counting calls to [`AppDomain.CurrentDomain.FirstChanceException`](https://learn.microsoft.com/dotnet/api/system.appdomain.firstchanceexception). - */ - exports.METRIC_DOTNET_EXCEPTIONS = "dotnet.exceptions"; - /** - * The number of garbage collections that have occurred since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric uses the [`GC.CollectionCount(int generation)`](https://learn.microsoft.com/dotnet/api/system.gc.collectioncount) API to calculate exclusive collections per generation. - */ - exports.METRIC_DOTNET_GC_COLLECTIONS = "dotnet.gc.collections"; - /** - * The *approximate* number of bytes allocated on the managed GC heap since the process has started. The returned value does not include any native allocations. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetTotalAllocatedBytes()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalallocatedbytes). - */ - exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = "dotnet.gc.heap.total_allocated"; - /** - * The heap fragmentation, as observed during the latest garbage collection. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.FragmentationAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.fragmentationafterbytes). - */ - exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = "dotnet.gc.last_collection.heap.fragmentation.size"; - /** - * The managed GC heap size (including fragmentation), as observed during the latest garbage collection. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.SizeAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.sizeafterbytes). - */ - exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = "dotnet.gc.last_collection.heap.size"; - /** - * The amount of committed virtual memory in use by the .NET GC, as observed during the latest garbage collection. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetGCMemoryInfo().TotalCommittedBytes`](https://learn.microsoft.com/dotnet/api/system.gcmemoryinfo.totalcommittedbytes). Committed virtual memory may be larger than the heap size because it includes both memory for storing existing objects (the heap size) and some extra memory that is ready to handle newly allocated objects in the future. - */ - exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = "dotnet.gc.last_collection.memory.committed_size"; - /** - * The total amount of time paused in GC since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetTotalPauseDuration()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalpauseduration). - */ - exports.METRIC_DOTNET_GC_PAUSE_TIME = "dotnet.gc.pause.time"; - /** - * The amount of time the JIT compiler has spent compiling methods since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`JitInfo.GetCompilationTime()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompilationtime). - */ - exports.METRIC_DOTNET_JIT_COMPILATION_TIME = "dotnet.jit.compilation.time"; - /** - * Count of bytes of intermediate language that have been compiled since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`JitInfo.GetCompiledILBytes()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledilbytes). - */ - exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = "dotnet.jit.compiled_il.size"; - /** - * The number of times the JIT compiler (re)compiled methods since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`JitInfo.GetCompiledMethodCount()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledmethodcount). - */ - exports.METRIC_DOTNET_JIT_COMPILED_METHODS = "dotnet.jit.compiled_methods"; - /** - * The number of times there was contention when trying to acquire a monitor lock since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`Monitor.LockContentionCount`](https://learn.microsoft.com/dotnet/api/system.threading.monitor.lockcontentioncount). - */ - exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = "dotnet.monitor.lock_contentions"; - /** - * The number of processors available to the process. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as accessing [`Environment.ProcessorCount`](https://learn.microsoft.com/dotnet/api/system.environment.processorcount). - */ - exports.METRIC_DOTNET_PROCESS_CPU_COUNT = "dotnet.process.cpu.count"; - /** - * CPU time used by the process. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as accessing the corresponding processor time properties on [`System.Diagnostics.Process`](https://learn.microsoft.com/dotnet/api/system.diagnostics.process). - */ - exports.METRIC_DOTNET_PROCESS_CPU_TIME = "dotnet.process.cpu.time"; - /** - * The number of bytes of physical memory mapped to the process context. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`Environment.WorkingSet`](https://learn.microsoft.com/dotnet/api/system.environment.workingset). - */ - exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = "dotnet.process.memory.working_set"; - /** - * The number of work items that are currently queued to be processed by the thread pool. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`ThreadPool.PendingWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.pendingworkitemcount). - */ - exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = "dotnet.thread_pool.queue.length"; - /** - * The number of thread pool threads that currently exist. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`ThreadPool.ThreadCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.threadcount). - */ - exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = "dotnet.thread_pool.thread.count"; - /** - * The number of work items that the thread pool has completed since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`ThreadPool.CompletedWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.completedworkitemcount). - */ - exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = "dotnet.thread_pool.work_item.count"; - /** - * The number of timer instances that are currently active. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`Timer.ActiveCount`](https://learn.microsoft.com/dotnet/api/system.threading.timer.activecount). - */ - exports.METRIC_DOTNET_TIMER_COUNT = "dotnet.timer.count"; - /** - * Duration of HTTP client requests. - */ - exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = "http.client.request.duration"; - /** - * Duration of HTTP server requests. - */ - exports.METRIC_HTTP_SERVER_REQUEST_DURATION = "http.server.request.duration"; - /** - * Number of classes currently loaded. - */ - exports.METRIC_JVM_CLASS_COUNT = "jvm.class.count"; - /** - * Number of classes loaded since JVM start. - */ - exports.METRIC_JVM_CLASS_LOADED = "jvm.class.loaded"; - /** - * Number of classes unloaded since JVM start. - */ - exports.METRIC_JVM_CLASS_UNLOADED = "jvm.class.unloaded"; - /** - * Number of processors available to the Java virtual machine. - */ - exports.METRIC_JVM_CPU_COUNT = "jvm.cpu.count"; - /** - * Recent CPU utilization for the process as reported by the JVM. - * - * @note The value range is [0.0,1.0]. This utilization is not defined as being for the specific interval since last measurement (unlike `system.cpu.utilization`). [Reference](https://docs.oracle.com/en/java/javase/17/docs/api/jdk.management/com/sun/management/OperatingSystemMXBean.html#getProcessCpuLoad()). - */ - exports.METRIC_JVM_CPU_RECENT_UTILIZATION = "jvm.cpu.recent_utilization"; - /** - * CPU time used by the process as reported by the JVM. - */ - exports.METRIC_JVM_CPU_TIME = "jvm.cpu.time"; - /** - * Duration of JVM garbage collection actions. - */ - exports.METRIC_JVM_GC_DURATION = "jvm.gc.duration"; - /** - * Measure of memory committed. - */ - exports.METRIC_JVM_MEMORY_COMMITTED = "jvm.memory.committed"; - /** - * Measure of max obtainable memory. - */ - exports.METRIC_JVM_MEMORY_LIMIT = "jvm.memory.limit"; - /** - * Measure of memory used. - */ - exports.METRIC_JVM_MEMORY_USED = "jvm.memory.used"; - /** - * Measure of memory used, as measured after the most recent garbage collection event on this pool. - */ - exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = "jvm.memory.used_after_last_gc"; - /** - * Number of executing platform threads. - */ - exports.METRIC_JVM_THREAD_COUNT = "jvm.thread.count"; - /** - * Number of connections that are currently active on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = "kestrel.active_connections"; - /** - * Number of TLS handshakes that are currently in progress on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = "kestrel.active_tls_handshakes"; - /** - * The duration of connections on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_CONNECTION_DURATION = "kestrel.connection.duration"; - /** - * Number of connections that are currently queued and are waiting to start. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_QUEUED_CONNECTIONS = "kestrel.queued_connections"; - /** - * Number of HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are currently queued and are waiting to start. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_QUEUED_REQUESTS = "kestrel.queued_requests"; - /** - * Number of connections rejected by the server. - * - * @note Connections are rejected when the currently active count exceeds the value configured with `MaxConcurrentConnections`. - * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_REJECTED_CONNECTIONS = "kestrel.rejected_connections"; - /** - * The duration of TLS handshakes on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = "kestrel.tls_handshake.duration"; - /** - * Number of connections that are currently upgraded (WebSockets). . - * - * @note The counter only tracks HTTP/1.1 connections. - * - * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = "kestrel.upgraded_connections"; - /** - * Number of connections that are currently active on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = "signalr.server.active_connections"; - /** - * The duration of connections on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = "signalr.server.connection.duration"; -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js -var require_stable_events = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.EVENT_EXCEPTION = void 0; - /** - * This event describes a single exception. - */ - exports.EVENT_EXCEPTION = "exception"; -})); -//#endregion -//#region node_modules/@better-auth/core/dist/instrumentation/attributes.mjs -var import_src = (/* @__PURE__ */ __commonJSMin(((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = { - enumerable: true, - get: function() { - return m[k]; - } - }; - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar = exports && exports.__exportStar || function(m, exports$1) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - __exportStar(require_trace(), exports); - __exportStar(require_resource(), exports); - __exportStar(require_stable_attributes(), exports); - __exportStar(require_stable_metrics(), exports); - __exportStar(require_stable_events(), exports); -})))(); -/** Operation identifier (e.g. getSession, signUpWithEmailAndPassword). Uses endpoint operationId when set, otherwise the endpoint key. */ -var ATTR_OPERATION_ID = "better_auth.operation_id"; -/** Hook type (e.g. before, after, create.before). */ -var ATTR_HOOK_TYPE = "better_auth.hook.type"; -/** Execution context (e.g. user, plugin:id). */ -var ATTR_CONTEXT = "better_auth.context"; -//#endregion -//#region node_modules/@better-auth/core/dist/instrumentation/noop.mjs -function createNoopSpan() { - const span = { - end() {}, - setAttribute(_key, _value) {}, - setStatus(_status) {}, - recordException(_exception) {}, - updateName(_name) { - return span; - } - }; - return span; -} -function createNoopTracer(noopSpan) { - function startActiveSpan(_name, ...rest) { - const fn = rest[rest.length - 1]; - return fn(noopSpan); - } - return { startActiveSpan }; -} -function createNoopTraceAPI() { - const noopTracer = createNoopTracer(createNoopSpan()); - return { - getTracer(_name, _version) { - return noopTracer; - }, - getActiveSpan() {} - }; -} -function createNoopOpenTelemetryAPI() { - return { - SpanStatusCode: { - UNSET: 0, - OK: 1, - ERROR: 2 - }, - trace: createNoopTraceAPI() - }; -} -var noopOpenTelemetryAPI = createNoopOpenTelemetryAPI(); -//#endregion -//#region node_modules/@better-auth/core/dist/instrumentation/api.mjs -var openTelemetryAPIPromise; -var openTelemetryAPI; -function getOpenTelemetryAPI() { - if (!openTelemetryAPIPromise) openTelemetryAPIPromise = import("../../_chunks/core.mjs").then((mod) => { - openTelemetryAPI = mod; - }).catch(() => void 0); - return openTelemetryAPI ?? noopOpenTelemetryAPI; -} -//#endregion -//#region node_modules/@better-auth/core/dist/instrumentation/tracer.mjs -var INSTRUMENTATION_SCOPE = "better-auth"; -var INSTRUMENTATION_VERSION = "1.6.25"; -/** -* Better-auth uses `throw ctx.redirect(url)` for flow control (e.g. OAuth -* callbacks). These are APIErrors with 3xx status codes and should not be -* recorded as span errors. -*/ -function isRedirectError(err) { - if (err != null && typeof err === "object" && "name" in err && err.name === "APIError" && "statusCode" in err) { - const status = err.statusCode; - return status >= 300 && status < 400; - } - return false; -} -function endSpanWithError(span, err) { - const { SpanStatusCode } = getOpenTelemetryAPI(); - if (isRedirectError(err)) { - span.setAttribute(import_src.ATTR_HTTP_RESPONSE_STATUS_CODE, err.statusCode); - span.setStatus({ code: SpanStatusCode.OK }); - } else { - span.recordException(err); - span.setStatus({ - code: SpanStatusCode.ERROR, - message: String(err?.message ?? err) - }); - } - span.end(); -} -function withSpan(name, attributes, fn) { - const { trace } = getOpenTelemetryAPI(); - return trace.getTracer(INSTRUMENTATION_SCOPE, INSTRUMENTATION_VERSION).startActiveSpan(name, { attributes }, (span) => { - try { - const result = fn(); - if (result instanceof Promise) return result.then((value) => { - span.end(); - return value; - }).catch((err) => { - endSpanWithError(span, err); - throw err; - }); - span.end(); - return result; - } catch (err) { - endSpanWithError(span, err); - throw err; - } - }); -} -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/factory.mjs -var debugLogs = []; -var transactionId = -1; -var createAsIsTransaction = (adapter) => (fn) => fn(adapter); -var createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => { - const uniqueAdapterFactoryInstanceId = Math.random().toString(36).substring(2, 15); - const config = { - ...cfg, - supportsBooleans: cfg.supportsBooleans ?? true, - supportsDates: cfg.supportsDates ?? true, - supportsJSON: cfg.supportsJSON ?? false, - adapterName: cfg.adapterName ?? cfg.adapterId, - supportsNumericIds: cfg.supportsNumericIds ?? true, - supportsUUIDs: cfg.supportsUUIDs ?? false, - supportsArrays: cfg.supportsArrays ?? false, - transaction: cfg.transaction ?? false, - disableTransformInput: cfg.disableTransformInput ?? false, - disableTransformOutput: cfg.disableTransformOutput ?? false, - disableTransformJoin: cfg.disableTransformJoin ?? false - }; - if (options.advanced?.database?.generateId === "serial" && config.supportsNumericIds === false) throw new BetterAuthError(`[${config.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`); - const schema = getAuthTables(options); - const debugLog = (...args) => { - if (config.debugLogs === true || typeof config.debugLogs === "object") { - const logger = createLogger({ level: "info" }); - if (typeof config.debugLogs === "object" && "isRunningAdapterTests" in config.debugLogs) { - if (config.debugLogs.isRunningAdapterTests) { - args.shift(); - debugLogs.push({ - instance: uniqueAdapterFactoryInstanceId, - args - }); - } - return; - } - if (typeof config.debugLogs === "object" && config.debugLogs.logCondition && !config.debugLogs.logCondition?.()) return; - if (typeof args[0] === "object" && "method" in args[0]) { - const method = args.shift().method; - if (typeof config.debugLogs === "object") { - if (method === "create" && !config.debugLogs.create) return; - else if (method === "update" && !config.debugLogs.update) return; - else if (method === "updateMany" && !config.debugLogs.updateMany) return; - else if (method === "findOne" && !config.debugLogs.findOne) return; - else if (method === "findMany" && !config.debugLogs.findMany) return; - else if (method === "delete" && !config.debugLogs.delete) return; - else if (method === "deleteMany" && !config.debugLogs.deleteMany) return; - else if (method === "consumeOne" && !config.debugLogs.consumeOne) return; - else if (method === "incrementOne" && !config.debugLogs.incrementOne) return; - else if (method === "count" && !config.debugLogs.count) return; - } - logger.info(`[${config.adapterName}]`, ...args); - } else logger.info(`[${config.adapterName}]`, ...args); - } - }; - const logger = createLogger(options.logger); - const getDefaultModelName = initGetDefaultModelName({ - usePlural: config.usePlural, - schema - }); - const getDefaultFieldName = initGetDefaultFieldName({ - usePlural: config.usePlural, - schema - }); - const getModelName = initGetModelName({ - usePlural: config.usePlural, - schema - }); - const getFieldName = initGetFieldName({ - schema, - usePlural: config.usePlural - }); - const idField = initGetIdField({ - schema, - options, - usePlural: config.usePlural, - disableIdGeneration: config.disableIdGeneration, - customIdGenerator: config.customIdGenerator, - supportsUUIDs: config.supportsUUIDs - }); - const getFieldAttributes = initGetFieldAttributes({ - schema, - options, - usePlural: config.usePlural, - disableIdGeneration: config.disableIdGeneration, - customIdGenerator: config.customIdGenerator - }); - const transformInput = async (data, defaultModelName, action, forceAllowId) => { - const transformedData = {}; - const fields = schema[defaultModelName].fields; - const newMappedKeys = config.mapKeysTransformInput ?? {}; - const useNumberId = options.advanced?.database?.generateId === "serial"; - fields.id = idField({ - customModelName: defaultModelName, - forceAllowId: forceAllowId && "id" in data - }); - for (const field in fields) { - let value = data[field]; - const fieldAttributes = fields[field]; - const newFieldName = newMappedKeys[field] || fields[field].fieldName || field; - if (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === "update" && fieldAttributes.onUpdate) || action === "update" && !fieldAttributes.onUpdate)) continue; - if (fieldAttributes && fieldAttributes.type === "date" && !(value instanceof Date) && typeof value === "string") try { - value = new Date(value); - } catch { - logger.error("[Adapter Factory] Failed to convert string to date", { - value, - field - }); - } - let newValue = withApplyDefault(value, fieldAttributes, action); - if (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue); - if (fieldAttributes.references?.field === "id" && useNumberId) if (Array.isArray(newValue)) newValue = newValue.map((x) => x !== null ? Number(x) : null); - else newValue = newValue !== null ? Number(newValue) : null; - else if (config.supportsJSON === false && typeof newValue === "object" && fieldAttributes.type === "json") newValue = JSON.stringify(newValue); - else if (config.supportsArrays === false && Array.isArray(newValue) && (fieldAttributes.type === "string[]" || fieldAttributes.type === "number[]")) newValue = JSON.stringify(newValue); - else if (config.supportsDates === false && newValue instanceof Date && fieldAttributes.type === "date") newValue = newValue.toISOString(); - else if (config.supportsBooleans === false && typeof newValue === "boolean") newValue = newValue ? 1 : 0; - if (config.customTransformInput) newValue = config.customTransformInput({ - data: newValue, - action, - field: newFieldName, - fieldAttributes, - model: getModelName(defaultModelName), - schema, - options - }); - if (newValue !== void 0) transformedData[newFieldName] = newValue; - } - return transformedData; - }; - const transformOutput = async (data, unsafe_model, select = [], join) => { - const transformSingleOutput = async (data, unsafe_model, select = []) => { - if (!data) return null; - const newMappedKeys = config.mapKeysTransformOutput ?? {}; - const transformedData = {}; - const tableSchema = schema[getDefaultModelName(unsafe_model)].fields; - const idKey = Object.entries(newMappedKeys).find(([_, v]) => v === "id")?.[0]; - tableSchema[idKey ?? "id"] = { type: options.advanced?.database?.generateId === "serial" ? "number" : "string" }; - for (const key in tableSchema) { - if (select.length && !select.includes(key)) continue; - const field = tableSchema[key]; - if (field) { - const originalKey = field.fieldName || key; - let newValue = data[Object.entries(newMappedKeys).find(([_, v]) => v === originalKey)?.[0] || originalKey]; - if (field.transform?.output) newValue = await field.transform.output(newValue); - const newFieldName = newMappedKeys[key] || key; - if (originalKey === "id" || field.references?.field === "id") { - if (typeof newValue !== "undefined" && newValue !== null) newValue = String(newValue); - } else if (config.supportsJSON === false && typeof newValue === "string" && field.type === "json") newValue = safeJSONParse(newValue); - else if (config.supportsArrays === false && typeof newValue === "string" && (field.type === "string[]" || field.type === "number[]")) newValue = safeJSONParse(newValue); - else if (config.supportsDates === false && typeof newValue === "string" && field.type === "date") newValue = new Date(newValue); - else if (config.supportsBooleans === false && typeof newValue === "number" && field.type === "boolean") newValue = newValue === 1; - if (config.customTransformOutput) newValue = config.customTransformOutput({ - data: newValue, - field: newFieldName, - fieldAttributes: field, - select, - model: getModelName(unsafe_model), - schema, - options - }); - transformedData[newFieldName] = newValue; - } - } - return transformedData; - }; - if (!join || Object.keys(join).length === 0) return await transformSingleOutput(data, unsafe_model, select); - unsafe_model = getDefaultModelName(unsafe_model); - const transformedData = await transformSingleOutput(data, unsafe_model, select); - const requiredModels = Object.entries(join).map(([model, joinConfig]) => ({ - modelName: getModelName(model), - defaultModelName: getDefaultModelName(model), - joinConfig - })); - if (!data) return null; - for (const { modelName, defaultModelName, joinConfig } of requiredModels) { - let joinedData = await (async () => { - if (options.experimental?.joins) return data[modelName]; - else return await handleFallbackJoin({ - baseModel: unsafe_model, - baseData: transformedData, - joinModel: modelName, - specificJoinConfig: joinConfig - }); - })(); - if (joinedData === void 0 || joinedData === null) joinedData = joinConfig.relation === "one-to-one" ? null : []; - if (joinConfig.relation === "one-to-many" && !Array.isArray(joinedData)) joinedData = [joinedData]; - const transformed = []; - if (Array.isArray(joinedData)) for (const item of joinedData) { - const transformedItem = await transformSingleOutput(item, modelName, []); - transformed.push(transformedItem); - } - else { - const transformedItem = await transformSingleOutput(joinedData, modelName, []); - transformed.push(transformedItem); - } - transformedData[defaultModelName] = (joinConfig.relation === "one-to-one" ? transformed[0] : transformed) ?? null; - } - return transformedData; - }; - const transformWhereClause = ({ model, where, action }) => { - if (!where) return void 0; - const newMappedKeys = config.mapKeysTransformInput ?? {}; - return where.map((w) => { - const { field: unsafe_field, value, operator = "eq", connector = "AND", mode = "sensitive" } = w; - if (operator === "in") { - if (!Array.isArray(value)) throw new BetterAuthError("Value must be an array"); - } - let newValue = value; - const defaultModelName = getDefaultModelName(model); - const defaultFieldName = getDefaultFieldName({ - field: unsafe_field, - model - }); - const fieldName = newMappedKeys[defaultFieldName] || getFieldName({ - field: defaultFieldName, - model: defaultModelName - }); - const fieldAttr = getFieldAttributes({ - field: defaultFieldName, - model: defaultModelName - }); - const useNumberId = options.advanced?.database?.generateId === "serial"; - if (defaultFieldName === "id" || fieldAttr.references?.field === "id") { - if (useNumberId) if (Array.isArray(value)) newValue = value.map(Number); - else newValue = Number(value); - } - if (fieldAttr.type === "date" && value instanceof Date && !config.supportsDates) newValue = value.toISOString(); - if (fieldAttr.type === "boolean" && typeof newValue === "string") newValue = newValue === "true"; - if (fieldAttr.type === "number") { - if (typeof newValue === "string" && newValue.trim() !== "") { - const parsed = Number(newValue); - if (!Number.isNaN(parsed)) newValue = parsed; - } else if (Array.isArray(newValue)) { - const parsed = newValue.map((v) => typeof v === "string" && v.trim() !== "" ? Number(v) : NaN); - if (parsed.every((n) => !Number.isNaN(n))) newValue = parsed; - } - } - if (fieldAttr.type === "boolean" && typeof newValue === "boolean" && !config.supportsBooleans) newValue = newValue ? 1 : 0; - if (fieldAttr.type === "json" && typeof value === "object" && !config.supportsJSON) try { - newValue = JSON.stringify(value); - } catch (error) { - throw new Error(`Failed to stringify JSON value for field ${fieldName}`, { cause: error }); - } - if (config.customTransformInput) newValue = config.customTransformInput({ - data: newValue, - fieldAttributes: fieldAttr, - field: fieldName, - model: getModelName(model), - schema, - options, - action - }); - return { - operator, - connector, - field: fieldName, - value: newValue, - mode - }; - }); - }; - const transformJoinClause = (baseModel, unsanitizedJoin, select) => { - if (!unsanitizedJoin) return void 0; - if (Object.keys(unsanitizedJoin).length === 0) return void 0; - const transformedJoin = {}; - for (const [model, join] of Object.entries(unsanitizedJoin)) { - if (!join) continue; - const defaultModelName = getDefaultModelName(model); - const defaultBaseModelName = getDefaultModelName(baseModel); - let foreignKeys = Object.entries(schema[defaultModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultBaseModelName); - let isForwardJoin = true; - if (!foreignKeys.length) { - foreignKeys = Object.entries(schema[defaultBaseModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultModelName); - isForwardJoin = false; - } - if (!foreignKeys.length) throw new BetterAuthError(`No foreign key found for model ${model} and base model ${baseModel} while performing join operation.`); - else if (foreignKeys.length > 1) throw new BetterAuthError(`Multiple foreign keys found for model ${model} and base model ${baseModel} while performing join operation. Only one foreign key is supported.`); - const [foreignKey, foreignKeyAttributes] = foreignKeys[0]; - if (!foreignKeyAttributes.references) throw new BetterAuthError(`No references found for foreign key ${foreignKey} on model ${model} while performing join operation.`); - let from; - let to; - let requiredSelectField; - if (isForwardJoin) { - requiredSelectField = foreignKeyAttributes.references.field; - from = getFieldName({ - model: baseModel, - field: requiredSelectField - }); - to = getFieldName({ - model, - field: foreignKey - }); - } else { - requiredSelectField = foreignKey; - from = getFieldName({ - model: baseModel, - field: requiredSelectField - }); - to = getFieldName({ - model, - field: foreignKeyAttributes.references.field - }); - } - if (select && !select.includes(requiredSelectField)) select.push(requiredSelectField); - const isUnique = to === "id" ? true : foreignKeyAttributes.unique ?? false; - let limit = options.advanced?.database?.defaultFindManyLimit ?? 100; - if (isUnique) limit = 1; - else if (typeof join === "object" && typeof join.limit === "number") limit = join.limit; - transformedJoin[getModelName(model)] = { - on: { - from, - to - }, - limit, - relation: isUnique ? "one-to-one" : "one-to-many" - }; - } - return { - join: transformedJoin, - select - }; - }; - /** - * Handle joins by making separate queries and combining results (fallback for adapters that don't support native joins). - */ - const handleFallbackJoin = async ({ baseModel, baseData, joinModel, specificJoinConfig: joinConfig }) => { - if (!baseData) return baseData; - const modelName = getModelName(joinModel); - const field = joinConfig.on.to; - const value = baseData[getDefaultFieldName({ - field: joinConfig.on.from, - model: baseModel - })]; - if (value === null || value === void 0) return joinConfig.relation === "one-to-one" ? null : []; - let result; - const where = transformWhereClause({ - model: modelName, - where: [{ - field, - value, - operator: "eq", - connector: "AND" - }], - action: "findOne" - }); - try { - if (joinConfig.relation === "one-to-one") result = await withSpan(`db findOne ${modelName}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "findOne", - [import_src.ATTR_DB_COLLECTION_NAME]: modelName - }, () => adapterInstance.findOne({ - model: modelName, - where - })); - else { - const limit = joinConfig.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; - result = await withSpan(`db findMany ${modelName}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "findMany", - [import_src.ATTR_DB_COLLECTION_NAME]: modelName - }, () => adapterInstance.findMany({ - model: modelName, - where, - limit - })); - } - } catch (error) { - logger.error(`Failed to query fallback join for model ${modelName}:`, { - where, - limit: joinConfig.limit - }); - console.error(error); - throw error; - } - return result; - }; - const adapterInstance = customAdapter({ - options, - schema, - debugLog, - getFieldName, - getModelName, - getDefaultModelName, - getDefaultFieldName, - getFieldAttributes, - transformInput, - transformOutput, - transformWhereClause - }); - let lazyLoadTransaction = null; - const adapter = { - transaction: async (cb) => { - if (!lazyLoadTransaction) if (!config.transaction) lazyLoadTransaction = createAsIsTransaction(adapter); - else { - logger.debug(`[${config.adapterName}] - Using provided transaction implementation.`); - lazyLoadTransaction = config.transaction; - } - return lazyLoadTransaction(cb); - }, - create: async ({ data: unsafeData, model: unsafeModel, select, forceAllowId = false }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - unsafeModel = getDefaultModelName(unsafeModel); - if ("id" in unsafeData && typeof unsafeData.id !== "undefined" && !forceAllowId) { - logger.warn(`[${config.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`); - const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", "Create method with `id` being called at:"); - console.log(stack); - unsafeData.id = void 0; - } - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("create")} ${formatAction("Unsafe Input")}:`, { - model, - data: unsafeData - }); - let data = unsafeData; - if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "create", forceAllowId); - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Input")}:`, { - model, - data - }); - const res = await withSpan(`db create ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "create", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.create({ - data, - model - })); - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("create")} ${formatAction("DB Result")}:`, { - model, - res - }); - let transformed = res; - if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, void 0); - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - update: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { - transactionId++; - const thisTransactionId = transactionId; - unsafeModel = getDefaultModelName(unsafeModel); - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "update" - }); - if (where.length === 0) return null; - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("update")} ${formatAction("Unsafe Input")}:`, { - model, - data: unsafeData - }); - let data = unsafeData; - if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update"); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Input")}:`, { - model, - data - }); - const res = await withSpan(`db update ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "update", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.update({ - model, - where, - update: data - })); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("update")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, void 0, void 0); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - updateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "updateMany" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("updateMany")} ${formatAction("Unsafe Input")}:`, { - model, - data: unsafeData - }); - let data = unsafeData; - if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update"); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Input")}:`, { - model, - data - }); - const updatedCount = await withSpan(`db updateMany ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "updateMany", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.updateMany({ - model, - where, - update: data - })); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("updateMany")} ${formatAction("DB Result")}:`, { - model, - data: updatedCount - }); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Result")}:`, { - model, - data: updatedCount - }); - return updatedCount; - }, - findOne: async ({ model: unsafeModel, where: unsafeWhere, select, join: unsafeJoin }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "findOne" - }); - unsafeModel = getDefaultModelName(unsafeModel); - let join; - let passJoinToAdapter = true; - if (!config.disableTransformJoin) { - const result = transformJoinClause(unsafeModel, unsafeJoin, select); - if (result) { - join = result.join; - select = result.select; - } - if (!options.experimental?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false; - } else join = unsafeJoin; - debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findOne")}:`, { - model, - where, - select, - join - }); - const res = await withSpan(`db findOne ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "findOne", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.findOne({ - model, - where, - select, - join: passJoinToAdapter ? join : void 0 - })); - debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findOne")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, join); - debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findOne")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - findMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, select, sortBy, offset, join: unsafeJoin }) => { - transactionId++; - const thisTransactionId = transactionId; - const limit = unsafeLimit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "findMany" - }); - unsafeModel = getDefaultModelName(unsafeModel); - let join; - let passJoinToAdapter = true; - if (!config.disableTransformJoin) { - const result = transformJoinClause(unsafeModel, unsafeJoin, select); - if (result) { - join = result.join; - select = result.select; - } - if (!options.experimental?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false; - } else join = unsafeJoin; - debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findMany")}:`, { - model, - where, - limit, - sortBy, - offset, - join - }); - const res = await withSpan(`db findMany ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "findMany", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.findMany({ - model, - where, - limit, - select, - sortBy, - offset, - join: passJoinToAdapter ? join : void 0 - })); - debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findMany")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config.disableTransformOutput) transformed = await Promise.all(res.map(async (r) => { - return await transformOutput(r, unsafeModel, void 0, join); - })); - debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findMany")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - delete: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "delete" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("delete")}:`, { - model, - where - }); - await withSpan(`db delete ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "delete", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.delete({ - model, - where - })); - debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("delete")} ${formatAction("DB Result")}:`, { model }); - }, - deleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "deleteMany" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DeleteMany")}:`, { - model, - where - }); - const res = await withSpan(`db deleteMany ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "deleteMany", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.deleteMany({ - model, - where - })); - debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - return res; - }, - consumeOne: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "consumeOne" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("consumeOne")} ${formatAction("ConsumeOne")}:`, { - model, - where - }); - let res; - let resultNeedsOutputTransform = true; - if (adapterInstance.consumeOne) res = await withSpan(`db consumeOne ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "consumeOne", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.consumeOne({ - model, - where - })); - else { - res = await withSpan(`db consumeOne ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "consumeOne", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => runWithTransaction(adapter, async () => { - const trx = await getCurrentAdapter(adapter); - const target = (await trx.findMany({ - model: unsafeModel, - where: unsafeWhere, - limit: 1 - }))[0]; - if (!target) return null; - const deleted = await trx.deleteMany({ - model: unsafeModel, - where: [...unsafeWhere, { - field: "id", - value: target.id, - operator: "eq", - connector: "AND", - mode: "sensitive" - }] - }); - if (typeof deleted !== "number") throw new BetterAuthError(`Adapter "${config.adapterId}" returned a non-numeric value from deleteMany during the consumeOne fallback. Return the number of deleted rows, or implement a native consumeOne for atomic single-use consumption.`); - return deleted > 0 ? target : null; - })); - resultNeedsOutputTransform = false; - } - debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("consumeOne")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config.disableTransformOutput && resultNeedsOutputTransform && res) transformed = await transformOutput(res, unsafeModel, void 0, void 0); - debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("consumeOne")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - incrementOne: async ({ model: unsafeModel, where: unsafeWhere, increment: unsafeIncrement, set: unsafeSet }) => { - const hasIncrement = Object.keys(unsafeIncrement).length > 0; - const hasSet = !!unsafeSet && Object.keys(unsafeSet).length > 0; - if (!hasIncrement && !hasSet) throw new BetterAuthError("incrementOne requires a non-empty `increment` or `set`; both were empty."); - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "incrementOne" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "incrementOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("incrementOne")} ${formatAction("IncrementOne")}:`, { - model, - where, - increment: unsafeIncrement, - set: unsafeSet - }); - let res; - let resultNeedsOutputTransform = true; - if (adapterInstance.incrementOne) { - const mappedKeys = config.mapKeysTransformInput ?? {}; - const increment = {}; - for (const [field, delta] of Object.entries(unsafeIncrement)) increment[mappedKeys[field] || getFieldName({ - model: unsafeModel, - field - })] = delta; - let set; - if (unsafeSet && !config.disableTransformInput) set = await transformInput(unsafeSet, unsafeModel, "update"); - else set = unsafeSet; - if (Object.keys(increment).length === 0 && (!set || Object.keys(set).length === 0)) throw new BetterAuthError("incrementOne resolved to an empty update: every increment/set field was unknown to the schema or transformed away."); - res = await withSpan(`db incrementOne ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "incrementOne", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.incrementOne({ - model, - where, - increment, - set - })); - } else { - res = await withSpan(`db incrementOne ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "incrementOne", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => runWithTransaction(adapter, async () => { - const trx = await getCurrentAdapter(adapter); - const target = (await trx.findMany({ - model: unsafeModel, - where: unsafeWhere, - limit: 1 - }))[0]; - if (!target) return null; - const nextValues = { ...unsafeSet ?? {} }; - for (const [field, delta] of Object.entries(unsafeIncrement)) nextValues[field] = (typeof target[field] === "number" ? target[field] : 0) + delta; - const updated = await trx.updateMany({ - model: unsafeModel, - where: [...unsafeWhere, { - field: "id", - value: target.id, - operator: "eq", - connector: "AND", - mode: "sensitive" - }], - update: nextValues - }); - if (typeof updated !== "number") throw new BetterAuthError(`Adapter "${config.adapterId}" returned a non-numeric value from updateMany during the incrementOne fallback. Return the number of updated rows, or implement a native incrementOne for atomic guarded counter updates.`); - return updated > 0 ? { - ...target, - ...nextValues - } : null; - })); - resultNeedsOutputTransform = false; - } - debugLog({ method: "incrementOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("incrementOne")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config.disableTransformOutput && resultNeedsOutputTransform && res) transformed = await transformOutput(res, unsafeModel, void 0, void 0); - debugLog({ method: "incrementOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("incrementOne")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - count: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "count" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("count")}:`, { - model, - where - }); - const res = await withSpan(`db count ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "count", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.count({ - model, - where - })); - debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("count")}:`, { - model, - data: res - }); - return res; - }, - createSchema: adapterInstance.createSchema ? async (_, file) => { - const tables = getAuthTables(options); - if (options.secondaryStorage && !options.session?.storeSessionInDatabase) delete tables.session; - return adapterInstance.createSchema({ - file, - tables - }); - } : void 0, - options: { - adapterConfig: config, - ...adapterInstance.options ?? {} - }, - id: config.adapterId, - ...config.debugLogs?.isRunningAdapterTests ? { adapterTestDebugLogs: { - resetDebugLogs() { - debugLogs = debugLogs.filter((log) => log.instance !== uniqueAdapterFactoryInstanceId); - }, - printDebugLogs() { - const separator = `─`.repeat(80); - const logs = debugLogs.filter((log) => log.instance === uniqueAdapterFactoryInstanceId); - if (logs.length === 0) return; - const log = logs.reverse().map((log) => { - log.args[0] = `\n${log.args[0]}`; - return [...log.args, "\n"]; - }).reduce((prev, curr) => { - return [...curr, ...prev]; - }, [`\n${separator}`]); - console.log(...log); - } - } } : {} - }; - return adapter; -}; -function formatTransactionId(transactionId) { - if (getColorDepth() < 8) return `#${transactionId}`; - return `${TTY_COLORS.fg.magenta}#${transactionId}${TTY_COLORS.reset}`; -} -function formatStep(step, total) { - return `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`; -} -function formatMethod(method) { - return `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`; -} -function formatAction(action) { - return `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`; -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/buffer_utils.js -var encoder = new TextEncoder(); -var decoder = new TextDecoder(); -var MAX_INT32 = 2 ** 32; -function concat(...buffers) { - const size = buffers.reduce((acc, { length }) => acc + length, 0); - const buf = new Uint8Array(size); - let i = 0; - for (const buffer of buffers) { - buf.set(buffer, i); - i += buffer.length; - } - return buf; -} -function writeUInt32BE(buf, value, offset) { - if (value < 0 || value >= MAX_INT32) throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); - buf.set([ - value >>> 24, - value >>> 16, - value >>> 8, - value & 255 - ], offset); -} -function uint64be(value) { - const high = Math.floor(value / MAX_INT32); - const low = value % MAX_INT32; - const buf = /* @__PURE__ */ new Uint8Array(8); - writeUInt32BE(buf, high, 0); - writeUInt32BE(buf, low, 4); - return buf; -} -function uint32be(value) { - const buf = /* @__PURE__ */ new Uint8Array(4); - writeUInt32BE(buf, value); - return buf; -} -function encode$1(string) { - const bytes = new Uint8Array(string.length); - for (let i = 0; i < string.length; i++) { - const code = string.charCodeAt(i); - if (code > 127) throw new TypeError("non-ASCII string encountered in encode()"); - bytes[i] = code; - } - return bytes; -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/base64.js -function encodeBase64(input) { - if (Uint8Array.prototype.toBase64) return input.toBase64(); - const CHUNK_SIZE = 32768; - const arr = []; - for (let i = 0; i < input.length; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE))); - return btoa(arr.join("")); -} -function decodeBase64(encoded) { - if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded); - const binary = atob(encoded); - const bytes = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); - return bytes; -} -//#endregion -//#region node_modules/jose/dist/webapi/util/base64url.js -function decode(input) { - if (Uint8Array.fromBase64) return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" }); - let encoded = input; - if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded); - encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); - try { - return decodeBase64(encoded); - } catch { - throw new TypeError("The input to be decoded is not correctly encoded."); - } -} -function encode(input) { - let unencoded = input; - if (typeof unencoded === "string") unencoded = encoder.encode(unencoded); - if (Uint8Array.prototype.toBase64) return unencoded.toBase64({ - alphabet: "base64url", - omitPadding: true - }); - return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/crypto_key.js -var unusable = (name, prop = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); -var isAlgorithm = (algorithm, name) => algorithm.name === name; -function getHashLength(hash) { - return parseInt(hash.name.slice(4), 10); -} -function checkHashLength(algorithm, expected) { - if (getHashLength(algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); -} -function getNamedCurve(alg) { - switch (alg) { - case "ES256": return "P-256"; - case "ES384": return "P-384"; - case "ES512": return "P-521"; - default: throw new Error("unreachable"); - } -} -function checkUsage(key, usage) { - if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`); -} -function checkSigCryptoKey(key, alg, usage) { - switch (alg) { - case "HS256": - case "HS384": - case "HS512": - if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC"); - checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); - break; - case "RS256": - case "RS384": - case "RS512": - if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5"); - checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); - break; - case "PS256": - case "PS384": - case "PS512": - if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS"); - checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); - break; - case "Ed25519": - case "EdDSA": - if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519"); - break; - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": - if (!isAlgorithm(key.algorithm, alg)) throw unusable(alg); - break; - case "ES256": - case "ES384": - case "ES512": { - if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA"); - const expected = getNamedCurve(alg); - if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve"); - break; - } - default: throw new TypeError("CryptoKey does not support this operation"); - } - checkUsage(key, usage); -} -function checkEncCryptoKey(key, alg, usage) { - switch (alg) { - case "A128GCM": - case "A192GCM": - case "A256GCM": { - if (!isAlgorithm(key.algorithm, "AES-GCM")) throw unusable("AES-GCM"); - const expected = parseInt(alg.slice(1, 4), 10); - if (key.algorithm.length !== expected) throw unusable(expected, "algorithm.length"); - break; - } - case "A128KW": - case "A192KW": - case "A256KW": { - if (!isAlgorithm(key.algorithm, "AES-KW")) throw unusable("AES-KW"); - const expected = parseInt(alg.slice(1, 4), 10); - if (key.algorithm.length !== expected) throw unusable(expected, "algorithm.length"); - break; - } - case "ECDH": - switch (key.algorithm.name) { - case "ECDH": - case "X25519": break; - default: throw unusable("ECDH or X25519"); - } - break; - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": - if (!isAlgorithm(key.algorithm, "PBKDF2")) throw unusable("PBKDF2"); - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - if (!isAlgorithm(key.algorithm, "RSA-OAEP")) throw unusable("RSA-OAEP"); - checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1); - break; - default: throw new TypeError("CryptoKey does not support this operation"); - } - checkUsage(key, usage); -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/invalid_key_input.js -function message(msg, actual, ...types) { - types = types.filter(Boolean); - if (types.length > 2) { - const last = types.pop(); - msg += `one of type ${types.join(", ")}, or ${last}.`; - } else if (types.length === 2) msg += `one of type ${types[0]} or ${types[1]}.`; - else msg += `of type ${types[0]}.`; - if (actual == null) msg += ` Received ${actual}`; - else if (typeof actual === "function" && actual.name) msg += ` Received function ${actual.name}`; - else if (typeof actual === "object" && actual != null) { - if (actual.constructor?.name) msg += ` Received an instance of ${actual.constructor.name}`; - } - return msg; -} -var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types); -var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types); -//#endregion -//#region node_modules/jose/dist/webapi/util/errors.js -var JOSEError = class extends Error { - static code = "ERR_JOSE_GENERIC"; - code = "ERR_JOSE_GENERIC"; - constructor(message, options) { - super(message, options); - this.name = this.constructor.name; - Error.captureStackTrace?.(this, this.constructor); - } -}; -var JWTClaimValidationFailed = class extends JOSEError { - static code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; - code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; - claim; - reason; - payload; - constructor(message, payload, claim = "unspecified", reason = "unspecified") { - super(message, { cause: { - claim, - reason, - payload - } }); - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -}; -var JWTExpired = class extends JOSEError { - static code = "ERR_JWT_EXPIRED"; - code = "ERR_JWT_EXPIRED"; - claim; - reason; - payload; - constructor(message, payload, claim = "unspecified", reason = "unspecified") { - super(message, { cause: { - claim, - reason, - payload - } }); - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -}; -var JOSEAlgNotAllowed = class extends JOSEError { - static code = "ERR_JOSE_ALG_NOT_ALLOWED"; - code = "ERR_JOSE_ALG_NOT_ALLOWED"; -}; -var JOSENotSupported = class extends JOSEError { - static code = "ERR_JOSE_NOT_SUPPORTED"; - code = "ERR_JOSE_NOT_SUPPORTED"; -}; -var JWEDecryptionFailed = class extends JOSEError { - static code = "ERR_JWE_DECRYPTION_FAILED"; - code = "ERR_JWE_DECRYPTION_FAILED"; - constructor(message = "decryption operation failed", options) { - super(message, options); - } -}; -var JWEInvalid = class extends JOSEError { - static code = "ERR_JWE_INVALID"; - code = "ERR_JWE_INVALID"; -}; -var JWSInvalid = class extends JOSEError { - static code = "ERR_JWS_INVALID"; - code = "ERR_JWS_INVALID"; -}; -var JWTInvalid = class extends JOSEError { - static code = "ERR_JWT_INVALID"; - code = "ERR_JWT_INVALID"; -}; -var JWKInvalid = class extends JOSEError { - static code = "ERR_JWK_INVALID"; - code = "ERR_JWK_INVALID"; -}; -var JWKSInvalid = class extends JOSEError { - static code = "ERR_JWKS_INVALID"; - code = "ERR_JWKS_INVALID"; -}; -var JWKSNoMatchingKey = class extends JOSEError { - static code = "ERR_JWKS_NO_MATCHING_KEY"; - code = "ERR_JWKS_NO_MATCHING_KEY"; - constructor(message = "no applicable key found in the JSON Web Key Set", options) { - super(message, options); - } -}; -var JWKSMultipleMatchingKeys = class extends JOSEError { - [Symbol.asyncIterator]; - static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; - code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; - constructor(message = "multiple matching keys found in the JSON Web Key Set", options) { - super(message, options); - } -}; -var JWKSTimeout = class extends JOSEError { - static code = "ERR_JWKS_TIMEOUT"; - code = "ERR_JWKS_TIMEOUT"; - constructor(message = "request timed out", options) { - super(message, options); - } -}; -var JWSSignatureVerificationFailed = class extends JOSEError { - static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; - code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; - constructor(message = "signature verification failed", options) { - super(message, options); - } -}; -//#endregion -//#region node_modules/jose/dist/webapi/lib/is_key_like.js -function assertCryptoKey(key) { - if (!isCryptoKey(key)) throw new Error("CryptoKey instance expected"); -} -var isCryptoKey = (key) => { - if (key?.[Symbol.toStringTag] === "CryptoKey") return true; - try { - return key instanceof CryptoKey; - } catch { - return false; - } -}; -var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject"; -var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key); -//#endregion -//#region node_modules/jose/dist/webapi/lib/helpers.js -var unprotected = Symbol(); -function assertNotSet(value, name) { - if (value) throw new TypeError(`${name} can only be called once`); -} -function decodeBase64url(value, label, ErrorClass) { - try { - return decode(value); - } catch { - throw new ErrorClass(`Failed to base64url decode the ${label}`); - } -} -async function digest(algorithm, data) { - const subtleDigest = `SHA-${algorithm.slice(-3)}`; - return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/type_checks.js -var isObjectLike = (value) => typeof value === "object" && value !== null; -function isObject(input) { - if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") return false; - if (Object.getPrototypeOf(input) === null) return true; - let proto = input; - while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto); - return Object.getPrototypeOf(input) === proto; -} -function isDisjoint(...headers) { - const sources = headers.filter(Boolean); - if (sources.length === 0 || sources.length === 1) return true; - let acc; - for (const header of sources) { - const parameters = Object.keys(header); - if (!acc || acc.size === 0) { - acc = new Set(parameters); - continue; - } - for (const parameter of parameters) { - if (acc.has(parameter)) return false; - acc.add(parameter); - } - } - return true; -} -var isJWK = (key) => isObject(key) && typeof key.kty === "string"; -var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string"); -var isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0; -var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string"; -//#endregion -//#region node_modules/jose/dist/webapi/lib/signing.js -function checkKeyLength(alg, key) { - if (alg.startsWith("RS") || alg.startsWith("PS")) { - const { modulusLength } = key.algorithm; - if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); - } -} -function subtleAlgorithm(alg, algorithm) { - const hash = `SHA-${alg.slice(-3)}`; - switch (alg) { - case "HS256": - case "HS384": - case "HS512": return { - hash, - name: "HMAC" - }; - case "PS256": - case "PS384": - case "PS512": return { - hash, - name: "RSA-PSS", - saltLength: parseInt(alg.slice(-3), 10) >> 3 - }; - case "RS256": - case "RS384": - case "RS512": return { - hash, - name: "RSASSA-PKCS1-v1_5" - }; - case "ES256": - case "ES384": - case "ES512": return { - hash, - name: "ECDSA", - namedCurve: algorithm.namedCurve - }; - case "Ed25519": - case "EdDSA": return { name: "Ed25519" }; - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": return { name: alg }; - default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } -} -async function getSigKey(alg, key, usage) { - if (key instanceof Uint8Array) { - if (!alg.startsWith("HS")) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); - return crypto.subtle.importKey("raw", key, { - hash: `SHA-${alg.slice(-3)}`, - name: "HMAC" - }, false, [usage]); - } - checkSigCryptoKey(key, alg, usage); - return key; -} -async function sign(alg, key, data) { - const cryptoKey = await getSigKey(alg, key, "sign"); - checkKeyLength(alg, cryptoKey); - const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data); - return new Uint8Array(signature); -} -async function verify(alg, key, signature, data) { - const cryptoKey = await getSigKey(alg, key, "verify"); - checkKeyLength(alg, cryptoKey); - const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm); - try { - return await crypto.subtle.verify(algorithm, cryptoKey, signature, data); - } catch { - return false; - } -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/jwk_to_key.js -var unsupportedAlg = "Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value"; -function subtleMapping(jwk) { - let algorithm; - let keyUsages; - switch (jwk.kty) { - case "AKP": - switch (jwk.alg) { - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": - algorithm = { name: jwk.alg }; - keyUsages = jwk.priv ? ["sign"] : ["verify"]; - break; - default: throw new JOSENotSupported(unsupportedAlg); - } - break; - case "RSA": - switch (jwk.alg) { - case "PS256": - case "PS384": - case "PS512": - algorithm = { - name: "RSA-PSS", - hash: `SHA-${jwk.alg.slice(-3)}` - }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "RS256": - case "RS384": - case "RS512": - algorithm = { - name: "RSASSA-PKCS1-v1_5", - hash: `SHA-${jwk.alg.slice(-3)}` - }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - algorithm = { - name: "RSA-OAEP", - hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` - }; - keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; - break; - default: throw new JOSENotSupported(unsupportedAlg); - } - break; - case "EC": - switch (jwk.alg) { - case "ES256": - case "ES384": - case "ES512": - algorithm = { - name: "ECDSA", - namedCurve: { - ES256: "P-256", - ES384: "P-384", - ES512: "P-521" - }[jwk.alg] - }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - algorithm = { - name: "ECDH", - namedCurve: jwk.crv - }; - keyUsages = jwk.d ? ["deriveBits"] : []; - break; - default: throw new JOSENotSupported(unsupportedAlg); - } - break; - case "OKP": - switch (jwk.alg) { - case "Ed25519": - case "EdDSA": - algorithm = { name: "Ed25519" }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - algorithm = { name: jwk.crv }; - keyUsages = jwk.d ? ["deriveBits"] : []; - break; - default: throw new JOSENotSupported(unsupportedAlg); - } - break; - default: throw new JOSENotSupported("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value"); - } - return { - algorithm, - keyUsages - }; -} -async function jwkToKey(jwk) { - if (!jwk.alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present"); - const { algorithm, keyUsages } = subtleMapping(jwk); - const keyData = { ...jwk }; - if (keyData.kty !== "AKP") delete keyData.alg; - delete keyData.use; - return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages); -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/normalize_key.js -var unusableForAlg = "given KeyObject instance cannot be used for this algorithm"; -var cache; -var handleJWK = async (key, jwk, alg, freeze = false) => { - cache ||= /* @__PURE__ */ new WeakMap(); - let cached = cache.get(key); - if (cached?.[alg]) return cached[alg]; - const cryptoKey = await jwkToKey({ - ...jwk, - alg - }); - if (freeze) Object.freeze(key); - if (!cached) cache.set(key, { [alg]: cryptoKey }); - else cached[alg] = cryptoKey; - return cryptoKey; -}; -var handleKeyObject = (keyObject, alg) => { - cache ||= /* @__PURE__ */ new WeakMap(); - let cached = cache.get(keyObject); - if (cached?.[alg]) return cached[alg]; - const isPublic = keyObject.type === "public"; - const extractable = isPublic ? true : false; - let cryptoKey; - if (keyObject.asymmetricKeyType === "x25519") { - switch (alg) { - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": break; - default: throw new TypeError(unusableForAlg); - } - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]); - } - if (keyObject.asymmetricKeyType === "ed25519") { - if (alg !== "EdDSA" && alg !== "Ed25519") throw new TypeError(unusableForAlg); - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]); - } - switch (keyObject.asymmetricKeyType) { - case "ml-dsa-44": - case "ml-dsa-65": - case "ml-dsa-87": - if (alg !== keyObject.asymmetricKeyType.toUpperCase()) throw new TypeError(unusableForAlg); - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]); - } - if (keyObject.asymmetricKeyType === "rsa") { - let hash; - switch (alg) { - case "RSA-OAEP": - hash = "SHA-1"; - break; - case "RS256": - case "PS256": - case "RSA-OAEP-256": - hash = "SHA-256"; - break; - case "RS384": - case "PS384": - case "RSA-OAEP-384": - hash = "SHA-384"; - break; - case "RS512": - case "PS512": - case "RSA-OAEP-512": - hash = "SHA-512"; - break; - default: throw new TypeError(unusableForAlg); - } - if (alg.startsWith("RSA-OAEP")) return keyObject.toCryptoKey({ - name: "RSA-OAEP", - hash - }, extractable, isPublic ? ["encrypt"] : ["decrypt"]); - cryptoKey = keyObject.toCryptoKey({ - name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", - hash - }, extractable, [isPublic ? "verify" : "sign"]); - } - if (keyObject.asymmetricKeyType === "ec") { - const namedCurve = (/* @__PURE__ */ new Map([ - ["prime256v1", "P-256"], - ["secp384r1", "P-384"], - ["secp521r1", "P-521"] - ])).get(keyObject.asymmetricKeyDetails?.namedCurve); - if (!namedCurve) throw new TypeError(unusableForAlg); - const expectedCurve = { - ES256: "P-256", - ES384: "P-384", - ES512: "P-521" - }; - if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) cryptoKey = keyObject.toCryptoKey({ - name: "ECDSA", - namedCurve - }, extractable, [isPublic ? "verify" : "sign"]); - if (alg.startsWith("ECDH-ES")) cryptoKey = keyObject.toCryptoKey({ - name: "ECDH", - namedCurve - }, extractable, isPublic ? [] : ["deriveBits"]); - } - if (!cryptoKey) throw new TypeError(unusableForAlg); - if (!cached) cache.set(keyObject, { [alg]: cryptoKey }); - else cached[alg] = cryptoKey; - return cryptoKey; -}; -async function normalizeKey(key, alg) { - if (key instanceof Uint8Array) return key; - if (isCryptoKey(key)) return key; - if (isKeyObject(key)) { - if (key.type === "secret") return key.export(); - if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") try { - return handleKeyObject(key, alg); - } catch (err) { - if (err instanceof TypeError) throw err; - } - return handleJWK(key, key.export({ format: "jwk" }), alg); - } - if (isJWK(key)) { - if (key.k) return decode(key.k); - return handleJWK(key, key, alg, true); - } - throw new Error("unreachable"); -} -//#endregion -//#region node_modules/jose/dist/webapi/key/import.js -async function importJWK(jwk, alg, options) { - if (!isObject(jwk)) throw new TypeError("JWK must be an object"); - let ext; - alg ??= jwk.alg; - ext ??= options?.extractable ?? jwk.ext; - switch (jwk.kty) { - case "oct": - if (typeof jwk.k !== "string" || !jwk.k) throw new TypeError("missing \"k\" (Key Value) Parameter value"); - return decode(jwk.k); - case "RSA": - if ("oth" in jwk && jwk.oth !== void 0) throw new JOSENotSupported("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported"); - return jwkToKey({ - ...jwk, - alg, - ext - }); - case "AKP": - if (typeof jwk.alg !== "string" || !jwk.alg) throw new TypeError("missing \"alg\" (Algorithm) Parameter value"); - if (alg !== void 0 && alg !== jwk.alg) throw new TypeError("JWK alg and alg option value mismatch"); - return jwkToKey({ - ...jwk, - ext - }); - case "EC": - case "OKP": return jwkToKey({ - ...jwk, - alg, - ext - }); - default: throw new JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value"); - } -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/validate_crit.js -function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { - if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected"); - if (!protectedHeader || protectedHeader.crit === void 0) return /* @__PURE__ */ new Set(); - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) throw new Err("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present"); - let recognized; - if (recognizedOption !== void 0) recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); - else recognized = recognizedDefault; - for (const parameter of protectedHeader.crit) { - if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); - if (joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`); - if (recognized.get(parameter) && protectedHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); - } - return new Set(protectedHeader.crit); -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/validate_algorithms.js -function validateAlgorithms(option, algorithms) { - if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) throw new TypeError(`"${option}" option must be an array of strings`); - if (!algorithms) return; - return new Set(algorithms); -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/check_key_type.js -var tag = (key) => key?.[Symbol.toStringTag]; -var jwkMatchesOp = (alg, key, usage) => { - if (key.use !== void 0) { - let expected; - switch (usage) { - case "sign": - case "verify": - expected = "sig"; - break; - case "encrypt": - case "decrypt": - expected = "enc"; - break; - } - if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`); - } - if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`); - if (Array.isArray(key.key_ops)) { - let expectedKeyOp; - switch (true) { - case usage === "sign" || usage === "verify": - case alg === "dir": - case alg.includes("CBC-HS"): - expectedKeyOp = usage; - break; - case alg.startsWith("PBES2"): - expectedKeyOp = "deriveBits"; - break; - case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg): - if (!alg.includes("GCM") && alg.endsWith("KW")) expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey"; - else expectedKeyOp = usage; - break; - case usage === "encrypt" && alg.startsWith("RSA"): - expectedKeyOp = "wrapKey"; - break; - case usage === "decrypt": - expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits"; - break; - } - if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`); - } - return true; -}; -var symmetricTypeCheck = (alg, key, usage) => { - if (key instanceof Uint8Array) return; - if (isJWK(key)) { - if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return; - throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); - } - if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array")); - if (key.type !== "secret") throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); -}; -var asymmetricTypeCheck = (alg, key, usage) => { - if (isJWK(key)) switch (usage) { - case "decrypt": - case "sign": - if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return; - throw new TypeError(`JSON Web Key for this operation must be a private JWK`); - case "encrypt": - case "verify": - if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return; - throw new TypeError(`JSON Web Key for this operation must be a public JWK`); - } - if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key")); - if (key.type === "secret") throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); - if (key.type === "public") switch (usage) { - case "sign": throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); - case "decrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); - } - if (key.type === "private") switch (usage) { - case "verify": throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); - case "encrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); - } -}; -function checkKeyType(alg, key, usage) { - switch (alg.substring(0, 2)) { - case "A1": - case "A2": - case "di": - case "HS": - case "PB": - symmetricTypeCheck(alg, key, usage); - break; - default: asymmetricTypeCheck(alg, key, usage); - } -} -//#endregion -//#region node_modules/jose/dist/webapi/jws/flattened/verify.js -async function flattenedVerify(jws, key, options) { - if (!isObject(jws)) throw new JWSInvalid("Flattened JWS must be an object"); - if (jws.protected === void 0 && jws.header === void 0) throw new JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members"); - if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new JWSInvalid("JWS Protected Header incorrect type"); - if (jws.payload === void 0) throw new JWSInvalid("JWS Payload missing"); - if (typeof jws.signature !== "string") throw new JWSInvalid("JWS Signature missing or incorrect type"); - if (jws.header !== void 0 && !isObject(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type"); - let parsedProt = {}; - if (jws.protected) try { - const protectedHeader = decode(jws.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader)); - } catch { - throw new JWSInvalid("JWS Protected Header is invalid"); - } - if (!isDisjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); - const joseHeader = { - ...parsedProt, - ...jws.header - }; - const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader); - let b64 = true; - if (extensions.has("b64")) { - b64 = parsedProt.b64; - if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean"); - } - const { alg } = joseHeader; - if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid"); - const algorithms = options && validateAlgorithms("algorithms", options.algorithms); - if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed"); - if (b64) { - if (typeof jws.payload !== "string") throw new JWSInvalid("JWS Payload must be a string"); - } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); - let resolvedKey = false; - if (typeof key === "function") { - key = await key(parsedProt, jws); - resolvedKey = true; - } - checkKeyType(alg, key, "verify"); - const data = concat(jws.protected !== void 0 ? encode$1(jws.protected) : /* @__PURE__ */ new Uint8Array(), encode$1("."), typeof jws.payload === "string" ? b64 ? encode$1(jws.payload) : encoder.encode(jws.payload) : jws.payload); - const signature = decodeBase64url(jws.signature, "signature", JWSInvalid); - const k = await normalizeKey(key, alg); - if (!await verify(alg, k, signature, data)) throw new JWSSignatureVerificationFailed(); - let payload; - if (b64) payload = decodeBase64url(jws.payload, "payload", JWSInvalid); - else if (typeof jws.payload === "string") payload = encoder.encode(jws.payload); - else payload = jws.payload; - const result = { payload }; - if (jws.protected !== void 0) result.protectedHeader = parsedProt; - if (jws.header !== void 0) result.unprotectedHeader = jws.header; - if (resolvedKey) return { - ...result, - key: k - }; - return result; -} -//#endregion -//#region node_modules/jose/dist/webapi/jws/compact/verify.js -async function compactVerify(jws, key, options) { - if (jws instanceof Uint8Array) jws = decoder.decode(jws); - if (typeof jws !== "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); - const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); - if (length !== 3) throw new JWSInvalid("Invalid Compact JWS"); - const verified = await flattenedVerify({ - payload, - protected: protectedHeader, - signature - }, key, options); - const result = { - payload: verified.payload, - protectedHeader: verified.protectedHeader - }; - if (typeof key === "function") return { - ...result, - key: verified.key - }; - return result; -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/jwt_claims_set.js -var epoch = (date) => Math.floor(date.getTime() / 1e3); -var minute = 60; -var hour = minute * 60; -var day = hour * 24; -var week = day * 7; -var year = day * 365.25; -var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; -function secs(str) { - const matched = REGEX.exec(str); - if (!matched || matched[4] && matched[1]) throw new TypeError("Invalid time period format"); - const value = parseFloat(matched[2]); - const unit = matched[3].toLowerCase(); - let numericDate; - switch (unit) { - case "sec": - case "secs": - case "second": - case "seconds": - case "s": - numericDate = Math.round(value); - break; - case "minute": - case "minutes": - case "min": - case "mins": - case "m": - numericDate = Math.round(value * minute); - break; - case "hour": - case "hours": - case "hr": - case "hrs": - case "h": - numericDate = Math.round(value * hour); - break; - case "day": - case "days": - case "d": - numericDate = Math.round(value * day); - break; - case "week": - case "weeks": - case "w": - numericDate = Math.round(value * week); - break; - default: - numericDate = Math.round(value * year); - break; - } - if (matched[1] === "-" || matched[4] === "ago") return -numericDate; - return numericDate; -} -function validateInput(label, input) { - if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`); - return input; -} -var normalizeTyp = (value) => { - if (value.includes("/")) return value.toLowerCase(); - return `application/${value.toLowerCase()}`; -}; -var checkAudiencePresence = (audPayload, audOption) => { - if (typeof audPayload === "string") return audOption.includes(audPayload); - if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload))); - return false; -}; -function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { - let payload; - try { - payload = JSON.parse(decoder.decode(encodedPayload)); - } catch {} - if (!isObject(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); - const { typ } = options; - if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", "check_failed"); - const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; - const presenceCheck = [...requiredClaims]; - if (maxTokenAge !== void 0) presenceCheck.push("iat"); - if (audience !== void 0) presenceCheck.push("aud"); - if (subject !== void 0) presenceCheck.push("sub"); - if (issuer !== void 0) presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); - if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) throw new JWTClaimValidationFailed("unexpected \"iss\" claim value", payload, "iss", "check_failed"); - if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed("unexpected \"sub\" claim value", payload, "sub", "check_failed"); - if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) throw new JWTClaimValidationFailed("unexpected \"aud\" claim value", payload, "aud", "check_failed"); - let tolerance; - switch (typeof options.clockTolerance) { - case "string": - tolerance = secs(options.clockTolerance); - break; - case "number": - tolerance = options.clockTolerance; - break; - case "undefined": - tolerance = 0; - break; - default: throw new TypeError("Invalid clockTolerance option type"); - } - const { currentDate } = options; - const now = epoch(currentDate || /* @__PURE__ */ new Date()); - if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") throw new JWTClaimValidationFailed("\"iat\" claim must be a number", payload, "iat", "invalid"); - if (payload.nbf !== void 0) { - if (typeof payload.nbf !== "number") throw new JWTClaimValidationFailed("\"nbf\" claim must be a number", payload, "nbf", "invalid"); - if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", "check_failed"); - } - if (payload.exp !== void 0) { - if (typeof payload.exp !== "number") throw new JWTClaimValidationFailed("\"exp\" claim must be a number", payload, "exp", "invalid"); - if (payload.exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", "check_failed"); - } - if (maxTokenAge) { - const age = now - payload.iat; - const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge); - if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", "check_failed"); - if (age < 0 - tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", "check_failed"); - } - return payload; -} -var JWTClaimsBuilder = class { - #payload; - constructor(payload) { - if (!isObject(payload)) throw new TypeError("JWT Claims Set MUST be an object"); - this.#payload = structuredClone(payload); - } - data() { - return encoder.encode(JSON.stringify(this.#payload)); - } - get iss() { - return this.#payload.iss; - } - set iss(value) { - this.#payload.iss = value; - } - get sub() { - return this.#payload.sub; - } - set sub(value) { - this.#payload.sub = value; - } - get aud() { - return this.#payload.aud; - } - set aud(value) { - this.#payload.aud = value; - } - set jti(value) { - this.#payload.jti = value; - } - set nbf(value) { - if (typeof value === "number") this.#payload.nbf = validateInput("setNotBefore", value); - else if (value instanceof Date) this.#payload.nbf = validateInput("setNotBefore", epoch(value)); - else this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value); - } - set exp(value) { - if (typeof value === "number") this.#payload.exp = validateInput("setExpirationTime", value); - else if (value instanceof Date) this.#payload.exp = validateInput("setExpirationTime", epoch(value)); - else this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value); - } - set iat(value) { - if (value === void 0) this.#payload.iat = epoch(/* @__PURE__ */ new Date()); - else if (value instanceof Date) this.#payload.iat = validateInput("setIssuedAt", epoch(value)); - else if (typeof value === "string") this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)); - else this.#payload.iat = validateInput("setIssuedAt", value); - } -}; -//#endregion -//#region node_modules/jose/dist/webapi/jwt/verify.js -async function jwtVerify(jwt, key, options) { - const verified = await compactVerify(jwt, key, options); - if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); - const result = { - payload: validateClaimsSet(verified.protectedHeader, verified.payload, options), - protectedHeader: verified.protectedHeader - }; - if (typeof key === "function") return { - ...result, - key: verified.key - }; - return result; -} -//#endregion -//#region node_modules/jose/dist/webapi/jwks/local.js -function getKtyFromAlg(alg) { - switch (typeof alg === "string" && alg.slice(0, 2)) { - case "RS": - case "PS": return "RSA"; - case "ES": return "EC"; - case "Ed": return "OKP"; - case "ML": return "AKP"; - default: throw new JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set"); - } -} -function isJWKSLike(jwks) { - return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); -} -function isJWKLike(key) { - return isObject(key); -} -var LocalJWKSet = class { - #jwks; - #cached = /* @__PURE__ */ new WeakMap(); - constructor(jwks) { - if (!isJWKSLike(jwks)) throw new JWKSInvalid("JSON Web Key Set malformed"); - this.#jwks = structuredClone(jwks); - } - jwks() { - return this.#jwks; - } - async getKey(protectedHeader, token) { - const { alg, kid } = { - ...protectedHeader, - ...token?.header - }; - const kty = getKtyFromAlg(alg); - const candidates = this.#jwks.keys.filter((jwk) => { - let candidate = kty === jwk.kty; - if (candidate && typeof kid === "string") candidate = kid === jwk.kid; - if (candidate && (typeof jwk.alg === "string" || kty === "AKP")) candidate = alg === jwk.alg; - if (candidate && typeof jwk.use === "string") candidate = jwk.use === "sig"; - if (candidate && Array.isArray(jwk.key_ops)) candidate = jwk.key_ops.includes("verify"); - if (candidate) switch (alg) { - case "ES256": - candidate = jwk.crv === "P-256"; - break; - case "ES384": - candidate = jwk.crv === "P-384"; - break; - case "ES512": - candidate = jwk.crv === "P-521"; - break; - case "Ed25519": - case "EdDSA": - candidate = jwk.crv === "Ed25519"; - break; - } - return candidate; - }); - const { 0: jwk, length } = candidates; - if (length === 0) throw new JWKSNoMatchingKey(); - if (length !== 1) { - const error = new JWKSMultipleMatchingKeys(); - const _cached = this.#cached; - error[Symbol.asyncIterator] = async function* () { - for (const jwk of candidates) try { - yield await importWithAlgCache(_cached, jwk, alg); - } catch {} - }; - throw error; - } - return importWithAlgCache(this.#cached, jwk, alg); - } -}; -async function importWithAlgCache(cache, jwk, alg) { - const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); - if (cached[alg] === void 0) { - const key = await importJWK({ - ...jwk, - ext: true - }, alg); - if (key instanceof Uint8Array || key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); - cached[alg] = key; - } - return cached[alg]; -} -function createLocalJWKSet(jwks) { - const set = new LocalJWKSet(jwks); - const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(localJWKSet, { jwks: { - value: () => structuredClone(set.jwks()), - enumerable: false, - configurable: false, - writable: false - } }); - return localJWKSet; -} -//#endregion -//#region node_modules/jose/dist/webapi/jwks/remote.js -function isCloudflareWorkers() { - return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; -} -var USER_AGENT; -if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT = `jose/v6.2.4`; -var customFetch = Symbol(); -async function fetchJwks(url, headers, signal, fetchImpl = fetch) { - const response = await fetchImpl(url, { - method: "GET", - signal, - redirect: "manual", - headers - }).catch((err) => { - if (err.name === "TimeoutError") throw new JWKSTimeout(); - throw err; - }); - if (response.status !== 200) throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); - try { - return await response.json(); - } catch { - throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); - } -} -var jwksCache = Symbol(); -function isFreshJwksCache(input, cacheMaxAge) { - if (typeof input !== "object" || input === null) return false; - if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) return false; - if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) return false; - return true; -} -var RemoteJWKSet = class { - #url; - #timeoutDuration; - #cooldownDuration; - #cacheMaxAge; - #jwksTimestamp; - #pendingFetch; - #headers; - #customFetch; - #local; - #cache; - constructor(url, options) { - if (!(url instanceof URL)) throw new TypeError("url must be an instance of URL"); - this.#url = new URL(url.href); - this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3; - this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4; - this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5; - this.#headers = new Headers(options?.headers); - if (USER_AGENT && !this.#headers.has("User-Agent")) this.#headers.set("User-Agent", USER_AGENT); - if (!this.#headers.has("accept")) { - this.#headers.set("accept", "application/json"); - this.#headers.append("accept", "application/jwk-set+json"); - } - this.#customFetch = options?.[customFetch]; - if (options?.[jwksCache] !== void 0) { - this.#cache = options?.[jwksCache]; - if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) { - this.#jwksTimestamp = this.#cache.uat; - this.#local = createLocalJWKSet(this.#cache.jwks); - } - } - } - pendingFetch() { - return !!this.#pendingFetch; - } - coolingDown() { - return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false; - } - fresh() { - return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false; - } - jwks() { - return this.#local?.jwks(); - } - async getKey(protectedHeader, token) { - if (!this.#local || !this.fresh()) await this.reload(); - try { - return await this.#local(protectedHeader, token); - } catch (err) { - if (err instanceof JWKSNoMatchingKey) { - if (this.coolingDown() === false) { - await this.reload(); - return this.#local(protectedHeader, token); - } - } - throw err; - } - } - async reload() { - if (this.#pendingFetch && isCloudflareWorkers()) this.#pendingFetch = void 0; - this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json) => { - this.#local = createLocalJWKSet(json); - if (this.#cache) { - this.#cache.uat = Date.now(); - this.#cache.jwks = json; - } - this.#jwksTimestamp = Date.now(); - this.#pendingFetch = void 0; - }).catch((err) => { - this.#pendingFetch = void 0; - throw err; - }); - await this.#pendingFetch; - } -}; -function createRemoteJWKSet(url, options) { - const set = new RemoteJWKSet(url, options); - const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(remoteJWKSet, { - coolingDown: { - get: () => set.coolingDown(), - enumerable: true, - configurable: false - }, - fresh: { - get: () => set.fresh(), - enumerable: true, - configurable: false - }, - reload: { - value: () => set.reload(), - enumerable: true, - configurable: false, - writable: false - }, - reloading: { - get: () => set.pendingFetch(), - enumerable: true, - configurable: false - }, - jwks: { - value: () => set.jwks(), - enumerable: true, - configurable: false, - writable: false - } - }); - return remoteJWKSet; -} -//#endregion -//#region node_modules/jose/dist/webapi/util/decode_protected_header.js -function decodeProtectedHeader(token) { - let protectedB64u; - if (typeof token === "string") { - const parts = token.split("."); - if (parts.length === 3 || parts.length === 5) [protectedB64u] = parts; - } else if (typeof token === "object" && token) if ("protected" in token) protectedB64u = token.protected; - else throw new TypeError("Token does not contain a Protected Header"); - try { - if (typeof protectedB64u !== "string" || !protectedB64u) throw new Error(); - const result = JSON.parse(decoder.decode(decode(protectedB64u))); - if (!isObject(result)) throw new Error(); - return result; - } catch { - throw new TypeError("Invalid Token or Protected Header formatting"); - } -} -//#endregion -//#region node_modules/jose/dist/webapi/util/decode_jwt.js -function decodeJwt(jwt) { - if (typeof jwt !== "string") throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); - const { 1: payload, length } = jwt.split("."); - if (length === 5) throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); - if (length !== 3) throw new JWTInvalid("Invalid JWT"); - if (!payload) throw new JWTInvalid("JWTs must contain a payload"); - let decoded; - try { - decoded = decode(payload); - } catch { - throw new JWTInvalid("Failed to base64url decode the payload"); - } - let result; - try { - result = JSON.parse(decoder.decode(decoded)); - } catch { - throw new JWTInvalid("Failed to parse the decoded payload as JSON"); - } - if (!isObject(result)) throw new JWTInvalid("Invalid JWT Claims Set"); - return result; -} -//#endregion -//#region node_modules/@better-auth/utils/dist/index.mjs -function getWebcryptoSubtle() { - const cr = typeof globalThis !== "undefined" && globalThis.crypto; - if (cr && typeof cr.subtle === "object" && cr.subtle != null) return cr.subtle; - throw new Error("crypto.subtle must be defined"); -} -//#endregion -//#region node_modules/@better-auth/utils/dist/base64.mjs -function getAlphabet(urlSafe) { - return urlSafe ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -} -function base64Encode(data, alphabet, padding) { - let result = ""; - let buffer = 0; - let shift = 0; - for (const byte of data) { - buffer = buffer << 8 | byte; - shift += 8; - while (shift >= 6) { - shift -= 6; - result += alphabet[buffer >> shift & 63]; - } - } - if (shift > 0) result += alphabet[buffer << 6 - shift & 63]; - if (padding) { - const padCount = (4 - result.length % 4) % 4; - result += "=".repeat(padCount); - } - return result; -} -function base64Decode(data, alphabet) { - const decodeMap = /* @__PURE__ */ new Map(); - for (let i = 0; i < alphabet.length; i++) decodeMap.set(alphabet[i], i); - const result = []; - let buffer = 0; - let bitsCollected = 0; - for (const char of data) { - if (char === "=") break; - const value = decodeMap.get(char); - if (value === void 0) throw new Error(`Invalid Base64 character: ${char}`); - buffer = buffer << 6 | value; - bitsCollected += 6; - if (bitsCollected >= 8) { - bitsCollected -= 8; - result.push(buffer >> bitsCollected & 255); - } - } - return Uint8Array.from(result); -} -var base64 = { - encode(data, options = {}) { - const alphabet = getAlphabet(false); - return base64Encode(typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data), alphabet, options.padding ?? true); - }, - decode(data) { - if (typeof data !== "string") data = new TextDecoder().decode(data); - const alphabet = getAlphabet(data.includes("-") || data.includes("_")); - return base64Decode(data, alphabet); - } -}; -var base64Url = { - encode(data, options = {}) { - const alphabet = getAlphabet(true); - return base64Encode(typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data), alphabet, options.padding ?? true); - }, - decode(data) { - return base64Decode(data, getAlphabet(data.includes("-") || data.includes("_"))); - } -}; -//#endregion -//#region node_modules/@better-auth/core/dist/utils/db.mjs -/** -* Filters output data by removing fields with the `returned: false` attribute. -* This ensures sensitive fields are not exposed in API responses. -*/ -function filterOutputFields(data, additionalFields) { - if (!data || !additionalFields) return data; - const returnFiltered = Object.entries(additionalFields).filter(([, { returned }]) => returned === false).map(([key]) => key); - return Object.entries(structuredClone(data)).filter(([key]) => !returnFiltered.includes(key)).reduce((acc, [key, value]) => ({ - ...acc, - [key]: value - }), {}); -} -//#endregion -//#region node_modules/better-call/dist/utils.mjs -var jsonContentTypeRegex = /^application\/([a-z0-9.+-]*\+)?json/i; -async function getBody(request, allowedMediaTypes) { - const contentType = request.headers.get("content-type") || ""; - const normalizedContentType = contentType.toLowerCase(); - if (!request.body) return; - if (allowedMediaTypes && allowedMediaTypes.length > 0) { - if (!allowedMediaTypes.some((allowed) => { - const normalizedContentTypeBase = normalizedContentType.split(";")[0].trim(); - const normalizedAllowed = allowed.toLowerCase().trim(); - return normalizedContentTypeBase === normalizedAllowed || normalizedContentTypeBase.includes(normalizedAllowed); - })) { - if (!normalizedContentType) throw new APIError$1(415, { - message: `Content-Type is required. Allowed types: ${allowedMediaTypes.join(", ")}`, - code: "UNSUPPORTED_MEDIA_TYPE" - }); - throw new APIError$1(415, { - message: `Content-Type "${contentType}" is not allowed. Allowed types: ${allowedMediaTypes.join(", ")}`, - code: "UNSUPPORTED_MEDIA_TYPE" - }); - } - } - if (jsonContentTypeRegex.test(normalizedContentType)) try { - return await request.json(); - } catch (e) { - if (e instanceof SyntaxError) throw new APIError$1(400, { - message: "Invalid JSON in request body", - code: "BAD_REQUEST" - }); - throw e; - } - if (normalizedContentType.includes("application/x-www-form-urlencoded")) { - const formData = await request.formData(); - const result = {}; - formData.forEach((value, key) => { - result[key] = value.toString(); - }); - return result; - } - if (normalizedContentType.includes("multipart/form-data")) { - const formData = await request.formData(); - const result = {}; - formData.forEach((value, key) => { - result[key] = value; - }); - return result; - } - if (normalizedContentType.includes("text/plain")) return await request.text(); - if (normalizedContentType.includes("application/octet-stream")) return await request.arrayBuffer(); - if (normalizedContentType.includes("application/pdf") || normalizedContentType.includes("image/") || normalizedContentType.includes("video/")) return await request.blob(); - if (normalizedContentType.includes("application/stream") || request.body instanceof ReadableStream) return request.body; - return await request.text(); -} -function isAPIError$1(error) { - return error instanceof APIError$1 || error?.name === "APIError"; -} -function tryDecode(str) { - try { - return str.includes("%") ? decodeURIComponent(str) : str; - } catch { - return str; - } -} -async function tryCatch(promise) { - try { - return { - data: await promise, - error: null - }; - } catch (error) { - return { - data: null, - error - }; - } -} -/** -* Check if an object is a `Request` -* - `instanceof`: works for native Request instances -* - `toString`: handles where instanceof check fails but the object is still a valid Request -*/ -function isRequest(obj) { - return obj instanceof Request || Object.prototype.toString.call(obj) === "[object Request]"; -} -//#endregion -//#region node_modules/better-call/dist/to-response.mjs -function isJSONSerializable(value) { - if (value === void 0) return false; - const t = typeof value; - if (t === "string" || t === "number" || t === "boolean" || t === null) return true; - if (t !== "object") return false; - if (Array.isArray(value)) return true; - if (value.buffer) return false; - return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function"; -} -function safeStringify(obj) { - const parents = /* @__PURE__ */ new WeakMap(); - const ids = /* @__PURE__ */ new WeakMap(); - let id = 0; - const isAncestor = (value, holder) => { - let curr = holder; - while (curr) { - if (curr === value) return true; - curr = parents.get(curr); - } - return false; - }; - return JSON.stringify(obj, function(_key, value) { - if (typeof value === "bigint") return value.toString(); - if (typeof value === "object" && value !== null) { - if (isAncestor(value, this)) return `[Circular ref-${ids.get(value)}]`; - parents.set(value, this); - if (!ids.has(value)) ids.set(value, id++); - } - return value; - }); -} -function isJSONResponse(value) { - if (!value || typeof value !== "object") return false; - return "_flag" in value && value._flag === "json"; -} -/** -* Headers that MUST be stripped when building an HTTP response from -* arbitrary header input. These are request-only, hop-by-hop, or -* transport-managed headers that cause protocol violations when present -* on responses (e.g. Content-Length mismatch → net::ERR_CONTENT_LENGTH_MISMATCH). -* -* Sources: -* - RFC 9110 §10.1 (Request Context Fields) -* - RFC 9110 §7.6.1 (Connection / hop-by-hop) -* - RFC 9110 §11.6-7 (Authentication credentials) -* - RFC 9110 §12.5 (Content negotiation) -* - RFC 9110 §13.1 (Conditional request headers) -* - RFC 9110 §14.2 (Range requests) -* - RFC 6265 §5.4 (Cookie) -* - RFC 6454 (Origin) -*/ -var REQUEST_ONLY_HEADERS = /* @__PURE__ */ new Set([ - "host", - "user-agent", - "referer", - "from", - "expect", - "authorization", - "proxy-authorization", - "cookie", - "origin", - "accept-charset", - "accept-encoding", - "accept-language", - "if-match", - "if-none-match", - "if-modified-since", - "if-unmodified-since", - "if-range", - "range", - "max-forwards", - "connection", - "keep-alive", - "transfer-encoding", - "te", - "upgrade", - "trailer", - "proxy-connection", - "content-length" -]); -function stripRequestOnlyHeaders(headers) { - for (const name of REQUEST_ONLY_HEADERS) headers.delete(name); -} -/** -* Copy headers from `source` into `target`. `Set-Cookie` is appended (one -* header per cookie) because RFC 9110 §5.3 notes it cannot be combined -* into a single comma-separated value; other headers are set (replace). -*/ -function copyHeaders(target, source) { - if (!source) return; - for (const [key, value] of new Headers(source).entries()) if (key.toLowerCase() === "set-cookie") target.append(key, value); - else target.set(key, value); -} -function toResponse(data, init) { - if (data instanceof Response) { - if (init?.headers) { - const safeHeaders = new Headers(init.headers); - stripRequestOnlyHeaders(safeHeaders); - copyHeaders(data.headers, safeHeaders); - } - return data; - } - if (isJSONResponse(data)) { - const body = data.body; - const routerResponse = data.routerResponse; - if (routerResponse instanceof Response) return routerResponse; - const headers = new Headers(); - copyHeaders(headers, routerResponse?.headers); - copyHeaders(headers, data.headers); - if (init?.headers) { - const safeHeaders = new Headers(init.headers); - stripRequestOnlyHeaders(safeHeaders); - copyHeaders(headers, safeHeaders); - } - headers.set("Content-Type", "application/json"); - return new Response(JSON.stringify(body), { - ...routerResponse, - headers, - status: data.status ?? init?.status ?? routerResponse?.status, - statusText: init?.statusText ?? routerResponse?.statusText - }); - } - if (isAPIError$1(data)) return toResponse(data.body, { - status: init?.status ?? data.statusCode, - statusText: data.status.toString(), - headers: init?.headers || data.headers - }); - let body = data; - const headers = new Headers(init?.headers); - stripRequestOnlyHeaders(headers); - if (!data) { - if (data === null) body = JSON.stringify(null); - headers.set("content-type", "application/json"); - } else if (typeof data === "string") { - body = data; - headers.set("Content-Type", "text/plain"); - } else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) { - body = data; - headers.set("Content-Type", "application/octet-stream"); - } else if (data instanceof Blob) { - body = data; - headers.set("Content-Type", data.type || "application/octet-stream"); - } else if (data instanceof FormData) body = data; - else if (data instanceof URLSearchParams) { - body = data; - headers.set("Content-Type", "application/x-www-form-urlencoded"); - } else if (data instanceof ReadableStream) { - body = data; - headers.set("Content-Type", "application/octet-stream"); - } else if (isJSONSerializable(data)) { - body = safeStringify(data); - headers.set("Content-Type", "application/json"); - } - return new Response(body, { - ...init, - headers - }); -} -//#endregion -//#region node_modules/better-call/dist/crypto.mjs -var algorithm = { - name: "HMAC", - hash: "SHA-256" -}; -var getCryptoKey = async (secret) => { - const secretBuf = typeof secret === "string" ? new TextEncoder().encode(secret) : secret; - return await getWebcryptoSubtle().importKey("raw", secretBuf, algorithm, false, ["sign", "verify"]); -}; -var verifySignature = async (base64Signature, value, secret) => { - try { - const signatureBinStr = atob(base64Signature); - const signature = new Uint8Array(signatureBinStr.length); - for (let i = 0, len = signatureBinStr.length; i < len; i++) signature[i] = signatureBinStr.charCodeAt(i); - return await getWebcryptoSubtle().verify(algorithm, secret, signature, new TextEncoder().encode(value)); - } catch (e) { - return false; - } -}; -var makeSignature = async (value, secret) => { - const key = await getCryptoKey(secret); - const signature = await getWebcryptoSubtle().sign(algorithm.name, key, new TextEncoder().encode(value)); - return btoa(String.fromCharCode(...new Uint8Array(signature))); -}; -var signCookieValue = async (value, secret) => { - const signature = await makeSignature(value, secret); - value = `${value}.${signature}`; - value = encodeURIComponent(value); - return value; -}; -//#endregion -//#region node_modules/better-call/dist/cookies.mjs -var getCookieKey = (key, prefix) => { - let finalKey = key; - if (prefix) if (prefix === "secure") finalKey = "__Secure-" + key; - else if (prefix === "host") finalKey = "__Host-" + key; - else return; - return finalKey; -}; -/** -* Parse an HTTP Cookie header string and returning an object of all cookie -* name-value pairs. -* -* Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts -* -* @param str the string representing a `Cookie` header value -*/ -function parseCookies(str) { - if (typeof str !== "string") throw new TypeError("argument str must be a string"); - const cookies = /* @__PURE__ */ new Map(); - let index = 0; - while (index < str.length) { - const eqIdx = str.indexOf("=", index); - if (eqIdx === -1) break; - let endIdx = str.indexOf(";", index); - if (endIdx === -1) endIdx = str.length; - else if (endIdx < eqIdx) { - index = str.lastIndexOf(";", eqIdx - 1) + 1; - continue; - } - const key = str.slice(index, eqIdx).trim(); - if (!cookies.has(key)) { - let val = str.slice(eqIdx + 1, endIdx).trim(); - if (val.codePointAt(0) === 34) val = val.slice(1, -1); - cookies.set(key, tryDecode(val)); - } - index = endIdx + 1; - } - return cookies; -} -var _serialize = (key, value, opt = {}) => { - let cookie; - if (opt?.prefix === "secure") cookie = `${`__Secure-${key}`}=${value}`; - else if (opt?.prefix === "host") cookie = `${`__Host-${key}`}=${value}`; - else cookie = `${key}=${value}`; - if (key.startsWith("__Secure-") && !opt.secure) opt.secure = true; - if (key.startsWith("__Host-")) { - if (!opt.secure) opt.secure = true; - if (opt.path !== "/") opt.path = "/"; - if (opt.domain) opt.domain = void 0; - } - if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) { - if (opt.maxAge > 3456e4) throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration."); - cookie += `; Max-Age=${Math.floor(opt.maxAge)}`; - } - if (opt.domain && opt.prefix !== "host") cookie += `; Domain=${opt.domain}`; - if (opt.path) cookie += `; Path=${opt.path}`; - if (opt.expires) { - if (opt.expires.getTime() - Date.now() > 3456e7) throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future."); - cookie += `; Expires=${opt.expires.toUTCString()}`; - } - if (opt.httpOnly) cookie += "; HttpOnly"; - if (opt.secure) cookie += "; Secure"; - if (opt.sameSite) cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`; - if (opt.partitioned) { - if (!opt.secure) opt.secure = true; - cookie += "; Partitioned"; - } - return cookie; -}; -var serializeCookie = (key, value, opt) => { - value = encodeURIComponent(value); - return _serialize(key, value, opt); -}; -var serializeSignedCookie = async (key, value, secret, opt) => { - value = await signCookieValue(value, secret); - return _serialize(key, value, opt); -}; -//#endregion -//#region node_modules/better-call/dist/validator.mjs -/** -* Runs validation on body and query -* @returns error and data object -*/ -async function runValidation(options, context = {}) { - let request = { - body: context.body, - query: context.query - }; - if (options.body) { - const result = await options.body["~standard"].validate(context.body); - if (result.issues) return { - data: null, - error: fromError(result.issues, "body") - }; - request.body = result.value; - } - if (options.query) { - const result = await options.query["~standard"].validate(context.query); - if (result.issues) return { - data: null, - error: fromError(result.issues, "query") - }; - request.query = result.value; - } - if (options.requireHeaders && !context.headers) return { - data: null, - error: { - message: "Headers is required", - issues: [] - } - }; - if (options.requireRequest && !context.request) return { - data: null, - error: { - message: "Request is required", - issues: [] - } - }; - return { - data: request, - error: null - }; -} -function fromError(error, validating) { - return { - message: error.map((e) => { - return `[${e.path?.length ? `${validating}.` + e.path.map((x) => typeof x === "object" ? x.key : x).join(".") : validating}] ${e.message}`; - }).join("; "), - issues: error - }; -} -//#endregion -//#region node_modules/better-call/dist/context.mjs -var createInternalContext = async (context, { options, path }) => { - const headers = new Headers(); - let responseStatus = void 0; - const { data, error } = await runValidation(options, context); - if (error) throw new ValidationError$1(error.message, error.issues); - const requestHeaders = "headers" in context ? context.headers instanceof Headers ? context.headers : new Headers(context.headers) : "request" in context && isRequest(context.request) ? context.request.headers : null; - const requestCookies = requestHeaders?.get("cookie"); - const parsedCookies = requestCookies ? parseCookies(requestCookies) : void 0; - const internalContext = { - ...context, - body: data.body, - query: data.query, - path: context.path || path || "virtual:", - context: "context" in context && context.context ? context.context : {}, - returned: void 0, - headers: context?.headers, - request: context?.request, - params: "params" in context ? context.params : void 0, - method: context.method ?? (Array.isArray(options.method) ? options.method[0] : options.method === "*" ? "GET" : options.method), - setHeader: (key, value) => { - headers.set(key, value); - }, - getHeader: (key) => { - if (!requestHeaders) return null; - return requestHeaders.get(key); - }, - getCookie: (key, prefix) => { - const finalKey = getCookieKey(key, prefix); - if (!finalKey) return null; - return parsedCookies?.get(finalKey) || null; - }, - getSignedCookie: async (key, secret, prefix) => { - const finalKey = getCookieKey(key, prefix); - if (!finalKey) return null; - const value = parsedCookies?.get(finalKey); - if (!value) return null; - const signatureStartPos = value.lastIndexOf("."); - if (signatureStartPos < 1) return null; - const signedValue = value.substring(0, signatureStartPos); - const signature = value.substring(signatureStartPos + 1); - if (signature.length !== 44 || !signature.endsWith("=")) return null; - return await verifySignature(signature, signedValue, await getCryptoKey(secret)) ? signedValue : false; - }, - setCookie: (key, value, options) => { - const cookie = serializeCookie(key, value, options); - headers.append("set-cookie", cookie); - return cookie; - }, - setSignedCookie: async (key, value, secret, options) => { - const cookie = await serializeSignedCookie(key, value, secret, options); - headers.append("set-cookie", cookie); - return cookie; - }, - redirect: (url) => { - headers.set("location", url); - return new APIError$1("FOUND", void 0, headers); - }, - error: (status, body, headers) => { - return new APIError$1(status, body, headers); - }, - setStatus: (status) => { - responseStatus = status; - }, - json: (json, routerResponse) => { - if (!context.asResponse) return json; - return { - body: routerResponse?.body || json, - routerResponse, - _flag: "json" - }; - }, - responseHeaders: headers, - get responseStatus() { - return responseStatus; - } - }; - for (const middleware of options.use || []) { - const response = await middleware({ - ...internalContext, - returnHeaders: true, - asResponse: false - }); - if (response.response) Object.assign(internalContext.context, response.response); - /** - * Apply headers from the middleware to the endpoint headers - */ - if (response.headers) response.headers.forEach((value, key) => { - internalContext.responseHeaders.set(key, value); - }); - } - return internalContext; -}; -//#endregion -//#region node_modules/better-call/dist/endpoint.mjs -function createEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) { - const path = typeof pathOrOptions === "string" ? pathOrOptions : void 0; - const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions; - const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever; - if ((options.method === "GET" || options.method === "HEAD") && options.body) throw new BetterCallError("Body is not allowed with GET or HEAD methods"); - if (path && /\/{2,}/.test(path)) throw new BetterCallError("Path cannot contain consecutive slashes"); - const internalHandler = async (...inputCtx) => { - const context = inputCtx[0] || {}; - const { data: internalContext, error: validationError } = await tryCatch(createInternalContext(context, { - options, - path - })); - if (validationError) { - if (!(validationError instanceof ValidationError$1)) throw validationError; - if (options.onValidationError) await options.onValidationError({ - message: validationError.message, - issues: validationError.issues - }); - throw new APIError$1(400, { - message: validationError.message, - code: "VALIDATION_ERROR" - }); - } - const response = await handler(internalContext).catch(async (e) => { - if (isAPIError$1(e)) { - const onAPIError = options.onAPIError; - if (onAPIError) await onAPIError(e); - if (context.asResponse) return e; - } - throw e; - }); - const headers = internalContext.responseHeaders; - const status = internalContext.responseStatus; - return context.asResponse ? toResponse(response, { - headers, - status - }) : context.returnHeaders ? context.returnStatus ? { - headers, - response, - status - } : { - headers, - response - } : context.returnStatus ? { - response, - status - } : response; - }; - internalHandler.options = options; - internalHandler.path = path; - return internalHandler; -} -createEndpoint.create = (opts) => { - return (path, options, handler) => { - return createEndpoint(path, { - ...options, - use: [...options?.use || [], ...opts?.use || []] - }, handler); - }; -}; -//#endregion -//#region node_modules/better-call/dist/middleware.mjs -function createMiddleware(optionsOrHandler, handler) { - const internalHandler = async (inputCtx) => { - const context = inputCtx; - const _handler = typeof optionsOrHandler === "function" ? optionsOrHandler : handler; - const internalContext = await createInternalContext(context, { - options: typeof optionsOrHandler === "function" ? {} : optionsOrHandler, - path: "/" - }); - if (!_handler) throw new Error("handler must be defined"); - try { - const response = await _handler(internalContext); - const headers = internalContext.responseHeaders; - return context.returnHeaders ? { - headers, - response - } : response; - } catch (e) { - if (isAPIError$1(e)) Object.defineProperty(e, kAPIErrorHeaderSymbol, { - enumerable: false, - configurable: true, - get() { - return internalContext.responseHeaders; - } - }); - throw e; - } - }; - internalHandler.options = typeof optionsOrHandler === "function" ? {} : optionsOrHandler; - return internalHandler; -} -createMiddleware.create = (opts) => { - function fn(optionsOrHandler, handler) { - if (typeof optionsOrHandler === "function") return createMiddleware({ use: opts?.use }, optionsOrHandler); - if (!handler) throw new Error("Middleware handler is required"); - return createMiddleware({ - ...optionsOrHandler, - method: "*", - use: [...opts?.use || [], ...optionsOrHandler.use || []] - }, handler); - } - return fn; -}; -//#endregion -//#region node_modules/better-call/dist/openapi.mjs -var paths = {}; -function getTypeFromZodType(zodType) { - switch (zodType.constructor.name) { - case "ZodString": return "string"; - case "ZodNumber": return "number"; - case "ZodBoolean": return "boolean"; - case "ZodObject": return "object"; - case "ZodArray": return "array"; - default: return "string"; - } -} -function getParameters(options) { - const parameters = []; - if (options.metadata?.openapi?.parameters) { - parameters.push(...options.metadata.openapi.parameters); - return parameters; - } - if (options.query instanceof ZodObject) Object.entries(options.query.shape).forEach(([key, value]) => { - if (value instanceof ZodObject) parameters.push({ - name: key, - in: "query", - schema: { - type: getTypeFromZodType(value), - ..."minLength" in value && value.minLength ? { minLength: value.minLength } : {}, - description: value.description - } - }); - }); - return parameters; -} -function getRequestBody(options) { - if (options.metadata?.openapi?.requestBody) return options.metadata.openapi.requestBody; - if (!options.body) return void 0; - if (options.body instanceof ZodObject || options.body instanceof ZodOptional) { - const shape = options.body.shape; - if (!shape) return void 0; - const properties = {}; - const required = []; - Object.entries(shape).forEach(([key, value]) => { - if (value instanceof ZodObject) { - properties[key] = { - type: getTypeFromZodType(value), - description: value.description - }; - if (!(value instanceof ZodOptional)) required.push(key); - } - }); - return { - required: options.body instanceof ZodOptional ? false : options.body ? true : false, - content: { "application/json": { schema: { - type: "object", - properties, - required - } } } - }; - } -} -function getResponse(responses) { - return { - "400": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } }, - required: ["message"] - } } }, - description: "Bad Request. Usually due to missing parameters, or invalid parameters." - }, - "401": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } }, - required: ["message"] - } } }, - description: "Unauthorized. Due to missing or invalid authentication." - }, - "403": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } }, - description: "Forbidden. You do not have permission to access this resource or to perform this action." - }, - "404": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } }, - description: "Not Found. The requested resource was not found." - }, - "429": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } }, - description: "Too Many Requests. You have exceeded the rate limit. Try again later." - }, - "500": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } }, - description: "Internal Server Error. This is a problem with the server that you cannot fix." - }, - ...responses - }; -} -async function generator(endpoints, config) { - const components = { schemas: {} }; - Object.entries(endpoints).forEach(([_, value]) => { - const options = value.options; - if (!value.path || options.metadata?.SERVER_ONLY) return; - if (options.method === "GET") paths[value.path] = { get: { - tags: ["Default", ...options.metadata?.openapi?.tags || []], - description: options.metadata?.openapi?.description, - operationId: options.metadata?.openapi?.operationId, - security: [{ bearerAuth: [] }], - parameters: getParameters(options), - responses: getResponse(options.metadata?.openapi?.responses) - } }; - if (options.method === "POST") { - const body = getRequestBody(options); - paths[value.path] = { post: { - tags: ["Default", ...options.metadata?.openapi?.tags || []], - description: options.metadata?.openapi?.description, - operationId: options.metadata?.openapi?.operationId, - security: [{ bearerAuth: [] }], - parameters: getParameters(options), - ...body ? { requestBody: body } : { requestBody: { content: { "application/json": { schema: { - type: "object", - properties: {} - } } } } }, - responses: getResponse(options.metadata?.openapi?.responses) - } }; - } - }); - return { - openapi: "3.1.1", - info: { - title: "Better Auth", - description: "API Reference for your Better Auth Instance", - version: "1.1.0" - }, - components, - security: [{ apiKeyCookie: [] }], - servers: [{ url: config?.url }], - tags: [{ - name: "Default", - description: "Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin." - }], - paths - }; -} -var getHTML = (apiReference, config) => ` - - - Scalar API Reference - - - - - - - -
-

- Desktop shell ready. If the app UI does not load, re-run - npm run build:desktop after a successful web build. -

- - -`, - ); - } +// ── Verification ───────────────────────────────────────────────────────────── +// Fail here rather than three steps later, in front of someone staring at a +// blank window. +const indexPath = join(OUT, "index.html"); +const html = readFileSync(indexPath, "utf8"); + +if (!/]+src=/i.test(html)) { + console.error( + `${indexPath} contains no