@mastra/core
Version:
1 lines • 1.38 MB
Source Map (JSON)
{"version":3,"file":"dist-C4NOluIY.cjs","names":["marker","symbol","_a","_b","name","VERSION","getOriginalFetch","APICallError2","ZodFirstPartyTypeKind","ZodFirstPartyTypeKind2","ZodFirstPartyTypeKind3","z4","TypeValidationError2","TypeValidationError3","InvalidArgumentError2","APICallError3","APICallError4","z","_exhaustiveCheck","getResponseMetadata","z2","prepareTools","UnsupportedFunctionalityError2","z3","UnsupportedFunctionalityError3","getResponseMetadata2","z4","createJsonErrorResponseHandler2","parseProviderOptions2","postJsonToApi2","combineHeaders2","createJsonResponseHandler2","createEventSourceResponseHandler2","usageSchema","z5","z6","parseProviderOptions3","postJsonToApi3","combineHeaders3","createJsonErrorResponseHandler3","createJsonResponseHandler3","openaiTextEmbeddingResponseSchema","z7","combineHeaders4","fileToBlob","createJsonErrorResponseHandler4","createJsonResponseHandler4","postJsonToApi4","z8","convertBase64ToUint8Array2","VERSION","z","_exhaustiveCheck","z2","lazySchema2","zodSchema2","z3","UnsupportedFunctionalityError2","UnsupportedFunctionalityError3","lazySchema3","zodSchema3","z4","lazySchema4","zodSchema4","z5","parseProviderOptions2","postJsonToApi2","combineHeaders2","createJsonResponseHandler2","createEventSourceResponseHandler2","lazySchema5","zodSchema5","z6","lazySchema6","zodSchema6","z7","parseProviderOptions3","postJsonToApi3","combineHeaders3","createJsonResponseHandler3","lazySchema7","zodSchema7","z8","z9","lazySchema8","zodSchema8","parseProviderOptions4","combineHeaders4","createJsonResponseHandler4","postJsonToApi4","lazySchema9","zodSchema9","z10","lazySchema10","zodSchema10","z11","createProviderToolFactoryWithOutputSchema2","lazySchema11","zodSchema11","z12","z13","lazySchema12","zodSchema12","fileSearch","createProviderToolFactoryWithOutputSchema3","lazySchema13","zodSchema13","z14","createProviderToolFactoryWithOutputSchema4","lazySchema14","zodSchema14","z15","createProviderToolFactoryWithOutputSchema5","lazySchema15","zodSchema15","z16","createProviderToolFactoryWithOutputSchema6","lazySchema16","zodSchema16","z17","createProviderToolFactoryWithOutputSchema7","lazySchema17","zodSchema17","z18","createProviderToolFactoryWithOutputSchema8","lazySchema18","zodSchema18","z19","createProviderToolFactoryWithOutputSchema9","z20","lazySchema19","zodSchema19","createProviderToolFactoryWithOutputSchema10","convertToBase642","UnsupportedFunctionalityError4","parseProviderOptions5","z21","z22","lazySchema20","zodSchema20","lazySchema21","zodSchema21","z23","UnsupportedFunctionalityError5","validateTypes2","env2","env","parseProviderOptions6","postJsonToApi5","combineHeaders5","createJsonResponseHandler5","APICallError2","generateId2","createEventSourceResponseHandler3","lazySchema22","zodSchema22","z24","parseProviderOptions7","postJsonToApi6","combineHeaders6","lazySchema23","zodSchema23","z25","lazySchema24","zodSchema24","z26","parseProviderOptions8","convertBase64ToUint8Array2","postFormDataToApi2","combineHeaders7","createJsonResponseHandler6","VERSION","VERSION","z","z2","lazySchema2","zodSchema2","z3","lazySchema3","zodSchema3","z4","lazySchema4","zodSchema4","z5","lazySchema5","zodSchema5","z6","createProviderToolFactoryWithOutputSchema2","lazySchema6","zodSchema6","z7","createProviderToolFactoryWithOutputSchema3","lazySchema7","zodSchema7","z8","createProviderToolFactoryWithOutputSchema4","lazySchema8","zodSchema8","z9","createProviderToolFactoryWithOutputSchema5","prepareTools","_exhaustiveCheck","lazySchema9","zodSchema9","z10","createProviderToolFactoryWithOutputSchema6","lazySchema10","zodSchema10","z11","createProviderToolFactoryWithOutputSchema7","lazySchema11","zodSchema11","z12","createProviderToolFactoryWithOutputSchema8","lazySchema12","zodSchema12","z13","createProviderToolFactoryWithOutputSchema9","UnsupportedFunctionalityError2","validateTypes2","parseProviderOptions2","secureJsonParse2","createProviderToolFactory2","lazySchema13","zodSchema13","z14","createProviderToolFactory3","lazySchema14","zodSchema14","z15","createProviderToolFactory4","lazySchema15","zodSchema15","z16","createProviderToolFactory5","lazySchema16","zodSchema16","z17","createProviderToolFactory6","lazySchema17","zodSchema17","z18","createProviderToolFactory7","lazySchema18","zodSchema18","z19","createProviderToolFactory8","lazySchema19","zodSchema19","z20","createProviderToolFactory9","lazySchema20","zodSchema20","z21","createProviderToolFactory10","lazySchema21","zodSchema21","z22","lazySchema22","zodSchema22","z23","createProviderToolFactoryWithOutputSchema10","generateId2","z","z2","lazySchema2","zodSchema2","lazySchema3","zodSchema3","z3","lazySchema4","zodSchema4","z4","UnsupportedFunctionalityError2","_exhaustiveCheck","parseProviderOptions2","combineHeaders2","resolve2","postJsonToApi2","createJsonResponseHandler2","z5","lazySchema5","zodSchema5","z6","lazySchema6","zodSchema6","z7","z8","createProviderToolFactory2","lazySchema7","zodSchema7","createProviderToolFactory3","lazySchema8","zodSchema8","z9","z10","createProviderToolFactory4","lazySchema9","zodSchema9","createProviderToolFactory5","lazySchema10","zodSchema10","z11","createProviderToolFactory6","z12","parseProviderOptions3","postJsonToApi3","combineHeaders3","resolve3","createJsonResponseHandler3","defaultGenerateId","convertToBase642","lazySchema11","zodSchema11","z13","parseProviderOptions4","postJsonToApi4","combineHeaders4","resolve4","createJsonResponseHandler4","z14","lazySchema12","zodSchema12","event","convertToBase643","secureJsonParse2","z15","lazySchema13","zodSchema13","lazySchema14","zodSchema14","z16","combineHeaders5","delay2","getFromApi2","createJsonResponseHandler5","getFromApi3","createEventSourceResponseHandler2","isAbortError2","delay3","parseProviderOptions5","combineHeaders6","resolve5","postJsonToApi5","createJsonResponseHandler6","defaultGenerateId2","createEventSourceResponseHandler3","withUserAgentSuffix2","generateId2"],"sources":["../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider/3.0.14/30b98effe2636d5b58b60cf37530a90112258d4490ff3a92f52c5cf16e4b475d/node_modules/@ai-sdk/provider/dist/index.mjs","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/eventsource-parser/3.0.8/353c45c343d0acc1586e9cb9ff7be48ebf30a434bf7b8c9762d411b79278d167/node_modules/eventsource-parser/dist/index.js","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/eventsource-parser/3.0.8/353c45c343d0acc1586e9cb9ff7be48ebf30a434bf7b8c9762d411b79278d167/node_modules/eventsource-parser/dist/stream.js","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider-utils/4.0.40/fbc718cc8b378ba8d17f16edc5ab96640883c9d635eb2a54b9034b5c4fd5bdef/node_modules/@ai-sdk/provider-utils/dist/index.mjs","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/openai-compatible/2.0.62/b7acbd067f2ec09e10301f2fe9f80cac3c408d768c9a5df1e535b692cd074fce/node_modules/@ai-sdk/openai-compatible/dist/index.mjs","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/openai/3.0.88/3d5b955511aa68a7bfdd4e943259bc5526f882ed0b408ef9ec049ba36670be10/node_modules/@ai-sdk/openai/dist/index.mjs","../src/llm/model/gateways/base.ts","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/anthropic/3.0.103/88805d842ca0284fbaadef0ee46b0a71923da63cbf182540cfbfa25aaaf87106/node_modules/@ai-sdk/anthropic/dist/index.mjs","../src/llm/model/gateways/constants.ts","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/google/3.0.101/5ca337e1534fcee1d9ea7bc8f4b8cdc64d6879c9d864a0a3259940611b7e50ee/node_modules/@ai-sdk/google/dist/index.mjs"],"sourcesContent":["// src/errors/ai-sdk-error.ts\nvar marker = \"vercel.ai.error\";\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {\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: name14,\n message,\n cause\n }) {\n super(message);\n this[_a] = true;\n this.name = name14;\n this.cause = cause;\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) {\n return _AISDKError.hasMarker(error, marker);\n }\n static hasMarker(error, marker15) {\n const markerSymbol = Symbol.for(marker15);\n return error != null && typeof error === \"object\" && markerSymbol in error && typeof error[markerSymbol] === \"boolean\" && error[markerSymbol] === true;\n }\n};\n\n// src/errors/api-call-error.ts\nvar name = \"AI_APICallError\";\nvar marker2 = `vercel.ai.error.${name}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2, _b2;\nvar APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {\n constructor({\n message,\n url,\n requestBodyValues,\n statusCode,\n responseHeaders,\n responseBody,\n cause,\n isRetryable = statusCode != null && (statusCode === 408 || // request timeout\n statusCode === 409 || // conflict\n statusCode === 429 || // too many requests\n statusCode >= 500),\n // server error\n data\n }) {\n super({ name, message, cause });\n this[_a2] = true;\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 static isInstance(error) {\n return AISDKError.hasMarker(error, marker2);\n }\n};\n\n// src/errors/empty-response-body-error.ts\nvar name2 = \"AI_EmptyResponseBodyError\";\nvar marker3 = `vercel.ai.error.${name2}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3, _b3;\nvar EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {\n // used in isInstance\n constructor({ message = \"Empty response body\" } = {}) {\n super({ name: name2, message });\n this[_a3] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker3);\n }\n};\n\n// src/errors/get-error-message.ts\nfunction getErrorMessage(error) {\n if (error == null) {\n return \"unknown error\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return JSON.stringify(error);\n}\n\n// src/errors/invalid-argument-error.ts\nvar name3 = \"AI_InvalidArgumentError\";\nvar marker4 = `vercel.ai.error.${name3}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4, _b4;\nvar InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {\n constructor({\n message,\n cause,\n argument\n }) {\n super({ name: name3, message, cause });\n this[_a4] = true;\n this.argument = argument;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker4);\n }\n};\n\n// src/errors/invalid-prompt-error.ts\nvar name4 = \"AI_InvalidPromptError\";\nvar marker5 = `vercel.ai.error.${name4}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5, _b5;\nvar InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {\n constructor({\n prompt,\n message,\n cause\n }) {\n super({ name: name4, message: `Invalid prompt: ${message}`, cause });\n this[_a5] = true;\n this.prompt = prompt;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker5);\n }\n};\n\n// src/errors/invalid-response-data-error.ts\nvar name5 = \"AI_InvalidResponseDataError\";\nvar marker6 = `vercel.ai.error.${name5}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6, _b6;\nvar InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {\n constructor({\n data,\n message = `Invalid response data: ${JSON.stringify(data)}.`\n }) {\n super({ name: name5, message });\n this[_a6] = true;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker6);\n }\n};\n\n// src/errors/json-parse-error.ts\nvar name6 = \"AI_JSONParseError\";\nvar marker7 = `vercel.ai.error.${name6}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7, _b7;\nvar JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {\n constructor({ text, cause }) {\n super({\n name: name6,\n message: `JSON parsing failed: Text: ${text}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a7] = true;\n this.text = text;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker7);\n }\n};\n\n// src/errors/load-api-key-error.ts\nvar name7 = \"AI_LoadAPIKeyError\";\nvar marker8 = `vercel.ai.error.${name7}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8, _b8;\nvar LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name7, message });\n this[_a8] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker8);\n }\n};\n\n// src/errors/load-setting-error.ts\nvar name8 = \"AI_LoadSettingError\";\nvar marker9 = `vercel.ai.error.${name8}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9, _b9;\nvar LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name8, message });\n this[_a9] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker9);\n }\n};\n\n// src/errors/no-content-generated-error.ts\nvar name9 = \"AI_NoContentGeneratedError\";\nvar marker10 = `vercel.ai.error.${name9}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10, _b10;\nvar NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {\n // used in isInstance\n constructor({\n message = \"No content generated.\"\n } = {}) {\n super({ name: name9, message });\n this[_a10] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker10);\n }\n};\n\n// src/errors/no-such-model-error.ts\nvar name10 = \"AI_NoSuchModelError\";\nvar marker11 = `vercel.ai.error.${name10}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11, _b11;\nvar NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {\n constructor({\n errorName = name10,\n modelId,\n modelType,\n message = `No such ${modelType}: ${modelId}`\n }) {\n super({ name: errorName, message });\n this[_a11] = true;\n this.modelId = modelId;\n this.modelType = modelType;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker11);\n }\n};\n\n// src/errors/too-many-embedding-values-for-call-error.ts\nvar name11 = \"AI_TooManyEmbeddingValuesForCallError\";\nvar marker12 = `vercel.ai.error.${name11}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12, _b12;\nvar TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {\n constructor(options) {\n super({\n name: name11,\n message: `Too many values for a single embedding call. The ${options.provider} model \"${options.modelId}\" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`\n });\n this[_a12] = true;\n this.provider = options.provider;\n this.modelId = options.modelId;\n this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n this.values = options.values;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker12);\n }\n};\n\n// src/errors/type-validation-error.ts\nvar name12 = \"AI_TypeValidationError\";\nvar marker13 = `vercel.ai.error.${name12}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13, _b13;\nvar TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {\n constructor({\n value,\n cause,\n context\n }) {\n let contextPrefix = \"Type validation failed\";\n if (context == null ? void 0 : context.field) {\n contextPrefix += ` for ${context.field}`;\n }\n if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {\n contextPrefix += \" (\";\n const parts = [];\n if (context.entityName) {\n parts.push(context.entityName);\n }\n if (context.entityId) {\n parts.push(`id: \"${context.entityId}\"`);\n }\n contextPrefix += parts.join(\", \");\n contextPrefix += \")\";\n }\n super({\n name: name12,\n message: `${contextPrefix}: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a13] = true;\n this.value = value;\n this.context = context;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker13);\n }\n /**\n * Wraps an error into a TypeValidationError.\n * If the cause is already a TypeValidationError with the same value and context, 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 * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n * @returns {TypeValidationError} A TypeValidationError instance.\n */\n static wrap({\n value,\n cause,\n context\n }) {\n var _a15, _b15, _c;\n if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a15 = cause.context) == null ? void 0 : _a15.field) === (context == null ? void 0 : context.field) && ((_b15 = cause.context) == null ? void 0 : _b15.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) {\n return cause;\n }\n return new _TypeValidationError({ value, cause, context });\n }\n};\n\n// src/errors/unsupported-functionality-error.ts\nvar name13 = \"AI_UnsupportedFunctionalityError\";\nvar marker14 = `vercel.ai.error.${name13}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14, _b14;\nvar UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {\n constructor({\n functionality,\n message = `'${functionality}' functionality not supported.`\n }) {\n super({ name: name13, message });\n this[_a14] = true;\n this.functionality = functionality;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker14);\n }\n};\n\n// src/json-value/is-json.ts\nfunction isJSONValue(value) {\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every(isJSONValue);\n }\n if (typeof value === \"object\") {\n return Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n }\n return false;\n}\nfunction isJSONArray(value) {\n return Array.isArray(value) && value.every(isJSONValue);\n}\nfunction isJSONObject(value) {\n return value != null && typeof value === \"object\" && Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n}\nexport {\n AISDKError,\n APICallError,\n EmptyResponseBodyError,\n InvalidArgumentError,\n InvalidPromptError,\n InvalidResponseDataError,\n JSONParseError,\n LoadAPIKeyError,\n LoadSettingError,\n NoContentGeneratedError,\n NoSuchModelError,\n TooManyEmbeddingValuesForCallError,\n TypeValidationError,\n UnsupportedFunctionalityError,\n getErrorMessage,\n isJSONArray,\n isJSONObject,\n isJSONValue\n};\n//# sourceMappingURL=index.mjs.map","class ParseError extends Error {\n constructor(message, options) {\n super(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n }\n}\nconst LF = 10, CR = 13, SPACE = 32;\nfunction noop(_arg) {\n}\nfunction createParser(callbacks) {\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 const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = [];\n let isFirstChunk = !0, id, data = \"\", dataLines = 0, eventType;\n function feed(chunk) {\n if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {\n const trailing2 = processLines(chunk);\n trailing2 !== \"\" && pendingFragments.push(trailing2);\n return;\n }\n if (chunk.indexOf(`\n`) === -1 && chunk.indexOf(\"\\r\") === -1) {\n pendingFragments.push(chunk);\n return;\n }\n pendingFragments.push(chunk);\n const input = pendingFragments.join(\"\");\n pendingFragments.length = 0;\n const trailing = processLines(input);\n trailing !== \"\" && pendingFragments.push(trailing);\n }\n function processLines(chunk) {\n let searchIndex = 0;\n if (chunk.indexOf(\"\\r\") === -1) {\n let lfIndex = chunk.indexOf(`\n`, searchIndex);\n for (; lfIndex !== -1; ) {\n if (searchIndex === lfIndex) {\n dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = \"\", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n continue;\n }\n const firstCharCode = chunk.charCodeAt(searchIndex);\n if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);\n if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n onEvent({ id, event: eventType, data: value }), id = void 0, data = \"\", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`\n`, searchIndex);\n continue;\n }\n data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(\n chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,\n lfIndex\n ) || void 0 : parseLine(chunk, searchIndex, lfIndex);\n searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n }\n return chunk.slice(searchIndex);\n }\n for (; searchIndex < chunk.length; ) {\n const crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)\n break;\n parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;\n }\n return chunk.slice(searchIndex);\n }\n function parseLine(chunk, start, end) {\n if (start === end) {\n dispatchEvent();\n return;\n }\n const firstCharCode = chunk.charCodeAt(start);\n if (isDataPrefix(chunk, start, firstCharCode)) {\n const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);\n data = dataLines === 0 ? value2 : `${data}\n${value2}`, dataLines++;\n return;\n }\n if (isEventPrefix(chunk, start, firstCharCode)) {\n eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;\n return;\n }\n if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {\n const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n id = value2.includes(\"\\0\") ? void 0 : value2;\n return;\n }\n if (firstCharCode === 58) {\n if (onComment) {\n const line2 = chunk.slice(start, end);\n onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n }\n return;\n }\n const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(\":\");\n if (fieldSeparatorIndex === -1) {\n processField(line, \"\", line);\n return;\n }\n const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n }\n function processField(field, value, line) {\n switch (field) {\n case \"event\":\n eventType = value || void 0;\n break;\n case \"data\":\n data = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n break;\n case \"id\":\n id = value.includes(\"\\0\") ? void 0 : value;\n break;\n case \"retry\":\n /^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: \"invalid-retry\",\n value,\n line\n })\n );\n break;\n default:\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`,\n { type: \"unknown-field\", field, value, line }\n )\n );\n break;\n }\n }\n function dispatchEvent() {\n dataLines > 0 && onEvent({\n id,\n event: eventType,\n data\n }), id = void 0, data = \"\", dataLines = 0, eventType = void 0;\n }\n function reset(options = {}) {\n if (options.consume && pendingFragments.length > 0) {\n const incompleteLine = pendingFragments.join(\"\");\n parseLine(incompleteLine, 0, incompleteLine.length);\n }\n isFirstChunk = !0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, pendingFragments.length = 0;\n }\n return { feed, reset };\n}\nfunction isDataPrefix(chunk, i, firstCharCode) {\n return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;\n}\nfunction isEventPrefix(chunk, i, firstCharCode) {\n return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;\n}\nexport {\n ParseError,\n createParser\n};\n//# sourceMappingURL=index.js.map\n","import { createParser } from \"./index.js\";\nimport { ParseError } from \"./index.js\";\nclass EventSourceParserStream extends TransformStream {\n constructor({ onError, onRetry, onComment } = {}) {\n let parser;\n super({\n start(controller) {\n parser = createParser({\n onEvent: (event) => {\n controller.enqueue(event);\n },\n onError(error) {\n onError === \"terminate\" ? controller.error(error) : typeof onError == \"function\" && onError(error);\n },\n onRetry,\n onComment\n });\n },\n transform(chunk) {\n parser.feed(chunk);\n }\n });\n }\n}\nexport {\n EventSourceParserStream,\n ParseError\n};\n//# sourceMappingURL=stream.js.map\n","// src/combine-headers.ts\nfunction combineHeaders(...headers) {\n return headers.reduce(\n (combinedHeaders, currentHeaders) => ({\n ...combinedHeaders,\n ...currentHeaders != null ? currentHeaders : {}\n }),\n {}\n );\n}\n\n// src/convert-async-iterator-to-readable-stream.ts\nfunction convertAsyncIteratorToReadableStream(iterator) {\n let cancelled = false;\n return new ReadableStream({\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 if (cancelled) return;\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 async cancel(reason) {\n cancelled = true;\n if (iterator.return) {\n try {\n await iterator.return(reason);\n } catch (e) {\n }\n }\n }\n });\n}\n\n// src/create-tool-name-mapping.ts\nfunction createToolNameMapping({\n tools = [],\n providerToolNames,\n resolveProviderToolName\n}) {\n var _a2;\n const customToolNameToProviderToolName = {};\n const providerToolNameToCustomToolName = {};\n for (const tool2 of tools) {\n if (tool2.type === \"provider\") {\n const providerToolName = (_a2 = resolveProviderToolName == null ? void 0 : resolveProviderToolName(tool2)) != null ? _a2 : tool2.id in providerToolNames ? providerToolNames[tool2.id] : void 0;\n if (providerToolName == null) {\n continue;\n }\n customToolNameToProviderToolName[tool2.name] = providerToolName;\n providerToolNameToCustomToolName[providerToolName] = tool2.name;\n }\n }\n return {\n toProviderToolName: (customToolName) => {\n var _a3;\n return (_a3 = customToolNameToProviderToolName[customToolName]) != null ? _a3 : customToolName;\n },\n toCustomToolName: (providerToolName) => {\n var _a3;\n return (_a3 = providerToolNameToCustomToolName[providerToolName]) != null ? _a3 : providerToolName;\n }\n };\n}\n\n// src/delay.ts\nasync function delay(delayInMs, options) {\n if (delayInMs == null) {\n return Promise.resolve();\n }\n const signal = options == null ? void 0 : options.abortSignal;\n return new Promise((resolve2, reject) => {\n if (signal == null ? void 0 : signal.aborted) {\n reject(createAbortError());\n return;\n }\n const timeoutId = setTimeout(() => {\n cleanup();\n resolve2();\n }, delayInMs);\n const cleanup = () => {\n clearTimeout(timeoutId);\n signal == null ? void 0 : signal.removeEventListener(\"abort\", onAbort);\n };\n const onAbort = () => {\n cleanup();\n reject(createAbortError());\n };\n signal == null ? void 0 : signal.addEventListener(\"abort\", onAbort);\n });\n}\nfunction createAbortError() {\n return new DOMException(\"Delay was aborted\", \"AbortError\");\n}\n\n// src/delayed-promise.ts\nvar DelayedPromise = class {\n constructor() {\n this.status = { type: \"pending\" };\n this._resolve = void 0;\n this._reject = void 0;\n }\n get promise() {\n if (this._promise) {\n return this._promise;\n }\n this._promise = new Promise((resolve2, reject) => {\n if (this.status.type === \"resolved\") {\n resolve2(this.status.value);\n } else if (this.status.type === \"rejected\") {\n reject(this.status.error);\n }\n this._resolve = resolve2;\n this._reject = reject;\n });\n return this._promise;\n }\n resolve(value) {\n var _a2;\n this.status = { type: \"resolved\", value };\n if (this._promise) {\n (_a2 = this._resolve) == null ? void 0 : _a2.call(this, value);\n }\n }\n reject(error) {\n var _a2;\n this.status = { type: \"rejected\", error };\n if (this._promise) {\n (_a2 = this._reject) == null ? void 0 : _a2.call(this, error);\n }\n }\n isResolved() {\n return this.status.type === \"resolved\";\n }\n isRejected() {\n return this.status.type === \"rejected\";\n }\n isPending() {\n return this.status.type === \"pending\";\n }\n};\n\n// src/extract-response-headers.ts\nfunction extractResponseHeaders(response) {\n return Object.fromEntries([...response.headers]);\n}\n\n// src/uint8-utils.ts\nvar { btoa, atob } = globalThis;\nfunction convertBase64ToUint8Array(base64String) {\n const base64Url = base64String.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const latin1string = atob(base64Url);\n return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));\n}\nfunction convertUint8ArrayToBase64(array) {\n let latin1string = \"\";\n for (let i = 0; i < array.length; i++) {\n latin1string += String.fromCodePoint(array[i]);\n }\n return btoa(latin1string);\n}\nfunction convertToBase64(value) {\n return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;\n}\n\n// src/convert-image-model-file-to-data-uri.ts\nfunction convertImageModelFileToDataUri(file) {\n if (file.type === \"url\") return file.url;\n return `data:${file.mediaType};base64,${typeof file.data === \"string\" ? file.data : convertUint8ArrayToBase64(file.data)}`;\n}\n\n// src/convert-to-form-data.ts\nfunction convertToFormData(input, options = {}) {\n const { useArrayBrackets = true } = options;\n const formData = new FormData();\n for (const [key, value] of Object.entries(input)) {\n if (value == null) {\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length === 1) {\n formData.append(key, value[0]);\n continue;\n }\n const arrayKey = useArrayBrackets ? `${key}[]` : key;\n for (const item of value) {\n formData.append(arrayKey, item);\n }\n continue;\n }\n formData.append(key, value);\n }\n return formData;\n}\n\n// src/cancel-response-body.ts\nasync function cancelResponseBody(response) {\n var _a2;\n try {\n await ((_a2 = response.body) == null ? void 0 : _a2.cancel());\n } catch (e) {\n }\n}\n\n// src/download-error.ts\nimport { AISDKError } from \"@ai-sdk/provider\";\nvar name = \"AI_DownloadError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar DownloadError = class extends (_b = AISDKError, _a = symbol, _b) {\n constructor({\n url,\n statusCode,\n statusText,\n cause,\n message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`\n }) {\n super({ name, message, cause });\n this[_a] = true;\n this.url = url;\n this.statusCode = statusCode;\n this.statusText = statusText;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker);\n }\n};\n\n// src/is-browser-runtime.ts\nfunction isBrowserRuntime(globalThisAny = globalThis) {\n return globalThisAny.window != null;\n}\n\n// src/validate-download-url.ts\nfunction validateDownloadUrl(url) {\n let parsed;\n try {\n parsed = new URL(url);\n } catch (e) {\n throw new DownloadError({\n url,\n message: `Invalid URL: ${url}`\n });\n }\n if (parsed.protocol === \"data:\") {\n return;\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new DownloadError({\n url,\n message: `URL scheme must be http, https, or data, got ${parsed.protocol}`\n });\n }\n const hostname = parsed.hostname.toLowerCase().replace(/\\.+$/, \"\");\n if (!hostname) {\n throw new DownloadError({\n url,\n message: `URL must have a hostname`\n });\n }\n if (hostname === \"localhost\" || hostname.endsWith(\".local\") || hostname.endsWith(\".localhost\")) {\n throw new DownloadError({\n url,\n message: `URL with hostname ${hostname} is not allowed`\n });\n }\n if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n const ipv6 = hostname.slice(1, -1);\n if (isPrivateIPv6(ipv6)) {\n throw new DownloadError({\n url,\n message: `URL with IPv6 address ${hostname} is not allowed`\n });\n }\n return;\n }\n if (isIPv4(hostname)) {\n if (isPrivateIPv4(hostname)) {\n throw new DownloadError({\n url,\n message: `URL with IP address ${hostname} is not allowed`\n });\n }\n return;\n }\n}\nfunction isIPv4(hostname) {\n const parts = hostname.split(\".\");\n if (parts.length !== 4) return false;\n return parts.every((part) => {\n const num = Number(part);\n return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;\n });\n}\nfunction isPrivateIPv4(ip) {\n const parts = ip.split(\".\").map(Number);\n const [a, b, c] = parts;\n if (a === 0) return true;\n if (a === 10) return true;\n if (a === 100 && b >= 64 && b <= 127) return true;\n if (a === 127) return true;\n if (a === 169 && b === 254) return true;\n if (a === 172 && b >= 16 && b <= 31) return true;\n if (a === 192 && b === 0 && c === 0) return true;\n if (a === 192 && b === 168) return true;\n if (a === 198 && (b === 18 || b === 19)) return true;\n if (a >= 240) return true;\n return false;\n}\nfunction parseIPv6(ip) {\n let address = ip.toLowerCase();\n const zoneIndex = address.indexOf(\"%\");\n if (zoneIndex !== -1) {\n address = address.slice(0, zoneIndex);\n }\n const halves = address.split(\"::\");\n if (halves.length > 2) return null;\n const toGroups = (segment) => {\n if (segment === \"\") return [];\n const groups = [];\n const parts = segment.split(\":\");\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (part.includes(\".\")) {\n if (i !== parts.length - 1 || !isIPv4(part)) return null;\n const [a, b, c, d] = part.split(\".\").map(Number);\n groups.push(a << 8 | b, c << 8 | d);\n continue;\n }\n if (!/^[0-9a-f]{1,4}$/.test(part)) return null;\n groups.push(parseInt(part, 16));\n }\n return groups;\n };\n const head = toGroups(halves[0]);\n if (head === null) return null;\n if (halves.length === 2) {\n const tail = toGroups(halves[1]);\n if (tail === null) return null;\n const fill = 8 - head.length - tail.length;\n if (fill < 0) return null;\n return [...head, ...new Array(fill).fill(0), ...tail];\n }\n return head.length === 8 ? head : null;\n}\nfunction isPrivateIPv6(ip) {\n const groups = parseIPv6(ip);\n if (groups === null) return true;\n const topZero = (count) => groups.slice(0, count).every((group) => group === 0);\n if (topZero(7) && (groups[7] === 0 || groups[7] === 1)) return true;\n if ((groups[0] & 65024) === 64512) return true;\n if ((groups[0] & 65472) === 65152) return true;\n if ((groups[0] & 65472) === 65216) return true;\n if ((groups[0] & 65280) === 65280) return true;\n const embedsIPv4 = (\n // ::/96 — IPv4-compatible (deprecated)\n topZero(6) || // ::ffff:0:0/96 — IPv4-mapped (ffff in group 5)\n topZero(5) && groups[5] === 65535 || // ::ffff:0:0/96 — IPv4-translated form (ffff in group 4, group 5 zero)\n topZero(4) && groups[4] === 65535 && groups[5] === 0 || // 64:ff9b::/96 — NAT64 well-known prefix\n groups[0] === 100 && groups[1] === 65435 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0 || // 64:ff9b:1::/48 — NAT64 local-use prefix\n groups[0] === 100 && groups[1] === 65435 && groups[2] === 1\n );\n if (embedsIPv4) {\n const a = groups[6] >> 8 & 255;\n const b = groups[6] & 255;\n const c = groups[7] >> 8 & 255;\n const d = groups[7] & 255;\n return isPrivateIPv4(`${a}.${b}.${c}.${d}`);\n }\n return false;\n}\n\n// src/fetch-with-validated-redirects.ts\nvar MAX_DOWNLOAD_REDIRECTS = 10;\nasync function fetchWithValidatedRedirects({\n url,\n headers,\n abortSignal,\n maxRedirects = MAX_DOWNLOAD_REDIRECTS\n}) {\n const baseInit = { signal: abortSignal };\n if (headers !== void 0) {\n baseInit.headers = headers;\n }\n let currentUrl = url;\n for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {\n validateDownloadUrl(currentUrl);\n const response = await fetch(currentUrl, {\n ...baseInit,\n redirect: \"manual\"\n });\n if (response.type === \"opaqueredirect\") {\n if (!isBrowserRuntime()) {\n throw new DownloadError({\n url,\n message: `Redirect from ${currentUrl} could not be validated and was blocked`\n });\n }\n return await fetch(currentUrl, { ...baseInit, redirect: \"follow\" });\n }\n const location = response.headers.get(\"location\");\n if (response.status >= 300 && response.status < 400 && location) {\n await cancelResponseBody(response);\n currentUrl = new URL(location, currentUrl).toString();\n continue;\n }\n return response;\n }\n throw new DownloadError({\n url,\n message: `Too many redirects (max ${maxRedirects})`\n });\n}\n\n// src/read-response-with-size-limit.ts\nvar DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;\nasync function readResponseWithSizeLimit({\n response,\n url,\n maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE\n}) {\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength != null) {\n const length = parseInt(contentLength, 10);\n if (!isNaN(length) && length > maxBytes) {\n await cancelResponseBody(response);\n throw new DownloadError({\n url,\n message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`\n });\n }\n }\n const body = response.body;\n if (body == null) {\n return new Uint8Array(0);\n }\n const reader = body.getReader();\n const chunks = [];\n let totalBytes = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n totalBytes += value.length;\n if (totalBytes > maxBytes) {\n throw new DownloadError({\n url,\n message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`\n });\n }\n chunks.push(value);\n }\n } finally {\n try {\n await reader.cancel();\n } finally {\n reader.releaseLock();\n }\n }\n const result = new Uint8Array(totalBytes);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n}\n\n// src/download-blob.ts\nasync function downloadBlob(url, options) {\n var _a2, _b2;\n try {\n const response = await fetchWithValidatedRedirects({\n url,\n abortSignal: options == null ? void 0 : options.abortSignal\n });\n if (!response.ok) {\n await cancelResponseBody(response);\n throw new DownloadError({\n url,\n statusCode: response.status,\n statusText: response.statusText\n });\n }\n const data = await readResponseWithSizeLimit({\n response,\n url,\n maxBytes: (_a2 = options == null ? void 0 : options.maxBytes) != null ? _a2 : DEFAULT_MAX_DOWNLOAD_SIZE\n });\n const contentType = (_b2 = response.headers.get(\"content-type\")) != null ? _b2 : void 0;\n return new Blob([data], contentType ? { type: contentType } : void 0);\n } catch (error) {\n if (DownloadError.isInstance(error)) {\n throw error;\n }\n throw new DownloadError({ url, cause: error });\n }\n}\n\n// src/generate-id.ts\nimport { InvalidArgumentError } from \"@ai-sdk/provider\";\nvar createIdGenerator = ({\n prefix,\n size = 16,\n alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\",\n separator = \"-\"\n} = {}) => {\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 if (prefix == null) {\n return generator;\n }\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 return () => `${prefix}${separator}${generator()}`;\n};\nvar generateId = createIdGenerator();\n\n// src/get-error-message.ts\nfunction getErrorMessage(error) {\n if (error == null) {\n return \"unknown error\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return JSON.stringify(error);\n}\n\n// src/get-from-api.ts\nimport { APICallError as APICallError2 } from \"@ai-sdk/provider\";\n\n// src/handle-fetch-error.ts\nimport { APICallError } from \"@ai-sdk/provider\";\n\n// src/is-abort-error.ts\nfunction isAbortError(error) {\n return (error instanceof Error || error instanceof DOMException) && (error.name === \"AbortError\" || error.name === \"ResponseAborted\" || // Next.js\n error.name === \"TimeoutError\");\n}\n\n// src/handle-fetch-error.ts\nvar FETCH_FAILED_ERROR_MESSAGES = [\"fetch failed\", \"failed to fetch\"];\nvar BUN_ERROR_CODES = [\n \"ConnectionRefused\",\n \"ConnectionClosed\",\n \"FailedToOpenSocket\",\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n \"ETIMEDOUT\",\n \"EPIPE\"\n];\nfunction isBunNetworkError(error) {\n if (!(error instanceof Error)) {\n return false;\n }\n const code = error.code;\n if (typeof code === \"string\" && BUN_ERROR_CODES.includes(code)) {\n return true;\n }\n return false;\n}\nfunction handleFetchError({\n error,\n url,\n requestBodyValues\n}) {\n if (isAbortError(error)) {\n return error;\n }\n if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {\n const cause = error.cause;\n if (cause != null) {\n return new APICallError({\n message: `Cannot connect to API: ${cause.message}`,\n cause,\n url,\n requestBodyValues,\n isRetryable: true\n // retry when network error\n });\n }\n }\n if (isBunNetworkError(error)) {\n return new APICallError({\n message: `Cannot connect to API: ${error.message}`,\n cause: error,\n url,\n requestBodyValues,\n isRetryable: true\n });\n }\n return error;\n}\n\n// src/get-runtime-environment-user-agent.ts\nfunction getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {\n var _a2, _b2, _c;\n if (globalThisAny.window) {\n return `runtime/browser`;\n }\n if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) {\n return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;\n }\n if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) {\n return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;\n }\n if (globalThisAny.EdgeRuntime) {\n return `runtime/vercel-edge`;\n }\n return \"runtime/unknown\";\n}\n\n// src/normalize-headers.ts\nfunction normalizeHeaders(headers) {\n if (headers == null) {\n return {};\n }\n const normalized = {};\n if (headers instanceof Headers) {\n headers.forEach((value, key) => {\n normalized[key.toLowerCase()] = value;\n });\n } else {\n if (!Array.isArray(headers)) {\n headers = Object.entries(headers);\n }\n for (const [key, value] of headers) {\n if (value != null) {\n normalized[key.toLowerCase()] = value;\n }\n }\n }\n return normalized;\n}\n\n// src/with-user-agent-suffix.ts\nfunction withUserAgentSuffix(headers, ...userAgentSuffixParts) {\n const normalizedHeaders = new Headers(normalizeHeaders(headers));\n const currentUserAgentHeader = normalizedHeaders.get(\"user-agent\") || \"\";\n normalizedHeaders.set(\n \"user-agent\",\n [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(\" \")\n );\n return Object.fromEntries(normalizedHeaders.entries());\n}\n\n// src/version.ts\nvar VERSION = true ? \"4.0.40\" : \"0.0.0-test\";\n\n// src/get-from-api.ts\nvar getOriginalFetch = () => globalThis.fetch;\nvar getFromApi = async ({\n url,\n headers = {},\n successfulResponseHandler,\n failedResponseHandler,\n abortSignal,\n fetch: fetch2 = getOriginalFetch()\n}) => {\n try {\n const response = await fetch2(url, {\n method: \"GET\",\n headers: withUserAgentSuffix(\n headers,\n `ai-sdk/provider-utils/${VERSION}`,\n getRuntimeEnvironmentUserAgent()\n ),\n signal: abortSignal\n });\n const responseHeaders = extractResponseHeaders(response);\n if (!response.ok) {\n let errorInformation;\n try {\n errorInformation = await failedResponseHandler({\n response,\n url,\n requestBodyValues: {}\n });\n } catch (error) {\n if (isAbortError(error) || APICallError2.isInstance(error)) {\n throw error;\n }\n throw new APICallError2({\n message: \"Failed to process error response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: {}\n });\n }\n throw errorInformation.value;\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) || APICallError2.isInstance(error)) {\n throw error;\n }\n }\n