@ai-sdk/provider-utils 5.0.0-beta.18 → 5.0.0-beta.19

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