@openrouter/ai-sdk-provider
Version:
The [OpenRouter](https://openrouter.ai/) provider for the [Vercel AI SDK](https://sdk.vercel.ai/docs) gives access to over 300 large language models on the OpenRouter chat and completion APIs.
1 lines • 218 kB
Source Map (JSON)
{"version":3,"sources":["../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/ai-sdk-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/api-call-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/empty-response-body-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/get-error-message.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/invalid-argument-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/invalid-prompt-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/invalid-response-data-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/json-parse-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/load-api-key-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/load-setting-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/no-content-generated-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/no-such-model-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/too-many-embedding-values-for-call-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/type-validation-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/unsupported-functionality-error.ts","../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/json-value/is-json.ts","../../node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/src/errors.ts","../../node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/src/parse.ts","../../node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/src/stream.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/combine-headers.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/convert-async-iterator-to-readable-stream.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/delay.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/extract-response-headers.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/generate-id.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/get-error-message.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/get-from-api.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/handle-fetch-error.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/is-abort-error.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/remove-undefined-entries.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/is-url-supported.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/load-api-key.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/load-optional-setting.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/load-setting.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/parse-json.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/secure-json-parse.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/validate-types.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/validator.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/parse-json-event-stream.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/parse-provider-options.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/post-to-api.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/types/tool.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/provider-defined-tool-factory.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/resolve.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/response-handler.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/zod-schema.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/schema.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/uint8-utils.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/without-trailing-slash.ts","../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/src/index.ts","../../node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Options.js","../../node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/selectParser.js","../../node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/array.js","../../node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/record.js","../../node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/string.js","../../src/schemas/reasoning-details.ts","../../src/schemas/error-response.ts","../../src/utils/map-finish-reason.ts","../../src/chat/is-url.ts","../../src/chat/file-url-utils.ts","../../src/chat/convert-to-openrouter-chat-messages.ts","../../src/chat/get-tool-choice.ts","../../src/chat/schemas.ts","../../src/chat/index.ts","../../src/completion/convert-to-openrouter-completion-prompt.ts","../../src/completion/schemas.ts","../../src/completion/index.ts"],"sourcesContent":["/**\n * Symbol used for identifying AI SDK Error instances.\n * Enables checking if an error is an instance of AISDKError across package versions.\n */\nconst marker = 'vercel.ai.error';\nconst symbol = Symbol.for(marker);\n\n/**\n * Custom error class for AI SDK related errors.\n * @extends Error\n */\nexport class AISDKError extends Error {\n private readonly [symbol] = true; // used in isInstance\n\n /**\n * The underlying cause of the error, if any.\n */\n readonly cause?: unknown;\n\n /**\n * Creates an AI SDK Error.\n *\n * @param {Object} params - The parameters for creating the error.\n * @param {string} params.name - The name of the error.\n * @param {string} params.message - The error message.\n * @param {unknown} [params.cause] - The underlying cause of the error.\n */\n constructor({\n name,\n message,\n cause,\n }: {\n name: string;\n message: string;\n cause?: unknown;\n }) {\n super(message);\n\n this.name = name;\n this.cause = cause;\n }\n\n /**\n * Checks if the given error is an AI SDK Error.\n * @param {unknown} error - The error to check.\n * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n */\n static isInstance(error: unknown): error is AISDKError {\n return AISDKError.hasMarker(error, marker);\n }\n\n protected static hasMarker(error: unknown, marker: string): boolean {\n const markerSymbol = Symbol.for(marker);\n return (\n error != null &&\n typeof error === 'object' &&\n markerSymbol in error &&\n typeof error[markerSymbol] === 'boolean' &&\n error[markerSymbol] === true\n );\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_APICallError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class APICallError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly url: string;\n readonly requestBodyValues: unknown;\n readonly statusCode?: number;\n\n readonly responseHeaders?: Record<string, string>;\n readonly responseBody?: string;\n\n readonly isRetryable: boolean;\n readonly data?: unknown;\n\n constructor({\n message,\n url,\n requestBodyValues,\n statusCode,\n responseHeaders,\n responseBody,\n cause,\n isRetryable = statusCode != null &&\n (statusCode === 408 || // request timeout\n statusCode === 409 || // conflict\n statusCode === 429 || // too many requests\n statusCode >= 500), // server error\n data,\n }: {\n message: string;\n url: string;\n requestBodyValues: unknown;\n statusCode?: number;\n responseHeaders?: Record<string, string>;\n responseBody?: string;\n cause?: unknown;\n isRetryable?: boolean;\n data?: unknown;\n }) {\n super({ name, message, cause });\n\n this.url = url;\n this.requestBodyValues = requestBodyValues;\n this.statusCode = statusCode;\n this.responseHeaders = responseHeaders;\n this.responseBody = responseBody;\n this.isRetryable = isRetryable;\n this.data = data;\n }\n\n static isInstance(error: unknown): error is APICallError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_EmptyResponseBodyError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class EmptyResponseBodyError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n constructor({ message = 'Empty response body' }: { message?: string } = {}) {\n super({ name, message });\n }\n\n static isInstance(error: unknown): error is EmptyResponseBodyError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","export function getErrorMessage(error: unknown | undefined) {\n if (error == null) {\n return 'unknown error';\n }\n\n if (typeof error === 'string') {\n return error;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n return JSON.stringify(error);\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * A function argument is invalid.\n */\nexport class InvalidArgumentError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly argument: string;\n\n constructor({\n message,\n cause,\n argument,\n }: {\n argument: string;\n message: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n\n this.argument = argument;\n }\n\n static isInstance(error: unknown): error is InvalidArgumentError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidPromptError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * A prompt is invalid. This error should be thrown by providers when they cannot\n * process a prompt.\n */\nexport class InvalidPromptError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly prompt: unknown;\n\n constructor({\n prompt,\n message,\n cause,\n }: {\n prompt: unknown;\n message: string;\n cause?: unknown;\n }) {\n super({ name, message: `Invalid prompt: ${message}`, cause });\n\n this.prompt = prompt;\n }\n\n static isInstance(error: unknown): error is InvalidPromptError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidResponseDataError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Server returned a response with invalid data content.\n * This should be thrown by providers when they cannot parse the response from the API.\n */\nexport class InvalidResponseDataError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly data: unknown;\n\n constructor({\n data,\n message = `Invalid response data: ${JSON.stringify(data)}.`,\n }: {\n data: unknown;\n message?: string;\n }) {\n super({ name, message });\n\n this.data = data;\n }\n\n static isInstance(error: unknown): error is InvalidResponseDataError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\nimport { getErrorMessage } from './get-error-message';\n\nconst name = 'AI_JSONParseError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n// TODO v5: rename to ParseError\nexport class JSONParseError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly text: string;\n\n constructor({ text, cause }: { text: string; cause: unknown }) {\n super({\n name,\n message:\n `JSON parsing failed: ` +\n `Text: ${text}.\\n` +\n `Error message: ${getErrorMessage(cause)}`,\n cause,\n });\n\n this.text = text;\n }\n\n static isInstance(error: unknown): error is JSONParseError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_LoadAPIKeyError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class LoadAPIKeyError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n constructor({ message }: { message: string }) {\n super({ name, message });\n }\n\n static isInstance(error: unknown): error is LoadAPIKeyError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_LoadSettingError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class LoadSettingError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n constructor({ message }: { message: string }) {\n super({ name, message });\n }\n\n static isInstance(error: unknown): error is LoadSettingError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoContentGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\nThrown when the AI provider fails to generate any content.\n */\nexport class NoContentGeneratedError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n constructor({\n message = 'No content generated.',\n }: { message?: string } = {}) {\n super({ name, message });\n }\n\n static isInstance(error: unknown): error is NoContentGeneratedError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoSuchModelError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchModelError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly modelId: string;\n readonly modelType:\n | 'languageModel'\n | 'textEmbeddingModel'\n | 'imageModel'\n | 'transcriptionModel'\n | 'speechModel';\n\n constructor({\n errorName = name,\n modelId,\n modelType,\n message = `No such ${modelType}: ${modelId}`,\n }: {\n errorName?: string;\n modelId: string;\n modelType:\n | 'languageModel'\n | 'textEmbeddingModel'\n | 'imageModel'\n | 'transcriptionModel'\n | 'speechModel';\n message?: string;\n }) {\n super({ name: errorName, message });\n\n this.modelId = modelId;\n this.modelType = modelType;\n }\n\n static isInstance(error: unknown): error is NoSuchModelError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_TooManyEmbeddingValuesForCallError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class TooManyEmbeddingValuesForCallError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly provider: string;\n readonly modelId: string;\n readonly maxEmbeddingsPerCall: number;\n readonly values: Array<unknown>;\n\n constructor(options: {\n provider: string;\n modelId: string;\n maxEmbeddingsPerCall: number;\n values: Array<unknown>;\n }) {\n super({\n name,\n message:\n `Too many values for a single embedding call. ` +\n `The ${options.provider} model \"${options.modelId}\" can only embed up to ` +\n `${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`,\n });\n\n this.provider = options.provider;\n this.modelId = options.modelId;\n this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n this.values = options.values;\n }\n\n static isInstance(\n error: unknown,\n ): error is TooManyEmbeddingValuesForCallError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\nimport { getErrorMessage } from './get-error-message';\n\nconst name = 'AI_TypeValidationError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class TypeValidationError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly value: unknown;\n\n constructor({ value, cause }: { value: unknown; cause: unknown }) {\n super({\n name,\n message:\n `Type validation failed: ` +\n `Value: ${JSON.stringify(value)}.\\n` +\n `Error message: ${getErrorMessage(cause)}`,\n cause,\n });\n\n this.value = value;\n }\n\n static isInstance(error: unknown): error is TypeValidationError {\n return AISDKError.hasMarker(error, marker);\n }\n\n /**\n * Wraps an error into a TypeValidationError.\n * If the cause is already a TypeValidationError with the same value, it returns the cause.\n * Otherwise, it creates a new TypeValidationError.\n *\n * @param {Object} params - The parameters for wrapping the error.\n * @param {unknown} params.value - The value that failed validation.\n * @param {unknown} params.cause - The original error or cause of the validation failure.\n * @returns {TypeValidationError} A TypeValidationError instance.\n */\n static wrap({\n value,\n cause,\n }: {\n value: unknown;\n cause: unknown;\n }): TypeValidationError {\n return TypeValidationError.isInstance(cause) && cause.value === value\n ? cause\n : new TypeValidationError({ value, cause });\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_UnsupportedFunctionalityError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class UnsupportedFunctionalityError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly functionality: string;\n\n constructor({\n functionality,\n message = `'${functionality}' functionality not supported.`,\n }: {\n functionality: string;\n message?: string;\n }) {\n super({ name, message });\n this.functionality = functionality;\n }\n\n static isInstance(error: unknown): error is UnsupportedFunctionalityError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { JSONArray, JSONObject, JSONValue } from './json-value';\n\nexport function isJSONValue(value: unknown): value is JSONValue {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return true;\n }\n\n if (Array.isArray(value)) {\n return value.every(isJSONValue);\n }\n\n if (typeof value === 'object') {\n return Object.entries(value).every(\n ([key, val]) => typeof key === 'string' && isJSONValue(val),\n );\n }\n\n return false;\n}\n\nexport function isJSONArray(value: unknown): value is JSONArray {\n return Array.isArray(value) && value.every(isJSONValue);\n}\n\nexport function isJSONObject(value: unknown): value is JSONObject {\n return (\n value != null &&\n typeof value === 'object' &&\n Object.entries(value).every(\n ([key, val]) => typeof key === 'string' && isJSONValue(val),\n )\n );\n}\n","/**\n * The type of error that occurred.\n * @public\n */\nexport type ErrorType = 'invalid-retry' | 'unknown-field'\n\n/**\n * Error thrown when encountering an issue during parsing.\n *\n * @public\n */\nexport class ParseError extends Error {\n /**\n * The type of error that occurred.\n */\n type: ErrorType\n\n /**\n * In the case of an unknown field encountered in the stream, this will be the field name.\n */\n field?: string\n\n /**\n * In the case of an unknown field encountered in the stream, this will be the value of the field.\n */\n value?: string\n\n /**\n * The line that caused the error, if available.\n */\n line?: string\n\n constructor(\n message: string,\n options: {type: ErrorType; field?: string; value?: string; line?: string},\n ) {\n super(message)\n this.name = 'ParseError'\n this.type = options.type\n this.field = options.field\n this.value = options.value\n this.line = options.line\n }\n}\n","/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nimport {ParseError} from './errors.ts'\nimport type {EventSourceParser, ParserCallbacks} from './types.ts'\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction noop(_arg: unknown) {\n // intentional noop\n}\n\n/**\n * Creates a new EventSource parser.\n *\n * @param callbacks - Callbacks to invoke on different parsing events:\n * - `onEvent` when a new event is parsed\n * - `onError` when an error occurs\n * - `onRetry` when a new reconnection interval has been sent from the server\n * - `onComment` when a comment is encountered in the stream\n *\n * @returns A new EventSource parser, with `parse` and `reset` methods.\n * @public\n */\nexport function createParser(callbacks: ParserCallbacks): EventSourceParser {\n if (typeof callbacks === 'function') {\n throw new TypeError(\n '`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?',\n )\n }\n\n const {onEvent = noop, onError = noop, onRetry = noop, onComment} = callbacks\n\n let incompleteLine = ''\n\n let isFirstChunk = true\n let id: string | undefined\n let data = ''\n let eventType = ''\n\n function feed(newChunk: string) {\n // Strip any UTF8 byte order mark (BOM) at the start of the stream\n const chunk = isFirstChunk ? newChunk.replace(/^\\xEF\\xBB\\xBF/, '') : newChunk\n\n // If there was a previous incomplete line, append it to the new chunk,\n // so we may process it together as a new (hopefully complete) chunk.\n const [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`)\n\n for (const line of complete) {\n parseLine(line)\n }\n\n incompleteLine = incomplete\n isFirstChunk = false\n }\n\n function parseLine(line: string) {\n // If the line is empty (a blank line), dispatch the event\n if (line === '') {\n dispatchEvent()\n return\n }\n\n // If the line starts with a U+003A COLON character (:), ignore the line.\n if (line.startsWith(':')) {\n if (onComment) {\n onComment(line.slice(line.startsWith(': ') ? 2 : 1))\n }\n return\n }\n\n // If the line contains a U+003A COLON character (:)\n const fieldSeparatorIndex = line.indexOf(':')\n if (fieldSeparatorIndex !== -1) {\n // Collect the characters on the line before the first U+003A COLON character (:),\n // and let `field` be that string.\n const field = line.slice(0, fieldSeparatorIndex)\n\n // Collect the characters on the line after the first U+003A COLON character (:),\n // and let `value` be that string. If value starts with a U+0020 SPACE character,\n // remove it from value.\n const offset = line[fieldSeparatorIndex + 1] === ' ' ? 2 : 1\n const value = line.slice(fieldSeparatorIndex + offset)\n\n processField(field, value, line)\n return\n }\n\n // Otherwise, the string is not empty but does not contain a U+003A COLON character (:)\n // Process the field using the whole line as the field name, and an empty string as the field value.\n // 👆 This is according to spec. That means that a line that has the value `data` will result in\n // a newline being added to the current `data` buffer, for instance.\n processField(line, '', line)\n }\n\n function processField(field: string, value: string, line: string) {\n // Field names must be compared literally, with no case folding performed.\n switch (field) {\n case 'event':\n // Set the `event type` buffer to field value\n eventType = value\n break\n case 'data':\n // Append the field value to the `data` buffer, then append a single U+000A LINE FEED(LF)\n // character to the `data` buffer.\n data = `${data}${value}\\n`\n break\n case 'id':\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n id = value.includes('\\0') ? undefined : value\n break\n case 'retry':\n // If the field value consists of only ASCII digits, then interpret the field value as an\n // integer in base ten, and set the event stream's reconnection time to that integer.\n // Otherwise, ignore the field.\n if (/^\\d+$/.test(value)) {\n onRetry(parseInt(value, 10))\n } else {\n onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: 'invalid-retry',\n value,\n line,\n }),\n )\n }\n break\n default:\n // Otherwise, the field is ignored.\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}…` : field}\"`,\n {type: 'unknown-field', field, value, line},\n ),\n )\n break\n }\n }\n\n function dispatchEvent() {\n const shouldDispatch = data.length > 0\n if (shouldDispatch) {\n onEvent({\n id,\n event: eventType || undefined,\n // If the data buffer's last character is a U+000A LINE FEED (LF) character,\n // then remove the last character from the data buffer.\n data: data.endsWith('\\n') ? data.slice(0, -1) : data,\n })\n }\n\n // Reset for the next event\n id = undefined\n data = ''\n eventType = ''\n }\n\n function reset(options: {consume?: boolean} = {}) {\n if (incompleteLine && options.consume) {\n parseLine(incompleteLine)\n }\n\n isFirstChunk = true\n id = undefined\n data = ''\n eventType = ''\n incompleteLine = ''\n }\n\n return {feed, reset}\n}\n\n/**\n * For the given `chunk`, split it into lines according to spec, and return any remaining incomplete line.\n *\n * @param chunk - The chunk to split into lines\n * @returns A tuple containing an array of complete lines, and any remaining incomplete line\n * @internal\n */\nfunction splitLines(chunk: string): [complete: Array<string>, incomplete: string] {\n /**\n * According to the spec, a line is terminated by either:\n * - U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair\n * - a single U+000A LINE FEED(LF) character not preceded by a U+000D CARRIAGE RETURN(CR) character\n * - a single U+000D CARRIAGE RETURN(CR) character not followed by a U+000A LINE FEED(LF) character\n */\n const lines: Array<string> = []\n let incompleteLine = ''\n let searchIndex = 0\n\n while (searchIndex < chunk.length) {\n // Find next line terminator\n const crIndex = chunk.indexOf('\\r', searchIndex)\n const lfIndex = chunk.indexOf('\\n', searchIndex)\n\n // Determine line end\n let lineEnd = -1\n if (crIndex !== -1 && lfIndex !== -1) {\n // CRLF case\n lineEnd = Math.min(crIndex, lfIndex)\n } else if (crIndex !== -1) {\n lineEnd = crIndex\n } else if (lfIndex !== -1) {\n lineEnd = lfIndex\n }\n\n // Extract line if terminator found\n if (lineEnd === -1) {\n // No terminator found, rest is incomplete\n incompleteLine = chunk.slice(searchIndex)\n break\n } else {\n const line = chunk.slice(searchIndex, lineEnd)\n lines.push(line)\n\n // Move past line terminator\n searchIndex = lineEnd + 1\n if (chunk[searchIndex - 1] === '\\r' && chunk[searchIndex] === '\\n') {\n searchIndex++\n }\n }\n }\n\n return [lines, incompleteLine]\n}\n","import {createParser} from './parse.ts'\nimport type {EventSourceMessage, EventSourceParser} from './types.ts'\n\n/**\n * Options for the EventSourceParserStream.\n *\n * @public\n */\nexport interface StreamOptions {\n /**\n * Behavior when a parsing error occurs.\n *\n * - A custom function can be provided to handle the error.\n * - `'terminate'` will error the stream and stop parsing.\n * - Any other value will ignore the error and continue parsing.\n *\n * @defaultValue `undefined`\n */\n onError?: 'terminate' | ((error: Error) => void)\n\n /**\n * Callback for when a reconnection interval is sent from the server.\n *\n * @param retry - The number of milliseconds to wait before reconnecting.\n */\n onRetry?: (retry: number) => void\n\n /**\n * Callback for when a comment is encountered in the stream.\n *\n * @param comment - The comment encountered in the stream.\n */\n onComment?: (comment: string) => void\n}\n\n/**\n * A TransformStream that ingests a stream of strings and produces a stream of `EventSourceMessage`.\n *\n * @example Basic usage\n * ```\n * const eventStream =\n * response.body\n * .pipeThrough(new TextDecoderStream())\n * .pipeThrough(new EventSourceParserStream())\n * ```\n *\n * @example Terminate stream on parsing errors\n * ```\n * const eventStream =\n * response.body\n * .pipeThrough(new TextDecoderStream())\n * .pipeThrough(new EventSourceParserStream({terminateOnError: true}))\n * ```\n *\n * @public\n */\nexport class EventSourceParserStream extends TransformStream<string, EventSourceMessage> {\n constructor({onError, onRetry, onComment}: StreamOptions = {}) {\n let parser!: EventSourceParser\n\n super({\n start(controller) {\n parser = createParser({\n onEvent: (event) => {\n controller.enqueue(event)\n },\n onError(error) {\n if (onError === 'terminate') {\n controller.error(error)\n } else if (typeof onError === 'function') {\n onError(error)\n }\n\n // Ignore by default\n },\n onRetry,\n onComment,\n })\n },\n transform(chunk) {\n parser.feed(chunk)\n },\n })\n }\n}\n\nexport {type ErrorType, ParseError} from './errors.ts'\nexport type {EventSourceMessage} from './types.ts'\n","export function combineHeaders(\n ...headers: Array<Record<string, string | undefined> | undefined>\n): Record<string, string | undefined> {\n return headers.reduce(\n (combinedHeaders, currentHeaders) => ({\n ...combinedHeaders,\n ...(currentHeaders ?? {}),\n }),\n {},\n ) as Record<string, string | undefined>;\n}\n","/**\n * Converts an AsyncIterator to a ReadableStream.\n *\n * @template T - The type of elements produced by the AsyncIterator.\n * @param { <T>} iterator - The AsyncIterator to convert.\n * @returns {ReadableStream<T>} - A ReadableStream that provides the same data as the AsyncIterator.\n */\nexport function convertAsyncIteratorToReadableStream<T>(\n iterator: AsyncIterator<T>,\n): ReadableStream<T> {\n return new ReadableStream<T>({\n /**\n * Called when the consumer wants to pull more data from the stream.\n *\n * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.\n * @returns {Promise<void>}\n */\n async pull(controller) {\n try {\n const { value, done } = await iterator.next();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n },\n /**\n * Called when the consumer cancels the stream.\n */\n cancel() {},\n });\n}\n","/**\n * Creates a Promise that resolves after a specified delay\n * @param delayInMs - The delay duration in milliseconds. If null or undefined, resolves immediately.\n * @param signal - Optional AbortSignal to cancel the delay\n * @returns A Promise that resolves after the specified delay\n * @throws {DOMException} When the signal is aborted\n */\nexport async function delay(\n delayInMs?: number | null,\n options?: {\n abortSignal?: AbortSignal;\n },\n): Promise<void> {\n if (delayInMs == null) {\n return Promise.resolve();\n }\n\n const signal = options?.abortSignal;\n\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(createAbortError());\n return;\n }\n\n const timeoutId = setTimeout(() => {\n cleanup();\n resolve();\n }, delayInMs);\n\n const cleanup = () => {\n clearTimeout(timeoutId);\n signal?.removeEventListener('abort', onAbort);\n };\n\n const onAbort = () => {\n cleanup();\n reject(createAbortError());\n };\n\n signal?.addEventListener('abort', onAbort);\n });\n}\n\nfunction createAbortError(): DOMException {\n return new DOMException('Delay was aborted', 'AbortError');\n}\n","/**\nExtracts the headers from a response object and returns them as a key-value object.\n\n@param response - The response object to extract headers from.\n@returns The headers as a key-value object.\n*/\nexport function extractResponseHeaders(response: Response) {\n return Object.fromEntries<string>([...response.headers]);\n}\n","import { InvalidArgumentError } from '@ai-sdk/provider';\n\n/**\nCreates an ID generator.\nThe total length of the ID is the sum of the prefix, separator, and random part length.\nNot cryptographically secure.\n\n@param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.\n@param prefix - The prefix of the ID to generate. Optional.\n@param separator - The separator between the prefix and the random part of the ID. Default: '-'.\n@param size - The size of the random part of the ID to generate. Default: 16.\n */\nexport const createIdGenerator = ({\n prefix,\n size = 16,\n alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n separator = '-',\n}: {\n prefix?: string;\n separator?: string;\n size?: number;\n alphabet?: string;\n} = {}): IdGenerator => {\n const generator = () => {\n const alphabetLength = alphabet.length;\n const chars = new Array(size);\n for (let i = 0; i < size; i++) {\n chars[i] = alphabet[(Math.random() * alphabetLength) | 0];\n }\n return chars.join('');\n };\n\n if (prefix == null) {\n return generator;\n }\n\n // check that the prefix is not part of the alphabet (otherwise prefix checking can fail randomly)\n if (alphabet.includes(separator)) {\n throw new InvalidArgumentError({\n argument: 'separator',\n message: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`,\n });\n }\n\n return () => `${prefix}${separator}${generator()}`;\n};\n\n/**\nA function that generates an ID.\n */\nexport type IdGenerator = () => string;\n\n/**\nGenerates a 16-character random string to use for IDs.\nNot cryptographically secure.\n */\nexport const generateId = createIdGenerator();\n","export function getErrorMessage(error: unknown | undefined) {\n if (error == null) {\n return 'unknown error';\n }\n\n if (typeof error === 'string') {\n return error;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n return JSON.stringify(error);\n}\n","import { APICallError } from '@ai-sdk/provider';\nimport { extractResponseHeaders } from './extract-response-headers';\nimport { FetchFunction } from './fetch-function';\nimport { handleFetchError } from './handle-fetch-error';\nimport { isAbortError } from './is-abort-error';\nimport { removeUndefinedEntries } from './remove-undefined-entries';\nimport { ResponseHandler } from './response-handler';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => globalThis.fetch;\n\nexport const getFromApi = async <T>({\n url,\n headers = {},\n successfulResponseHandler,\n failedResponseHandler,\n abortSignal,\n fetch = getOriginalFetch(),\n}: {\n url: string;\n headers?: Record<string, string | undefined>;\n failedResponseHandler: ResponseHandler<Error>;\n successfulResponseHandler: ResponseHandler<T>;\n abortSignal?: AbortSignal;\n fetch?: FetchFunction;\n}) => {\n try {\n const response = await fetch(url, {\n method: 'GET',\n headers: removeUndefinedEntries(headers),\n signal: abortSignal,\n });\n\n const responseHeaders = extractResponseHeaders(response);\n\n if (!response.ok) {\n let errorInformation: {\n value: Error;\n responseHeaders?: Record<string, string> | undefined;\n };\n\n try {\n errorInformation = await failedResponseHandler({\n response,\n url,\n requestBodyValues: {},\n });\n } catch (error) {\n if (isAbortError(error) || APICallError.isInstance(error)) {\n throw error;\n }\n\n throw new APICallError({\n message: 'Failed to process error response',\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: {},\n });\n }\n\n throw errorInformation.value;\n }\n\n try {\n return await successfulResponseHandler({\n response,\n url,\n requestBodyValues: {},\n });\n } catch (error) {\n if (error instanceof Error) {\n if (isAbortError(error) || APICallError.isInstance(error)) {\n throw error;\n }\n }\n\n throw new APICallError({\n message: 'Failed to process successful response',\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: {},\n });\n }\n } catch (error) {\n throw handleFetchError({ error, url, requestBodyValues: {} });\n }\n};\n","import { APICallError } from '@ai-sdk/provider';\nimport { isAbortError } from './is-abort-error';\n\nconst FETCH_FAILED_ERROR_MESSAGES = ['fetch failed', 'failed to fetch'];\n\nexport function handleFetchError({\n error,\n url,\n requestBodyValues,\n}: {\n error: unknown;\n url: string;\n requestBodyValues: unknown;\n}) {\n if (isAbortError(error)) {\n return error;\n }\n\n // unwrap original error when fetch failed (for easier debugging):\n if (\n error instanceof TypeError &&\n FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())\n ) {\n const cause = (error as any).cause;\n\n if (cause != null) {\n // Failed to connect to server:\n return new APICallError({\n message: `Cannot connect to API: ${cause.message}`,\n cause,\n url,\n requestBodyValues,\n isRetryable: true, // retry when network error\n });\n }\n }\n\n return error;\n}\n","export function isAbortError(error: unknown): error is Error {\n return (\n (error instanceof Error || error instanceof DOMException) &&\n (error.name === 'AbortError' ||\n error.name === 'ResponseAborted' || // Next.js\n error.name === 'TimeoutError')\n );\n}\n","/**\n * Removes entries from a record where the value is null or undefined.\n * @param record - The input object whose entries may be null or undefined.\n * @returns A new object containing only entries with non-null and non-undefined values.\n */\nexport function removeUndefinedEntries<T>(\n record: Record<string, T | undefined>,\n): Record<string, T> {\n return Object.fromEntries(\n Object.entries(record).filter(([_key, value]) => value != null),\n ) as Record<string, T>;\n}\n","/**\n * Checks if the given URL is supported natively by the model.\n *\n * @param mediaType - The media type of the URL. Case-sensitive.\n * @param url - The URL to check.\n * @param supportedUrls - A record where keys are case-sensitive media types (or '*')\n * and values are arrays of RegExp patterns for URLs.\n *\n * @returns `true` if the URL matches a pattern under the specific media type\n * or the wildcard '*', `false` otherwise.\n */\nexport function isUrlSupported({\n mediaType,\n url,\n supportedUrls,\n}: {\n mediaType: string;\n url: string;\n supportedUrls: Record<string, RegExp[]>;\n}): boolean {\n // standardize media type and url to lower case\n url = url.toLowerCase();\n mediaType = mediaType.toLowerCase();\n\n return (\n Object.entries(supportedUrls)\n // standardize supported url map into lowercase prefixes:\n .map(([key, value]) => {\n const mediaType = key.toLowerCase();\n return mediaType === '*' || mediaType === '*/*'\n ? { mediaTypePrefix: '', regexes: value }\n : { mediaTypePrefix: mediaType.replace(/\\*/, ''), regexes: value };\n })\n // gather all regexp pattern from matched media type prefixes:\n .filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix))\n .flatMap(({ regexes }) => regexes)\n // check if any pattern matches the url:\n .some(pattern => pattern.test(url))\n );\n}\n","import { LoadAPIKeyError } from '@ai-sdk/provider';\n\nexport function loadApiKey({\n apiKey,\n environmentVariableName,\n apiKeyParameterName = 'apiKey',\n description,\n}: {\n apiKey: string | undefined;\n environmentVariableName: string;\n apiKeyParameterName?: string;\n description: string;\n}): string {\n if (typeof apiKey === 'string') {\n return apiKey;\n }\n\n if (apiKey != null) {\n throw new LoadAPIKeyError({\n message: `${description} API key must be a string.`,\n });\n }\n\n if (typeof process === 'undefined') {\n throw new LoadAPIKeyError({\n message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`,\n });\n }\n\n apiKey = process.env[environmentVariableName];\n\n if (apiKey == null) {\n throw new LoadAPIKeyError({\n message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`,\n });\n }\n\n if (typeof apiKey !== 'string') {\n throw new LoadAPIKeyError({\n message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`,\n });\n }\n\n return apiKey;\n}\n","/**\n * Loads an optional `string` setting from the environment or a parameter.\n *\n * @param settingValue - The setting value.\n * @param environmentVariableName - The environment variable name.\n * @returns The setting value.\n */\nexport function loadOptionalSetting({\n settingValue,\n environmentVariableName,\n}: {\n settingValue: string | undefined;\n environmentVariableName: string;\n}): string | undefined {\n if (typeof settingValue === 'string') {\n return settingValue;\n }\n\n if (settingValue != null || typeof process === 'undefined') {\n return undefined;\n }\n\n settingValue = process.env[environmentVariableName];\n\n if (settingValue == null || typeof settingValue !== 'string') {\n return undefined;\n }\n\n return settingValue;\n}\n","import { LoadSettingError } from '@ai-sdk/provider';\n\n/**\n * Loads a `string` setting from the environment or a parameter.\n *\n * @param settingValue - The setting value.\n * @param environmentVariableName - The environment variable name.\n * @param settingName - The setting name.\n * @param description - The description of the setting.\n * @returns The setting value.\n */\nexport function loadSetting({\n settingValue,\n environmentVariableName,\n settingName,\n description,\n}: {\n settingValue: string | undefined;\n environmentVariableName: string;\n settingName: string;\n description: string;\n}): string {\n if (typeof settingValue === 'string') {\n return settingValue;\n }\n\n if (settingValue != null) {\n throw new LoadSettingError({\n message: `${description} setting must be a string.`,\n });\n }\n\n if (typeof process === 'undefined') {\n throw new LoadSettingError({\n message:\n `${description} setting is missing. ` +\n `Pass it using the '${settingName}' parameter. ` +\n `Environment variables is not supported in this environment.`,\n });\n }\n\n settingValue = process.env[environmentVariableName];\n\n if (settingValue == null) {\n throw new LoadSettingError({\n message:\n `${description} setting is missing. ` +\n `Pass it using the '${settingName}' parameter ` +\n `or the ${environmentVariableName} environment variable.`,\n });\n }\n\n if (typeof settingValue !== 'string') {\n throw new LoadSettingError({\n message:\n `${description} setting must be a string. ` +\n `The value of the ${environmentVariableName} environment variable is not a string.`,\n });\n }\n\n return settingValue;\n}\n","import {\n JSONParseError,\n JSONValue,\n TypeValidationError,\n} from '@ai-sdk/provider';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4';\nimport { secureJsonParse } from './secure-json-parse';\nimport { safeValidateTypes, validateTypes } from './validate-types';\nimport { Validator } from './validator';\n\n/**\n * Parses a JSON string into an unknown object.\n *\n * @param text - The JSON string to parse.\n * @returns {JSONValue} - The parsed JSON object.\n */\nexport async function parseJSON(options: {\n text: string;\n schema?: undefined;\n}): Promise<JSONValue>;\n/**\n * Parses a JSON string into a strongly-typed object using the provided schema.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Validator<T>} schema - The schema to use for parsing the JSON.\n * @returns {Promise<T>} - The parsed object.\n */\nexport async function parseJSON<T>(options: {\n text: string;\n schema: z4.core.$ZodType<T> | z3.Schema<T> | Validator<T>;\n}): Promise<T>;\nexport async function parseJSON<T>({\n text,\n schema,\n}: {\n text: string;\n schema?: z4.core.$ZodType<T> | z3.Schema<T> | Validator<T>;\n}): Promise<T> {\n try {\n const value = secureJsonParse(text);\n\n if (schema == null) {\n return value;\n }\n\n return validateTypes<T>({ value, schema });\n } catch (error) {\n if (\n JSONParseError.isInstance(error) ||\n TypeValidationError.isInstance(error)\n ) {\n throw error;\n }\n\n throw new JSONParseError({ text, cause: error });\n }\n}\n\nexport type ParseResult<T> =\n | { success: true; value: T; rawValue: unknown }\n | {\n success: false;\n error: JSONParseError | TypeValidationError;\n rawValue: unknown;\n };\n\n/**\n * Safely parses a JSON string and returns the result as an object of type `unknown`.\n *\n * @param text - The JSON string to parse.\n * @returns {Promise<object>} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.\n */\nexport async function safeParseJSON(options: {\n text: string;\n schema?: undefined;\n}): Promise<ParseResult<JSONValue>>;\n/**\n * Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Validator<T>} schema - The schema to use for parsing the JSON.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport async function safeParseJSON<T>(options: {\n text: string;\n schema: z4.core.$ZodType<T> | z3.Schema<T> | Validator<T>;\n}): Promise<ParseResult<T>>;\nexport async function safeParseJSON<T>({\n text,\n schema,\n}: {\n text: strin