@ai-sdk/provider-utils 0.0.0-01d6317c-20260129172110

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/CHANGELOG.md +1506 -0
  2. package/README.md +1 -0
  3. package/dist/index.d.mts +1372 -0
  4. package/dist/index.d.ts +1372 -0
  5. package/dist/index.js +2667 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/index.mjs +2581 -0
  8. package/dist/index.mjs.map +1 -0
  9. package/dist/test/index.d.mts +17 -0
  10. package/dist/test/index.d.ts +17 -0
  11. package/dist/test/index.js +110 -0
  12. package/dist/test/index.js.map +1 -0
  13. package/dist/test/index.mjs +77 -0
  14. package/dist/test/index.mjs.map +1 -0
  15. package/package.json +81 -0
  16. package/src/add-additional-properties-to-json-schema.ts +53 -0
  17. package/src/combine-headers.ts +11 -0
  18. package/src/convert-async-iterator-to-readable-stream.ts +47 -0
  19. package/src/convert-image-model-file-to-data-uri.ts +19 -0
  20. package/src/convert-to-form-data.ts +61 -0
  21. package/src/create-tool-name-mapping.ts +66 -0
  22. package/src/delay.ts +47 -0
  23. package/src/delayed-promise.ts +61 -0
  24. package/src/download-blob.ts +31 -0
  25. package/src/download-error.ts +39 -0
  26. package/src/extract-response-headers.ts +9 -0
  27. package/src/fetch-function.ts +4 -0
  28. package/src/generate-id.ts +57 -0
  29. package/src/get-error-message.ts +15 -0
  30. package/src/get-from-api.ts +97 -0
  31. package/src/get-runtime-environment-user-agent.ts +24 -0
  32. package/src/handle-fetch-error.ts +72 -0
  33. package/src/index.ts +67 -0
  34. package/src/inject-json-instruction.ts +63 -0
  35. package/src/is-abort-error.ts +8 -0
  36. package/src/is-async-iterable.ts +3 -0
  37. package/src/is-non-nullable.ts +12 -0
  38. package/src/is-url-supported.ts +40 -0
  39. package/src/load-api-key.ts +45 -0
  40. package/src/load-optional-setting.ts +30 -0
  41. package/src/load-setting.ts +62 -0
  42. package/src/maybe-promise-like.ts +3 -0
  43. package/src/media-type-to-extension.ts +22 -0
  44. package/src/normalize-headers.ts +38 -0
  45. package/src/parse-json-event-stream.ts +33 -0
  46. package/src/parse-json.ts +122 -0
  47. package/src/parse-provider-options.ts +32 -0
  48. package/src/post-to-api.ts +166 -0
  49. package/src/provider-tool-factory.ts +125 -0
  50. package/src/remove-undefined-entries.ts +12 -0
  51. package/src/resolve.ts +17 -0
  52. package/src/response-handler.ts +187 -0
  53. package/src/schema.ts +267 -0
  54. package/src/secure-json-parse.ts +92 -0
  55. package/src/test/convert-array-to-async-iterable.ts +9 -0
  56. package/src/test/convert-array-to-readable-stream.ts +15 -0
  57. package/src/test/convert-async-iterable-to-array.ts +9 -0
  58. package/src/test/convert-readable-stream-to-array.ts +14 -0
  59. package/src/test/convert-response-stream-to-array.ts +9 -0
  60. package/src/test/index.ts +7 -0
  61. package/src/test/is-node-version.ts +4 -0
  62. package/src/test/mock-id.ts +8 -0
  63. package/src/to-json-schema/zod3-to-json-schema/LICENSE +16 -0
  64. package/src/to-json-schema/zod3-to-json-schema/README.md +24 -0
  65. package/src/to-json-schema/zod3-to-json-schema/get-relative-path.ts +7 -0
  66. package/src/to-json-schema/zod3-to-json-schema/index.ts +1 -0
  67. package/src/to-json-schema/zod3-to-json-schema/options.ts +98 -0
  68. package/src/to-json-schema/zod3-to-json-schema/parse-def.ts +109 -0
  69. package/src/to-json-schema/zod3-to-json-schema/parse-types.ts +57 -0
  70. package/src/to-json-schema/zod3-to-json-schema/parsers/any.ts +5 -0
  71. package/src/to-json-schema/zod3-to-json-schema/parsers/array.ts +38 -0
  72. package/src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts +44 -0
  73. package/src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts +7 -0
  74. package/src/to-json-schema/zod3-to-json-schema/parsers/branded.ts +7 -0
  75. package/src/to-json-schema/zod3-to-json-schema/parsers/catch.ts +7 -0
  76. package/src/to-json-schema/zod3-to-json-schema/parsers/date.ts +64 -0
  77. package/src/to-json-schema/zod3-to-json-schema/parsers/default.ts +14 -0
  78. package/src/to-json-schema/zod3-to-json-schema/parsers/effects.ts +14 -0
  79. package/src/to-json-schema/zod3-to-json-schema/parsers/enum.ts +13 -0
  80. package/src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts +52 -0
  81. package/src/to-json-schema/zod3-to-json-schema/parsers/literal.ts +29 -0
  82. package/src/to-json-schema/zod3-to-json-schema/parsers/map.ts +47 -0
  83. package/src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts +31 -0
  84. package/src/to-json-schema/zod3-to-json-schema/parsers/never.ts +9 -0
  85. package/src/to-json-schema/zod3-to-json-schema/parsers/null.ts +9 -0
  86. package/src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts +42 -0
  87. package/src/to-json-schema/zod3-to-json-schema/parsers/number.ts +44 -0
  88. package/src/to-json-schema/zod3-to-json-schema/parsers/object.ts +88 -0
  89. package/src/to-json-schema/zod3-to-json-schema/parsers/optional.ts +23 -0
  90. package/src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts +29 -0
  91. package/src/to-json-schema/zod3-to-json-schema/parsers/promise.ts +11 -0
  92. package/src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts +7 -0
  93. package/src/to-json-schema/zod3-to-json-schema/parsers/record.ts +71 -0
  94. package/src/to-json-schema/zod3-to-json-schema/parsers/set.ts +35 -0
  95. package/src/to-json-schema/zod3-to-json-schema/parsers/string.ts +426 -0
  96. package/src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts +61 -0
  97. package/src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts +11 -0
  98. package/src/to-json-schema/zod3-to-json-schema/parsers/union.ts +144 -0
  99. package/src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts +7 -0
  100. package/src/to-json-schema/zod3-to-json-schema/refs.ts +39 -0
  101. package/src/to-json-schema/zod3-to-json-schema/select-parser.ts +115 -0
  102. package/src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts +93 -0
  103. package/src/types/assistant-model-message.ts +39 -0
  104. package/src/types/content-part.ts +379 -0
  105. package/src/types/data-content.ts +4 -0
  106. package/src/types/execute-tool.ts +27 -0
  107. package/src/types/index.ts +40 -0
  108. package/src/types/model-message.ts +14 -0
  109. package/src/types/provider-options.ts +9 -0
  110. package/src/types/system-model-message.ts +20 -0
  111. package/src/types/tool-approval-request.ts +16 -0
  112. package/src/types/tool-approval-response.ts +27 -0
  113. package/src/types/tool-call.ts +31 -0
  114. package/src/types/tool-model-message.ts +23 -0
  115. package/src/types/tool-result.ts +35 -0
  116. package/src/types/tool.ts +324 -0
  117. package/src/types/user-model-message.ts +22 -0
  118. package/src/uint8-utils.ts +26 -0
  119. package/src/validate-types.ts +87 -0
  120. package/src/version.ts +6 -0
  121. package/src/with-user-agent-suffix.ts +27 -0
  122. package/src/without-trailing-slash.ts +3 -0
  123. package/test.d.ts +1 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,2581 @@
