@codemation/core-nodes-ocr 0.2.5 → 0.2.7

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