1
+ // src/combine-headers.ts
2
+ function combineHeaders(...headers) {
3
+ return headers.reduce(
4
+ (combinedHeaders, currentHeaders) => ({
5
+ ...combinedHeaders,
6
+ ...currentHeaders != null ? currentHeaders : {}
7
+ }),
8
+ {}
9
+ );
10
+ }
11
+
12
+ // src/convert-async-iterator-to-readable-stream.ts
13
+ function convertAsyncIteratorToReadableStream(iterator) {
14
+ let cancelled = false;
15
+ return new ReadableStream({
16
+ /**
17
+ * Called when the consumer wants to pull more data from the stream.
18
+ *
19
+ * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.
20
+ * @returns {Promise<void>}
21
+ */
22
+ async pull(controller) {
23
+ if (cancelled) return;
24
+ try {
25
+ const { value, done } = await iterator.next();
26
+ if (done) {
27
+ controller.close();
28
+ } else {
29
+ controller.enqueue(value);
30
+ }
31
+ } catch (error) {
32
+ controller.error(error);
33
+ }
34
+ },
35
+ /**
36
+ * Called when the consumer cancels the stream.
37
+ */
38
+ async cancel(reason) {
39
+ cancelled = true;
40
+ if (iterator.return) {
41
+ try {
42
+ await iterator.return(reason);
43
+ } catch (e) {
44
+ }
45
+ }
46
+ }
47
+ });
48
+ }
49
+
50
+ // src/create-tool-name-mapping.ts
51
+ function createToolNameMapping({
52
+ tools = [],
53
+ providerToolNames
54
+ }) {
55
+ const customToolNameToProviderToolName = {};
56
+ const providerToolNameToCustomToolName = {};
57
+ for (const tool2 of tools) {
58
+ if (tool2.type === "provider" && tool2.id in providerToolNames) {
59
+ const providerToolName = providerToolNames[tool2.id];
60
+ customToolNameToProviderToolName[tool2.name] = providerToolName;
61
+ providerToolNameToCustomToolName[providerToolName] = tool2.name;
62
+ }
63
+ }
64
+ return {
65
+ toProviderToolName: (customToolName) => {
66
+ var _a2;
67
+ return (_a2 = customToolNameToProviderToolName[customToolName]) != null ? _a2 : customToolName;
68
+ },
69
+ toCustomToolName: (providerToolName) => {
70
+ var _a2;
71
+ return (_a2 = providerToolNameToCustomToolName[providerToolName]) != null ? _a2 : providerToolName;
72
+ }
73
+ };
74
+ }
75
+
76
+ // src/delay.ts
77
+ async function delay(delayInMs, options) {
78
+ if (delayInMs == null) {
79
+ return Promise.resolve();
80
+ }
81
+ const signal = options == null ? void 0 : options.abortSignal;
82
+ return new Promise((resolve2, reject) => {
83
+ if (signal == null ? void 0 : signal.aborted) {
84
+ reject(createAbortError());
85
+ return;
86
+ }
87
+ const timeoutId = setTimeout(() => {
88
+ cleanup();
89
+ resolve2();
90
+ }, delayInMs);
91
+ const cleanup = () => {
92
+ clearTimeout(timeoutId);
93
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
94
+ };
95
+ const onAbort = () => {
96
+ cleanup();
97
+ reject(createAbortError());
98
+ };
99
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort);
100
+ });
101
+ }
102
+ function createAbortError() {
103
+ return new DOMException("Delay was aborted", "AbortError");
104
+ }
105
+
106
+ // src/delayed-promise.ts
107
+ var DelayedPromise = class {
108
+ constructor() {
109
+ this.status = { type: "pending" };
110
+ this._resolve = void 0;
111
+ this._reject = void 0;
112
+ }
113
+ get promise() {
114
+ if (this._promise) {
115
+ return this._promise;
116
+ }
117
+ this._promise = new Promise((resolve2, reject) => {
118
+ if (this.status.type === "resolved") {
119
+ resolve2(this.status.value);
120
+ } else if (this.status.type === "rejected") {
121
+ reject(this.status.error);
122
+ }
123
+ this._resolve = resolve2;
124
+ this._reject = reject;
125
+ });
126
+ return this._promise;
127
+ }
128
+ resolve(value) {
129
+ var _a2;
130
+ this.status = { type: "resolved", value };
131
+ if (this._promise) {
132
+ (_a2 = this._resolve) == null ? void 0 : _a2.call(this, value);
133
+ }
134
+ }
135
+ reject(error) {
136
+ var _a2;
137
+ this.status = { type: "rejected", error };
138
+ if (this._promise) {
139
+ (_a2 = this._reject) == null ? void 0 : _a2.call(this, error);
140
+ }
141
+ }
142
+ isResolved() {
143
+ return this.status.type === "resolved";
144
+ }
145
+ isRejected() {
146
+ return this.status.type === "rejected";
147
+ }
148
+ isPending() {
149
+ return this.status.type === "pending";
150
+ }
151
+ };
152
+
153
+ // src/extract-response-headers.ts
154
+ function extractResponseHeaders(response) {
155
+ return Object.fromEntries([...response.headers]);
156
+ }
157
+
158
+ // src/uint8-utils.ts
159
+ var { btoa, atob } = globalThis;
160
+ function convertBase64ToUint8Array(base64String) {
161
+ const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
162
+ const latin1string = atob(base64Url);
163
+ return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
164
+ }
165
+ function convertUint8ArrayToBase64(array) {
166
+ let latin1string = "";
167
+ for (let i = 0; i < array.length; i++) {
168
+ latin1string += String.fromCodePoint(array[i]);
169
+ }
170
+ return btoa(latin1string);
171
+ }
172
+ function convertToBase64(value) {
173
+ return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;
174
+ }
175
+
176
+ // src/convert-image-model-file-to-data-uri.ts
177
+ function convertImageModelFileToDataUri(file) {
178
+ if (file.type === "url") return file.url;
179
+ return `data:${file.mediaType};base64,${typeof file.data === "string" ? file.data : convertUint8ArrayToBase64(file.data)}`;
180
+ }
181
+
182
+ // src/convert-to-form-data.ts
183
+ function convertToFormData(input, options = {}) {
184
+ const { useArrayBrackets = true } = options;
185
+ const formData = new FormData();
186
+ for (const [key, value] of Object.entries(input)) {
187
+ if (value == null) {
188
+ continue;
189
+ }
190
+ if (Array.isArray(value)) {
191
+ if (value.length === 1) {
192
+ formData.append(key, value[0]);
193
+ continue;
194
+ }
195
+ const arrayKey = useArrayBrackets ? `${key}[]` : key;
196
+ for (const item of value) {
197
+ formData.append(arrayKey, item);
198
+ }
199
+ continue;
200
+ }
201
+ formData.append(key, value);
202
+ }
203
+ return formData;
204
+ }
205
+
206
+ // src/download-error.ts
207
+ import { AISDKError } from "@ai-sdk/provider";
208
+ var name = "AI_DownloadError";
209
+ var marker = `vercel.ai.error.${name}`;
210
+ var symbol = Symbol.for(marker);
211
+ var _a, _b;
212
+ var DownloadError = class extends (_b = AISDKError, _a = symbol, _b) {
213
+ constructor({
214
+ url,
215
+ statusCode,
216
+ statusText,
217
+ cause,
218
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
219
+ }) {
220
+ super({ name, message, cause });
221
+ this[_a] = true;
222
+ this.url = url;
223
+ this.statusCode = statusCode;
224
+ this.statusText = statusText;
225
+ }
226
+ static isInstance(error) {
227
+ return AISDKError.hasMarker(error, marker);
228
+ }
229
+ };
230
+
231
+ // src/download-blob.ts
232
+ async function downloadBlob(url) {
233
+ try {
234
+ const response = await fetch(url);
235
+ if (!response.ok) {
236
+ throw new DownloadError({
237
+ url,
238
+ statusCode: response.status,
239
+ statusText: response.statusText
240
+ });
241
+ }
242
+ return await response.blob();
243
+ } catch (error) {
244
+ if (DownloadError.isInstance(error)) {
245
+ throw error;
246
+ }
247
+ throw new DownloadError({ url, cause: error });
248
+ }
249
+ }
250
+
251
+ // src/generate-id.ts
252
+ import { InvalidArgumentError } from "@ai-sdk/provider";
253
+ var createIdGenerator = ({
254
+ prefix,
255
+ size = 16,
256
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
257
+ separator = "-"
258
+ } = {}) => {
259
+ const generator = () => {
260
+ const alphabetLength = alphabet.length;
261
+ const chars = new Array(size);
262
+ for (let i = 0; i < size; i++) {
263
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
264
+ }
265
+ return chars.join("");
266
+ };
267
+ if (prefix == null) {
268
+ return generator;
269
+ }
270
+ if (alphabet.includes(separator)) {
271
+ throw new InvalidArgumentError({
272
+ argument: "separator",
273
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
274
+ });
275
+ }
276
+ return () => `${prefix}${separator}${generator()}`;
277
+ };
278
+ var generateId = createIdGenerator();
279
+
280
+ // src/get-error-message.ts
281
+ function getErrorMessage(error) {
282
+ if (error == null) {
283
+ return "unknown error";
284
+ }
285
+ if (typeof error === "string") {
286
+ return error;
287
+ }
288
+ if (error instanceof Error) {
289
+ return error.message;
290
+ }
291
+ return JSON.stringify(error);
292
+ }
293
+
294
+ // src/get-from-api.ts
295
+ import { APICallError as APICallError2 } from "@ai-sdk/provider";
296
+
297
+ // src/handle-fetch-error.ts
298
+ import { APICallError } from "@ai-sdk/provider";
299
+
300
+ // src/is-abort-error.ts
301
+ function isAbortError(error) {
302
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
303
+ error.name === "TimeoutError");
304
+ }
305
+
306
+ // src/handle-fetch-error.ts
307
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
308
+ var BUN_ERROR_CODES = [
309
+ "ConnectionRefused",
310
+ "ConnectionClosed",
311
+ "FailedToOpenSocket",
312
+ "ECONNRESET",
313
+ "ECONNREFUSED",
314
+ "ETIMEDOUT",
315
+ "EPIPE"
316
+ ];
317
+ function isBunNetworkError(error) {
318
+ if (!(error instanceof Error)) {
319
+ return false;
320
+ }
321
+ const code = error.code;
322
+ if (typeof code === "string" && BUN_ERROR_CODES.includes(code)) {
323
+ return true;
324
+ }
325
+ return false;
326
+ }
327
+ function handleFetchError({
328
+ error,
329
+ url,
330
+ requestBodyValues
331
+ }) {
332
+ if (isAbortError(error)) {
333
+ return error;
334
+ }
335
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
336
+ const cause = error.cause;
337
+ if (cause != null) {
338
+ return new APICallError({
339
+ message: `Cannot connect to API: ${cause.message}`,
340
+ cause,
341
+ url,
342
+ requestBodyValues,
343
+ isRetryable: true
344
+ // retry when network error
345
+ });
346
+ }
347
+ }
348
+ if (isBunNetworkError(error)) {
349
+ return new APICallError({
350
+ message: `Cannot connect to API: ${error.message}`,
351
+ cause: error,
352
+ url,
353
+ requestBodyValues,
354
+ isRetryable: true
355
+ });
356
+ }
357
+ return error;
358
+ }
359
+
360
+ // src/get-runtime-environment-user-agent.ts
361
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
362
+ var _a2, _b2, _c;
363
+ if (globalThisAny.window) {
364
+ return `runtime/browser`;
365
+ }
366
+ if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) {
367
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
368
+ }
369
+ if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) {
370
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
371
+ }
372
+ if (globalThisAny.EdgeRuntime) {
373
+ return `runtime/vercel-edge`;
374
+ }
375
+ return "runtime/unknown";
376
+ }
377
+
378
+ // src/normalize-headers.ts
379
+ function normalizeHeaders(headers) {
380
+ if (headers == null) {
381
+ return {};
382
+ }
383
+ const normalized = {};
384
+ if (headers instanceof Headers) {
385
+ headers.forEach((value, key) => {
386
+ normalized[key.toLowerCase()] = value;
387
+ });
388
+ } else {
389
+ if (!Array.isArray(headers)) {
390
+ headers = Object.entries(headers);
391
+ }
392
+ for (const [key, value] of headers) {
393
+ if (value != null) {
394
+ normalized[key.toLowerCase()] = value;
395
+ }
396
+ }
397
+ }
398
+ return normalized;
399
+ }
400
+
401
+ // src/with-user-agent-suffix.ts
402
+ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
403
+ const normalizedHeaders = new Headers(normalizeHeaders(headers));
404
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
405
+ normalizedHeaders.set(
406
+ "user-agent",
407
+ [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
408
+ );
409
+ return Object.fromEntries(normalizedHeaders.entries());
410
+ }
411
+
412
+ // src/version.ts
413
+ var VERSION = true ? "0.0.0-01d6317c-20260129172110" : "0.0.0-test";
414
+
415
+ // src/get-from-api.ts
416
+ var getOriginalFetch = () => globalThis.fetch;
417
+ var getFromApi = async ({
418
+ url,
419
+ headers = {},
420
+ successfulResponseHandler,
421
+ failedResponseHandler,
422
+ abortSignal,
423
+ fetch: fetch2 = getOriginalFetch()
424
+ }) => {
425
+ try {
426
+ const response = await fetch2(url, {
427
+ method: "GET",
428
+ headers: withUserAgentSuffix(
429
+ headers,
430
+ `ai-sdk/provider-utils/${VERSION}`,
431
+ getRuntimeEnvironmentUserAgent()
432
+ ),
433
+ signal: abortSignal
434
+ });
435
+ const responseHeaders = extractResponseHeaders(response);
436
+ if (!response.ok) {
437
+ let errorInformation;
438
+ try {
439
+ errorInformation = await failedResponseHandler({
440
+ response,
441
+ url,
442
+ requestBodyValues: {}
443
+ });
444
+ } catch (error) {
445
+ if (isAbortError(error) || APICallError2.isInstance(error)) {
446
+ throw error;
447
+ }
448
+ throw new APICallError2({
449
+ message: "Failed to process error response",
450
+ cause: error,
451
+ statusCode: response.status,
452
+ url,
453
+ responseHeaders,
454
+ requestBodyValues: {}
455
+ });
456
+ }
457
+ throw errorInformation.value;
458
+ }
459
+ try {
460
+ return await successfulResponseHandler({
461
+ response,
462
+ url,
463
+ requestBodyValues: {}
464
+ });
465
+ } catch (error) {
466
+ if (error instanceof Error) {
467
+ if (isAbortError(error) || APICallError2.isInstance(error)) {
468
+ throw error;
469
+ }
470
+ }
471
+ throw new APICallError2({
472
+ message: "Failed to process successful response",
473
+ cause: error,
474
+ statusCode: response.status,
475
+ url,
476
+ responseHeaders,
477
+ requestBodyValues: {}
478
+ });
479
+ }
480
+ } catch (error) {
481
+ throw handleFetchError({ error, url, requestBodyValues: {} });
482
+ }
483
+ };
484
+
485
+ // src/inject-json-instruction.ts
486
+ var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
487
+ var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
488
+ var DEFAULT_GENERIC_SUFFIX = "You MUST answer with JSON.";
489
+ function injectJsonInstruction({
490
+ prompt,
491
+ schema,
492
+ schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0,
493
+ schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX
494
+ }) {
495
+ return [
496
+ prompt != null && prompt.length > 0 ? prompt : void 0,
497
+ prompt != null && prompt.length > 0 ? "" : void 0,
498
+ // add a newline if prompt is not null
499
+ schemaPrefix,
500
+ schema != null ? JSON.stringify(schema) : void 0,
501
+ schemaSuffix
502
+ ].filter((line) => line != null).join("\n");
503
+ }
504
+ function injectJsonInstructionIntoMessages({
505
+ messages,
506
+ schema,
507
+ schemaPrefix,
508
+ schemaSuffix
509
+ }) {
510
+ var _a2, _b2;
511
+ const systemMessage = ((_a2 = messages[0]) == null ? void 0 : _a2.role) === "system" ? { ...messages[0] } : { role: "system", content: "" };
512
+ systemMessage.content = injectJsonInstruction({
513
+ prompt: systemMessage.content,
514
+ schema,
515
+ schemaPrefix,
516
+ schemaSuffix
517
+ });
518
+ return [
519
+ systemMessage,
520
+ ...((_b2 = messages[0]) == null ? void 0 : _b2.role) === "system" ? messages.slice(1) : messages
521
+ ];
522
+ }
523
+
524
+ // src/is-non-nullable.ts
525
+ function isNonNullable(value) {
526
+ return value != null;
527
+ }
528
+
529
+ // src/is-url-supported.ts
530
+ function isUrlSupported({
531
+ mediaType,
532
+ url,
533
+ supportedUrls
534
+ }) {
535
+ url = url.toLowerCase();
536
+ mediaType = mediaType.toLowerCase();
537
+ return Object.entries(supportedUrls).map(([key, value]) => {
538
+ const mediaType2 = key.toLowerCase();
539
+ return mediaType2 === "*" || mediaType2 === "*/*" ? { mediaTypePrefix: "", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\*/, ""), regexes: value };
540
+ }).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));
541
+ }
542
+
543
+ // src/load-api-key.ts
544
+ import { LoadAPIKeyError } from "@ai-sdk/provider";
545
+ function loadApiKey({
546
+ apiKey,
547
+ environmentVariableName,
548
+ apiKeyParameterName = "apiKey",
549
+ description
550
+ }) {
551
+ if (typeof apiKey === "string") {
552
+ return apiKey;
553
+ }
554
+ if (apiKey != null) {
555
+ throw new LoadAPIKeyError({
556
+ message: `${description} API key must be a string.`
557
+ });
558
+ }
559
+ if (typeof process === "undefined") {
560
+ throw new LoadAPIKeyError({
561
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
562
+ });
563
+ }
564
+ apiKey = process.env[environmentVariableName];
565
+ if (apiKey == null) {
566
+ throw new LoadAPIKeyError({
567
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
568
+ });
569
+ }
570
+ if (typeof apiKey !== "string") {
571
+ throw new LoadAPIKeyError({
572
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
573
+ });
574
+ }
575
+ return apiKey;
576
+ }
577
+
578
+ // src/load-optional-setting.ts
579
+ function loadOptionalSetting({
580
+ settingValue,
581
+ environmentVariableName
582
+ }) {
583
+ if (typeof settingValue === "string") {
584
+ return settingValue;
585
+ }
586
+ if (settingValue != null || typeof process === "undefined") {
587
+ return void 0;
588
+ }
589
+ settingValue = process.env[environmentVariableName];
590
+ if (settingValue == null || typeof settingValue !== "string") {
591
+ return void 0;
592
+ }
593
+ return settingValue;
594
+ }
595
+
596
+ // src/load-setting.ts
597
+ import { LoadSettingError } from "@ai-sdk/provider";
598
+ function loadSetting({
599
+ settingValue,
600
+ environmentVariableName,
601
+ settingName,
602
+ description
603
+ }) {
604
+ if (typeof settingValue === "string") {
605
+ return settingValue;
606
+ }
607
+ if (settingValue != null) {
608
+ throw new LoadSettingError({
609
+ message: `${description} setting must be a string.`
610
+ });
611
+ }
612
+ if (typeof process === "undefined") {
613
+ throw new LoadSettingError({
614
+ message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables is not supported in this environment.`
615
+ });
616
+ }
617
+ settingValue = process.env[environmentVariableName];
618
+ if (settingValue == null) {
619
+ throw new LoadSettingError({
620
+ message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.`
621
+ });
622
+ }
623
+ if (typeof settingValue !== "string") {
624
+ throw new LoadSettingError({
625
+ message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
626
+ });
627
+ }
628
+ return settingValue;
629
+ }
630
+
631
+ // src/media-type-to-extension.ts
632
+ function mediaTypeToExtension(mediaType) {
633
+ var _a2;
634
+ const [_type, subtype = ""] = mediaType.toLowerCase().split("/");
635
+ return (_a2 = {
636
+ mpeg: "mp3",
637
+ "x-wav": "wav",
638
+ opus: "ogg",
639
+ mp4: "m4a",
640
+ "x-m4a": "m4a"
641
+ }[subtype]) != null ? _a2 : subtype;
642
+ }
643
+
644
+ // src/parse-json.ts
645
+ import {
646
+ JSONParseError,
647
+ TypeValidationError as TypeValidationError3
648
+ } from "@ai-sdk/provider";
649
+
650
+ // src/secure-json-parse.ts
651
+ var suspectProtoRx = /"__proto__"\s*:/;
652
+ var suspectConstructorRx = /"constructor"\s*:/;
653
+ function _parse(text) {
654
+ const obj = JSON.parse(text);
655
+ if (obj === null || typeof obj !== "object") {
656
+ return obj;
657
+ }
658
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
659
+ return obj;
660
+ }
661
+ return filter(obj);
662
+ }
663
+ function filter(obj) {
664
+ let next = [obj];
665
+ while (next.length) {
666
+ const nodes = next;
667
+ next = [];
668
+ for (const node of nodes) {
669
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
670
+ throw new SyntaxError("Object contains forbidden prototype property");
671
+ }
672
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
673
+ throw new SyntaxError("Object contains forbidden prototype property");
674
+ }
675
+ for (const key in node) {
676
+ const value = node[key];
677
+ if (value && typeof value === "object") {
678
+ next.push(value);
679
+ }
680
+ }
681
+ }
682
+ }
683
+ return obj;
684
+ }
685
+ function secureJsonParse(text) {
686
+ const { stackTraceLimit } = Error;
687
+ try {
688
+ Error.stackTraceLimit = 0;
689
+ } catch (e) {
690
+ return _parse(text);
691
+ }
692
+ try {
693
+ return _parse(text);
694
+ } finally {
695
+ Error.stackTraceLimit = stackTraceLimit;
696
+ }
697
+ }
698
+
699
+ // src/validate-types.ts
700
+ import { TypeValidationError as TypeValidationError2 } from "@ai-sdk/provider";
701
+
702
+ // src/schema.ts
703
+ import { TypeValidationError } from "@ai-sdk/provider";
704
+ import * as z4 from "zod/v4";
705
+
706
+ // src/add-additional-properties-to-json-schema.ts
707
+ function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
708
+ if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
709
+ jsonSchema2.additionalProperties = false;
710
+ const { properties } = jsonSchema2;
711
+ if (properties != null) {
712
+ for (const key of Object.keys(properties)) {
713
+ properties[key] = visit(properties[key]);
714
+ }
715
+ }
716
+ }
717
+ if (jsonSchema2.items != null) {
718
+ jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
719
+ }
720
+ if (jsonSchema2.anyOf != null) {
721
+ jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
722
+ }
723
+ if (jsonSchema2.allOf != null) {
724
+ jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
725
+ }
726
+ if (jsonSchema2.oneOf != null) {
727
+ jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
728
+ }
729
+ const { definitions } = jsonSchema2;
730
+ if (definitions != null) {
731
+ for (const key of Object.keys(definitions)) {
732
+ definitions[key] = visit(definitions[key]);
733
+ }
734
+ }
735
+ return jsonSchema2;
736
+ }
737
+ function visit(def) {
738
+ if (typeof def === "boolean") return def;
739
+ return addAdditionalPropertiesToJsonSchema(def);
740
+ }
741
+
742
+ // src/to-json-schema/zod3-to-json-schema/options.ts
743
+ var ignoreOverride = Symbol(
744
+ "Let zodToJsonSchema decide on which parser to use"
745
+ );
746
+ var defaultOptions = {
747
+ name: void 0,
748
+ $refStrategy: "root",
749
+ basePath: ["#"],
750
+ effectStrategy: "input",
751
+ pipeStrategy: "all",
752
+ dateStrategy: "format:date-time",
753
+ mapStrategy: "entries",
754
+ removeAdditionalStrategy: "passthrough",
755
+ allowedAdditionalProperties: true,
756
+ rejectedAdditionalProperties: false,
757
+ definitionPath: "definitions",
758
+ strictUnions: false,
759
+ definitions: {},
760
+ errorMessages: false,
761
+ patternStrategy: "escape",
762
+ applyRegexFlags: false,
763
+ emailStrategy: "format:email",
764
+ base64Strategy: "contentEncoding:base64",
765
+ nameStrategy: "ref"
766
+ };
767
+ var getDefaultOptions = (options) => typeof options === "string" ? {
768
+ ...defaultOptions,
769
+ name: options
770
+ } : {
771
+ ...defaultOptions,
772
+ ...options
773
+ };
774
+
775
+ // src/to-json-schema/zod3-to-json-schema/select-parser.ts
776
+ import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
777
+
778
+ // src/to-json-schema/zod3-to-json-schema/parsers/any.ts
779
+ function parseAnyDef() {
780
+ return {};
781
+ }
782
+
783
+ // src/to-json-schema/zod3-to-json-schema/parsers/array.ts
784
+ import { ZodFirstPartyTypeKind } from "zod/v3";
785
+ function parseArrayDef(def, refs) {
786
+ var _a2, _b2, _c;
787
+ const res = {
788
+ type: "array"
789
+ };
790
+ if (((_a2 = def.type) == null ? void 0 : _a2._def) && ((_c = (_b2 = def.type) == null ? void 0 : _b2._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
791
+ res.items = parseDef(def.type._def, {
792
+ ...refs,
793
+ currentPath: [...refs.currentPath, "items"]
794
+ });
795
+ }
796
+ if (def.minLength) {
797
+ res.minItems = def.minLength.value;
798
+ }
799
+ if (def.maxLength) {
800
+ res.maxItems = def.maxLength.value;
801
+ }
802
+ if (def.exactLength) {
803
+ res.minItems = def.exactLength.value;
804
+ res.maxItems = def.exactLength.value;
805
+ }
806
+ return res;
807
+ }
808
+
809
+ // src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts
810
+ function parseBigintDef(def) {
811
+ const res = {
812
+ type: "integer",
813
+ format: "int64"
814
+ };
815
+ if (!def.checks) return res;
816
+ for (const check of def.checks) {
817
+ switch (check.kind) {
818
+ case "min":
819
+ if (check.inclusive) {
820
+ res.minimum = check.value;
821
+ } else {
822
+ res.exclusiveMinimum = check.value;
823
+ }
824
+ break;
825
+ case "max":
826
+ if (check.inclusive) {
827
+ res.maximum = check.value;
828
+ } else {
829
+ res.exclusiveMaximum = check.value;
830
+ }
831
+ break;
832
+ case "multipleOf":
833
+ res.multipleOf = check.value;
834
+ break;
835
+ }
836
+ }
837
+ return res;
838
+ }
839
+
840
+ // src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts
841
+ function parseBooleanDef() {
842
+ return { type: "boolean" };
843
+ }
844
+
845
+ // src/to-json-schema/zod3-to-json-schema/parsers/branded.ts
846
+ function parseBrandedDef(_def, refs) {
847
+ return parseDef(_def.type._def, refs);
848
+ }
849
+
850
+ // src/to-json-schema/zod3-to-json-schema/parsers/catch.ts
851
+ var parseCatchDef = (def, refs) => {
852
+ return parseDef(def.innerType._def, refs);
853
+ };
854
+
855
+ // src/to-json-schema/zod3-to-json-schema/parsers/date.ts
856
+ function parseDateDef(def, refs, overrideDateStrategy) {
857
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
858
+ if (Array.isArray(strategy)) {
859
+ return {
860
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
861
+ };
862
+ }
863
+ switch (strategy) {
864
+ case "string":
865
+ case "format:date-time":
866
+ return {
867
+ type: "string",
868
+ format: "date-time"
869
+ };
870
+ case "format:date":
871
+ return {
872
+ type: "string",
873
+ format: "date"
874
+ };
875
+ case "integer":
876
+ return integerDateParser(def);
877
+ }
878
+ }
879
+ var integerDateParser = (def) => {
880
+ const res = {
881
+ type: "integer",
882
+ format: "unix-time"
883
+ };
884
+ for (const check of def.checks) {
885
+ switch (check.kind) {
886
+ case "min":
887
+ res.minimum = check.value;
888
+ break;
889
+ case "max":
890
+ res.maximum = check.value;
891
+ break;
892
+ }
893
+ }
894
+ return res;
895
+ };
896
+
897
+ // src/to-json-schema/zod3-to-json-schema/parsers/default.ts
898
+ function parseDefaultDef(_def, refs) {
899
+ return {
900
+ ...parseDef(_def.innerType._def, refs),
901
+ default: _def.defaultValue()
902
+ };
903
+ }
904
+
905
+ // src/to-json-schema/zod3-to-json-schema/parsers/effects.ts
906
+ function parseEffectsDef(_def, refs) {
907
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
908
+ }
909
+
910
+ // src/to-json-schema/zod3-to-json-schema/parsers/enum.ts
911
+ function parseEnumDef(def) {
912
+ return {
913
+ type: "string",
914
+ enum: Array.from(def.values)
915
+ };
916
+ }
917
+
918
+ // src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts
919
+ var isJsonSchema7AllOfType = (type) => {
920
+ if ("type" in type && type.type === "string") return false;
921
+ return "allOf" in type;
922
+ };
923
+ function parseIntersectionDef(def, refs) {
924
+ const allOf = [
925
+ parseDef(def.left._def, {
926
+ ...refs,
927
+ currentPath: [...refs.currentPath, "allOf", "0"]
928
+ }),
929
+ parseDef(def.right._def, {
930
+ ...refs,
931
+ currentPath: [...refs.currentPath, "allOf", "1"]
932
+ })
933
+ ].filter((x) => !!x);
934
+ const mergedAllOf = [];
935
+ allOf.forEach((schema) => {
936
+ if (isJsonSchema7AllOfType(schema)) {
937
+ mergedAllOf.push(...schema.allOf);
938
+ } else {
939
+ let nestedSchema = schema;
940
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
941
+ const { additionalProperties, ...rest } = schema;
942
+ nestedSchema = rest;
943
+ }
944
+ mergedAllOf.push(nestedSchema);
945
+ }
946
+ });
947
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
948
+ }
949
+
950
+ // src/to-json-schema/zod3-to-json-schema/parsers/literal.ts
951
+ function parseLiteralDef(def) {
952
+ const parsedType = typeof def.value;
953
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
954
+ return {
955
+ type: Array.isArray(def.value) ? "array" : "object"
956
+ };
957
+ }
958
+ return {
959
+ type: parsedType === "bigint" ? "integer" : parsedType,
960
+ const: def.value
961
+ };
962
+ }
963
+
964
+ // src/to-json-schema/zod3-to-json-schema/parsers/record.ts
965
+ import {
966
+ ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2
967
+ } from "zod/v3";
968
+
969
+ // src/to-json-schema/zod3-to-json-schema/parsers/string.ts
970
+ var emojiRegex = void 0;
971
+ var zodPatterns = {
972
+ /**
973
+ * `c` was changed to `[cC]` to replicate /i flag
974
+ */
975
+ cuid: /^[cC][^\s-]{8,}$/,
976
+ cuid2: /^[0-9a-z]+$/,
977
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
978
+ /**
979
+ * `a-z` was added to replicate /i flag
980
+ */
981
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
982
+ /**
983
+ * Constructed a valid Unicode RegExp
984
+ *
985
+ * Lazily instantiate since this type of regex isn't supported
986
+ * in all envs (e.g. React Native).
987
+ *
988
+ * See:
989
+ * https://github.com/colinhacks/zod/issues/2433
990
+ * Fix in Zod:
991
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
992
+ */
993
+ emoji: () => {
994
+ if (emojiRegex === void 0) {
995
+ emojiRegex = RegExp(
996
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
997
+ "u"
998
+ );
999
+ }
1000
+ return emojiRegex;
1001
+ },
1002
+ /**
1003
+ * Unused
1004
+ */
1005
+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
1006
+ /**
1007
+ * Unused
1008
+ */
1009
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
1010
+ ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
1011
+ /**
1012
+ * Unused
1013
+ */
1014
+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
1015
+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
1016
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1017
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1018
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
1019
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1020
+ };
1021
+ function parseStringDef(def, refs) {
1022
+ const res = {
1023
+ type: "string"
1024
+ };
1025
+ if (def.checks) {
1026
+ for (const check of def.checks) {
1027
+ switch (check.kind) {
1028
+ case "min":
1029
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1030
+ break;
1031
+ case "max":
1032
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1033
+ break;
1034
+ case "email":
1035
+ switch (refs.emailStrategy) {
1036
+ case "format:email":
1037
+ addFormat(res, "email", check.message, refs);
1038
+ break;
1039
+ case "format:idn-email":
1040
+ addFormat(res, "idn-email", check.message, refs);
1041
+ break;
1042
+ case "pattern:zod":
1043
+ addPattern(res, zodPatterns.email, check.message, refs);
1044
+ break;
1045
+ }
1046
+ break;
1047
+ case "url":
1048
+ addFormat(res, "uri", check.message, refs);
1049
+ break;
1050
+ case "uuid":
1051
+ addFormat(res, "uuid", check.message, refs);
1052
+ break;
1053
+ case "regex":
1054
+ addPattern(res, check.regex, check.message, refs);
1055
+ break;
1056
+ case "cuid":
1057
+ addPattern(res, zodPatterns.cuid, check.message, refs);
1058
+ break;
1059
+ case "cuid2":
1060
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
1061
+ break;
1062
+ case "startsWith":
1063
+ addPattern(
1064
+ res,
1065
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
1066
+ check.message,
1067
+ refs
1068
+ );
1069
+ break;
1070
+ case "endsWith":
1071
+ addPattern(
1072
+ res,
1073
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
1074
+ check.message,
1075
+ refs
1076
+ );
1077
+ break;
1078
+ case "datetime":
1079
+ addFormat(res, "date-time", check.message, refs);
1080
+ break;
1081
+ case "date":
1082
+ addFormat(res, "date", check.message, refs);
1083
+ break;
1084
+ case "time":
1085
+ addFormat(res, "time", check.message, refs);
1086
+ break;
1087
+ case "duration":
1088
+ addFormat(res, "duration", check.message, refs);
1089
+ break;
1090
+ case "length":
1091
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1092
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1093
+ break;
1094
+ case "includes": {
1095
+ addPattern(
1096
+ res,
1097
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
1098
+ check.message,
1099
+ refs
1100
+ );
1101
+ break;
1102
+ }
1103
+ case "ip": {
1104
+ if (check.version !== "v6") {
1105
+ addFormat(res, "ipv4", check.message, refs);
1106
+ }
1107
+ if (check.version !== "v4") {
1108
+ addFormat(res, "ipv6", check.message, refs);
1109
+ }
1110
+ break;
1111
+ }
1112
+ case "base64url":
1113
+ addPattern(res, zodPatterns.base64url, check.message, refs);
1114
+ break;
1115
+ case "jwt":
1116
+ addPattern(res, zodPatterns.jwt, check.message, refs);
1117
+ break;
1118
+ case "cidr": {
1119
+ if (check.version !== "v6") {
1120
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1121
+ }
1122
+ if (check.version !== "v4") {
1123
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1124
+ }
1125
+ break;
1126
+ }
1127
+ case "emoji":
1128
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
1129
+ break;
1130
+ case "ulid": {
1131
+ addPattern(res, zodPatterns.ulid, check.message, refs);
1132
+ break;
1133
+ }
1134
+ case "base64": {
1135
+ switch (refs.base64Strategy) {
1136
+ case "format:binary": {
1137
+ addFormat(res, "binary", check.message, refs);
1138
+ break;
1139
+ }
1140
+ case "contentEncoding:base64": {
1141
+ res.contentEncoding = "base64";
1142
+ break;
1143
+ }
1144
+ case "pattern:zod": {
1145
+ addPattern(res, zodPatterns.base64, check.message, refs);
1146
+ break;
1147
+ }
1148
+ }
1149
+ break;
1150
+ }
1151
+ case "nanoid": {
1152
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
1153
+ }
1154
+ case "toLowerCase":
1155
+ case "toUpperCase":
1156
+ case "trim":
1157
+ break;
1158
+ default:
1159
+ /* @__PURE__ */ ((_) => {
1160
+ })(check);
1161
+ }
1162
+ }
1163
+ }
1164
+ return res;
1165
+ }
1166
+ function escapeLiteralCheckValue(literal, refs) {
1167
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1168
+ }
1169
+ var ALPHA_NUMERIC = new Set(
1170
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1171
+ );
1172
+ function escapeNonAlphaNumeric(source) {
1173
+ let result = "";
1174
+ for (let i = 0; i < source.length; i++) {
1175
+ if (!ALPHA_NUMERIC.has(source[i])) {
1176
+ result += "\\";
1177
+ }
1178
+ result += source[i];
1179
+ }
1180
+ return result;
1181
+ }
1182
+ function addFormat(schema, value, message, refs) {
1183
+ var _a2;
1184
+ if (schema.format || ((_a2 = schema.anyOf) == null ? void 0 : _a2.some((x) => x.format))) {
1185
+ if (!schema.anyOf) {
1186
+ schema.anyOf = [];
1187
+ }
1188
+ if (schema.format) {
1189
+ schema.anyOf.push({
1190
+ format: schema.format
1191
+ });
1192
+ delete schema.format;
1193
+ }
1194
+ schema.anyOf.push({
1195
+ format: value,
1196
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
1197
+ });
1198
+ } else {
1199
+ schema.format = value;
1200
+ }
1201
+ }
1202
+ function addPattern(schema, regex, message, refs) {
1203
+ var _a2;
1204
+ if (schema.pattern || ((_a2 = schema.allOf) == null ? void 0 : _a2.some((x) => x.pattern))) {
1205
+ if (!schema.allOf) {
1206
+ schema.allOf = [];
1207
+ }
1208
+ if (schema.pattern) {
1209
+ schema.allOf.push({
1210
+ pattern: schema.pattern
1211
+ });
1212
+ delete schema.pattern;
1213
+ }
1214
+ schema.allOf.push({
1215
+ pattern: stringifyRegExpWithFlags(regex, refs),
1216
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
1217
+ });
1218
+ } else {
1219
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
1220
+ }
1221
+ }
1222
+ function stringifyRegExpWithFlags(regex, refs) {
1223
+ var _a2;
1224
+ if (!refs.applyRegexFlags || !regex.flags) {
1225
+ return regex.source;
1226
+ }
1227
+ const flags = {
1228
+ i: regex.flags.includes("i"),
1229
+ // Case-insensitive
1230
+ m: regex.flags.includes("m"),
1231
+ // `^` and `$` matches adjacent to newline characters
1232
+ s: regex.flags.includes("s")
1233
+ // `.` matches newlines
1234
+ };
1235
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1236
+ let pattern = "";
1237
+ let isEscaped = false;
1238
+ let inCharGroup = false;
1239
+ let inCharRange = false;
1240
+ for (let i = 0; i < source.length; i++) {
1241
+ if (isEscaped) {
1242
+ pattern += source[i];
1243
+ isEscaped = false;
1244
+ continue;
1245
+ }
1246
+ if (flags.i) {
1247
+ if (inCharGroup) {
1248
+ if (source[i].match(/[a-z]/)) {
1249
+ if (inCharRange) {
1250
+ pattern += source[i];
1251
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1252
+ inCharRange = false;
1253
+ } else if (source[i + 1] === "-" && ((_a2 = source[i + 2]) == null ? void 0 : _a2.match(/[a-z]/))) {
1254
+ pattern += source[i];
1255
+ inCharRange = true;
1256
+ } else {
1257
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1258
+ }
1259
+ continue;
1260
+ }
1261
+ } else if (source[i].match(/[a-z]/)) {
1262
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1263
+ continue;
1264
+ }
1265
+ }
1266
+ if (flags.m) {
1267
+ if (source[i] === "^") {
1268
+ pattern += `(^|(?<=[\r
1269
+ ]))`;
1270
+ continue;
1271
+ } else if (source[i] === "$") {
1272
+ pattern += `($|(?=[\r
1273
+ ]))`;
1274
+ continue;
1275
+ }
1276
+ }
1277
+ if (flags.s && source[i] === ".") {
1278
+ pattern += inCharGroup ? `${source[i]}\r
1279
+ ` : `[${source[i]}\r
1280
+ ]`;
1281
+ continue;
1282
+ }
1283
+ pattern += source[i];
1284
+ if (source[i] === "\\") {
1285
+ isEscaped = true;
1286
+ } else if (inCharGroup && source[i] === "]") {
1287
+ inCharGroup = false;
1288
+ } else if (!inCharGroup && source[i] === "[") {
1289
+ inCharGroup = true;
1290
+ }
1291
+ }
1292
+ try {
1293
+ new RegExp(pattern);
1294
+ } catch (e) {
1295
+ console.warn(
1296
+ `Could not convert regex pattern at ${refs.currentPath.join(
1297
+ "/"
1298
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1299
+ );
1300
+ return regex.source;
1301
+ }
1302
+ return pattern;
1303
+ }
1304
+
1305
+ // src/to-json-schema/zod3-to-json-schema/parsers/record.ts
1306
+ function parseRecordDef(def, refs) {
1307
+ var _a2, _b2, _c, _d, _e, _f;
1308
+ const schema = {
1309
+ type: "object",
1310
+ additionalProperties: (_a2 = parseDef(def.valueType._def, {
1311
+ ...refs,
1312
+ currentPath: [...refs.currentPath, "additionalProperties"]
1313
+ })) != null ? _a2 : refs.allowedAdditionalProperties
1314
+ };
1315
+ if (((_b2 = def.keyType) == null ? void 0 : _b2._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1316
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1317
+ return {
1318
+ ...schema,
1319
+ propertyNames: keyType
1320
+ };
1321
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1322
+ return {
1323
+ ...schema,
1324
+ propertyNames: {
1325
+ enum: def.keyType._def.values
1326
+ }
1327
+ };
1328
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1329
+ const { type, ...keyType } = parseBrandedDef(
1330
+ def.keyType._def,
1331
+ refs
1332
+ );
1333
+ return {
1334
+ ...schema,
1335
+ propertyNames: keyType
1336
+ };
1337
+ }
1338
+ return schema;
1339
+ }
1340
+
1341
+ // src/to-json-schema/zod3-to-json-schema/parsers/map.ts
1342
+ function parseMapDef(def, refs) {
1343
+ if (refs.mapStrategy === "record") {
1344
+ return parseRecordDef(def, refs);
1345
+ }
1346
+ const keys = parseDef(def.keyType._def, {
1347
+ ...refs,
1348
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1349
+ }) || parseAnyDef();
1350
+ const values = parseDef(def.valueType._def, {
1351
+ ...refs,
1352
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1353
+ }) || parseAnyDef();
1354
+ return {
1355
+ type: "array",
1356
+ maxItems: 125,
1357
+ items: {
1358
+ type: "array",
1359
+ items: [keys, values],
1360
+ minItems: 2,
1361
+ maxItems: 2
1362
+ }
1363
+ };
1364
+ }
1365
+
1366
+ // src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts
1367
+ function parseNativeEnumDef(def) {
1368
+ const object = def.values;
1369
+ const actualKeys = Object.keys(def.values).filter((key) => {
1370
+ return typeof object[object[key]] !== "number";
1371
+ });
1372
+ const actualValues = actualKeys.map((key) => object[key]);
1373
+ const parsedTypes = Array.from(
1374
+ new Set(actualValues.map((values) => typeof values))
1375
+ );
1376
+ return {
1377
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1378
+ enum: actualValues
1379
+ };
1380
+ }
1381
+
1382
+ // src/to-json-schema/zod3-to-json-schema/parsers/never.ts
1383
+ function parseNeverDef() {
1384
+ return { not: parseAnyDef() };
1385
+ }
1386
+
1387
+ // src/to-json-schema/zod3-to-json-schema/parsers/null.ts
1388
+ function parseNullDef() {
1389
+ return {
1390
+ type: "null"
1391
+ };
1392
+ }
1393
+
1394
+ // src/to-json-schema/zod3-to-json-schema/parsers/union.ts
1395
+ var primitiveMappings = {
1396
+ ZodString: "string",
1397
+ ZodNumber: "number",
1398
+ ZodBigInt: "integer",
1399
+ ZodBoolean: "boolean",
1400
+ ZodNull: "null"
1401
+ };
1402
+ function parseUnionDef(def, refs) {
1403
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1404
+ if (options.every(
1405
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1406
+ )) {
1407
+ const types = options.reduce((types2, x) => {
1408
+ const type = primitiveMappings[x._def.typeName];
1409
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1410
+ }, []);
1411
+ return {
1412
+ type: types.length > 1 ? types : types[0]
1413
+ };
1414
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1415
+ const types = options.reduce(
1416
+ (acc, x) => {
1417
+ const type = typeof x._def.value;
1418
+ switch (type) {
1419
+ case "string":
1420
+ case "number":
1421
+ case "boolean":
1422
+ return [...acc, type];
1423
+ case "bigint":
1424
+ return [...acc, "integer"];
1425
+ case "object":
1426
+ if (x._def.value === null) return [...acc, "null"];
1427
+ case "symbol":
1428
+ case "undefined":
1429
+ case "function":
1430
+ default:
1431
+ return acc;
1432
+ }
1433
+ },
1434
+ []
1435
+ );
1436
+ if (types.length === options.length) {
1437
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1438
+ return {
1439
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1440
+ enum: options.reduce(
1441
+ (acc, x) => {
1442
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1443
+ },
1444
+ []
1445
+ )
1446
+ };
1447
+ }
1448
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1449
+ return {
1450
+ type: "string",
1451
+ enum: options.reduce(
1452
+ (acc, x) => [
1453
+ ...acc,
1454
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1455
+ ],
1456
+ []
1457
+ )
1458
+ };
1459
+ }
1460
+ return asAnyOf(def, refs);
1461
+ }
1462
+ var asAnyOf = (def, refs) => {
1463
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1464
+ (x, i) => parseDef(x._def, {
1465
+ ...refs,
1466
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1467
+ })
1468
+ ).filter(
1469
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1470
+ );
1471
+ return anyOf.length ? { anyOf } : void 0;
1472
+ };
1473
+
1474
+ // src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts
1475
+ function parseNullableDef(def, refs) {
1476
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1477
+ def.innerType._def.typeName
1478
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1479
+ return {
1480
+ type: [
1481
+ primitiveMappings[def.innerType._def.typeName],
1482
+ "null"
1483
+ ]
1484
+ };
1485
+ }
1486
+ const base = parseDef(def.innerType._def, {
1487
+ ...refs,
1488
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1489
+ });
1490
+ return base && { anyOf: [base, { type: "null" }] };
1491
+ }
1492
+
1493
+ // src/to-json-schema/zod3-to-json-schema/parsers/number.ts
1494
+ function parseNumberDef(def) {
1495
+ const res = {
1496
+ type: "number"
1497
+ };
1498
+ if (!def.checks) return res;
1499
+ for (const check of def.checks) {
1500
+ switch (check.kind) {
1501
+ case "int":
1502
+ res.type = "integer";
1503
+ break;
1504
+ case "min":
1505
+ if (check.inclusive) {
1506
+ res.minimum = check.value;
1507
+ } else {
1508
+ res.exclusiveMinimum = check.value;
1509
+ }
1510
+ break;
1511
+ case "max":
1512
+ if (check.inclusive) {
1513
+ res.maximum = check.value;
1514
+ } else {
1515
+ res.exclusiveMaximum = check.value;
1516
+ }
1517
+ break;
1518
+ case "multipleOf":
1519
+ res.multipleOf = check.value;
1520
+ break;
1521
+ }
1522
+ }
1523
+ return res;
1524
+ }
1525
+
1526
+ // src/to-json-schema/zod3-to-json-schema/parsers/object.ts
1527
+ function parseObjectDef(def, refs) {
1528
+ const result = {
1529
+ type: "object",
1530
+ properties: {}
1531
+ };
1532
+ const required = [];
1533
+ const shape = def.shape();
1534
+ for (const propName in shape) {
1535
+ let propDef = shape[propName];
1536
+ if (propDef === void 0 || propDef._def === void 0) {
1537
+ continue;
1538
+ }
1539
+ const propOptional = safeIsOptional(propDef);
1540
+ const parsedDef = parseDef(propDef._def, {
1541
+ ...refs,
1542
+ currentPath: [...refs.currentPath, "properties", propName],
1543
+ propertyPath: [...refs.currentPath, "properties", propName]
1544
+ });
1545
+ if (parsedDef === void 0) {
1546
+ continue;
1547
+ }
1548
+ result.properties[propName] = parsedDef;
1549
+ if (!propOptional) {
1550
+ required.push(propName);
1551
+ }
1552
+ }
1553
+ if (required.length) {
1554
+ result.required = required;
1555
+ }
1556
+ const additionalProperties = decideAdditionalProperties(def, refs);
1557
+ if (additionalProperties !== void 0) {
1558
+ result.additionalProperties = additionalProperties;
1559
+ }
1560
+ return result;
1561
+ }
1562
+ function decideAdditionalProperties(def, refs) {
1563
+ if (def.catchall._def.typeName !== "ZodNever") {
1564
+ return parseDef(def.catchall._def, {
1565
+ ...refs,
1566
+ currentPath: [...refs.currentPath, "additionalProperties"]
1567
+ });
1568
+ }
1569
+ switch (def.unknownKeys) {
1570
+ case "passthrough":
1571
+ return refs.allowedAdditionalProperties;
1572
+ case "strict":
1573
+ return refs.rejectedAdditionalProperties;
1574
+ case "strip":
1575
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1576
+ }
1577
+ }
1578
+ function safeIsOptional(schema) {
1579
+ try {
1580
+ return schema.isOptional();
1581
+ } catch (e) {
1582
+ return true;
1583
+ }
1584
+ }
1585
+
1586
+ // src/to-json-schema/zod3-to-json-schema/parsers/optional.ts
1587
+ var parseOptionalDef = (def, refs) => {
1588
+ var _a2;
1589
+ if (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? void 0 : _a2.toString())) {
1590
+ return parseDef(def.innerType._def, refs);
1591
+ }
1592
+ const innerSchema = parseDef(def.innerType._def, {
1593
+ ...refs,
1594
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1595
+ });
1596
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1597
+ };
1598
+
1599
+ // src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts
1600
+ var parsePipelineDef = (def, refs) => {
1601
+ if (refs.pipeStrategy === "input") {
1602
+ return parseDef(def.in._def, refs);
1603
+ } else if (refs.pipeStrategy === "output") {
1604
+ return parseDef(def.out._def, refs);
1605
+ }
1606
+ const a = parseDef(def.in._def, {
1607
+ ...refs,
1608
+ currentPath: [...refs.currentPath, "allOf", "0"]
1609
+ });
1610
+ const b = parseDef(def.out._def, {
1611
+ ...refs,
1612
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1613
+ });
1614
+ return {
1615
+ allOf: [a, b].filter((x) => x !== void 0)
1616
+ };
1617
+ };
1618
+
1619
+ // src/to-json-schema/zod3-to-json-schema/parsers/promise.ts
1620
+ function parsePromiseDef(def, refs) {
1621
+ return parseDef(def.type._def, refs);
1622
+ }
1623
+
1624
+ // src/to-json-schema/zod3-to-json-schema/parsers/set.ts
1625
+ function parseSetDef(def, refs) {
1626
+ const items = parseDef(def.valueType._def, {
1627
+ ...refs,
1628
+ currentPath: [...refs.currentPath, "items"]
1629
+ });
1630
+ const schema = {
1631
+ type: "array",
1632
+ uniqueItems: true,
1633
+ items
1634
+ };
1635
+ if (def.minSize) {
1636
+ schema.minItems = def.minSize.value;
1637
+ }
1638
+ if (def.maxSize) {
1639
+ schema.maxItems = def.maxSize.value;
1640
+ }
1641
+ return schema;
1642
+ }
1643
+
1644
+ // src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts
1645
+ function parseTupleDef(def, refs) {
1646
+ if (def.rest) {
1647
+ return {
1648
+ type: "array",
1649
+ minItems: def.items.length,
1650
+ items: def.items.map(
1651
+ (x, i) => parseDef(x._def, {
1652
+ ...refs,
1653
+ currentPath: [...refs.currentPath, "items", `${i}`]
1654
+ })
1655
+ ).reduce(
1656
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1657
+ []
1658
+ ),
1659
+ additionalItems: parseDef(def.rest._def, {
1660
+ ...refs,
1661
+ currentPath: [...refs.currentPath, "additionalItems"]
1662
+ })
1663
+ };
1664
+ } else {
1665
+ return {
1666
+ type: "array",
1667
+ minItems: def.items.length,
1668
+ maxItems: def.items.length,
1669
+ items: def.items.map(
1670
+ (x, i) => parseDef(x._def, {
1671
+ ...refs,
1672
+ currentPath: [...refs.currentPath, "items", `${i}`]
1673
+ })
1674
+ ).reduce(
1675
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1676
+ []
1677
+ )
1678
+ };
1679
+ }
1680
+ }
1681
+
1682
+ // src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts
1683
+ function parseUndefinedDef() {
1684
+ return {
1685
+ not: parseAnyDef()
1686
+ };
1687
+ }
1688
+
1689
+ // src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts
1690
+ function parseUnknownDef() {
1691
+ return parseAnyDef();
1692
+ }
1693
+
1694
+ // src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts
1695
+ var parseReadonlyDef = (def, refs) => {
1696
+ return parseDef(def.innerType._def, refs);
1697
+ };
1698
+
1699
+ // src/to-json-schema/zod3-to-json-schema/select-parser.ts
1700
+ var selectParser = (def, typeName, refs) => {
1701
+ switch (typeName) {
1702
+ case ZodFirstPartyTypeKind3.ZodString:
1703
+ return parseStringDef(def, refs);
1704
+ case ZodFirstPartyTypeKind3.ZodNumber:
1705
+ return parseNumberDef(def);
1706
+ case ZodFirstPartyTypeKind3.ZodObject:
1707
+ return parseObjectDef(def, refs);
1708
+ case ZodFirstPartyTypeKind3.ZodBigInt:
1709
+ return parseBigintDef(def);
1710
+ case ZodFirstPartyTypeKind3.ZodBoolean:
1711
+ return parseBooleanDef();
1712
+ case ZodFirstPartyTypeKind3.ZodDate:
1713
+ return parseDateDef(def, refs);
1714
+ case ZodFirstPartyTypeKind3.ZodUndefined:
1715
+ return parseUndefinedDef();
1716
+ case ZodFirstPartyTypeKind3.ZodNull:
1717
+ return parseNullDef();
1718
+ case ZodFirstPartyTypeKind3.ZodArray:
1719
+ return parseArrayDef(def, refs);
1720
+ case ZodFirstPartyTypeKind3.ZodUnion:
1721
+ case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1722
+ return parseUnionDef(def, refs);
1723
+ case ZodFirstPartyTypeKind3.ZodIntersection:
1724
+ return parseIntersectionDef(def, refs);
1725
+ case ZodFirstPartyTypeKind3.ZodTuple:
1726
+ return parseTupleDef(def, refs);
1727
+ case ZodFirstPartyTypeKind3.ZodRecord:
1728
+ return parseRecordDef(def, refs);
1729
+ case ZodFirstPartyTypeKind3.ZodLiteral:
1730
+ return parseLiteralDef(def);
1731
+ case ZodFirstPartyTypeKind3.ZodEnum:
1732
+ return parseEnumDef(def);
1733
+ case ZodFirstPartyTypeKind3.ZodNativeEnum:
1734
+ return parseNativeEnumDef(def);
1735
+ case ZodFirstPartyTypeKind3.ZodNullable:
1736
+ return parseNullableDef(def, refs);
1737
+ case ZodFirstPartyTypeKind3.ZodOptional:
1738
+ return parseOptionalDef(def, refs);
1739
+ case ZodFirstPartyTypeKind3.ZodMap:
1740
+ return parseMapDef(def, refs);
1741
+ case ZodFirstPartyTypeKind3.ZodSet:
1742
+ return parseSetDef(def, refs);
1743
+ case ZodFirstPartyTypeKind3.ZodLazy:
1744
+ return () => def.getter()._def;
1745
+ case ZodFirstPartyTypeKind3.ZodPromise:
1746
+ return parsePromiseDef(def, refs);
1747
+ case ZodFirstPartyTypeKind3.ZodNaN:
1748
+ case ZodFirstPartyTypeKind3.ZodNever:
1749
+ return parseNeverDef();
1750
+ case ZodFirstPartyTypeKind3.ZodEffects:
1751
+ return parseEffectsDef(def, refs);
1752
+ case ZodFirstPartyTypeKind3.ZodAny:
1753
+ return parseAnyDef();
1754
+ case ZodFirstPartyTypeKind3.ZodUnknown:
1755
+ return parseUnknownDef();
1756
+ case ZodFirstPartyTypeKind3.ZodDefault:
1757
+ return parseDefaultDef(def, refs);
1758
+ case ZodFirstPartyTypeKind3.ZodBranded:
1759
+ return parseBrandedDef(def, refs);
1760
+ case ZodFirstPartyTypeKind3.ZodReadonly:
1761
+ return parseReadonlyDef(def, refs);
1762
+ case ZodFirstPartyTypeKind3.ZodCatch:
1763
+ return parseCatchDef(def, refs);
1764
+ case ZodFirstPartyTypeKind3.ZodPipeline:
1765
+ return parsePipelineDef(def, refs);
1766
+ case ZodFirstPartyTypeKind3.ZodFunction:
1767
+ case ZodFirstPartyTypeKind3.ZodVoid:
1768
+ case ZodFirstPartyTypeKind3.ZodSymbol:
1769
+ return void 0;
1770
+ default:
1771
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
1772
+ }
1773
+ };
1774
+
1775
+ // src/to-json-schema/zod3-to-json-schema/get-relative-path.ts
1776
+ var getRelativePath = (pathA, pathB) => {
1777
+ let i = 0;
1778
+ for (; i < pathA.length && i < pathB.length; i++) {
1779
+ if (pathA[i] !== pathB[i]) break;
1780
+ }
1781
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1782
+ };
1783
+
1784
+ // src/to-json-schema/zod3-to-json-schema/parse-def.ts
1785
+ function parseDef(def, refs, forceResolution = false) {
1786
+ var _a2;
1787
+ const seenItem = refs.seen.get(def);
1788
+ if (refs.override) {
1789
+ const overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.call(
1790
+ refs,
1791
+ def,
1792
+ refs,
1793
+ seenItem,
1794
+ forceResolution
1795
+ );
1796
+ if (overrideResult !== ignoreOverride) {
1797
+ return overrideResult;
1798
+ }
1799
+ }
1800
+ if (seenItem && !forceResolution) {
1801
+ const seenSchema = get$ref(seenItem, refs);
1802
+ if (seenSchema !== void 0) {
1803
+ return seenSchema;
1804
+ }
1805
+ }
1806
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1807
+ refs.seen.set(def, newItem);
1808
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1809
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1810
+ if (jsonSchema2) {
1811
+ addMeta(def, refs, jsonSchema2);
1812
+ }
1813
+ if (refs.postProcess) {
1814
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1815
+ newItem.jsonSchema = jsonSchema2;
1816
+ return postProcessResult;
1817
+ }
1818
+ newItem.jsonSchema = jsonSchema2;
1819
+ return jsonSchema2;
1820
+ }
1821
+ var get$ref = (item, refs) => {
1822
+ switch (refs.$refStrategy) {
1823
+ case "root":
1824
+ return { $ref: item.path.join("/") };
1825
+ case "relative":
1826
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1827
+ case "none":
1828
+ case "seen": {
1829
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1830
+ console.warn(
1831
+ `Recursive reference detected at ${refs.currentPath.join(
1832
+ "/"
1833
+ )}! Defaulting to any`
1834
+ );
1835
+ return parseAnyDef();
1836
+ }
1837
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1838
+ }
1839
+ }
1840
+ };
1841
+ var addMeta = (def, refs, jsonSchema2) => {
1842
+ if (def.description) {
1843
+ jsonSchema2.description = def.description;
1844
+ }
1845
+ return jsonSchema2;
1846
+ };
1847
+
1848
+ // src/to-json-schema/zod3-to-json-schema/refs.ts
1849
+ var getRefs = (options) => {
1850
+ const _options = getDefaultOptions(options);
1851
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1852
+ return {
1853
+ ..._options,
1854
+ currentPath,
1855
+ propertyPath: void 0,
1856
+ seen: new Map(
1857
+ Object.entries(_options.definitions).map(([name2, def]) => [
1858
+ def._def,
1859
+ {
1860
+ def: def._def,
1861
+ path: [..._options.basePath, _options.definitionPath, name2],
1862
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1863
+ jsonSchema: void 0
1864
+ }
1865
+ ])
1866
+ )
1867
+ };
1868
+ };
1869
+
1870
+ // src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts
1871
+ var zod3ToJsonSchema = (schema, options) => {
1872
+ var _a2;
1873
+ const refs = getRefs(options);
1874
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1875
+ (acc, [name3, schema2]) => {
1876
+ var _a3;
1877
+ return {
1878
+ ...acc,
1879
+ [name3]: (_a3 = parseDef(
1880
+ schema2._def,
1881
+ {
1882
+ ...refs,
1883
+ currentPath: [...refs.basePath, refs.definitionPath, name3]
1884
+ },
1885
+ true
1886
+ )) != null ? _a3 : parseAnyDef()
1887
+ };
1888
+ },
1889
+ {}
1890
+ ) : void 0;
1891
+ const name2 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1892
+ const main = (_a2 = parseDef(
1893
+ schema._def,
1894
+ name2 === void 0 ? refs : {
1895
+ ...refs,
1896
+ currentPath: [...refs.basePath, refs.definitionPath, name2]
1897
+ },
1898
+ false
1899
+ )) != null ? _a2 : parseAnyDef();
1900
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1901
+ if (title !== void 0) {
1902
+ main.title = title;
1903
+ }
1904
+ const combined = name2 === void 0 ? definitions ? {
1905
+ ...main,
1906
+ [refs.definitionPath]: definitions
1907
+ } : main : {
1908
+ $ref: [
1909
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1910
+ refs.definitionPath,
1911
+ name2
1912
+ ].join("/"),
1913
+ [refs.definitionPath]: {
1914
+ ...definitions,
1915
+ [name2]: main
1916
+ }
1917
+ };
1918
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1919
+ return combined;
1920
+ };
1921
+
1922
+ // src/schema.ts
1923
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
1924
+ function lazySchema(createSchema) {
1925
+ let schema;
1926
+ return () => {
1927
+ if (schema == null) {
1928
+ schema = createSchema();
1929
+ }
1930
+ return schema;
1931
+ };
1932
+ }
1933
+ function jsonSchema(jsonSchema2, {
1934
+ validate
1935
+ } = {}) {
1936
+ return {
1937
+ [schemaSymbol]: true,
1938
+ _type: void 0,
1939
+ // should never be used directly
1940
+ get jsonSchema() {
1941
+ if (typeof jsonSchema2 === "function") {
1942
+ jsonSchema2 = jsonSchema2();
1943
+ }
1944
+ return jsonSchema2;
1945
+ },
1946
+ validate
1947
+ };
1948
+ }
1949
+ function isSchema(value) {
1950
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
1951
+ }
1952
+ function asSchema(schema) {
1953
+ return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
1954
+ }
1955
+ function standardSchema(standardSchema2) {
1956
+ return jsonSchema(
1957
+ () => addAdditionalPropertiesToJsonSchema(
1958
+ standardSchema2["~standard"].jsonSchema.input({
1959
+ target: "draft-07"
1960
+ })
1961
+ ),
1962
+ {
1963
+ validate: async (value) => {
1964
+ const result = await standardSchema2["~standard"].validate(value);
1965
+ return "value" in result ? { success: true, value: result.value } : {
1966
+ success: false,
1967
+ error: new TypeValidationError({
1968
+ value,
1969
+ cause: result.issues
1970
+ })
1971
+ };
1972
+ }
1973
+ }
1974
+ );
1975
+ }
1976
+ function zod3Schema(zodSchema2, options) {
1977
+ var _a2;
1978
+ const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
1979
+ return jsonSchema(
1980
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1981
+ () => zod3ToJsonSchema(zodSchema2, {
1982
+ $refStrategy: useReferences ? "root" : "none"
1983
+ }),
1984
+ {
1985
+ validate: async (value) => {
1986
+ const result = await zodSchema2.safeParseAsync(value);
1987
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1988
+ }
1989
+ }
1990
+ );
1991
+ }
1992
+ function zod4Schema(zodSchema2, options) {
1993
+ var _a2;
1994
+ const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
1995
+ return jsonSchema(
1996
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1997
+ () => addAdditionalPropertiesToJsonSchema(
1998
+ z4.toJSONSchema(zodSchema2, {
1999
+ target: "draft-7",
2000
+ io: "input",
2001
+ reused: useReferences ? "ref" : "inline"
2002
+ })
2003
+ ),
2004
+ {
2005
+ validate: async (value) => {
2006
+ const result = await z4.safeParseAsync(zodSchema2, value);
2007
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2008
+ }
2009
+ }
2010
+ );
2011
+ }
2012
+ function isZod4Schema(zodSchema2) {
2013
+ return "_zod" in zodSchema2;
2014
+ }
2015
+ function zodSchema(zodSchema2, options) {
2016
+ if (isZod4Schema(zodSchema2)) {
2017
+ return zod4Schema(zodSchema2, options);
2018
+ } else {
2019
+ return zod3Schema(zodSchema2, options);
2020
+ }
2021
+ }
2022
+
2023
+ // src/validate-types.ts
2024
+ async function validateTypes({
2025
+ value,
2026
+ schema,
2027
+ context
2028
+ }) {
2029
+ const result = await safeValidateTypes({ value, schema, context });
2030
+ if (!result.success) {
2031
+ throw TypeValidationError2.wrap({ value, cause: result.error, context });
2032
+ }
2033
+ return result.value;
2034
+ }
2035
+ async function safeValidateTypes({
2036
+ value,
2037
+ schema,
2038
+ context
2039
+ }) {
2040
+ const actualSchema = asSchema(schema);
2041
+ try {
2042
+ if (actualSchema.validate == null) {
2043
+ return { success: true, value, rawValue: value };
2044
+ }
2045
+ const result = await actualSchema.validate(value);
2046
+ if (result.success) {
2047
+ return { success: true, value: result.value, rawValue: value };
2048
+ }
2049
+ return {
2050
+ success: false,
2051
+ error: TypeValidationError2.wrap({ value, cause: result.error, context }),
2052
+ rawValue: value
2053
+ };
2054
+ } catch (error) {
2055
+ return {
2056
+ success: false,
2057
+ error: TypeValidationError2.wrap({ value, cause: error, context }),
2058
+ rawValue: value
2059
+ };
2060
+ }
2061
+ }
2062
+
2063
+ // src/parse-json.ts
2064
+ async function parseJSON({
2065
+ text,
2066
+ schema
2067
+ }) {
2068
+ try {
2069
+ const value = secureJsonParse(text);
2070
+ if (schema == null) {
2071
+ return value;
2072
+ }
2073
+ return validateTypes({ value, schema });
2074
+ } catch (error) {
2075
+ if (JSONParseError.isInstance(error) || TypeValidationError3.isInstance(error)) {
2076
+ throw error;
2077
+ }
2078
+ throw new JSONParseError({ text, cause: error });
2079
+ }
2080
+ }
2081
+ async function safeParseJSON({
2082
+ text,
2083
+ schema
2084
+ }) {
2085
+ try {
2086
+ const value = secureJsonParse(text);
2087
+ if (schema == null) {
2088
+ return { success: true, value, rawValue: value };
2089
+ }
2090
+ return await safeValidateTypes({ value, schema });
2091
+ } catch (error) {
2092
+ return {
2093
+ success: false,
2094
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
2095
+ rawValue: void 0
2096
+ };
2097
+ }
2098
+ }
2099
+ function isParsableJson(input) {
2100
+ try {
2101
+ secureJsonParse(input);
2102
+ return true;
2103
+ } catch (e) {
2104
+ return false;
2105
+ }
2106
+ }
2107
+
2108
+ // src/parse-json-event-stream.ts
2109
+ import {
2110
+ EventSourceParserStream
2111
+ } from "eventsource-parser/stream";
2112
+ function parseJsonEventStream({
2113
+ stream,
2114
+ schema
2115
+ }) {
2116
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
2117
+ new TransformStream({
2118
+ async transform({ data }, controller) {
2119
+ if (data === "[DONE]") {
2120
+ return;
2121
+ }
2122
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
2123
+ }
2124
+ })
2125
+ );
2126
+ }
2127
+
2128
+ // src/parse-provider-options.ts
2129
+ import { InvalidArgumentError as InvalidArgumentError2 } from "@ai-sdk/provider";
2130
+ async function parseProviderOptions({
2131
+ provider,
2132
+ providerOptions,
2133
+ schema
2134
+ }) {
2135
+ if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
2136
+ return void 0;
2137
+ }
2138
+ const parsedProviderOptions = await safeValidateTypes({
2139
+ value: providerOptions[provider],
2140
+ schema
2141
+ });
2142
+ if (!parsedProviderOptions.success) {
2143
+ throw new InvalidArgumentError2({
2144
+ argument: "providerOptions",
2145
+ message: `invalid ${provider} provider options`,
2146
+ cause: parsedProviderOptions.error
2147
+ });
2148
+ }
2149
+ return parsedProviderOptions.value;
2150
+ }
2151
+
2152
+ // src/post-to-api.ts
2153
+ import { APICallError as APICallError3 } from "@ai-sdk/provider";
2154
+ var getOriginalFetch2 = () => globalThis.fetch;
2155
+ var postJsonToApi = async ({
2156
+ url,
2157
+ headers,
2158
+ body,
2159
+ failedResponseHandler,
2160
+ successfulResponseHandler,
2161
+ abortSignal,
2162
+ fetch: fetch2
2163
+ }) => postToApi({
2164
+ url,
2165
+ headers: {
2166
+ "Content-Type": "application/json",
2167
+ ...headers
2168
+ },
2169
+ body: {
2170
+ content: JSON.stringify(body),
2171
+ values: body
2172
+ },
2173
+ failedResponseHandler,
2174
+ successfulResponseHandler,
2175
+ abortSignal,
2176
+ fetch: fetch2
2177
+ });
2178
+ var postFormDataToApi = async ({
2179
+ url,
2180
+ headers,
2181
+ formData,
2182
+ failedResponseHandler,
2183
+ successfulResponseHandler,
2184
+ abortSignal,
2185
+ fetch: fetch2
2186
+ }) => postToApi({
2187
+ url,
2188
+ headers,
2189
+ body: {
2190
+ content: formData,
2191
+ values: Object.fromEntries(formData.entries())
2192
+ },
2193
+ failedResponseHandler,
2194
+ successfulResponseHandler,
2195
+ abortSignal,
2196
+ fetch: fetch2
2197
+ });
2198
+ var postToApi = async ({
2199
+ url,
2200
+ headers = {},
2201
+ body,
2202
+ successfulResponseHandler,
2203
+ failedResponseHandler,
2204
+ abortSignal,
2205
+ fetch: fetch2 = getOriginalFetch2()
2206
+ }) => {
2207
+ try {
2208
+ const response = await fetch2(url, {
2209
+ method: "POST",
2210
+ headers: withUserAgentSuffix(
2211
+ headers,
2212
+ `ai-sdk/provider-utils/${VERSION}`,
2213
+ getRuntimeEnvironmentUserAgent()
2214
+ ),
2215
+ body: body.content,
2216
+ signal: abortSignal
2217
+ });
2218
+ const responseHeaders = extractResponseHeaders(response);
2219
+ if (!response.ok) {
2220
+ let errorInformation;
2221
+ try {
2222
+ errorInformation = await failedResponseHandler({
2223
+ response,
2224
+ url,
2225
+ requestBodyValues: body.values
2226
+ });
2227
+ } catch (error) {
2228
+ if (isAbortError(error) || APICallError3.isInstance(error)) {
2229
+ throw error;
2230
+ }
2231
+ throw new APICallError3({
2232
+ message: "Failed to process error response",
2233
+ cause: error,
2234
+ statusCode: response.status,
2235
+ url,
2236
+ responseHeaders,
2237
+ requestBodyValues: body.values
2238
+ });
2239
+ }
2240
+ throw errorInformation.value;
2241
+ }
2242
+ try {
2243
+ return await successfulResponseHandler({
2244
+ response,
2245
+ url,
2246
+ requestBodyValues: body.values
2247
+ });
2248
+ } catch (error) {
2249
+ if (error instanceof Error) {
2250
+ if (isAbortError(error) || APICallError3.isInstance(error)) {
2251
+ throw error;
2252
+ }
2253
+ }
2254
+ throw new APICallError3({
2255
+ message: "Failed to process successful response",
2256
+ cause: error,
2257
+ statusCode: response.status,
2258
+ url,
2259
+ responseHeaders,
2260
+ requestBodyValues: body.values
2261
+ });
2262
+ }
2263
+ } catch (error) {
2264
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
2265
+ }
2266
+ };
2267
+
2268
+ // src/types/tool.ts
2269
+ function tool(tool2) {
2270
+ return tool2;
2271
+ }
2272
+ function dynamicTool(tool2) {
2273
+ return { ...tool2, type: "dynamic" };
2274
+ }
2275
+
2276
+ // src/provider-tool-factory.ts
2277
+ function createProviderToolFactory({
2278
+ id,
2279
+ inputSchema
2280
+ }) {
2281
+ return ({
2282
+ execute,
2283
+ outputSchema,
2284
+ needsApproval,
2285
+ toModelOutput,
2286
+ onInputStart,
2287
+ onInputDelta,
2288
+ onInputAvailable,
2289
+ ...args
2290
+ }) => tool({
2291
+ type: "provider",
2292
+ id,
2293
+ args,
2294
+ inputSchema,
2295
+ outputSchema,
2296
+ execute,
2297
+ needsApproval,
2298
+ toModelOutput,
2299
+ onInputStart,
2300
+ onInputDelta,
2301
+ onInputAvailable
2302
+ });
2303
+ }
2304
+ function createProviderToolFactoryWithOutputSchema({
2305
+ id,
2306
+ inputSchema,
2307
+ outputSchema,
2308
+ supportsDeferredResults
2309
+ }) {
2310
+ return ({
2311
+ execute,
2312
+ needsApproval,
2313
+ toModelOutput,
2314
+ onInputStart,
2315
+ onInputDelta,
2316
+ onInputAvailable,
2317
+ ...args
2318
+ }) => tool({
2319
+ type: "provider",
2320
+ id,
2321
+ args,
2322
+ inputSchema,
2323
+ outputSchema,
2324
+ execute,
2325
+ needsApproval,
2326
+ toModelOutput,
2327
+ onInputStart,
2328
+ onInputDelta,
2329
+ onInputAvailable,
2330
+ supportsDeferredResults
2331
+ });
2332
+ }
2333
+
2334
+ // src/remove-undefined-entries.ts
2335
+ function removeUndefinedEntries(record) {
2336
+ return Object.fromEntries(
2337
+ Object.entries(record).filter(([_key, value]) => value != null)
2338
+ );
2339
+ }
2340
+
2341
+ // src/resolve.ts
2342
+ async function resolve(value) {
2343
+ if (typeof value === "function") {
2344
+ value = value();
2345
+ }
2346
+ return Promise.resolve(value);
2347
+ }
2348
+
2349
+ // src/response-handler.ts
2350
+ import { APICallError as APICallError4, EmptyResponseBodyError } from "@ai-sdk/provider";
2351
+ var createJsonErrorResponseHandler = ({
2352
+ errorSchema,
2353
+ errorToMessage,
2354
+ isRetryable
2355
+ }) => async ({ response, url, requestBodyValues }) => {
2356
+ const responseBody = await response.text();
2357
+ const responseHeaders = extractResponseHeaders(response);
2358
+ if (responseBody.trim() === "") {
2359
+ return {
2360
+ responseHeaders,
2361
+ value: new APICallError4({
2362
+ message: response.statusText,
2363
+ url,
2364
+ requestBodyValues,
2365
+ statusCode: response.status,
2366
+ responseHeaders,
2367
+ responseBody,
2368
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
2369
+ })
2370
+ };
2371
+ }
2372
+ try {
2373
+ const parsedError = await parseJSON({
2374
+ text: responseBody,
2375
+ schema: errorSchema
2376
+ });
2377
+ return {
2378
+ responseHeaders,
2379
+ value: new APICallError4({
2380
+ message: errorToMessage(parsedError),
2381
+ url,
2382
+ requestBodyValues,
2383
+ statusCode: response.status,
2384
+ responseHeaders,
2385
+ responseBody,
2386
+ data: parsedError,
2387
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
2388
+ })
2389
+ };
2390
+ } catch (parseError) {
2391
+ return {
2392
+ responseHeaders,
2393
+ value: new APICallError4({
2394
+ message: response.statusText,
2395
+ url,
2396
+ requestBodyValues,
2397
+ statusCode: response.status,
2398
+ responseHeaders,
2399
+ responseBody,
2400
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
2401
+ })
2402
+ };
2403
+ }
2404
+ };
2405
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
2406
+ const responseHeaders = extractResponseHeaders(response);
2407
+ if (response.body == null) {
2408
+ throw new EmptyResponseBodyError({});
2409
+ }
2410
+ return {
2411
+ responseHeaders,
2412
+ value: parseJsonEventStream({
2413
+ stream: response.body,
2414
+ schema: chunkSchema
2415
+ })
2416
+ };
2417
+ };
2418
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
2419
+ const responseBody = await response.text();
2420
+ const parsedResult = await safeParseJSON({
2421
+ text: responseBody,
2422
+ schema: responseSchema
2423
+ });
2424
+ const responseHeaders = extractResponseHeaders(response);
2425
+ if (!parsedResult.success) {
2426
+ throw new APICallError4({
2427
+ message: "Invalid JSON response",
2428
+ cause: parsedResult.error,
2429
+ statusCode: response.status,
2430
+ responseHeaders,
2431
+ responseBody,
2432
+ url,
2433
+ requestBodyValues
2434
+ });
2435
+ }
2436
+ return {
2437
+ responseHeaders,
2438
+ value: parsedResult.value,
2439
+ rawValue: parsedResult.rawValue
2440
+ };
2441
+ };
2442
+ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
2443
+ const responseHeaders = extractResponseHeaders(response);
2444
+ if (!response.body) {
2445
+ throw new APICallError4({
2446
+ message: "Response body is empty",
2447
+ url,
2448
+ requestBodyValues,
2449
+ statusCode: response.status,
2450
+ responseHeaders,
2451
+ responseBody: void 0
2452
+ });
2453
+ }
2454
+ try {
2455
+ const buffer = await response.arrayBuffer();
2456
+ return {
2457
+ responseHeaders,
2458
+ value: new Uint8Array(buffer)
2459
+ };
2460
+ } catch (error) {
2461
+ throw new APICallError4({
2462
+ message: "Failed to read response as array buffer",
2463
+ url,
2464
+ requestBodyValues,
2465
+ statusCode: response.status,
2466
+ responseHeaders,
2467
+ responseBody: void 0,
2468
+ cause: error
2469
+ });
2470
+ }
2471
+ };
2472
+ var createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {
2473
+ const responseHeaders = extractResponseHeaders(response);
2474
+ const responseBody = await response.text();
2475
+ return {
2476
+ responseHeaders,
2477
+ value: new APICallError4({
2478
+ message: response.statusText,
2479
+ url,
2480
+ requestBodyValues,
2481
+ statusCode: response.status,
2482
+ responseHeaders,
2483
+ responseBody
2484
+ })
2485
+ };
2486
+ };
2487
+
2488
+ // src/without-trailing-slash.ts
2489
+ function withoutTrailingSlash(url) {
2490
+ return url == null ? void 0 : url.replace(/\/$/, "");
2491
+ }
2492
+
2493
+ // src/is-async-iterable.ts
2494
+ function isAsyncIterable(obj) {
2495
+ return obj != null && typeof obj[Symbol.asyncIterator] === "function";
2496
+ }
2497
+
2498
+ // src/types/execute-tool.ts
2499
+ async function* executeTool({
2500
+ execute,
2501
+ input,
2502
+ options
2503
+ }) {
2504
+ const result = execute(input, options);
2505
+ if (isAsyncIterable(result)) {
2506
+ let lastOutput;
2507
+ for await (const output of result) {
2508
+ lastOutput = output;
2509
+ yield { type: "preliminary", output };
2510
+ }
2511
+ yield { type: "final", output: lastOutput };
2512
+ } else {
2513
+ yield { type: "final", output: await result };
2514
+ }
2515
+ }
2516
+
2517
+ // src/index.ts
2518
+ export * from "@standard-schema/spec";
2519
+ import {
2520
+ EventSourceParserStream as EventSourceParserStream2
2521
+ } from "eventsource-parser/stream";
2522
+ export {
2523
+ DelayedPromise,
2524
+ DownloadError,
2525
+ EventSourceParserStream2 as EventSourceParserStream,
2526
+ VERSION,
2527
+ asSchema,
2528
+ combineHeaders,
2529
+ convertAsyncIteratorToReadableStream,
2530
+ convertBase64ToUint8Array,
2531
+ convertImageModelFileToDataUri,
2532
+ convertToBase64,
2533
+ convertToFormData,
2534
+ convertUint8ArrayToBase64,
2535
+ createBinaryResponseHandler,
2536
+ createEventSourceResponseHandler,
2537
+ createIdGenerator,
2538
+ createJsonErrorResponseHandler,
2539
+ createJsonResponseHandler,
2540
+ createProviderToolFactory,
2541
+ createProviderToolFactoryWithOutputSchema,
2542
+ createStatusCodeErrorResponseHandler,
2543
+ createToolNameMapping,
2544
+ delay,
2545
+ downloadBlob,
2546
+ dynamicTool,
2547
+ executeTool,
2548
+ extractResponseHeaders,
2549
+ generateId,
2550
+ getErrorMessage,
2551
+ getFromApi,
2552
+ getRuntimeEnvironmentUserAgent,
2553
+ injectJsonInstructionIntoMessages,
2554
+ isAbortError,
2555
+ isNonNullable,
2556
+ isParsableJson,
2557
+ isUrlSupported,
2558
+ jsonSchema,
2559
+ lazySchema,
2560
+ loadApiKey,
2561
+ loadOptionalSetting,
2562
+ loadSetting,
2563
+ mediaTypeToExtension,
2564
+ normalizeHeaders,
2565
+ parseJSON,
2566
+ parseJsonEventStream,
2567
+ parseProviderOptions,
2568
+ postFormDataToApi,
2569
+ postJsonToApi,
2570
+ postToApi,
2571
+ removeUndefinedEntries,
2572
+ resolve,
2573
+ safeParseJSON,
2574
+ safeValidateTypes,
2575
+ tool,
2576
+ validateTypes,
2577
+ withUserAgentSuffix,
2578
+ withoutTrailingSlash,
2579
+ zodSchema
2580
+ };
2581
+ //# sourceMappingURL=index.mjs.map