@mettlelabs/mettle 0.0.0-0 → 0.0.0-beta.1-linux-x64

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 (59) hide show
  1. package/THIRD_PARTY_NOTICES.md +11479 -0
  2. package/bin/mettle +4 -0
  3. package/harness/audit-investigation.mjs +203 -0
  4. package/harness/chunk-13tgmdey.mjs +33761 -0
  5. package/harness/chunk-1sygmp11.mjs +18142 -0
  6. package/harness/chunk-1ykxpmaz.mjs +7887 -0
  7. package/harness/chunk-2gt4cy7x.mjs +2290 -0
  8. package/harness/chunk-2pm2sayw.mjs +248 -0
  9. package/harness/chunk-32y07kkp.mjs +3747 -0
  10. package/harness/chunk-3m7jn5ac.mjs +16242 -0
  11. package/harness/chunk-3wvjs93w.mjs +538 -0
  12. package/harness/chunk-4bepyxmq.mjs +113 -0
  13. package/harness/chunk-4jtnt9k5.mjs +95 -0
  14. package/harness/chunk-50sbrf09.mjs +18972 -0
  15. package/harness/chunk-56csr8sw.mjs +322 -0
  16. package/harness/chunk-5cvb1jnb.mjs +41 -0
  17. package/harness/chunk-5wgmv4np.mjs +585 -0
  18. package/harness/chunk-65eyq32y.mjs +225 -0
  19. package/harness/chunk-6fnh6qhk.mjs +195 -0
  20. package/harness/chunk-6kgqw9ny.mjs +32303 -0
  21. package/harness/chunk-7b242j0n.mjs +14 -0
  22. package/harness/chunk-7bg2gnv2.mjs +7540 -0
  23. package/harness/chunk-ageqxj9v.mjs +63008 -0
  24. package/harness/chunk-b0qbt5jd.mjs +14 -0
  25. package/harness/chunk-b5g1r3fz.mjs +4785 -0
  26. package/harness/chunk-b71gpkxg.mjs +1514 -0
  27. package/harness/chunk-bdv1rx4a.mjs +20364 -0
  28. package/harness/chunk-c1631s2x.mjs +12241 -0
  29. package/harness/chunk-d5xgxsnp.mjs +74 -0
  30. package/harness/chunk-erg1fbh0.mjs +0 -0
  31. package/harness/chunk-fh78v9vn.mjs +19366 -0
  32. package/harness/chunk-fjx29qvp.mjs +50 -0
  33. package/harness/chunk-gryka6kg.mjs +39 -0
  34. package/harness/chunk-jb0r19et.mjs +180 -0
  35. package/harness/chunk-mfn574ss.mjs +179 -0
  36. package/harness/chunk-msg872ea.mjs +334 -0
  37. package/harness/chunk-nz5sv9as.mjs +1642 -0
  38. package/harness/chunk-p9d3cgvq.mjs +452 -0
  39. package/harness/chunk-pq6wvwxr.mjs +12 -0
  40. package/harness/chunk-qcm9arf8.mjs +7736 -0
  41. package/harness/chunk-qr8zfqjd.mjs +24 -0
  42. package/harness/chunk-rz2tz6jp.mjs +26 -0
  43. package/harness/chunk-sbkgc3kn.mjs +8 -0
  44. package/harness/chunk-v66qvpnb.mjs +169 -0
  45. package/harness/chunk-vjaxzab3.mjs +136 -0
  46. package/harness/chunk-vr1n5nza.mjs +1045 -0
  47. package/harness/chunk-vsf2zajv.mjs +3867 -0
  48. package/harness/chunk-wq253fj4.mjs +19041 -0
  49. package/harness/chunk-wyv7ceq4.mjs +0 -0
  50. package/harness/chunk-xnqknk2r.mjs +198 -0
  51. package/harness/chunk-xqyc4ca2.mjs +1890 -0
  52. package/harness/chunk-z6n9thea.mjs +45146 -0
  53. package/harness/chunk-zty0d3bw.mjs +0 -0
  54. package/harness/chunk-zvkxtj82.mjs +42 -0
  55. package/harness/issue-api-token.mjs +35 -0
  56. package/harness/launcher.mjs +159 -0
  57. package/harness/sandbox.mjs +132 -0
  58. package/harness/server.mjs +66322 -0
  59. package/package.json +20 -3
@@ -0,0 +1,4785 @@
1
+ import {
2
+ ZodFirstPartyTypeKind
3
+ } from "./chunk-vsf2zajv.mjs";
4
+ import {
5
+ toJSONSchema,
6
+ safeParseAsync,
7
+ string,
8
+ number,
9
+ boolean,
10
+ any,
11
+ unknown,
12
+ array,
13
+ object,
14
+ union,
15
+ discriminatedUnion,
16
+ record,
17
+ _enum,
18
+ literal
19
+ } from "./chunk-1sygmp11.mjs";
20
+
21
+ // node_modules/.bun/@mastra+core@1.71.0+95d98e20cbc6e6e1/node_modules/@mastra/core/dist/dist-CWofJnzt-CYIIKerc.js
22
+ var marker$2 = "vercel.ai.error";
23
+ var symbol$2 = Symbol.for(marker$2);
24
+ var _a$2;
25
+ var _b$2;
26
+ var AISDKError$1 = class _AISDKError extends (_b$2 = Error, _a$2 = symbol$2, _b$2) {
27
+ constructor({ name: name14, message, cause }) {
28
+ super(message);
29
+ this[_a$2] = true;
30
+ this.name = name14;
31
+ this.cause = cause;
32
+ }
33
+ static isInstance(error) {
34
+ return _AISDKError.hasMarker(error, marker$2);
35
+ }
36
+ static hasMarker(error, marker15) {
37
+ const markerSymbol = Symbol.for(marker15);
38
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
39
+ }
40
+ };
41
+ var name$2 = "AI_APICallError";
42
+ var marker2$1 = `vercel.ai.error.${name$2}`;
43
+ var symbol2$1 = Symbol.for(marker2$1);
44
+ var _a2$1;
45
+ var _b2$1;
46
+ var APICallError$1 = class extends (_b2$1 = AISDKError$1, _a2$1 = symbol2$1, _b2$1) {
47
+ constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) {
48
+ super({
49
+ name: name$2,
50
+ message,
51
+ cause
52
+ });
53
+ this[_a2$1] = true;
54
+ this.url = url;
55
+ this.requestBodyValues = requestBodyValues;
56
+ this.statusCode = statusCode;
57
+ this.responseHeaders = responseHeaders;
58
+ this.responseBody = responseBody;
59
+ this.isRetryable = isRetryable;
60
+ this.data = data;
61
+ }
62
+ static isInstance(error) {
63
+ return AISDKError$1.hasMarker(error, marker2$1);
64
+ }
65
+ };
66
+ var name2$1 = "AI_EmptyResponseBodyError";
67
+ var marker3$1 = `vercel.ai.error.${name2$1}`;
68
+ var symbol3$1 = Symbol.for(marker3$1);
69
+ var _a3$1;
70
+ var _b3$1;
71
+ var EmptyResponseBodyError$1 = class extends (_b3$1 = AISDKError$1, _a3$1 = symbol3$1, _b3$1) {
72
+ constructor({ message = "Empty response body" } = {}) {
73
+ super({
74
+ name: name2$1,
75
+ message
76
+ });
77
+ this[_a3$1] = true;
78
+ }
79
+ static isInstance(error) {
80
+ return AISDKError$1.hasMarker(error, marker3$1);
81
+ }
82
+ };
83
+ function getErrorMessage$2(error) {
84
+ if (error == null)
85
+ return "unknown error";
86
+ if (typeof error === "string")
87
+ return error;
88
+ if (error instanceof Error)
89
+ return error.message;
90
+ return JSON.stringify(error);
91
+ }
92
+ var name3$1 = "AI_InvalidArgumentError";
93
+ var marker4$1 = `vercel.ai.error.${name3$1}`;
94
+ var symbol4$1 = Symbol.for(marker4$1);
95
+ var _a4$1;
96
+ var _b4$1;
97
+ var InvalidArgumentError$1 = class extends (_b4$1 = AISDKError$1, _a4$1 = symbol4$1, _b4$1) {
98
+ constructor({ message, cause, argument }) {
99
+ super({
100
+ name: name3$1,
101
+ message,
102
+ cause
103
+ });
104
+ this[_a4$1] = true;
105
+ this.argument = argument;
106
+ }
107
+ static isInstance(error) {
108
+ return AISDKError$1.hasMarker(error, marker4$1);
109
+ }
110
+ };
111
+ var name4$1 = "AI_InvalidPromptError";
112
+ var marker5$1 = `vercel.ai.error.${name4$1}`;
113
+ var symbol5$1 = Symbol.for(marker5$1);
114
+ var _a5$1;
115
+ var _b5$1;
116
+ (class extends (_b5$1 = AISDKError$1, _a5$1 = symbol5$1, _b5$1) {
117
+ constructor({ prompt, message, cause }) {
118
+ super({
119
+ name: name4$1,
120
+ message: `Invalid prompt: ${message}`,
121
+ cause
122
+ });
123
+ this[_a5$1] = true;
124
+ this.prompt = prompt;
125
+ }
126
+ static isInstance(error) {
127
+ return AISDKError$1.hasMarker(error, marker5$1);
128
+ }
129
+ });
130
+ var name5$1 = "AI_InvalidResponseDataError";
131
+ var marker6$1 = `vercel.ai.error.${name5$1}`;
132
+ var symbol6$1 = Symbol.for(marker6$1);
133
+ var _a6$1;
134
+ var _b6$1;
135
+ (class extends (_b6$1 = AISDKError$1, _a6$1 = symbol6$1, _b6$1) {
136
+ constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) {
137
+ super({
138
+ name: name5$1,
139
+ message
140
+ });
141
+ this[_a6$1] = true;
142
+ this.data = data;
143
+ }
144
+ static isInstance(error) {
145
+ return AISDKError$1.hasMarker(error, marker6$1);
146
+ }
147
+ });
148
+ var name6$1 = "AI_JSONParseError";
149
+ var marker7$1 = `vercel.ai.error.${name6$1}`;
150
+ var symbol7$1 = Symbol.for(marker7$1);
151
+ var _a7$1;
152
+ var _b7$1;
153
+ var JSONParseError$1 = class extends (_b7$1 = AISDKError$1, _a7$1 = symbol7$1, _b7$1) {
154
+ constructor({ text, cause }) {
155
+ super({
156
+ name: name6$1,
157
+ message: `JSON parsing failed: Text: ${text}.
158
+ Error message: ${getErrorMessage$2(cause)}`,
159
+ cause
160
+ });
161
+ this[_a7$1] = true;
162
+ this.text = text;
163
+ }
164
+ static isInstance(error) {
165
+ return AISDKError$1.hasMarker(error, marker7$1);
166
+ }
167
+ };
168
+ var name7$1 = "AI_LoadAPIKeyError";
169
+ var marker8$1 = `vercel.ai.error.${name7$1}`;
170
+ var symbol8$1 = Symbol.for(marker8$1);
171
+ var _a8$1;
172
+ var _b8$1;
173
+ (class extends (_b8$1 = AISDKError$1, _a8$1 = symbol8$1, _b8$1) {
174
+ constructor({ message }) {
175
+ super({
176
+ name: name7$1,
177
+ message
178
+ });
179
+ this[_a8$1] = true;
180
+ }
181
+ static isInstance(error) {
182
+ return AISDKError$1.hasMarker(error, marker8$1);
183
+ }
184
+ });
185
+ var name8$1 = "AI_LoadSettingError";
186
+ var marker9$1 = `vercel.ai.error.${name8$1}`;
187
+ var symbol9$1 = Symbol.for(marker9$1);
188
+ var _a9$1;
189
+ var _b9$1;
190
+ (class extends (_b9$1 = AISDKError$1, _a9$1 = symbol9$1, _b9$1) {
191
+ constructor({ message }) {
192
+ super({
193
+ name: name8$1,
194
+ message
195
+ });
196
+ this[_a9$1] = true;
197
+ }
198
+ static isInstance(error) {
199
+ return AISDKError$1.hasMarker(error, marker9$1);
200
+ }
201
+ });
202
+ var name9$1 = "AI_NoContentGeneratedError";
203
+ var marker10$1 = `vercel.ai.error.${name9$1}`;
204
+ var symbol10$1 = Symbol.for(marker10$1);
205
+ var _a10$1;
206
+ var _b10$1;
207
+ (class extends (_b10$1 = AISDKError$1, _a10$1 = symbol10$1, _b10$1) {
208
+ constructor({ message = "No content generated." } = {}) {
209
+ super({
210
+ name: name9$1,
211
+ message
212
+ });
213
+ this[_a10$1] = true;
214
+ }
215
+ static isInstance(error) {
216
+ return AISDKError$1.hasMarker(error, marker10$1);
217
+ }
218
+ });
219
+ var name10$1 = "AI_NoSuchModelError";
220
+ var marker11$1 = `vercel.ai.error.${name10$1}`;
221
+ var symbol11$1 = Symbol.for(marker11$1);
222
+ var _a11$1;
223
+ var _b11$1;
224
+ (class extends (_b11$1 = AISDKError$1, _a11$1 = symbol11$1, _b11$1) {
225
+ constructor({ errorName = name10$1, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) {
226
+ super({
227
+ name: errorName,
228
+ message
229
+ });
230
+ this[_a11$1] = true;
231
+ this.modelId = modelId;
232
+ this.modelType = modelType;
233
+ }
234
+ static isInstance(error) {
235
+ return AISDKError$1.hasMarker(error, marker11$1);
236
+ }
237
+ });
238
+ var name11$1 = "AI_TooManyEmbeddingValuesForCallError";
239
+ var marker12$1 = `vercel.ai.error.${name11$1}`;
240
+ var symbol12$1 = Symbol.for(marker12$1);
241
+ var _a12$1;
242
+ var _b12$1;
243
+ (class extends (_b12$1 = AISDKError$1, _a12$1 = symbol12$1, _b12$1) {
244
+ constructor(options) {
245
+ super({
246
+ name: name11$1,
247
+ 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.`
248
+ });
249
+ this[_a12$1] = true;
250
+ this.provider = options.provider;
251
+ this.modelId = options.modelId;
252
+ this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
253
+ this.values = options.values;
254
+ }
255
+ static isInstance(error) {
256
+ return AISDKError$1.hasMarker(error, marker12$1);
257
+ }
258
+ });
259
+ var name12$1 = "AI_TypeValidationError";
260
+ var marker13$1 = `vercel.ai.error.${name12$1}`;
261
+ var symbol13$1 = Symbol.for(marker13$1);
262
+ var _a13$1;
263
+ var _b13$1;
264
+ var TypeValidationError$1 = class _TypeValidationError extends (_b13$1 = AISDKError$1, _a13$1 = symbol13$1, _b13$1) {
265
+ constructor({ value, cause, context }) {
266
+ let contextPrefix = "Type validation failed";
267
+ if (context == null ? undefined : context.field)
268
+ contextPrefix += ` for ${context.field}`;
269
+ if ((context == null ? undefined : context.entityName) || (context == null ? undefined : context.entityId)) {
270
+ contextPrefix += " (";
271
+ const parts = [];
272
+ if (context.entityName)
273
+ parts.push(context.entityName);
274
+ if (context.entityId)
275
+ parts.push(`id: "${context.entityId}"`);
276
+ contextPrefix += parts.join(", ");
277
+ contextPrefix += ")";
278
+ }
279
+ super({
280
+ name: name12$1,
281
+ message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
282
+ Error message: ${getErrorMessage$2(cause)}`,
283
+ cause
284
+ });
285
+ this[_a13$1] = true;
286
+ this.value = value;
287
+ this.context = context;
288
+ }
289
+ static isInstance(error) {
290
+ return AISDKError$1.hasMarker(error, marker13$1);
291
+ }
292
+ static wrap({ value, cause, context }) {
293
+ var _a15, _b15, _c;
294
+ if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a15 = cause.context) == null ? undefined : _a15.field) === (context == null ? undefined : context.field) && ((_b15 = cause.context) == null ? undefined : _b15.entityName) === (context == null ? undefined : context.entityName) && ((_c = cause.context) == null ? undefined : _c.entityId) === (context == null ? undefined : context.entityId))
295
+ return cause;
296
+ return new _TypeValidationError({
297
+ value,
298
+ cause,
299
+ context
300
+ });
301
+ }
302
+ };
303
+ var name13$1 = "AI_UnsupportedFunctionalityError";
304
+ var marker14$1 = `vercel.ai.error.${name13$1}`;
305
+ var symbol14$1 = Symbol.for(marker14$1);
306
+ var _a14$1;
307
+ var _b14$1;
308
+ (class extends (_b14$1 = AISDKError$1, _a14$1 = symbol14$1, _b14$1) {
309
+ constructor({ functionality, message = `'${functionality}' functionality not supported.` }) {
310
+ super({
311
+ name: name13$1,
312
+ message
313
+ });
314
+ this[_a14$1] = true;
315
+ this.functionality = functionality;
316
+ }
317
+ static isInstance(error) {
318
+ return AISDKError$1.hasMarker(error, marker14$1);
319
+ }
320
+ });
321
+ var ParseError = class extends Error {
322
+ constructor(message, options) {
323
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
324
+ }
325
+ };
326
+ var LF = 10;
327
+ var CR = 13;
328
+ var SPACE = 32;
329
+ function noop(_arg) {}
330
+ function createParser(callbacks) {
331
+ if (typeof callbacks == "function")
332
+ throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");
333
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = [];
334
+ let isFirstChunk = true, id, data = "", dataLines = 0, eventType;
335
+ function feed(chunk) {
336
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
337
+ const trailing2 = processLines(chunk);
338
+ trailing2 !== "" && pendingFragments.push(trailing2);
339
+ return;
340
+ }
341
+ if (chunk.indexOf(`
342
+ `) === -1 && chunk.indexOf("\r") === -1) {
343
+ pendingFragments.push(chunk);
344
+ return;
345
+ }
346
+ pendingFragments.push(chunk);
347
+ const input = pendingFragments.join("");
348
+ pendingFragments.length = 0;
349
+ const trailing = processLines(input);
350
+ trailing !== "" && pendingFragments.push(trailing);
351
+ }
352
+ function processLines(chunk) {
353
+ let searchIndex = 0;
354
+ if (chunk.indexOf("\r") === -1) {
355
+ let lfIndex = chunk.indexOf(`
356
+ `, searchIndex);
357
+ for (;lfIndex !== -1; ) {
358
+ if (searchIndex === lfIndex) {
359
+ dataLines > 0 && onEvent({
360
+ id,
361
+ event: eventType,
362
+ data
363
+ }), id = undefined, data = "", dataLines = 0, eventType = undefined, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
364
+ `, searchIndex);
365
+ continue;
366
+ }
367
+ const firstCharCode = chunk.charCodeAt(searchIndex);
368
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
369
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
370
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
371
+ onEvent({
372
+ id,
373
+ event: eventType,
374
+ data: value
375
+ }), id = undefined, data = "", eventType = undefined, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
376
+ `, searchIndex);
377
+ continue;
378
+ }
379
+ data = dataLines === 0 ? value : `${data}
380
+ ${value}`, dataLines++;
381
+ } else
382
+ isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || undefined : parseLine(chunk, searchIndex, lfIndex);
383
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
384
+ `, searchIndex);
385
+ }
386
+ return chunk.slice(searchIndex);
387
+ }
388
+ for (;searchIndex < chunk.length; ) {
389
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
390
+ `, searchIndex);
391
+ let lineEnd = -1;
392
+ 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)
393
+ break;
394
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
395
+ }
396
+ return chunk.slice(searchIndex);
397
+ }
398
+ function parseLine(chunk, start, end) {
399
+ if (start === end) {
400
+ dispatchEvent();
401
+ return;
402
+ }
403
+ const firstCharCode = chunk.charCodeAt(start);
404
+ if (isDataPrefix(chunk, start, firstCharCode)) {
405
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
406
+ data = dataLines === 0 ? value2 : `${data}
407
+ ${value2}`, dataLines++;
408
+ return;
409
+ }
410
+ if (isEventPrefix(chunk, start, firstCharCode)) {
411
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined;
412
+ return;
413
+ }
414
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
415
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
416
+ id = value2.includes("\x00") ? undefined : value2;
417
+ return;
418
+ }
419
+ if (firstCharCode === 58) {
420
+ if (onComment) {
421
+ const line2 = chunk.slice(start, end);
422
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
423
+ }
424
+ return;
425
+ }
426
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
427
+ if (fieldSeparatorIndex === -1) {
428
+ processField(line, "", line);
429
+ return;
430
+ }
431
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;
432
+ processField(field, line.slice(fieldSeparatorIndex + offset), line);
433
+ }
434
+ function processField(field, value, line) {
435
+ switch (field) {
436
+ case "event":
437
+ eventType = value || undefined;
438
+ break;
439
+ case "data":
440
+ data = dataLines === 0 ? value : `${data}
441
+ ${value}`, dataLines++;
442
+ break;
443
+ case "id":
444
+ id = value.includes("\x00") ? undefined : value;
445
+ break;
446
+ case "retry":
447
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
448
+ type: "invalid-retry",
449
+ value,
450
+ line
451
+ }));
452
+ break;
453
+ default:
454
+ onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}…` : field}"`, {
455
+ type: "unknown-field",
456
+ field,
457
+ value,
458
+ line
459
+ }));
460
+ break;
461
+ }
462
+ }
463
+ function dispatchEvent() {
464
+ dataLines > 0 && onEvent({
465
+ id,
466
+ event: eventType,
467
+ data
468
+ }), id = undefined, data = "", dataLines = 0, eventType = undefined;
469
+ }
470
+ function reset(options = {}) {
471
+ if (options.consume && pendingFragments.length > 0) {
472
+ const incompleteLine = pendingFragments.join("");
473
+ parseLine(incompleteLine, 0, incompleteLine.length);
474
+ }
475
+ isFirstChunk = true, id = undefined, data = "", dataLines = 0, eventType = undefined, pendingFragments.length = 0;
476
+ }
477
+ return {
478
+ feed,
479
+ reset
480
+ };
481
+ }
482
+ function isDataPrefix(chunk, i, firstCharCode) {
483
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
484
+ }
485
+ function isEventPrefix(chunk, i, firstCharCode) {
486
+ 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;
487
+ }
488
+ var EventSourceParserStream = class extends TransformStream {
489
+ constructor({ onError, onRetry, onComment } = {}) {
490
+ let parser;
491
+ super({
492
+ start(controller) {
493
+ parser = createParser({
494
+ onEvent: (event) => {
495
+ controller.enqueue(event);
496
+ },
497
+ onError(error) {
498
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
499
+ },
500
+ onRetry,
501
+ onComment
502
+ });
503
+ },
504
+ transform(chunk) {
505
+ parser.feed(chunk);
506
+ }
507
+ });
508
+ }
509
+ };
510
+ function combineHeaders(...headers) {
511
+ return headers.reduce((combinedHeaders, currentHeaders) => ({
512
+ ...combinedHeaders,
513
+ ...currentHeaders != null ? currentHeaders : {}
514
+ }), {});
515
+ }
516
+ async function delay(delayInMs, options) {
517
+ if (delayInMs == null)
518
+ return Promise.resolve();
519
+ const signal = options == null ? undefined : options.abortSignal;
520
+ return new Promise((resolve2, reject) => {
521
+ if (signal == null ? undefined : signal.aborted) {
522
+ reject(createAbortError());
523
+ return;
524
+ }
525
+ const timeoutId = setTimeout(() => {
526
+ cleanup();
527
+ resolve2();
528
+ }, delayInMs);
529
+ const cleanup = () => {
530
+ clearTimeout(timeoutId);
531
+ signal?.removeEventListener("abort", onAbort);
532
+ };
533
+ const onAbort = () => {
534
+ cleanup();
535
+ reject(createAbortError());
536
+ };
537
+ signal?.addEventListener("abort", onAbort);
538
+ });
539
+ }
540
+ function createAbortError() {
541
+ return new DOMException("Delay was aborted", "AbortError");
542
+ }
543
+ var DelayedPromise2 = class {
544
+ constructor() {
545
+ this.status = { type: "pending" };
546
+ this._resolve = undefined;
547
+ this._reject = undefined;
548
+ }
549
+ get promise() {
550
+ if (this._promise)
551
+ return this._promise;
552
+ this._promise = new Promise((resolve2, reject) => {
553
+ if (this.status.type === "resolved")
554
+ resolve2(this.status.value);
555
+ else if (this.status.type === "rejected")
556
+ reject(this.status.error);
557
+ this._resolve = resolve2;
558
+ this._reject = reject;
559
+ });
560
+ return this._promise;
561
+ }
562
+ resolve(value) {
563
+ var _a2;
564
+ this.status = {
565
+ type: "resolved",
566
+ value
567
+ };
568
+ if (this._promise)
569
+ (_a2 = this._resolve) == null || _a2.call(this, value);
570
+ }
571
+ reject(error) {
572
+ var _a2;
573
+ this.status = {
574
+ type: "rejected",
575
+ error
576
+ };
577
+ if (this._promise)
578
+ (_a2 = this._reject) == null || _a2.call(this, error);
579
+ }
580
+ isResolved() {
581
+ return this.status.type === "resolved";
582
+ }
583
+ isRejected() {
584
+ return this.status.type === "rejected";
585
+ }
586
+ isPending() {
587
+ return this.status.type === "pending";
588
+ }
589
+ };
590
+ function extractResponseHeaders(response) {
591
+ return Object.fromEntries([...response.headers]);
592
+ }
593
+ var { btoa, atob } = globalThis;
594
+ function convertBase64ToUint8Array(base64String) {
595
+ const latin1string = atob(base64String.replace(/-/g, "+").replace(/_/g, "/"));
596
+ return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
597
+ }
598
+ function convertUint8ArrayToBase64(array2) {
599
+ const chunks = [];
600
+ const chunkSize = 4096;
601
+ for (let i = 0;i < array2.length; i += chunkSize)
602
+ chunks.push(String.fromCodePoint(...array2.subarray(i, i + chunkSize)));
603
+ return btoa(chunks.join(""));
604
+ }
605
+ async function cancelResponseBody(response) {
606
+ var _a2;
607
+ try {
608
+ await ((_a2 = response.body) == null ? undefined : _a2.cancel());
609
+ } catch (e) {}
610
+ }
611
+ var name$1 = "AI_DownloadError";
612
+ var marker$1 = `vercel.ai.error.${name$1}`;
613
+ var symbol$1 = Symbol.for(marker$1);
614
+ var _a$1;
615
+ var _b$1;
616
+ var DownloadError = class extends (_b$1 = AISDKError$1, _a$1 = symbol$1, _b$1) {
617
+ constructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) {
618
+ super({
619
+ name: name$1,
620
+ message,
621
+ cause
622
+ });
623
+ this[_a$1] = true;
624
+ this.url = url;
625
+ this.statusCode = statusCode;
626
+ this.statusText = statusText;
627
+ }
628
+ static isInstance(error) {
629
+ return AISDKError$1.hasMarker(error, marker$1);
630
+ }
631
+ };
632
+ function isBrowserRuntime(globalThisAny = globalThis) {
633
+ return globalThisAny.window != null;
634
+ }
635
+ function validateDownloadUrl(url) {
636
+ let parsed;
637
+ try {
638
+ parsed = new URL(url);
639
+ } catch (e) {
640
+ throw new DownloadError({
641
+ url,
642
+ message: `Invalid URL: ${url}`
643
+ });
644
+ }
645
+ if (parsed.protocol === "data:")
646
+ return;
647
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
648
+ throw new DownloadError({
649
+ url,
650
+ message: `URL scheme must be http, https, or data, got ${parsed.protocol}`
651
+ });
652
+ const hostname = parsed.hostname.toLowerCase().replace(/\.+$/, "");
653
+ if (!hostname)
654
+ throw new DownloadError({
655
+ url,
656
+ message: `URL must have a hostname`
657
+ });
658
+ if (hostname === "localhost" || hostname.endsWith(".local") || hostname.endsWith(".localhost"))
659
+ throw new DownloadError({
660
+ url,
661
+ message: `URL with hostname ${hostname} is not allowed`
662
+ });
663
+ if (hostname.startsWith("[") && hostname.endsWith("]")) {
664
+ if (isPrivateIPv6(hostname.slice(1, -1)))
665
+ throw new DownloadError({
666
+ url,
667
+ message: `URL with IPv6 address ${hostname} is not allowed`
668
+ });
669
+ return;
670
+ }
671
+ if (isIPv4(hostname)) {
672
+ if (isPrivateIPv4(hostname))
673
+ throw new DownloadError({
674
+ url,
675
+ message: `URL with IP address ${hostname} is not allowed`
676
+ });
677
+ return;
678
+ }
679
+ }
680
+ function validateDownloadAddress({ address, family, hostname }) {
681
+ if (family === 4 ? !isIPv4(address) || isPrivateIPv4(address) : family === 6 ? isPrivateIPv6(address) : true)
682
+ throw new DownloadError({
683
+ url: hostname,
684
+ message: `Hostname ${hostname} resolved to disallowed IP address ${address}`
685
+ });
686
+ }
687
+ function isIPv4(hostname) {
688
+ const parts = hostname.split(".");
689
+ if (parts.length !== 4)
690
+ return false;
691
+ return parts.every((part) => {
692
+ const num = Number(part);
693
+ return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;
694
+ });
695
+ }
696
+ function isPrivateIPv4(ip) {
697
+ const [a, b, c] = ip.split(".").map(Number);
698
+ if (a === 0)
699
+ return true;
700
+ if (a === 10)
701
+ return true;
702
+ if (a === 100 && b >= 64 && b <= 127)
703
+ return true;
704
+ if (a === 127)
705
+ return true;
706
+ if (a === 169 && b === 254)
707
+ return true;
708
+ if (a === 172 && b >= 16 && b <= 31)
709
+ return true;
710
+ if (a === 192 && b === 0 && c === 0)
711
+ return true;
712
+ if (a === 192 && b === 168)
713
+ return true;
714
+ if (a === 198 && (b === 18 || b === 19))
715
+ return true;
716
+ if (a >= 240)
717
+ return true;
718
+ return false;
719
+ }
720
+ function parseIPv6(ip) {
721
+ let address = ip.toLowerCase();
722
+ const zoneIndex = address.indexOf("%");
723
+ if (zoneIndex !== -1)
724
+ address = address.slice(0, zoneIndex);
725
+ const halves = address.split("::");
726
+ if (halves.length > 2)
727
+ return null;
728
+ const toGroups = (segment) => {
729
+ if (segment === "")
730
+ return [];
731
+ const groups = [];
732
+ const parts = segment.split(":");
733
+ for (let i = 0;i < parts.length; i++) {
734
+ const part = parts[i];
735
+ if (part.includes(".")) {
736
+ if (i !== parts.length - 1 || !isIPv4(part))
737
+ return null;
738
+ const [a, b, c, d] = part.split(".").map(Number);
739
+ groups.push(a << 8 | b, c << 8 | d);
740
+ continue;
741
+ }
742
+ if (!/^[0-9a-f]{1,4}$/.test(part))
743
+ return null;
744
+ groups.push(parseInt(part, 16));
745
+ }
746
+ return groups;
747
+ };
748
+ const head = toGroups(halves[0]);
749
+ if (head === null)
750
+ return null;
751
+ if (halves.length === 2) {
752
+ const tail = toGroups(halves[1]);
753
+ if (tail === null)
754
+ return null;
755
+ const fill = 8 - head.length - tail.length;
756
+ if (fill < 0)
757
+ return null;
758
+ return [
759
+ ...head,
760
+ ...new Array(fill).fill(0),
761
+ ...tail
762
+ ];
763
+ }
764
+ return head.length === 8 ? head : null;
765
+ }
766
+ function isPrivateIPv6(ip) {
767
+ const groups = parseIPv6(ip);
768
+ if (groups === null)
769
+ return true;
770
+ const topZero = (count) => groups.slice(0, count).every((group) => group === 0);
771
+ if (topZero(7) && (groups[7] === 0 || groups[7] === 1))
772
+ return true;
773
+ if ((groups[0] & 65024) === 64512)
774
+ return true;
775
+ if ((groups[0] & 65472) === 65152)
776
+ return true;
777
+ if ((groups[0] & 65472) === 65216)
778
+ return true;
779
+ if ((groups[0] & 65280) === 65280)
780
+ return true;
781
+ 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)
782
+ return isPrivateIPv4(`${groups[6] >> 8 & 255}.${groups[6] & 255}.${groups[7] >> 8 & 255}.${groups[7] & 255}`);
783
+ return false;
784
+ }
785
+ function createSafeLookup(lookup) {
786
+ return (hostname, options, callback) => {
787
+ lookup(hostname, {
788
+ ...options,
789
+ all: true
790
+ }, (error, addresses) => {
791
+ if (error) {
792
+ callback(error);
793
+ return;
794
+ }
795
+ try {
796
+ const [firstAddress] = addresses;
797
+ if (firstAddress == null)
798
+ throw new Error(`Hostname ${hostname} did not resolve to an address`);
799
+ for (const { address, family } of addresses)
800
+ validateDownloadAddress({
801
+ address,
802
+ family,
803
+ hostname
804
+ });
805
+ if (options.all === true)
806
+ callback(null, addresses);
807
+ else
808
+ callback(null, firstAddress.address, firstAddress.family);
809
+ } catch (error2) {
810
+ callback(error2 instanceof Error ? error2 : new Error(String(error2)));
811
+ }
812
+ });
813
+ };
814
+ }
815
+ var safeNodeFetchPromise;
816
+ var initialGlobalFetch = globalThis.fetch;
817
+ var initialGlobalFetchIsNodeDefault = isNodeDefaultFetch(initialGlobalFetch);
818
+ function isNodeRuntime() {
819
+ var _a2, _b2;
820
+ const runtimeProcess = globalThis.process;
821
+ return ((_a2 = runtimeProcess == null ? undefined : runtimeProcess.release) == null ? undefined : _a2.name) === "node" && ((_b2 = runtimeProcess.versions) == null ? undefined : _b2.bun) == null;
822
+ }
823
+ async function getDefaultDownloadFetch() {
824
+ if (!isNodeRuntime() || !initialGlobalFetchIsNodeDefault || globalThis.fetch !== initialGlobalFetch)
825
+ return globalThis.fetch;
826
+ return safeNodeFetchPromise != null ? safeNodeFetchPromise : safeNodeFetchPromise = createSafeNodeFetch();
827
+ }
828
+ function isNodeDefaultFetch(fetch) {
829
+ if (typeof fetch !== "function")
830
+ return false;
831
+ const source = Function.prototype.toString.call(fetch);
832
+ return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
833
+ }
834
+ async function createSafeNodeFetch() {
835
+ const [{ createRequire }, { lookup }] = await Promise.all([loadNodeModule("node:module"), loadNodeModule("node:dns")]);
836
+ const { Agent, fetch } = createRequire(getCurrentModulePath())("undici");
837
+ const dispatcher = new Agent({ connect: { lookup: createSafeLookup(lookup) } });
838
+ return (input, init) => fetch(input, {
839
+ ...init,
840
+ dispatcher
841
+ });
842
+ }
843
+ async function loadNodeModule(id) {
844
+ var _a2;
845
+ const processWithBuiltins = globalThis.process;
846
+ const builtinModule = (_a2 = processWithBuiltins == null ? undefined : processWithBuiltins.getBuiltinModule) == null ? undefined : _a2.call(processWithBuiltins, id);
847
+ if (builtinModule == null)
848
+ throw new Error(`Node.js built-in module ${id} is unavailable`);
849
+ return builtinModule;
850
+ }
851
+ function getCurrentModulePath() {
852
+ const originalPrepareStackTrace = Error.prepareStackTrace;
853
+ try {
854
+ Error.prepareStackTrace = (_error, callSites) => callSites;
855
+ const error = /* @__PURE__ */ new Error("Capture current module path");
856
+ Error.captureStackTrace(error, getCurrentModulePath);
857
+ const [caller] = error.stack;
858
+ const fileName = caller == null ? undefined : caller.getFileName();
859
+ if (fileName == null)
860
+ throw new Error("Unable to determine the current module path");
861
+ return fileName;
862
+ } finally {
863
+ Error.prepareStackTrace = originalPrepareStackTrace;
864
+ }
865
+ }
866
+ var MAX_DOWNLOAD_REDIRECTS = 10;
867
+ async function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects = MAX_DOWNLOAD_REDIRECTS }) {
868
+ const baseInit = { signal: abortSignal };
869
+ if (headers !== undefined)
870
+ baseInit.headers = headers;
871
+ let currentUrl = url;
872
+ for (let redirectCount = 0;redirectCount <= maxRedirects; redirectCount++) {
873
+ validateDownloadUrl(currentUrl);
874
+ const fetch = await getDefaultDownloadFetch();
875
+ const response = await fetch(currentUrl, {
876
+ ...baseInit,
877
+ redirect: "manual"
878
+ });
879
+ if (response.type === "opaqueredirect") {
880
+ if (!isBrowserRuntime())
881
+ throw new DownloadError({
882
+ url,
883
+ message: `Redirect from ${currentUrl} could not be validated and was blocked`
884
+ });
885
+ return await fetch(currentUrl, {
886
+ ...baseInit,
887
+ redirect: "follow"
888
+ });
889
+ }
890
+ const location = response.headers.get("location");
891
+ if (response.status >= 300 && response.status < 400 && location) {
892
+ await cancelResponseBody(response);
893
+ currentUrl = new URL(location, currentUrl).toString();
894
+ continue;
895
+ }
896
+ return response;
897
+ }
898
+ throw new DownloadError({
899
+ url,
900
+ message: `Too many redirects (max ${maxRedirects})`
901
+ });
902
+ }
903
+ var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
904
+ async function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE }) {
905
+ const contentLength = response.headers.get("content-length");
906
+ if (contentLength != null) {
907
+ const length = parseInt(contentLength, 10);
908
+ if (!isNaN(length) && length > maxBytes) {
909
+ await cancelResponseBody(response);
910
+ throw new DownloadError({
911
+ url,
912
+ message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`
913
+ });
914
+ }
915
+ }
916
+ const body = response.body;
917
+ if (body == null)
918
+ return /* @__PURE__ */ new Uint8Array(0);
919
+ const reader = body.getReader();
920
+ const chunks = [];
921
+ let totalBytes = 0;
922
+ try {
923
+ while (true) {
924
+ const { done, value } = await reader.read();
925
+ if (done)
926
+ break;
927
+ totalBytes += value.length;
928
+ if (totalBytes > maxBytes)
929
+ throw new DownloadError({
930
+ url,
931
+ message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`
932
+ });
933
+ chunks.push(value);
934
+ }
935
+ } finally {
936
+ try {
937
+ await reader.cancel();
938
+ } catch (e) {} finally {
939
+ reader.releaseLock();
940
+ }
941
+ }
942
+ const result = new Uint8Array(totalBytes);
943
+ let offset = 0;
944
+ for (const chunk of chunks) {
945
+ result.set(chunk, offset);
946
+ offset += chunk.length;
947
+ }
948
+ return result;
949
+ }
950
+ var createIdGenerator = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => {
951
+ const generator = () => {
952
+ const alphabetLength = alphabet.length;
953
+ const chars = new Array(size);
954
+ for (let i = 0;i < size; i++)
955
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
956
+ return chars.join("");
957
+ };
958
+ if (prefix == null)
959
+ return generator;
960
+ if (alphabet.includes(separator))
961
+ throw new InvalidArgumentError$1({
962
+ argument: "separator",
963
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
964
+ });
965
+ return () => `${prefix}${separator}${generator()}`;
966
+ };
967
+ createIdGenerator();
968
+ function getErrorMessage$1(error) {
969
+ if (error == null)
970
+ return "unknown error";
971
+ if (typeof error === "string")
972
+ return error;
973
+ if (error instanceof Error)
974
+ return error.message;
975
+ return JSON.stringify(error);
976
+ }
977
+ function isAbortError2(error) {
978
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError");
979
+ }
980
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
981
+ var RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
982
+ "ConnectionRefused",
983
+ "ConnectionClosed",
984
+ "FailedToOpenSocket",
985
+ "ECONNRESET",
986
+ "ECONNREFUSED",
987
+ "ETIMEDOUT",
988
+ "EPIPE",
989
+ "UND_ERR_SOCKET",
990
+ "UND_ERR_HEADERS_TIMEOUT",
991
+ "UND_ERR_BODY_TIMEOUT",
992
+ "UND_ERR_CONNECT_TIMEOUT"
993
+ ]);
994
+ function findNetworkError(error) {
995
+ const visited = /* @__PURE__ */ new Set;
996
+ let current = error;
997
+ while (current instanceof Error && !visited.has(current)) {
998
+ visited.add(current);
999
+ const errorWithCode = current;
1000
+ if (typeof errorWithCode.code === "string" && RETRYABLE_NETWORK_ERROR_CODES.has(errorWithCode.code))
1001
+ return errorWithCode;
1002
+ current = current.cause;
1003
+ }
1004
+ }
1005
+ function handleFetchError({ error, url, requestBodyValues }) {
1006
+ if (isAbortError2(error))
1007
+ return error;
1008
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
1009
+ const cause = error.cause;
1010
+ if (cause != null)
1011
+ return new APICallError$1({
1012
+ message: `Cannot connect to API: ${cause.message}`,
1013
+ cause,
1014
+ url,
1015
+ requestBodyValues,
1016
+ isRetryable: true
1017
+ });
1018
+ }
1019
+ const networkError = findNetworkError(error);
1020
+ if (networkError != null) {
1021
+ if (APICallError$1.isInstance(error))
1022
+ return new APICallError$1({
1023
+ message: error.message,
1024
+ cause: error.cause,
1025
+ url: error.url,
1026
+ requestBodyValues: error.requestBodyValues,
1027
+ statusCode: error.statusCode,
1028
+ responseHeaders: error.responseHeaders,
1029
+ responseBody: error.responseBody,
1030
+ data: error.data,
1031
+ isRetryable: true
1032
+ });
1033
+ return new APICallError$1({
1034
+ message: `Cannot connect to API: ${error instanceof Error ? error.message : networkError.message}`,
1035
+ cause: error,
1036
+ url,
1037
+ requestBodyValues,
1038
+ isRetryable: true
1039
+ });
1040
+ }
1041
+ return error;
1042
+ }
1043
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
1044
+ var _a2, _b2, _c;
1045
+ if (globalThisAny.window)
1046
+ return `runtime/browser`;
1047
+ if ((_a2 = globalThisAny.navigator) == null ? undefined : _a2.userAgent)
1048
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
1049
+ if ((_c = (_b2 = globalThisAny.process) == null ? undefined : _b2.versions) == null ? undefined : _c.node)
1050
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
1051
+ if (globalThisAny.EdgeRuntime)
1052
+ return `runtime/vercel-edge`;
1053
+ return "runtime/unknown";
1054
+ }
1055
+ function normalizeHeaders(headers) {
1056
+ if (headers == null)
1057
+ return {};
1058
+ const normalized = {};
1059
+ if (headers instanceof Headers)
1060
+ headers.forEach((value, key) => {
1061
+ normalized[key.toLowerCase()] = value;
1062
+ });
1063
+ else {
1064
+ if (!Array.isArray(headers))
1065
+ headers = Object.entries(headers);
1066
+ for (const [key, value] of headers)
1067
+ if (value != null)
1068
+ normalized[key.toLowerCase()] = value;
1069
+ }
1070
+ return normalized;
1071
+ }
1072
+ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
1073
+ const normalizedHeaders = new Headers(normalizeHeaders(headers));
1074
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
1075
+ normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
1076
+ return Object.fromEntries(normalizedHeaders.entries());
1077
+ }
1078
+ var VERSION$1 = "4.0.53";
1079
+ var getOriginalFetch = () => globalThis.fetch;
1080
+ var getFromApi = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch() }) => {
1081
+ try {
1082
+ const response = await fetch(url, {
1083
+ method: "GET",
1084
+ headers: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION$1}`, getRuntimeEnvironmentUserAgent()),
1085
+ signal: abortSignal
1086
+ });
1087
+ const responseHeaders = extractResponseHeaders(response);
1088
+ if (!response.ok) {
1089
+ let errorInformation;
1090
+ try {
1091
+ errorInformation = await failedResponseHandler({
1092
+ response,
1093
+ url,
1094
+ requestBodyValues: {}
1095
+ });
1096
+ } catch (error) {
1097
+ if (isAbortError2(error) || APICallError$1.isInstance(error))
1098
+ throw error;
1099
+ throw new APICallError$1({
1100
+ message: "Failed to process error response",
1101
+ cause: error,
1102
+ statusCode: response.status,
1103
+ url,
1104
+ responseHeaders,
1105
+ requestBodyValues: {}
1106
+ });
1107
+ }
1108
+ throw errorInformation.value;
1109
+ }
1110
+ try {
1111
+ return await successfulResponseHandler({
1112
+ response,
1113
+ url,
1114
+ requestBodyValues: {}
1115
+ });
1116
+ } catch (error) {
1117
+ if (error instanceof Error) {
1118
+ if (isAbortError2(error) || APICallError$1.isInstance(error))
1119
+ throw error;
1120
+ }
1121
+ throw new APICallError$1({
1122
+ message: "Failed to process successful response",
1123
+ cause: error,
1124
+ statusCode: response.status,
1125
+ url,
1126
+ responseHeaders,
1127
+ requestBodyValues: {}
1128
+ });
1129
+ }
1130
+ } catch (error) {
1131
+ throw handleFetchError({
1132
+ error,
1133
+ url,
1134
+ requestBodyValues: {}
1135
+ });
1136
+ }
1137
+ };
1138
+ function isUrlSupported({ mediaType, url, supportedUrls }) {
1139
+ url = url.toLowerCase();
1140
+ mediaType = mediaType.toLowerCase();
1141
+ return Object.entries(supportedUrls).map(([key, value]) => {
1142
+ const mediaType2 = key.toLowerCase();
1143
+ return mediaType2 === "*" || mediaType2 === "*/*" ? {
1144
+ mediaTypePrefix: "",
1145
+ regexes: value
1146
+ } : {
1147
+ mediaTypePrefix: mediaType2.replace(/\*/, ""),
1148
+ regexes: value
1149
+ };
1150
+ }).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));
1151
+ }
1152
+ function loadOptionalSetting({ settingValue, environmentVariableName }) {
1153
+ if (typeof settingValue === "string")
1154
+ return settingValue;
1155
+ if (settingValue != null || typeof process === "undefined")
1156
+ return;
1157
+ settingValue = process.env[environmentVariableName];
1158
+ if (settingValue == null || typeof settingValue !== "string")
1159
+ return;
1160
+ return settingValue;
1161
+ }
1162
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
1163
+ 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*:/;
1164
+ function _parse(text) {
1165
+ const obj = JSON.parse(text);
1166
+ if (obj === null || typeof obj !== "object")
1167
+ return obj;
1168
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false)
1169
+ return obj;
1170
+ return filter(obj);
1171
+ }
1172
+ function filter(obj) {
1173
+ let next = [obj];
1174
+ while (next.length) {
1175
+ const nodes = next;
1176
+ next = [];
1177
+ for (const node of nodes) {
1178
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__"))
1179
+ throw new SyntaxError("Object contains forbidden prototype property");
1180
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype"))
1181
+ throw new SyntaxError("Object contains forbidden prototype property");
1182
+ for (const key in node) {
1183
+ const value = node[key];
1184
+ if (value && typeof value === "object")
1185
+ next.push(value);
1186
+ }
1187
+ }
1188
+ }
1189
+ return obj;
1190
+ }
1191
+ function secureJsonParse(text) {
1192
+ const { stackTraceLimit } = Error;
1193
+ try {
1194
+ Error.stackTraceLimit = 0;
1195
+ } catch (e) {
1196
+ return _parse(text);
1197
+ }
1198
+ try {
1199
+ return _parse(text);
1200
+ } finally {
1201
+ Error.stackTraceLimit = stackTraceLimit;
1202
+ }
1203
+ }
1204
+ function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
1205
+ if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
1206
+ const { additionalProperties } = jsonSchema2;
1207
+ jsonSchema2.additionalProperties = additionalProperties != null && typeof additionalProperties !== "boolean" ? visit(additionalProperties) : false;
1208
+ const { properties } = jsonSchema2;
1209
+ if (properties != null)
1210
+ for (const key of Object.keys(properties))
1211
+ properties[key] = visit(properties[key]);
1212
+ }
1213
+ if (jsonSchema2.items != null)
1214
+ jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
1215
+ if (jsonSchema2.anyOf != null)
1216
+ jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
1217
+ if (jsonSchema2.allOf != null)
1218
+ jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
1219
+ if (jsonSchema2.oneOf != null)
1220
+ jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
1221
+ const { definitions } = jsonSchema2;
1222
+ if (definitions != null)
1223
+ for (const key of Object.keys(definitions))
1224
+ definitions[key] = visit(definitions[key]);
1225
+ return jsonSchema2;
1226
+ }
1227
+ function visit(def) {
1228
+ if (typeof def === "boolean")
1229
+ return def;
1230
+ return addAdditionalPropertiesToJsonSchema(def);
1231
+ }
1232
+ var ignoreOverride = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use");
1233
+ var defaultOptions = {
1234
+ name: undefined,
1235
+ $refStrategy: "root",
1236
+ basePath: ["#"],
1237
+ effectStrategy: "input",
1238
+ pipeStrategy: "all",
1239
+ dateStrategy: "format:date-time",
1240
+ mapStrategy: "entries",
1241
+ removeAdditionalStrategy: "passthrough",
1242
+ allowedAdditionalProperties: true,
1243
+ rejectedAdditionalProperties: false,
1244
+ definitionPath: "definitions",
1245
+ strictUnions: false,
1246
+ definitions: {},
1247
+ errorMessages: false,
1248
+ patternStrategy: "escape",
1249
+ applyRegexFlags: false,
1250
+ emailStrategy: "format:email",
1251
+ base64Strategy: "contentEncoding:base64",
1252
+ nameStrategy: "ref"
1253
+ };
1254
+ var getDefaultOptions = (options) => typeof options === "string" ? {
1255
+ ...defaultOptions,
1256
+ name: options
1257
+ } : {
1258
+ ...defaultOptions,
1259
+ ...options
1260
+ };
1261
+ function parseAnyDef() {
1262
+ return {};
1263
+ }
1264
+ function parseArrayDef(def, refs) {
1265
+ var _a2, _b2, _c;
1266
+ const res = { type: "array" };
1267
+ if (((_a2 = def.type) == null ? undefined : _a2._def) && ((_c = (_b2 = def.type) == null ? undefined : _b2._def) == null ? undefined : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny)
1268
+ res.items = parseDef(def.type._def, {
1269
+ ...refs,
1270
+ currentPath: [...refs.currentPath, "items"]
1271
+ });
1272
+ if (def.minLength)
1273
+ res.minItems = def.minLength.value;
1274
+ if (def.maxLength)
1275
+ res.maxItems = def.maxLength.value;
1276
+ if (def.exactLength) {
1277
+ res.minItems = def.exactLength.value;
1278
+ res.maxItems = def.exactLength.value;
1279
+ }
1280
+ return res;
1281
+ }
1282
+ function parseBigintDef(def) {
1283
+ const res = {
1284
+ type: "integer",
1285
+ format: "int64"
1286
+ };
1287
+ if (!def.checks)
1288
+ return res;
1289
+ for (const check of def.checks)
1290
+ switch (check.kind) {
1291
+ case "min":
1292
+ if (check.inclusive)
1293
+ res.minimum = check.value;
1294
+ else
1295
+ res.exclusiveMinimum = check.value;
1296
+ break;
1297
+ case "max":
1298
+ if (check.inclusive)
1299
+ res.maximum = check.value;
1300
+ else
1301
+ res.exclusiveMaximum = check.value;
1302
+ break;
1303
+ case "multipleOf":
1304
+ res.multipleOf = check.value;
1305
+ break;
1306
+ }
1307
+ return res;
1308
+ }
1309
+ function parseBooleanDef() {
1310
+ return { type: "boolean" };
1311
+ }
1312
+ function parseBrandedDef(_def, refs) {
1313
+ return parseDef(_def.type._def, refs);
1314
+ }
1315
+ var parseCatchDef = (def, refs) => {
1316
+ return parseDef(def.innerType._def, refs);
1317
+ };
1318
+ function parseDateDef(def, refs, overrideDateStrategy) {
1319
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
1320
+ if (Array.isArray(strategy))
1321
+ return { anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) };
1322
+ switch (strategy) {
1323
+ case "string":
1324
+ case "format:date-time":
1325
+ return {
1326
+ type: "string",
1327
+ format: "date-time"
1328
+ };
1329
+ case "format:date":
1330
+ return {
1331
+ type: "string",
1332
+ format: "date"
1333
+ };
1334
+ case "integer":
1335
+ return integerDateParser(def);
1336
+ }
1337
+ }
1338
+ var integerDateParser = (def) => {
1339
+ const res = {
1340
+ type: "integer",
1341
+ format: "unix-time"
1342
+ };
1343
+ for (const check of def.checks)
1344
+ switch (check.kind) {
1345
+ case "min":
1346
+ res.minimum = check.value;
1347
+ break;
1348
+ case "max":
1349
+ res.maximum = check.value;
1350
+ break;
1351
+ }
1352
+ return res;
1353
+ };
1354
+ function parseDefaultDef(_def, refs) {
1355
+ return {
1356
+ ...parseDef(_def.innerType._def, refs),
1357
+ default: _def.defaultValue()
1358
+ };
1359
+ }
1360
+ function parseEffectsDef(_def, refs) {
1361
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
1362
+ }
1363
+ function parseEnumDef(def) {
1364
+ return {
1365
+ type: "string",
1366
+ enum: Array.from(def.values)
1367
+ };
1368
+ }
1369
+ var isJsonSchema7AllOfType = (type) => {
1370
+ if ("type" in type && type.type === "string")
1371
+ return false;
1372
+ return "allOf" in type;
1373
+ };
1374
+ function parseIntersectionDef(def, refs) {
1375
+ const allOf = [parseDef(def.left._def, {
1376
+ ...refs,
1377
+ currentPath: [
1378
+ ...refs.currentPath,
1379
+ "allOf",
1380
+ "0"
1381
+ ]
1382
+ }), parseDef(def.right._def, {
1383
+ ...refs,
1384
+ currentPath: [
1385
+ ...refs.currentPath,
1386
+ "allOf",
1387
+ "1"
1388
+ ]
1389
+ })].filter((x) => !!x);
1390
+ const mergedAllOf = [];
1391
+ allOf.forEach((schema) => {
1392
+ if (isJsonSchema7AllOfType(schema))
1393
+ mergedAllOf.push(...schema.allOf);
1394
+ else {
1395
+ let nestedSchema = schema;
1396
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
1397
+ const { additionalProperties, ...rest } = schema;
1398
+ nestedSchema = rest;
1399
+ }
1400
+ mergedAllOf.push(nestedSchema);
1401
+ }
1402
+ });
1403
+ return mergedAllOf.length ? { allOf: mergedAllOf } : undefined;
1404
+ }
1405
+ function parseLiteralDef(def) {
1406
+ const parsedType = typeof def.value;
1407
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string")
1408
+ return { type: Array.isArray(def.value) ? "array" : "object" };
1409
+ return {
1410
+ type: parsedType === "bigint" ? "integer" : parsedType,
1411
+ const: def.value
1412
+ };
1413
+ }
1414
+ var emojiRegex = undefined;
1415
+ var zodPatterns = {
1416
+ cuid: /^[cC][^\s-]{8,}$/,
1417
+ cuid2: /^[0-9a-z]+$/,
1418
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
1419
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1420
+ emoji: () => {
1421
+ if (emojiRegex === undefined)
1422
+ emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
1423
+ return emojiRegex;
1424
+ },
1425
+ 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}$/,
1426
+ 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])$/,
1427
+ 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])$/,
1428
+ 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})))$/,
1429
+ 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])$/,
1430
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1431
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1432
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
1433
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1434
+ };
1435
+ function parseStringDef(def, refs) {
1436
+ const res = { type: "string" };
1437
+ if (def.checks)
1438
+ for (const check of def.checks)
1439
+ switch (check.kind) {
1440
+ case "min":
1441
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1442
+ break;
1443
+ case "max":
1444
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1445
+ break;
1446
+ case "email":
1447
+ switch (refs.emailStrategy) {
1448
+ case "format:email":
1449
+ addFormat(res, "email", check.message, refs);
1450
+ break;
1451
+ case "format:idn-email":
1452
+ addFormat(res, "idn-email", check.message, refs);
1453
+ break;
1454
+ case "pattern:zod":
1455
+ addPattern(res, zodPatterns.email, check.message, refs);
1456
+ break;
1457
+ }
1458
+ break;
1459
+ case "url":
1460
+ addFormat(res, "uri", check.message, refs);
1461
+ break;
1462
+ case "uuid":
1463
+ addFormat(res, "uuid", check.message, refs);
1464
+ break;
1465
+ case "regex":
1466
+ addPattern(res, check.regex, check.message, refs);
1467
+ break;
1468
+ case "cuid":
1469
+ addPattern(res, zodPatterns.cuid, check.message, refs);
1470
+ break;
1471
+ case "cuid2":
1472
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
1473
+ break;
1474
+ case "startsWith":
1475
+ addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
1476
+ break;
1477
+ case "endsWith":
1478
+ addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
1479
+ break;
1480
+ case "datetime":
1481
+ addFormat(res, "date-time", check.message, refs);
1482
+ break;
1483
+ case "date":
1484
+ addFormat(res, "date", check.message, refs);
1485
+ break;
1486
+ case "time":
1487
+ addFormat(res, "time", check.message, refs);
1488
+ break;
1489
+ case "duration":
1490
+ addFormat(res, "duration", check.message, refs);
1491
+ break;
1492
+ case "length":
1493
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1494
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1495
+ break;
1496
+ case "includes":
1497
+ addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
1498
+ break;
1499
+ case "ip":
1500
+ if (check.version !== "v6")
1501
+ addFormat(res, "ipv4", check.message, refs);
1502
+ if (check.version !== "v4")
1503
+ addFormat(res, "ipv6", check.message, refs);
1504
+ break;
1505
+ case "base64url":
1506
+ addPattern(res, zodPatterns.base64url, check.message, refs);
1507
+ break;
1508
+ case "jwt":
1509
+ addPattern(res, zodPatterns.jwt, check.message, refs);
1510
+ break;
1511
+ case "cidr":
1512
+ if (check.version !== "v6")
1513
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1514
+ if (check.version !== "v4")
1515
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1516
+ break;
1517
+ case "emoji":
1518
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
1519
+ break;
1520
+ case "ulid":
1521
+ addPattern(res, zodPatterns.ulid, check.message, refs);
1522
+ break;
1523
+ case "base64":
1524
+ switch (refs.base64Strategy) {
1525
+ case "format:binary":
1526
+ addFormat(res, "binary", check.message, refs);
1527
+ break;
1528
+ case "contentEncoding:base64":
1529
+ res.contentEncoding = "base64";
1530
+ break;
1531
+ case "pattern:zod":
1532
+ addPattern(res, zodPatterns.base64, check.message, refs);
1533
+ break;
1534
+ }
1535
+ break;
1536
+ case "nanoid":
1537
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
1538
+ case "toLowerCase":
1539
+ case "toUpperCase":
1540
+ case "trim":
1541
+ break;
1542
+ default:
1543
+ }
1544
+ return res;
1545
+ }
1546
+ function escapeLiteralCheckValue(literal2, refs) {
1547
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal2) : literal2;
1548
+ }
1549
+ var ALPHA_NUMERIC = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
1550
+ function escapeNonAlphaNumeric(source) {
1551
+ let result = "";
1552
+ for (let i = 0;i < source.length; i++) {
1553
+ if (!ALPHA_NUMERIC.has(source[i]))
1554
+ result += "\\";
1555
+ result += source[i];
1556
+ }
1557
+ return result;
1558
+ }
1559
+ function addFormat(schema, value, message, refs) {
1560
+ var _a2;
1561
+ if (schema.format || ((_a2 = schema.anyOf) == null ? undefined : _a2.some((x) => x.format))) {
1562
+ if (!schema.anyOf)
1563
+ schema.anyOf = [];
1564
+ if (schema.format) {
1565
+ schema.anyOf.push({ format: schema.format });
1566
+ delete schema.format;
1567
+ }
1568
+ schema.anyOf.push({
1569
+ format: value,
1570
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
1571
+ });
1572
+ } else
1573
+ schema.format = value;
1574
+ }
1575
+ function addPattern(schema, regex, message, refs) {
1576
+ var _a2;
1577
+ if (schema.pattern || ((_a2 = schema.allOf) == null ? undefined : _a2.some((x) => x.pattern))) {
1578
+ if (!schema.allOf)
1579
+ schema.allOf = [];
1580
+ if (schema.pattern) {
1581
+ schema.allOf.push({ pattern: schema.pattern });
1582
+ delete schema.pattern;
1583
+ }
1584
+ schema.allOf.push({
1585
+ pattern: stringifyRegExpWithFlags(regex, refs),
1586
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
1587
+ });
1588
+ } else
1589
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
1590
+ }
1591
+ function stringifyRegExpWithFlags(regex, refs) {
1592
+ var _a2;
1593
+ if (!refs.applyRegexFlags || !regex.flags)
1594
+ return regex.source;
1595
+ const flags = {
1596
+ i: regex.flags.includes("i"),
1597
+ m: regex.flags.includes("m"),
1598
+ s: regex.flags.includes("s")
1599
+ };
1600
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1601
+ let pattern = "";
1602
+ let isEscaped = false;
1603
+ let inCharGroup = false;
1604
+ let inCharRange = false;
1605
+ for (let i = 0;i < source.length; i++) {
1606
+ if (isEscaped) {
1607
+ pattern += source[i];
1608
+ isEscaped = false;
1609
+ continue;
1610
+ }
1611
+ if (flags.i) {
1612
+ if (inCharGroup) {
1613
+ if (source[i].match(/[a-z]/)) {
1614
+ if (inCharRange) {
1615
+ pattern += source[i];
1616
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1617
+ inCharRange = false;
1618
+ } else if (source[i + 1] === "-" && ((_a2 = source[i + 2]) == null ? undefined : _a2.match(/[a-z]/))) {
1619
+ pattern += source[i];
1620
+ inCharRange = true;
1621
+ } else
1622
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1623
+ continue;
1624
+ }
1625
+ } else if (source[i].match(/[a-z]/)) {
1626
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1627
+ continue;
1628
+ }
1629
+ }
1630
+ if (flags.m) {
1631
+ if (source[i] === "^") {
1632
+ pattern += `(^|(?<=[\r
1633
+ ]))`;
1634
+ continue;
1635
+ } else if (source[i] === "$") {
1636
+ pattern += `($|(?=[\r
1637
+ ]))`;
1638
+ continue;
1639
+ }
1640
+ }
1641
+ if (flags.s && source[i] === ".") {
1642
+ pattern += inCharGroup ? `${source[i]}\r
1643
+ ` : `[${source[i]}\r
1644
+ ]`;
1645
+ continue;
1646
+ }
1647
+ pattern += source[i];
1648
+ if (source[i] === "\\")
1649
+ isEscaped = true;
1650
+ else if (inCharGroup && source[i] === "]")
1651
+ inCharGroup = false;
1652
+ else if (!inCharGroup && source[i] === "[")
1653
+ inCharGroup = true;
1654
+ }
1655
+ try {
1656
+ new RegExp(pattern);
1657
+ } catch (e) {
1658
+ console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
1659
+ return regex.source;
1660
+ }
1661
+ return pattern;
1662
+ }
1663
+ function parseRecordDef(def, refs) {
1664
+ var _a2, _b2, _c, _d, _e, _f;
1665
+ const schema = {
1666
+ type: "object",
1667
+ additionalProperties: (_a2 = parseDef(def.valueType._def, {
1668
+ ...refs,
1669
+ currentPath: [...refs.currentPath, "additionalProperties"]
1670
+ })) != null ? _a2 : refs.allowedAdditionalProperties
1671
+ };
1672
+ if (((_b2 = def.keyType) == null ? undefined : _b2._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? undefined : _c.length)) {
1673
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1674
+ return {
1675
+ ...schema,
1676
+ propertyNames: keyType
1677
+ };
1678
+ } else if (((_d = def.keyType) == null ? undefined : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum)
1679
+ return {
1680
+ ...schema,
1681
+ propertyNames: { enum: def.keyType._def.values }
1682
+ };
1683
+ else if (((_e = def.keyType) == null ? undefined : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? undefined : _f.length)) {
1684
+ const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
1685
+ return {
1686
+ ...schema,
1687
+ propertyNames: keyType
1688
+ };
1689
+ }
1690
+ return schema;
1691
+ }
1692
+ function parseMapDef(def, refs) {
1693
+ if (refs.mapStrategy === "record")
1694
+ return parseRecordDef(def, refs);
1695
+ return {
1696
+ type: "array",
1697
+ maxItems: 125,
1698
+ items: {
1699
+ type: "array",
1700
+ items: [parseDef(def.keyType._def, {
1701
+ ...refs,
1702
+ currentPath: [
1703
+ ...refs.currentPath,
1704
+ "items",
1705
+ "items",
1706
+ "0"
1707
+ ]
1708
+ }) || parseAnyDef(), parseDef(def.valueType._def, {
1709
+ ...refs,
1710
+ currentPath: [
1711
+ ...refs.currentPath,
1712
+ "items",
1713
+ "items",
1714
+ "1"
1715
+ ]
1716
+ }) || parseAnyDef()],
1717
+ minItems: 2,
1718
+ maxItems: 2
1719
+ }
1720
+ };
1721
+ }
1722
+ function parseNativeEnumDef(def) {
1723
+ const object2 = def.values;
1724
+ const actualValues = Object.keys(def.values).filter((key) => {
1725
+ return typeof object2[object2[key]] !== "number";
1726
+ }).map((key) => object2[key]);
1727
+ const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
1728
+ return {
1729
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1730
+ enum: actualValues
1731
+ };
1732
+ }
1733
+ function parseNeverDef() {
1734
+ return { not: parseAnyDef() };
1735
+ }
1736
+ function parseNullDef() {
1737
+ return { type: "null" };
1738
+ }
1739
+ var primitiveMappings = {
1740
+ ZodString: "string",
1741
+ ZodNumber: "number",
1742
+ ZodBigInt: "integer",
1743
+ ZodBoolean: "boolean",
1744
+ ZodNull: "null"
1745
+ };
1746
+ function parseUnionDef(def, refs) {
1747
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1748
+ if (options.every((x) => (x._def.typeName in primitiveMappings) && (!x._def.checks || !x._def.checks.length))) {
1749
+ const types = options.reduce((types2, x) => {
1750
+ const type = primitiveMappings[x._def.typeName];
1751
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1752
+ }, []);
1753
+ return { type: types.length > 1 ? types : types[0] };
1754
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1755
+ const types = options.reduce((acc, x) => {
1756
+ const type = typeof x._def.value;
1757
+ switch (type) {
1758
+ case "string":
1759
+ case "number":
1760
+ case "boolean":
1761
+ return [...acc, type];
1762
+ case "bigint":
1763
+ return [...acc, "integer"];
1764
+ case "object":
1765
+ if (x._def.value === null)
1766
+ return [...acc, "null"];
1767
+ default:
1768
+ return acc;
1769
+ }
1770
+ }, []);
1771
+ if (types.length === options.length) {
1772
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1773
+ return {
1774
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1775
+ enum: options.reduce((acc, x) => {
1776
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1777
+ }, [])
1778
+ };
1779
+ }
1780
+ } else if (options.every((x) => x._def.typeName === "ZodEnum"))
1781
+ return {
1782
+ type: "string",
1783
+ enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x2) => !acc.includes(x2))], [])
1784
+ };
1785
+ return asAnyOf(def, refs);
1786
+ }
1787
+ var asAnyOf = (def, refs) => {
1788
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
1789
+ ...refs,
1790
+ currentPath: [
1791
+ ...refs.currentPath,
1792
+ "anyOf",
1793
+ `${i}`
1794
+ ]
1795
+ })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
1796
+ return anyOf.length ? { anyOf } : undefined;
1797
+ };
1798
+ function parseNullableDef(def, refs) {
1799
+ if ([
1800
+ "ZodString",
1801
+ "ZodNumber",
1802
+ "ZodBigInt",
1803
+ "ZodBoolean",
1804
+ "ZodNull"
1805
+ ].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length))
1806
+ return { type: [primitiveMappings[def.innerType._def.typeName], "null"] };
1807
+ const base = parseDef(def.innerType._def, {
1808
+ ...refs,
1809
+ currentPath: [
1810
+ ...refs.currentPath,
1811
+ "anyOf",
1812
+ "0"
1813
+ ]
1814
+ });
1815
+ return base && { anyOf: [base, { type: "null" }] };
1816
+ }
1817
+ function parseNumberDef(def) {
1818
+ const res = { type: "number" };
1819
+ if (!def.checks)
1820
+ return res;
1821
+ for (const check of def.checks)
1822
+ switch (check.kind) {
1823
+ case "int":
1824
+ res.type = "integer";
1825
+ break;
1826
+ case "min":
1827
+ if (check.inclusive)
1828
+ res.minimum = check.value;
1829
+ else
1830
+ res.exclusiveMinimum = check.value;
1831
+ break;
1832
+ case "max":
1833
+ if (check.inclusive)
1834
+ res.maximum = check.value;
1835
+ else
1836
+ res.exclusiveMaximum = check.value;
1837
+ break;
1838
+ case "multipleOf":
1839
+ res.multipleOf = check.value;
1840
+ break;
1841
+ }
1842
+ return res;
1843
+ }
1844
+ function parseObjectDef(def, refs) {
1845
+ const result = {
1846
+ type: "object",
1847
+ properties: {}
1848
+ };
1849
+ const required = [];
1850
+ const shape = def.shape();
1851
+ for (const propName in shape) {
1852
+ let propDef = shape[propName];
1853
+ if (propDef === undefined || propDef._def === undefined)
1854
+ continue;
1855
+ const propOptional = safeIsOptional(propDef);
1856
+ const parsedDef = parseDef(propDef._def, {
1857
+ ...refs,
1858
+ currentPath: [
1859
+ ...refs.currentPath,
1860
+ "properties",
1861
+ propName
1862
+ ],
1863
+ propertyPath: [
1864
+ ...refs.currentPath,
1865
+ "properties",
1866
+ propName
1867
+ ]
1868
+ });
1869
+ if (parsedDef === undefined)
1870
+ continue;
1871
+ result.properties[propName] = parsedDef;
1872
+ if (!propOptional)
1873
+ required.push(propName);
1874
+ }
1875
+ if (required.length)
1876
+ result.required = required;
1877
+ const additionalProperties = decideAdditionalProperties(def, refs);
1878
+ if (additionalProperties !== undefined)
1879
+ result.additionalProperties = additionalProperties;
1880
+ return result;
1881
+ }
1882
+ function decideAdditionalProperties(def, refs) {
1883
+ if (def.catchall._def.typeName !== "ZodNever")
1884
+ return parseDef(def.catchall._def, {
1885
+ ...refs,
1886
+ currentPath: [...refs.currentPath, "additionalProperties"]
1887
+ });
1888
+ switch (def.unknownKeys) {
1889
+ case "passthrough":
1890
+ return refs.allowedAdditionalProperties;
1891
+ case "strict":
1892
+ return refs.rejectedAdditionalProperties;
1893
+ case "strip":
1894
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1895
+ }
1896
+ }
1897
+ function safeIsOptional(schema) {
1898
+ try {
1899
+ return schema.isOptional();
1900
+ } catch (e) {
1901
+ return true;
1902
+ }
1903
+ }
1904
+ var parseOptionalDef = (def, refs) => {
1905
+ var _a2;
1906
+ if (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? undefined : _a2.toString()))
1907
+ return parseDef(def.innerType._def, refs);
1908
+ const innerSchema = parseDef(def.innerType._def, {
1909
+ ...refs,
1910
+ currentPath: [
1911
+ ...refs.currentPath,
1912
+ "anyOf",
1913
+ "1"
1914
+ ]
1915
+ });
1916
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1917
+ };
1918
+ var parsePipelineDef = (def, refs) => {
1919
+ if (refs.pipeStrategy === "input")
1920
+ return parseDef(def.in._def, refs);
1921
+ else if (refs.pipeStrategy === "output")
1922
+ return parseDef(def.out._def, refs);
1923
+ const a = parseDef(def.in._def, {
1924
+ ...refs,
1925
+ currentPath: [
1926
+ ...refs.currentPath,
1927
+ "allOf",
1928
+ "0"
1929
+ ]
1930
+ });
1931
+ return { allOf: [a, parseDef(def.out._def, {
1932
+ ...refs,
1933
+ currentPath: [
1934
+ ...refs.currentPath,
1935
+ "allOf",
1936
+ a ? "1" : "0"
1937
+ ]
1938
+ })].filter((x) => x !== undefined) };
1939
+ };
1940
+ function parsePromiseDef(def, refs) {
1941
+ return parseDef(def.type._def, refs);
1942
+ }
1943
+ function parseSetDef(def, refs) {
1944
+ const schema = {
1945
+ type: "array",
1946
+ uniqueItems: true,
1947
+ items: parseDef(def.valueType._def, {
1948
+ ...refs,
1949
+ currentPath: [...refs.currentPath, "items"]
1950
+ })
1951
+ };
1952
+ if (def.minSize)
1953
+ schema.minItems = def.minSize.value;
1954
+ if (def.maxSize)
1955
+ schema.maxItems = def.maxSize.value;
1956
+ return schema;
1957
+ }
1958
+ function parseTupleDef(def, refs) {
1959
+ if (def.rest)
1960
+ return {
1961
+ type: "array",
1962
+ minItems: def.items.length,
1963
+ items: def.items.map((x, i) => parseDef(x._def, {
1964
+ ...refs,
1965
+ currentPath: [
1966
+ ...refs.currentPath,
1967
+ "items",
1968
+ `${i}`
1969
+ ]
1970
+ })).reduce((acc, x) => x === undefined ? acc : [...acc, x], []),
1971
+ additionalItems: parseDef(def.rest._def, {
1972
+ ...refs,
1973
+ currentPath: [...refs.currentPath, "additionalItems"]
1974
+ })
1975
+ };
1976
+ else
1977
+ return {
1978
+ type: "array",
1979
+ minItems: def.items.length,
1980
+ maxItems: def.items.length,
1981
+ items: def.items.map((x, i) => parseDef(x._def, {
1982
+ ...refs,
1983
+ currentPath: [
1984
+ ...refs.currentPath,
1985
+ "items",
1986
+ `${i}`
1987
+ ]
1988
+ })).reduce((acc, x) => x === undefined ? acc : [...acc, x], [])
1989
+ };
1990
+ }
1991
+ function parseUndefinedDef() {
1992
+ return { not: parseAnyDef() };
1993
+ }
1994
+ function parseUnknownDef() {
1995
+ return parseAnyDef();
1996
+ }
1997
+ var parseReadonlyDef = (def, refs) => {
1998
+ return parseDef(def.innerType._def, refs);
1999
+ };
2000
+ var selectParser = (def, typeName, refs) => {
2001
+ switch (typeName) {
2002
+ case ZodFirstPartyTypeKind.ZodString:
2003
+ return parseStringDef(def, refs);
2004
+ case ZodFirstPartyTypeKind.ZodNumber:
2005
+ return parseNumberDef(def);
2006
+ case ZodFirstPartyTypeKind.ZodObject:
2007
+ return parseObjectDef(def, refs);
2008
+ case ZodFirstPartyTypeKind.ZodBigInt:
2009
+ return parseBigintDef(def);
2010
+ case ZodFirstPartyTypeKind.ZodBoolean:
2011
+ return parseBooleanDef();
2012
+ case ZodFirstPartyTypeKind.ZodDate:
2013
+ return parseDateDef(def, refs);
2014
+ case ZodFirstPartyTypeKind.ZodUndefined:
2015
+ return parseUndefinedDef();
2016
+ case ZodFirstPartyTypeKind.ZodNull:
2017
+ return parseNullDef();
2018
+ case ZodFirstPartyTypeKind.ZodArray:
2019
+ return parseArrayDef(def, refs);
2020
+ case ZodFirstPartyTypeKind.ZodUnion:
2021
+ case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
2022
+ return parseUnionDef(def, refs);
2023
+ case ZodFirstPartyTypeKind.ZodIntersection:
2024
+ return parseIntersectionDef(def, refs);
2025
+ case ZodFirstPartyTypeKind.ZodTuple:
2026
+ return parseTupleDef(def, refs);
2027
+ case ZodFirstPartyTypeKind.ZodRecord:
2028
+ return parseRecordDef(def, refs);
2029
+ case ZodFirstPartyTypeKind.ZodLiteral:
2030
+ return parseLiteralDef(def);
2031
+ case ZodFirstPartyTypeKind.ZodEnum:
2032
+ return parseEnumDef(def);
2033
+ case ZodFirstPartyTypeKind.ZodNativeEnum:
2034
+ return parseNativeEnumDef(def);
2035
+ case ZodFirstPartyTypeKind.ZodNullable:
2036
+ return parseNullableDef(def, refs);
2037
+ case ZodFirstPartyTypeKind.ZodOptional:
2038
+ return parseOptionalDef(def, refs);
2039
+ case ZodFirstPartyTypeKind.ZodMap:
2040
+ return parseMapDef(def, refs);
2041
+ case ZodFirstPartyTypeKind.ZodSet:
2042
+ return parseSetDef(def, refs);
2043
+ case ZodFirstPartyTypeKind.ZodLazy:
2044
+ return () => def.getter()._def;
2045
+ case ZodFirstPartyTypeKind.ZodPromise:
2046
+ return parsePromiseDef(def, refs);
2047
+ case ZodFirstPartyTypeKind.ZodNaN:
2048
+ case ZodFirstPartyTypeKind.ZodNever:
2049
+ return parseNeverDef();
2050
+ case ZodFirstPartyTypeKind.ZodEffects:
2051
+ return parseEffectsDef(def, refs);
2052
+ case ZodFirstPartyTypeKind.ZodAny:
2053
+ return parseAnyDef();
2054
+ case ZodFirstPartyTypeKind.ZodUnknown:
2055
+ return parseUnknownDef();
2056
+ case ZodFirstPartyTypeKind.ZodDefault:
2057
+ return parseDefaultDef(def, refs);
2058
+ case ZodFirstPartyTypeKind.ZodBranded:
2059
+ return parseBrandedDef(def, refs);
2060
+ case ZodFirstPartyTypeKind.ZodReadonly:
2061
+ return parseReadonlyDef(def, refs);
2062
+ case ZodFirstPartyTypeKind.ZodCatch:
2063
+ return parseCatchDef(def, refs);
2064
+ case ZodFirstPartyTypeKind.ZodPipeline:
2065
+ return parsePipelineDef(def, refs);
2066
+ case ZodFirstPartyTypeKind.ZodFunction:
2067
+ case ZodFirstPartyTypeKind.ZodVoid:
2068
+ case ZodFirstPartyTypeKind.ZodSymbol:
2069
+ return;
2070
+ default:
2071
+ return /* @__PURE__ */ ((_) => {
2072
+ return;
2073
+ })(typeName);
2074
+ }
2075
+ };
2076
+ var getRelativePath = (pathA, pathB) => {
2077
+ let i = 0;
2078
+ for (;i < pathA.length && i < pathB.length; i++)
2079
+ if (pathA[i] !== pathB[i])
2080
+ break;
2081
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
2082
+ };
2083
+ function parseDef(def, refs, forceResolution = false) {
2084
+ var _a2;
2085
+ const seenItem = refs.seen.get(def);
2086
+ if (refs.override) {
2087
+ const overrideResult = (_a2 = refs.override) == null ? undefined : _a2.call(refs, def, refs, seenItem, forceResolution);
2088
+ if (overrideResult !== ignoreOverride)
2089
+ return overrideResult;
2090
+ }
2091
+ if (seenItem && !forceResolution) {
2092
+ const seenSchema = get$ref(seenItem, refs);
2093
+ if (seenSchema !== undefined)
2094
+ return seenSchema;
2095
+ }
2096
+ const newItem = {
2097
+ def,
2098
+ path: refs.currentPath,
2099
+ jsonSchema: undefined
2100
+ };
2101
+ refs.seen.set(def, newItem);
2102
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
2103
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
2104
+ if (jsonSchema2)
2105
+ addMeta(def, refs, jsonSchema2);
2106
+ if (refs.postProcess) {
2107
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
2108
+ newItem.jsonSchema = jsonSchema2;
2109
+ return postProcessResult;
2110
+ }
2111
+ newItem.jsonSchema = jsonSchema2;
2112
+ return jsonSchema2;
2113
+ }
2114
+ var get$ref = (item, refs) => {
2115
+ switch (refs.$refStrategy) {
2116
+ case "root":
2117
+ return { $ref: item.path.join("/") };
2118
+ case "relative":
2119
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
2120
+ case "none":
2121
+ case "seen":
2122
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
2123
+ console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
2124
+ return parseAnyDef();
2125
+ }
2126
+ return refs.$refStrategy === "seen" ? parseAnyDef() : undefined;
2127
+ }
2128
+ };
2129
+ var addMeta = (def, refs, jsonSchema2) => {
2130
+ if (def.description)
2131
+ jsonSchema2.description = def.description;
2132
+ return jsonSchema2;
2133
+ };
2134
+ var getRefs = (options) => {
2135
+ const _options = getDefaultOptions(options);
2136
+ const currentPath = _options.name !== undefined ? [
2137
+ ..._options.basePath,
2138
+ _options.definitionPath,
2139
+ _options.name
2140
+ ] : _options.basePath;
2141
+ return {
2142
+ ..._options,
2143
+ currentPath,
2144
+ propertyPath: undefined,
2145
+ seen: new Map(Object.entries(_options.definitions).map(([name2, def]) => [def._def, {
2146
+ def: def._def,
2147
+ path: [
2148
+ ..._options.basePath,
2149
+ _options.definitionPath,
2150
+ name2
2151
+ ],
2152
+ jsonSchema: undefined
2153
+ }]))
2154
+ };
2155
+ };
2156
+ var zod3ToJsonSchema = (schema, options) => {
2157
+ var _a2;
2158
+ const refs = getRefs(options);
2159
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name3, schema2]) => {
2160
+ var _a3;
2161
+ return {
2162
+ ...acc,
2163
+ [name3]: (_a3 = parseDef(schema2._def, {
2164
+ ...refs,
2165
+ currentPath: [
2166
+ ...refs.basePath,
2167
+ refs.definitionPath,
2168
+ name3
2169
+ ]
2170
+ }, true)) != null ? _a3 : parseAnyDef()
2171
+ };
2172
+ }, {}) : undefined;
2173
+ const name2 = typeof options === "string" ? options : (options == null ? undefined : options.nameStrategy) === "title" ? undefined : options == null ? undefined : options.name;
2174
+ const main = (_a2 = parseDef(schema._def, name2 === undefined ? refs : {
2175
+ ...refs,
2176
+ currentPath: [
2177
+ ...refs.basePath,
2178
+ refs.definitionPath,
2179
+ name2
2180
+ ]
2181
+ }, false)) != null ? _a2 : parseAnyDef();
2182
+ const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" ? options.name : undefined;
2183
+ if (title !== undefined)
2184
+ main.title = title;
2185
+ const combined = name2 === undefined ? definitions ? {
2186
+ ...main,
2187
+ [refs.definitionPath]: definitions
2188
+ } : main : {
2189
+ $ref: [
2190
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
2191
+ refs.definitionPath,
2192
+ name2
2193
+ ].join("/"),
2194
+ [refs.definitionPath]: {
2195
+ ...definitions,
2196
+ [name2]: main
2197
+ }
2198
+ };
2199
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
2200
+ return combined;
2201
+ };
2202
+ var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
2203
+ function lazySchema(createSchema) {
2204
+ let schema;
2205
+ return () => {
2206
+ if (schema == null)
2207
+ schema = createSchema();
2208
+ return schema;
2209
+ };
2210
+ }
2211
+ function jsonSchema(jsonSchema2, { validate } = {}) {
2212
+ return {
2213
+ [schemaSymbol]: true,
2214
+ _type: undefined,
2215
+ get jsonSchema() {
2216
+ if (typeof jsonSchema2 === "function")
2217
+ jsonSchema2 = jsonSchema2();
2218
+ return jsonSchema2;
2219
+ },
2220
+ validate
2221
+ };
2222
+ }
2223
+ function isSchema(value) {
2224
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2225
+ }
2226
+ function asSchema2(schema) {
2227
+ return schema == null ? jsonSchema({
2228
+ type: "object",
2229
+ properties: {},
2230
+ additionalProperties: false
2231
+ }) : isSchema(schema) ? schema : ("~standard" in schema) ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
2232
+ }
2233
+ function standardSchema(standardSchema2) {
2234
+ return jsonSchema(() => {
2235
+ if (!hasStandardJsonSchema(standardSchema2))
2236
+ throw new Error(`Standard schema vendor '${standardSchema2["~standard"].vendor}' does not support JSON Schema conversion.`);
2237
+ return addAdditionalPropertiesToJsonSchema(standardSchema2["~standard"].jsonSchema.input({ target: "draft-07" }));
2238
+ }, { validate: async (value) => {
2239
+ const result = await standardSchema2["~standard"].validate(value);
2240
+ return "value" in result ? {
2241
+ success: true,
2242
+ value: result.value
2243
+ } : {
2244
+ success: false,
2245
+ error: new TypeValidationError$1({
2246
+ value,
2247
+ cause: result.issues
2248
+ })
2249
+ };
2250
+ } });
2251
+ }
2252
+ function hasStandardJsonSchema(schema) {
2253
+ return schema["~standard"].jsonSchema != null;
2254
+ }
2255
+ function zod3Schema(zodSchema2, options) {
2256
+ var _a2;
2257
+ const useReferences = (_a2 = options == null ? undefined : options.useReferences) != null ? _a2 : false;
2258
+ return jsonSchema(() => zod3ToJsonSchema(zodSchema2, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => {
2259
+ const result = await zodSchema2.safeParseAsync(value);
2260
+ return result.success ? {
2261
+ success: true,
2262
+ value: result.data
2263
+ } : {
2264
+ success: false,
2265
+ error: result.error
2266
+ };
2267
+ } });
2268
+ }
2269
+ function zod4Schema(zodSchema2, options) {
2270
+ var _a2;
2271
+ const useReferences = (_a2 = options == null ? undefined : options.useReferences) != null ? _a2 : false;
2272
+ return jsonSchema(() => addAdditionalPropertiesToJsonSchema(toJSONSchema(zodSchema2, {
2273
+ target: "draft-7",
2274
+ io: "input",
2275
+ reused: useReferences ? "ref" : "inline"
2276
+ })), { validate: async (value) => {
2277
+ const result = await safeParseAsync(zodSchema2, value);
2278
+ return result.success ? {
2279
+ success: true,
2280
+ value: result.data
2281
+ } : {
2282
+ success: false,
2283
+ error: result.error
2284
+ };
2285
+ } });
2286
+ }
2287
+ function isZod4Schema(zodSchema2) {
2288
+ return "_zod" in zodSchema2;
2289
+ }
2290
+ function zodSchema(zodSchema2, options) {
2291
+ if (isZod4Schema(zodSchema2))
2292
+ return zod4Schema(zodSchema2, options);
2293
+ else
2294
+ return zod3Schema(zodSchema2, options);
2295
+ }
2296
+ async function validateTypes({ value, schema, context }) {
2297
+ const result = await safeValidateTypes({
2298
+ value,
2299
+ schema,
2300
+ context
2301
+ });
2302
+ if (!result.success)
2303
+ throw TypeValidationError$1.wrap({
2304
+ value,
2305
+ cause: result.error,
2306
+ context
2307
+ });
2308
+ return result.value;
2309
+ }
2310
+ async function safeValidateTypes({ value, schema, context }) {
2311
+ const actualSchema = asSchema2(schema);
2312
+ try {
2313
+ if (actualSchema.validate == null)
2314
+ return {
2315
+ success: true,
2316
+ value,
2317
+ rawValue: value
2318
+ };
2319
+ const result = await actualSchema.validate(value);
2320
+ if (result.success)
2321
+ return {
2322
+ success: true,
2323
+ value: result.value,
2324
+ rawValue: value
2325
+ };
2326
+ return {
2327
+ success: false,
2328
+ error: TypeValidationError$1.wrap({
2329
+ value,
2330
+ cause: result.error,
2331
+ context
2332
+ }),
2333
+ rawValue: value
2334
+ };
2335
+ } catch (error) {
2336
+ return {
2337
+ success: false,
2338
+ error: TypeValidationError$1.wrap({
2339
+ value,
2340
+ cause: error,
2341
+ context
2342
+ }),
2343
+ rawValue: value
2344
+ };
2345
+ }
2346
+ }
2347
+ async function parseJSON({ text, schema }) {
2348
+ try {
2349
+ const value = secureJsonParse(text);
2350
+ if (schema == null)
2351
+ return value;
2352
+ return validateTypes({
2353
+ value,
2354
+ schema
2355
+ });
2356
+ } catch (error) {
2357
+ if (JSONParseError$1.isInstance(error) || TypeValidationError$1.isInstance(error))
2358
+ throw error;
2359
+ throw new JSONParseError$1({
2360
+ text,
2361
+ cause: error
2362
+ });
2363
+ }
2364
+ }
2365
+ async function safeParseJSON({ text, schema }) {
2366
+ try {
2367
+ const value = secureJsonParse(text);
2368
+ if (schema == null)
2369
+ return {
2370
+ success: true,
2371
+ value,
2372
+ rawValue: value
2373
+ };
2374
+ return await safeValidateTypes({
2375
+ value,
2376
+ schema
2377
+ });
2378
+ } catch (error) {
2379
+ return {
2380
+ success: false,
2381
+ error: JSONParseError$1.isInstance(error) ? error : new JSONParseError$1({
2382
+ text,
2383
+ cause: error
2384
+ }),
2385
+ rawValue: undefined
2386
+ };
2387
+ }
2388
+ }
2389
+ function parseJsonEventStream({ stream, schema }) {
2390
+ return stream.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).pipeThrough(new TransformStream({ async transform({ data }, controller) {
2391
+ if (data === "[DONE]")
2392
+ return;
2393
+ controller.enqueue(await safeParseJSON({
2394
+ text: data,
2395
+ schema
2396
+ }));
2397
+ } }));
2398
+ }
2399
+ var getOriginalFetch2 = () => globalThis.fetch;
2400
+ var postJsonToApi = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => postToApi({
2401
+ url,
2402
+ headers: {
2403
+ "Content-Type": "application/json",
2404
+ ...headers
2405
+ },
2406
+ body: {
2407
+ content: JSON.stringify(body),
2408
+ values: body
2409
+ },
2410
+ failedResponseHandler,
2411
+ successfulResponseHandler,
2412
+ abortSignal,
2413
+ fetch
2414
+ });
2415
+ var postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch2() }) => {
2416
+ try {
2417
+ const response = await fetch(url, {
2418
+ method: "POST",
2419
+ headers: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION$1}`, getRuntimeEnvironmentUserAgent()),
2420
+ body: body.content,
2421
+ signal: abortSignal
2422
+ });
2423
+ const responseHeaders = extractResponseHeaders(response);
2424
+ if (!response.ok) {
2425
+ let errorInformation;
2426
+ try {
2427
+ errorInformation = await failedResponseHandler({
2428
+ response,
2429
+ url,
2430
+ requestBodyValues: body.values
2431
+ });
2432
+ } catch (error) {
2433
+ if (isAbortError2(error) || APICallError$1.isInstance(error))
2434
+ throw error;
2435
+ throw new APICallError$1({
2436
+ message: "Failed to process error response",
2437
+ cause: error,
2438
+ statusCode: response.status,
2439
+ url,
2440
+ responseHeaders,
2441
+ requestBodyValues: body.values
2442
+ });
2443
+ }
2444
+ throw errorInformation.value;
2445
+ }
2446
+ try {
2447
+ return await successfulResponseHandler({
2448
+ response,
2449
+ url,
2450
+ requestBodyValues: body.values
2451
+ });
2452
+ } catch (error) {
2453
+ if (error instanceof Error) {
2454
+ if (isAbortError2(error) || APICallError$1.isInstance(error))
2455
+ throw error;
2456
+ }
2457
+ throw new APICallError$1({
2458
+ message: "Failed to process successful response",
2459
+ cause: error,
2460
+ statusCode: response.status,
2461
+ url,
2462
+ responseHeaders,
2463
+ requestBodyValues: body.values
2464
+ });
2465
+ }
2466
+ } catch (error) {
2467
+ throw handleFetchError({
2468
+ error,
2469
+ url,
2470
+ requestBodyValues: body.values
2471
+ });
2472
+ }
2473
+ };
2474
+ function tool(tool2) {
2475
+ return tool2;
2476
+ }
2477
+ function createProviderToolFactoryWithOutputSchema({ id, inputSchema, outputSchema, supportsDeferredResults }) {
2478
+ return ({ execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({
2479
+ type: "provider",
2480
+ id,
2481
+ args,
2482
+ inputSchema,
2483
+ outputSchema,
2484
+ execute,
2485
+ needsApproval,
2486
+ toModelOutput,
2487
+ onInputStart,
2488
+ onInputDelta,
2489
+ onInputAvailable,
2490
+ supportsDeferredResults
2491
+ });
2492
+ }
2493
+ async function resolve(value) {
2494
+ if (typeof value === "function")
2495
+ value = value();
2496
+ return Promise.resolve(value);
2497
+ }
2498
+ var retryWithExponentialBackoff = ({ maxRetries = 2, initialDelayInMs = 2000, backoffFactor = 2, abortSignal, shouldRetry, getDelayInMs = ({ exponentialBackoffDelay }) => exponentialBackoffDelay, createRetryError = ({ message }) => new Error(message) }) => async (f) => retryWithExponentialBackoffInternal(f, {
2499
+ maxRetries,
2500
+ delayInMs: initialDelayInMs,
2501
+ backoffFactor,
2502
+ abortSignal,
2503
+ shouldRetry,
2504
+ getDelayInMs,
2505
+ createRetryError
2506
+ });
2507
+ async function retryWithExponentialBackoffInternal(f, { maxRetries, delayInMs, backoffFactor, abortSignal, shouldRetry, getDelayInMs, createRetryError }, errors = []) {
2508
+ try {
2509
+ return await f();
2510
+ } catch (error) {
2511
+ if (isAbortError2(error))
2512
+ throw error;
2513
+ if (maxRetries === 0)
2514
+ throw error;
2515
+ const errorMessage = getErrorMessage$1(error);
2516
+ const newErrors = [...errors, error];
2517
+ const tryNumber = newErrors.length;
2518
+ if (tryNumber > maxRetries)
2519
+ throw createRetryError({
2520
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
2521
+ reason: "maxRetriesExceeded",
2522
+ errors: newErrors
2523
+ });
2524
+ if (await shouldRetry(error) && tryNumber <= maxRetries) {
2525
+ await delay(getDelayInMs({
2526
+ error,
2527
+ exponentialBackoffDelay: delayInMs
2528
+ }), { abortSignal });
2529
+ return retryWithExponentialBackoffInternal(f, {
2530
+ maxRetries,
2531
+ delayInMs: backoffFactor * delayInMs,
2532
+ backoffFactor,
2533
+ abortSignal,
2534
+ shouldRetry,
2535
+ getDelayInMs,
2536
+ createRetryError
2537
+ }, newErrors);
2538
+ }
2539
+ if (tryNumber === 1)
2540
+ throw error;
2541
+ throw createRetryError({
2542
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
2543
+ reason: "errorNotRetryable",
2544
+ errors: newErrors
2545
+ });
2546
+ }
2547
+ }
2548
+ var textDecoder = new TextDecoder;
2549
+ function wrapResponseBodyStream({ stream, url, requestBodyValues, statusCode, responseHeaders }) {
2550
+ const reader = stream.getReader();
2551
+ let readerReleased = false;
2552
+ const releaseReader = () => {
2553
+ if (!readerReleased) {
2554
+ reader.releaseLock();
2555
+ readerReleased = true;
2556
+ }
2557
+ };
2558
+ return new ReadableStream({
2559
+ async pull(controller) {
2560
+ try {
2561
+ const { done, value } = await reader.read();
2562
+ if (done) {
2563
+ releaseReader();
2564
+ controller.close();
2565
+ } else
2566
+ controller.enqueue(value);
2567
+ } catch (error) {
2568
+ releaseReader();
2569
+ if (isAbortError2(error)) {
2570
+ controller.error(error);
2571
+ return;
2572
+ }
2573
+ controller.error(handleFetchError({
2574
+ error: new APICallError$1({
2575
+ message: "Failed to process successful response",
2576
+ cause: error,
2577
+ statusCode,
2578
+ url,
2579
+ responseHeaders,
2580
+ requestBodyValues
2581
+ }),
2582
+ url,
2583
+ requestBodyValues
2584
+ }));
2585
+ }
2586
+ },
2587
+ async cancel(reason) {
2588
+ try {
2589
+ await reader.cancel(reason);
2590
+ } finally {
2591
+ releaseReader();
2592
+ }
2593
+ }
2594
+ });
2595
+ }
2596
+ async function readResponseBodyAsText({ response, url }) {
2597
+ return textDecoder.decode(await readResponseWithSizeLimit({
2598
+ response,
2599
+ url
2600
+ }));
2601
+ }
2602
+ var createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => {
2603
+ const responseBody = await readResponseBodyAsText({
2604
+ response,
2605
+ url
2606
+ });
2607
+ const responseHeaders = extractResponseHeaders(response);
2608
+ if (responseBody.trim() === "")
2609
+ return {
2610
+ responseHeaders,
2611
+ value: new APICallError$1({
2612
+ message: response.statusText,
2613
+ url,
2614
+ requestBodyValues,
2615
+ statusCode: response.status,
2616
+ responseHeaders,
2617
+ responseBody,
2618
+ isRetryable: isRetryable == null ? undefined : isRetryable(response)
2619
+ })
2620
+ };
2621
+ try {
2622
+ const parsedError = await parseJSON({
2623
+ text: responseBody,
2624
+ schema: errorSchema
2625
+ });
2626
+ return {
2627
+ responseHeaders,
2628
+ value: new APICallError$1({
2629
+ message: errorToMessage(parsedError),
2630
+ url,
2631
+ requestBodyValues,
2632
+ statusCode: response.status,
2633
+ responseHeaders,
2634
+ responseBody,
2635
+ data: parsedError,
2636
+ isRetryable: isRetryable == null ? undefined : isRetryable(response, parsedError)
2637
+ })
2638
+ };
2639
+ } catch (parseError) {
2640
+ return {
2641
+ responseHeaders,
2642
+ value: new APICallError$1({
2643
+ message: response.statusText,
2644
+ url,
2645
+ requestBodyValues,
2646
+ statusCode: response.status,
2647
+ responseHeaders,
2648
+ responseBody,
2649
+ isRetryable: isRetryable == null ? undefined : isRetryable(response)
2650
+ })
2651
+ };
2652
+ }
2653
+ };
2654
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response, url, requestBodyValues }) => {
2655
+ const responseHeaders = extractResponseHeaders(response);
2656
+ if (response.body == null)
2657
+ throw new EmptyResponseBodyError$1({});
2658
+ return {
2659
+ responseHeaders,
2660
+ value: parseJsonEventStream({
2661
+ stream: wrapResponseBodyStream({
2662
+ stream: response.body,
2663
+ url,
2664
+ requestBodyValues,
2665
+ statusCode: response.status,
2666
+ responseHeaders
2667
+ }),
2668
+ schema: chunkSchema
2669
+ })
2670
+ };
2671
+ };
2672
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
2673
+ const responseBody = await readResponseBodyAsText({
2674
+ response,
2675
+ url
2676
+ });
2677
+ const parsedResult = await safeParseJSON({
2678
+ text: responseBody,
2679
+ schema: responseSchema
2680
+ });
2681
+ const responseHeaders = extractResponseHeaders(response);
2682
+ if (!parsedResult.success)
2683
+ throw new APICallError$1({
2684
+ message: "Invalid JSON response",
2685
+ cause: parsedResult.error,
2686
+ statusCode: response.status,
2687
+ responseHeaders,
2688
+ responseBody,
2689
+ url,
2690
+ requestBodyValues
2691
+ });
2692
+ return {
2693
+ responseHeaders,
2694
+ value: parsedResult.value,
2695
+ rawValue: parsedResult.rawValue
2696
+ };
2697
+ };
2698
+ function withoutTrailingSlash(url) {
2699
+ return url == null ? undefined : url.replace(/\/$/, "");
2700
+ }
2701
+ function isAsyncIterable(obj) {
2702
+ return obj != null && typeof obj[Symbol.asyncIterator] === "function";
2703
+ }
2704
+ async function* executeTool({ execute, input, options }) {
2705
+ const result = execute(input, options);
2706
+ if (isAsyncIterable(result)) {
2707
+ let lastOutput;
2708
+ for await (const output of result) {
2709
+ lastOutput = output;
2710
+ yield {
2711
+ type: "preliminary",
2712
+ output
2713
+ };
2714
+ }
2715
+ yield {
2716
+ type: "final",
2717
+ output: lastOutput
2718
+ };
2719
+ } else
2720
+ yield {
2721
+ type: "final",
2722
+ output: await result
2723
+ };
2724
+ }
2725
+ var marker = "vercel.ai.error";
2726
+ var symbol$3 = Symbol.for(marker);
2727
+ var _a$3;
2728
+ var _b$3;
2729
+ var AISDKError = class _AISDKError extends (_b$3 = Error, _a$3 = symbol$3, _b$3) {
2730
+ constructor({ name: name14, message, cause }) {
2731
+ super(message);
2732
+ this[_a$3] = true;
2733
+ this.name = name14;
2734
+ this.cause = cause;
2735
+ }
2736
+ static isInstance(error) {
2737
+ return _AISDKError.hasMarker(error, marker);
2738
+ }
2739
+ static hasMarker(error, marker15) {
2740
+ const markerSymbol = Symbol.for(marker15);
2741
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
2742
+ }
2743
+ };
2744
+ var name$3 = "AI_APICallError";
2745
+ var marker2$2 = `vercel.ai.error.${name$3}`;
2746
+ var symbol2$2 = Symbol.for(marker2$2);
2747
+ var _a2$2;
2748
+ var _b2$2;
2749
+ var APICallError2 = class extends (_b2$2 = AISDKError, _a2$2 = symbol2$2, _b2$2) {
2750
+ constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) {
2751
+ super({
2752
+ name: name$3,
2753
+ message,
2754
+ cause
2755
+ });
2756
+ this[_a2$2] = true;
2757
+ this.url = url;
2758
+ this.requestBodyValues = requestBodyValues;
2759
+ this.statusCode = statusCode;
2760
+ this.responseHeaders = responseHeaders;
2761
+ this.responseBody = responseBody;
2762
+ this.isRetryable = isRetryable;
2763
+ this.data = data;
2764
+ }
2765
+ static isInstance(error) {
2766
+ return AISDKError.hasMarker(error, marker2$2);
2767
+ }
2768
+ };
2769
+ var name2$2 = "AI_EmptyResponseBodyError";
2770
+ var marker3$2 = `vercel.ai.error.${name2$2}`;
2771
+ var symbol3$2 = Symbol.for(marker3$2);
2772
+ var _a3$2;
2773
+ var _b3$2;
2774
+ (class extends (_b3$2 = AISDKError, _a3$2 = symbol3$2, _b3$2) {
2775
+ constructor({ message = "Empty response body" } = {}) {
2776
+ super({
2777
+ name: name2$2,
2778
+ message
2779
+ });
2780
+ this[_a3$2] = true;
2781
+ }
2782
+ static isInstance(error) {
2783
+ return AISDKError.hasMarker(error, marker3$2);
2784
+ }
2785
+ });
2786
+ function getErrorMessage(error) {
2787
+ if (error == null)
2788
+ return "unknown error";
2789
+ if (typeof error === "string")
2790
+ return error;
2791
+ if (error instanceof Error)
2792
+ return error.message;
2793
+ return JSON.stringify(error);
2794
+ }
2795
+ var name3$2 = "AI_InvalidArgumentError";
2796
+ var marker4$2 = `vercel.ai.error.${name3$2}`;
2797
+ var symbol4$2 = Symbol.for(marker4$2);
2798
+ var _a4$2;
2799
+ var _b4$2;
2800
+ (class extends (_b4$2 = AISDKError, _a4$2 = symbol4$2, _b4$2) {
2801
+ constructor({ message, cause, argument }) {
2802
+ super({
2803
+ name: name3$2,
2804
+ message,
2805
+ cause
2806
+ });
2807
+ this[_a4$2] = true;
2808
+ this.argument = argument;
2809
+ }
2810
+ static isInstance(error) {
2811
+ return AISDKError.hasMarker(error, marker4$2);
2812
+ }
2813
+ });
2814
+ var name4$2 = "AI_InvalidPromptError";
2815
+ var marker5$2 = `vercel.ai.error.${name4$2}`;
2816
+ var symbol5$2 = Symbol.for(marker5$2);
2817
+ var _a5$2;
2818
+ var _b5$2;
2819
+ var InvalidPromptError = class extends (_b5$2 = AISDKError, _a5$2 = symbol5$2, _b5$2) {
2820
+ constructor({ prompt, message, cause }) {
2821
+ super({
2822
+ name: name4$2,
2823
+ message: `Invalid prompt: ${message}`,
2824
+ cause
2825
+ });
2826
+ this[_a5$2] = true;
2827
+ this.prompt = prompt;
2828
+ }
2829
+ static isInstance(error) {
2830
+ return AISDKError.hasMarker(error, marker5$2);
2831
+ }
2832
+ };
2833
+ var name5$2 = "AI_InvalidResponseDataError";
2834
+ var marker6$2 = `vercel.ai.error.${name5$2}`;
2835
+ var symbol6$2 = Symbol.for(marker6$2);
2836
+ var _a6$2;
2837
+ var _b6$2;
2838
+ (class extends (_b6$2 = AISDKError, _a6$2 = symbol6$2, _b6$2) {
2839
+ constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) {
2840
+ super({
2841
+ name: name5$2,
2842
+ message
2843
+ });
2844
+ this[_a6$2] = true;
2845
+ this.data = data;
2846
+ }
2847
+ static isInstance(error) {
2848
+ return AISDKError.hasMarker(error, marker6$2);
2849
+ }
2850
+ });
2851
+ var name6$2 = "AI_JSONParseError";
2852
+ var marker7$2 = `vercel.ai.error.${name6$2}`;
2853
+ var symbol7$2 = Symbol.for(marker7$2);
2854
+ var _a7$2;
2855
+ var _b7$2;
2856
+ (class extends (_b7$2 = AISDKError, _a7$2 = symbol7$2, _b7$2) {
2857
+ constructor({ text, cause }) {
2858
+ super({
2859
+ name: name6$2,
2860
+ message: `JSON parsing failed: Text: ${text}.
2861
+ Error message: ${getErrorMessage(cause)}`,
2862
+ cause
2863
+ });
2864
+ this[_a7$2] = true;
2865
+ this.text = text;
2866
+ }
2867
+ static isInstance(error) {
2868
+ return AISDKError.hasMarker(error, marker7$2);
2869
+ }
2870
+ });
2871
+ var name7$2 = "AI_LoadAPIKeyError";
2872
+ var marker8$2 = `vercel.ai.error.${name7$2}`;
2873
+ var symbol8$2 = Symbol.for(marker8$2);
2874
+ var _a8$2;
2875
+ var _b8$2;
2876
+ (class extends (_b8$2 = AISDKError, _a8$2 = symbol8$2, _b8$2) {
2877
+ constructor({ message }) {
2878
+ super({
2879
+ name: name7$2,
2880
+ message
2881
+ });
2882
+ this[_a8$2] = true;
2883
+ }
2884
+ static isInstance(error) {
2885
+ return AISDKError.hasMarker(error, marker8$2);
2886
+ }
2887
+ });
2888
+ var name8$2 = "AI_LoadSettingError";
2889
+ var marker9$2 = `vercel.ai.error.${name8$2}`;
2890
+ var symbol9$2 = Symbol.for(marker9$2);
2891
+ var _a9$2;
2892
+ var _b9$2;
2893
+ (class extends (_b9$2 = AISDKError, _a9$2 = symbol9$2, _b9$2) {
2894
+ constructor({ message }) {
2895
+ super({
2896
+ name: name8$2,
2897
+ message
2898
+ });
2899
+ this[_a9$2] = true;
2900
+ }
2901
+ static isInstance(error) {
2902
+ return AISDKError.hasMarker(error, marker9$2);
2903
+ }
2904
+ });
2905
+ var name9$2 = "AI_NoContentGeneratedError";
2906
+ var marker10$2 = `vercel.ai.error.${name9$2}`;
2907
+ var symbol10$2 = Symbol.for(marker10$2);
2908
+ var _a10$2;
2909
+ var _b10$2;
2910
+ (class extends (_b10$2 = AISDKError, _a10$2 = symbol10$2, _b10$2) {
2911
+ constructor({ message = "No content generated." } = {}) {
2912
+ super({
2913
+ name: name9$2,
2914
+ message
2915
+ });
2916
+ this[_a10$2] = true;
2917
+ }
2918
+ static isInstance(error) {
2919
+ return AISDKError.hasMarker(error, marker10$2);
2920
+ }
2921
+ });
2922
+ var name10 = "AI_NoSuchModelError";
2923
+ var marker11 = `vercel.ai.error.${name10}`;
2924
+ var symbol11 = Symbol.for(marker11);
2925
+ var _a11;
2926
+ var _b11;
2927
+ (class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {
2928
+ constructor({ errorName = name10, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) {
2929
+ super({
2930
+ name: errorName,
2931
+ message
2932
+ });
2933
+ this[_a11] = true;
2934
+ this.modelId = modelId;
2935
+ this.modelType = modelType;
2936
+ }
2937
+ static isInstance(error) {
2938
+ return AISDKError.hasMarker(error, marker11);
2939
+ }
2940
+ });
2941
+ var name11 = "AI_TooManyEmbeddingValuesForCallError";
2942
+ var marker12 = `vercel.ai.error.${name11}`;
2943
+ var symbol12 = Symbol.for(marker12);
2944
+ var _a12;
2945
+ var _b12;
2946
+ (class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {
2947
+ constructor(options) {
2948
+ super({
2949
+ name: name11,
2950
+ 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.`
2951
+ });
2952
+ this[_a12] = true;
2953
+ this.provider = options.provider;
2954
+ this.modelId = options.modelId;
2955
+ this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
2956
+ this.values = options.values;
2957
+ }
2958
+ static isInstance(error) {
2959
+ return AISDKError.hasMarker(error, marker12);
2960
+ }
2961
+ });
2962
+ var name12 = "AI_TypeValidationError";
2963
+ var marker13 = `vercel.ai.error.${name12}`;
2964
+ var symbol13 = Symbol.for(marker13);
2965
+ var _a13;
2966
+ var _b13;
2967
+ var TypeValidationError2 = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
2968
+ constructor({ value, cause, context }) {
2969
+ let contextPrefix = "Type validation failed";
2970
+ if (context == null ? undefined : context.field)
2971
+ contextPrefix += ` for ${context.field}`;
2972
+ if ((context == null ? undefined : context.entityName) || (context == null ? undefined : context.entityId)) {
2973
+ contextPrefix += " (";
2974
+ const parts = [];
2975
+ if (context.entityName)
2976
+ parts.push(context.entityName);
2977
+ if (context.entityId)
2978
+ parts.push(`id: "${context.entityId}"`);
2979
+ contextPrefix += parts.join(", ");
2980
+ contextPrefix += ")";
2981
+ }
2982
+ super({
2983
+ name: name12,
2984
+ message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
2985
+ Error message: ${getErrorMessage(cause)}`,
2986
+ cause
2987
+ });
2988
+ this[_a13] = true;
2989
+ this.value = value;
2990
+ this.context = context;
2991
+ }
2992
+ static isInstance(error) {
2993
+ return AISDKError.hasMarker(error, marker13);
2994
+ }
2995
+ static wrap({ value, cause, context }) {
2996
+ var _a15, _b15, _c;
2997
+ if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a15 = cause.context) == null ? undefined : _a15.field) === (context == null ? undefined : context.field) && ((_b15 = cause.context) == null ? undefined : _b15.entityName) === (context == null ? undefined : context.entityName) && ((_c = cause.context) == null ? undefined : _c.entityId) === (context == null ? undefined : context.entityId))
2998
+ return cause;
2999
+ return new _TypeValidationError({
3000
+ value,
3001
+ cause,
3002
+ context
3003
+ });
3004
+ }
3005
+ };
3006
+ var name13 = "AI_UnsupportedFunctionalityError";
3007
+ var marker14 = `vercel.ai.error.${name13}`;
3008
+ var symbol14 = Symbol.for(marker14);
3009
+ var _a14;
3010
+ var _b14;
3011
+ var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {
3012
+ constructor({ functionality, message = `'${functionality}' functionality not supported.` }) {
3013
+ super({
3014
+ name: name13,
3015
+ message
3016
+ });
3017
+ this[_a14] = true;
3018
+ this.functionality = functionality;
3019
+ }
3020
+ static isInstance(error) {
3021
+ return AISDKError.hasMarker(error, marker14);
3022
+ }
3023
+ };
3024
+ function getContext() {
3025
+ return { headers: {} };
3026
+ }
3027
+ async function getVercelOidcToken() {
3028
+ if (process.env.VERCEL_OIDC_TOKEN)
3029
+ return process.env.VERCEL_OIDC_TOKEN ?? "";
3030
+ throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
3031
+ }
3032
+ var symbol = Symbol.for("vercel.ai.gateway.error");
3033
+ var _a;
3034
+ var _b;
3035
+ var GatewayError = class _GatewayError extends (_b = Error, _a = symbol, _b) {
3036
+ constructor({ message, statusCode = 500, cause, generationId, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500) }) {
3037
+ super(generationId ? `${message} [${generationId}]` : message);
3038
+ this[_a] = true;
3039
+ this.statusCode = statusCode;
3040
+ this.cause = cause;
3041
+ this.generationId = generationId;
3042
+ this.isRetryable = isRetryable;
3043
+ }
3044
+ static isInstance(error) {
3045
+ return _GatewayError.hasMarker(error);
3046
+ }
3047
+ static hasMarker(error) {
3048
+ return typeof error === "object" && error !== null && symbol in error && error[symbol] === true;
3049
+ }
3050
+ };
3051
+ var name = "GatewayAuthenticationError";
3052
+ var marker2 = `vercel.ai.gateway.error.${name}`;
3053
+ var symbol2 = Symbol.for(marker2);
3054
+ var _a2;
3055
+ var _b2;
3056
+ var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a2 = symbol2, _b2) {
3057
+ constructor({ message = "Authentication failed", statusCode = 401, cause, generationId } = {}) {
3058
+ super({
3059
+ message,
3060
+ statusCode,
3061
+ cause,
3062
+ generationId
3063
+ });
3064
+ this[_a2] = true;
3065
+ this.name = name;
3066
+ this.type = "authentication_error";
3067
+ }
3068
+ static isInstance(error) {
3069
+ return GatewayError.hasMarker(error) && symbol2 in error;
3070
+ }
3071
+ static createContextualError({ apiKeyProvided, oidcTokenProvided, message = "Authentication failed", statusCode = 401, cause, generationId }) {
3072
+ let contextualMessage;
3073
+ if (apiKeyProvided)
3074
+ contextualMessage = `AI Gateway authentication failed: Invalid API key.
3075
+
3076
+ Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
3077
+
3078
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;
3079
+ else if (oidcTokenProvided)
3080
+ contextualMessage = `AI Gateway authentication failed: Invalid OIDC token.
3081
+
3082
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
3083
+
3084
+ Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`;
3085
+ else
3086
+ contextualMessage = `AI Gateway authentication failed: No authentication provided.
3087
+
3088
+ Option 1 - API key:
3089
+ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
3090
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
3091
+
3092
+ Option 2 - OIDC token:
3093
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;
3094
+ return new _GatewayAuthenticationError({
3095
+ message: contextualMessage,
3096
+ statusCode,
3097
+ cause,
3098
+ generationId
3099
+ });
3100
+ }
3101
+ };
3102
+ var name2 = "GatewayInvalidRequestError";
3103
+ var marker3 = `vercel.ai.gateway.error.${name2}`;
3104
+ var symbol3 = Symbol.for(marker3);
3105
+ var _a3;
3106
+ var _b3;
3107
+ var GatewayInvalidRequestError = class extends (_b3 = GatewayError, _a3 = symbol3, _b3) {
3108
+ constructor({ message = "Invalid request", statusCode = 400, cause, generationId } = {}) {
3109
+ super({
3110
+ message,
3111
+ statusCode,
3112
+ cause,
3113
+ generationId
3114
+ });
3115
+ this[_a3] = true;
3116
+ this.name = name2;
3117
+ this.type = "invalid_request_error";
3118
+ }
3119
+ static isInstance(error) {
3120
+ return GatewayError.hasMarker(error) && symbol3 in error;
3121
+ }
3122
+ };
3123
+ var name3 = "GatewayRateLimitError";
3124
+ var marker4 = `vercel.ai.gateway.error.${name3}`;
3125
+ var symbol4 = Symbol.for(marker4);
3126
+ var _a4;
3127
+ var _b4;
3128
+ var GatewayRateLimitError = class extends (_b4 = GatewayError, _a4 = symbol4, _b4) {
3129
+ constructor({ message = "Rate limit exceeded", statusCode = 429, cause, generationId } = {}) {
3130
+ super({
3131
+ message,
3132
+ statusCode,
3133
+ cause,
3134
+ generationId
3135
+ });
3136
+ this[_a4] = true;
3137
+ this.name = name3;
3138
+ this.type = "rate_limit_exceeded";
3139
+ }
3140
+ static isInstance(error) {
3141
+ return GatewayError.hasMarker(error) && symbol4 in error;
3142
+ }
3143
+ };
3144
+ var name4 = "GatewayModelNotFoundError";
3145
+ var marker5 = `vercel.ai.gateway.error.${name4}`;
3146
+ var symbol5 = Symbol.for(marker5);
3147
+ var modelNotFoundParamSchema = lazySchema(() => zodSchema(object({ modelId: string() })));
3148
+ var _a5;
3149
+ var _b5;
3150
+ var GatewayModelNotFoundError = class extends (_b5 = GatewayError, _a5 = symbol5, _b5) {
3151
+ constructor({ message = "Model not found", statusCode = 404, modelId, cause, generationId } = {}) {
3152
+ super({
3153
+ message,
3154
+ statusCode,
3155
+ cause,
3156
+ generationId
3157
+ });
3158
+ this[_a5] = true;
3159
+ this.name = name4;
3160
+ this.type = "model_not_found";
3161
+ this.modelId = modelId;
3162
+ }
3163
+ static isInstance(error) {
3164
+ return GatewayError.hasMarker(error) && symbol5 in error;
3165
+ }
3166
+ };
3167
+ var name5 = "GatewayInternalServerError";
3168
+ var marker6 = `vercel.ai.gateway.error.${name5}`;
3169
+ var symbol6 = Symbol.for(marker6);
3170
+ var _a6;
3171
+ var _b6;
3172
+ var GatewayInternalServerError = class extends (_b6 = GatewayError, _a6 = symbol6, _b6) {
3173
+ constructor({ message = "Internal server error", statusCode = 500, cause, generationId } = {}) {
3174
+ super({
3175
+ message,
3176
+ statusCode,
3177
+ cause,
3178
+ generationId
3179
+ });
3180
+ this[_a6] = true;
3181
+ this.name = name5;
3182
+ this.type = "internal_server_error";
3183
+ }
3184
+ static isInstance(error) {
3185
+ return GatewayError.hasMarker(error) && symbol6 in error;
3186
+ }
3187
+ };
3188
+ var name6 = "GatewayFailedDependencyError";
3189
+ var marker7 = `vercel.ai.gateway.error.${name6}`;
3190
+ var symbol7 = Symbol.for(marker7);
3191
+ var _a7;
3192
+ var _b7;
3193
+ var GatewayFailedDependencyError = class extends (_b7 = GatewayError, _a7 = symbol7, _b7) {
3194
+ constructor({ message = "Failed dependency", statusCode = 424, cause, generationId } = {}) {
3195
+ super({
3196
+ message,
3197
+ statusCode,
3198
+ cause,
3199
+ generationId
3200
+ });
3201
+ this[_a7] = true;
3202
+ this.name = name6;
3203
+ this.type = "failed_dependency";
3204
+ }
3205
+ static isInstance(error) {
3206
+ return GatewayError.hasMarker(error) && symbol7 in error;
3207
+ }
3208
+ };
3209
+ var name7 = "GatewayForbiddenError";
3210
+ var marker8 = `vercel.ai.gateway.error.${name7}`;
3211
+ var symbol8 = Symbol.for(marker8);
3212
+ var forbiddenParamSchema = lazySchema(() => zodSchema(object({ ruleId: string() })));
3213
+ var _a8;
3214
+ var _b8;
3215
+ var GatewayForbiddenError = class extends (_b8 = GatewayError, _a8 = symbol8, _b8) {
3216
+ constructor({ message = "Forbidden", statusCode = 403, cause, generationId, ruleId } = {}) {
3217
+ super({
3218
+ message,
3219
+ statusCode,
3220
+ cause,
3221
+ generationId
3222
+ });
3223
+ this[_a8] = true;
3224
+ this.name = name7;
3225
+ this.type = "forbidden";
3226
+ this.ruleId = ruleId;
3227
+ }
3228
+ static isInstance(error) {
3229
+ return GatewayError.hasMarker(error) && symbol8 in error;
3230
+ }
3231
+ };
3232
+ var name8 = "GatewayResponseError";
3233
+ var marker9 = `vercel.ai.gateway.error.${name8}`;
3234
+ var symbol9 = Symbol.for(marker9);
3235
+ var _a9;
3236
+ var _b9;
3237
+ var GatewayResponseError = class extends (_b9 = GatewayError, _a9 = symbol9, _b9) {
3238
+ constructor({ message = "Invalid response from Gateway", statusCode = 502, response, validationError, cause, generationId } = {}) {
3239
+ super({
3240
+ message,
3241
+ statusCode,
3242
+ cause,
3243
+ generationId
3244
+ });
3245
+ this[_a9] = true;
3246
+ this.name = name8;
3247
+ this.type = "response_error";
3248
+ this.response = response;
3249
+ this.validationError = validationError;
3250
+ }
3251
+ static isInstance(error) {
3252
+ return GatewayError.hasMarker(error) && symbol9 in error;
3253
+ }
3254
+ };
3255
+ async function createGatewayErrorFromResponse({ response, statusCode, defaultMessage = "Gateway request failed", cause, authMethod }) {
3256
+ var _a11;
3257
+ const parseResult = await safeValidateTypes({
3258
+ value: response,
3259
+ schema: gatewayErrorResponseSchema
3260
+ });
3261
+ if (!parseResult.success) {
3262
+ const rawGenerationId = typeof response === "object" && response !== null && "generationId" in response ? response.generationId : undefined;
3263
+ return new GatewayResponseError({
3264
+ message: `Invalid error response format: ${defaultMessage}`,
3265
+ statusCode,
3266
+ response,
3267
+ validationError: parseResult.error,
3268
+ cause,
3269
+ generationId: rawGenerationId
3270
+ });
3271
+ }
3272
+ const validatedResponse = parseResult.value;
3273
+ const errorType = validatedResponse.error.type;
3274
+ const message = validatedResponse.error.message;
3275
+ const generationId = (_a11 = validatedResponse.generationId) != null ? _a11 : undefined;
3276
+ switch (errorType) {
3277
+ case "authentication_error":
3278
+ return GatewayAuthenticationError.createContextualError({
3279
+ apiKeyProvided: authMethod === "api-key",
3280
+ oidcTokenProvided: authMethod === "oidc",
3281
+ statusCode,
3282
+ cause,
3283
+ generationId
3284
+ });
3285
+ case "invalid_request_error":
3286
+ return new GatewayInvalidRequestError({
3287
+ message,
3288
+ statusCode,
3289
+ cause,
3290
+ generationId
3291
+ });
3292
+ case "rate_limit_exceeded":
3293
+ return new GatewayRateLimitError({
3294
+ message,
3295
+ statusCode,
3296
+ cause,
3297
+ generationId
3298
+ });
3299
+ case "model_not_found": {
3300
+ const modelResult = await safeValidateTypes({
3301
+ value: validatedResponse.error.param,
3302
+ schema: modelNotFoundParamSchema
3303
+ });
3304
+ return new GatewayModelNotFoundError({
3305
+ message,
3306
+ statusCode,
3307
+ modelId: modelResult.success ? modelResult.value.modelId : undefined,
3308
+ cause,
3309
+ generationId
3310
+ });
3311
+ }
3312
+ case "internal_server_error":
3313
+ return new GatewayInternalServerError({
3314
+ message,
3315
+ statusCode,
3316
+ cause,
3317
+ generationId
3318
+ });
3319
+ case "failed_dependency":
3320
+ return new GatewayFailedDependencyError({
3321
+ message,
3322
+ statusCode,
3323
+ cause,
3324
+ generationId
3325
+ });
3326
+ case "forbidden": {
3327
+ const ruleResult = await safeValidateTypes({
3328
+ value: validatedResponse.error.param,
3329
+ schema: forbiddenParamSchema
3330
+ });
3331
+ return new GatewayForbiddenError({
3332
+ message,
3333
+ statusCode,
3334
+ cause,
3335
+ generationId,
3336
+ ruleId: ruleResult.success ? ruleResult.value.ruleId : undefined
3337
+ });
3338
+ }
3339
+ default:
3340
+ return new GatewayInternalServerError({
3341
+ message,
3342
+ statusCode,
3343
+ cause,
3344
+ generationId
3345
+ });
3346
+ }
3347
+ }
3348
+ var gatewayErrorResponseSchema = lazySchema(() => zodSchema(object({
3349
+ error: object({
3350
+ message: string(),
3351
+ type: string().nullish(),
3352
+ param: unknown().nullish(),
3353
+ code: union([string(), number()]).nullish()
3354
+ }),
3355
+ generationId: string().nullish()
3356
+ })));
3357
+ function extractApiCallResponse(error) {
3358
+ if (error.data !== undefined)
3359
+ return error.data;
3360
+ if (error.responseBody != null)
3361
+ try {
3362
+ return secureJsonParse(error.responseBody);
3363
+ } catch (e) {
3364
+ return error.responseBody;
3365
+ }
3366
+ return {};
3367
+ }
3368
+ var name9 = "GatewayTimeoutError";
3369
+ var marker10 = `vercel.ai.gateway.error.${name9}`;
3370
+ var symbol10 = Symbol.for(marker10);
3371
+ var _a10;
3372
+ var _b10;
3373
+ var GatewayTimeoutError = class _GatewayTimeoutError extends (_b10 = GatewayError, _a10 = symbol10, _b10) {
3374
+ constructor({ message = "Request timed out", statusCode = 408, cause, generationId } = {}) {
3375
+ super({
3376
+ message,
3377
+ statusCode,
3378
+ cause,
3379
+ generationId
3380
+ });
3381
+ this[_a10] = true;
3382
+ this.name = name9;
3383
+ this.type = "timeout_error";
3384
+ }
3385
+ static isInstance(error) {
3386
+ return GatewayError.hasMarker(error) && symbol10 in error;
3387
+ }
3388
+ static createTimeoutError({ originalMessage, statusCode = 408, cause, generationId }) {
3389
+ const message = `Gateway request timed out: ${originalMessage}
3390
+
3391
+ This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;
3392
+ return new _GatewayTimeoutError({
3393
+ message,
3394
+ statusCode,
3395
+ cause,
3396
+ generationId
3397
+ });
3398
+ }
3399
+ };
3400
+ function isTimeoutError(error) {
3401
+ if (!(error instanceof Error))
3402
+ return false;
3403
+ const errorCode = error.code;
3404
+ if (typeof errorCode === "string")
3405
+ return [
3406
+ "UND_ERR_HEADERS_TIMEOUT",
3407
+ "UND_ERR_BODY_TIMEOUT",
3408
+ "UND_ERR_CONNECT_TIMEOUT"
3409
+ ].includes(errorCode);
3410
+ return false;
3411
+ }
3412
+ async function asGatewayError(error, authMethod) {
3413
+ var _a11;
3414
+ if (GatewayError.isInstance(error))
3415
+ return error;
3416
+ if (isTimeoutError(error))
3417
+ return GatewayTimeoutError.createTimeoutError({
3418
+ originalMessage: error instanceof Error ? error.message : "Unknown error",
3419
+ cause: error
3420
+ });
3421
+ if (APICallError2.isInstance(error)) {
3422
+ if (error.cause && isTimeoutError(error.cause))
3423
+ return GatewayTimeoutError.createTimeoutError({
3424
+ originalMessage: error.message,
3425
+ cause: error
3426
+ });
3427
+ return await createGatewayErrorFromResponse({
3428
+ response: extractApiCallResponse(error),
3429
+ statusCode: (_a11 = error.statusCode) != null ? _a11 : 500,
3430
+ defaultMessage: "Gateway request failed",
3431
+ cause: error,
3432
+ authMethod
3433
+ });
3434
+ }
3435
+ return await createGatewayErrorFromResponse({
3436
+ response: {},
3437
+ statusCode: 500,
3438
+ defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
3439
+ cause: error,
3440
+ authMethod
3441
+ });
3442
+ }
3443
+ var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method";
3444
+ async function parseAuthMethod(headers) {
3445
+ const result = await safeValidateTypes({
3446
+ value: headers[GATEWAY_AUTH_METHOD_HEADER],
3447
+ schema: gatewayAuthMethodSchema
3448
+ });
3449
+ return result.success ? result.value : undefined;
3450
+ }
3451
+ var gatewayAuthMethodSchema = lazySchema(() => zodSchema(union([literal("api-key"), literal("oidc")])));
3452
+ var KNOWN_MODEL_TYPES = [
3453
+ "embedding",
3454
+ "image",
3455
+ "language",
3456
+ "reranking",
3457
+ "speech",
3458
+ "transcription",
3459
+ "video"
3460
+ ];
3461
+ var GatewayFetchMetadata = class {
3462
+ constructor(config) {
3463
+ this.config = config;
3464
+ }
3465
+ async getAvailableModels() {
3466
+ try {
3467
+ const { value } = await getFromApi({
3468
+ url: `${this.config.baseURL}/config`,
3469
+ headers: await resolve(this.config.headers()),
3470
+ successfulResponseHandler: createJsonResponseHandler(gatewayAvailableModelsResponseSchema),
3471
+ failedResponseHandler: createJsonErrorResponseHandler({
3472
+ errorSchema: any(),
3473
+ errorToMessage: (data) => data
3474
+ }),
3475
+ fetch: this.config.fetch
3476
+ });
3477
+ return value;
3478
+ } catch (error) {
3479
+ throw await asGatewayError(error);
3480
+ }
3481
+ }
3482
+ async getCredits() {
3483
+ try {
3484
+ const { value } = await getFromApi({
3485
+ url: `${new URL(this.config.baseURL).origin}/v1/credits`,
3486
+ headers: await resolve(this.config.headers()),
3487
+ successfulResponseHandler: createJsonResponseHandler(gatewayCreditsResponseSchema),
3488
+ failedResponseHandler: createJsonErrorResponseHandler({
3489
+ errorSchema: any(),
3490
+ errorToMessage: (data) => data
3491
+ }),
3492
+ fetch: this.config.fetch
3493
+ });
3494
+ return value;
3495
+ } catch (error) {
3496
+ throw await asGatewayError(error);
3497
+ }
3498
+ }
3499
+ };
3500
+ var gatewayAvailableModelsResponseSchema = lazySchema(() => zodSchema(object({ models: array(object({
3501
+ id: string(),
3502
+ name: string(),
3503
+ description: string().nullish(),
3504
+ pricing: object({
3505
+ input: string(),
3506
+ output: string(),
3507
+ input_cache_read: string().nullish(),
3508
+ input_cache_write: string().nullish()
3509
+ }).transform(({ input, output, input_cache_read, input_cache_write }) => ({
3510
+ input,
3511
+ output,
3512
+ ...input_cache_read ? { cachedInputTokens: input_cache_read } : {},
3513
+ ...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {}
3514
+ })).nullish(),
3515
+ specification: object({
3516
+ specificationVersion: literal("v3"),
3517
+ provider: string(),
3518
+ modelId: string()
3519
+ }),
3520
+ modelType: string().nullish()
3521
+ })).transform((models) => models.filter((m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType))) })));
3522
+ var gatewayCreditsResponseSchema = lazySchema(() => zodSchema(object({
3523
+ balance: string(),
3524
+ total_used: string()
3525
+ }).transform(({ balance, total_used }) => ({
3526
+ balance,
3527
+ totalUsed: total_used
3528
+ }))));
3529
+ var GatewaySpendReport = class {
3530
+ constructor(config) {
3531
+ this.config = config;
3532
+ }
3533
+ async getSpendReport(params) {
3534
+ try {
3535
+ const baseUrl = new URL(this.config.baseURL);
3536
+ const searchParams = new URLSearchParams;
3537
+ searchParams.set("start_date", params.startDate);
3538
+ searchParams.set("end_date", params.endDate);
3539
+ if (params.groupBy)
3540
+ searchParams.set("group_by", params.groupBy);
3541
+ if (params.datePart)
3542
+ searchParams.set("date_part", params.datePart);
3543
+ if (params.userId)
3544
+ searchParams.set("user_id", params.userId);
3545
+ if (params.model)
3546
+ searchParams.set("model", params.model);
3547
+ if (params.provider)
3548
+ searchParams.set("provider", params.provider);
3549
+ if (params.credentialType)
3550
+ searchParams.set("credential_type", params.credentialType);
3551
+ if (params.tags && params.tags.length > 0)
3552
+ searchParams.set("tags", params.tags.join(","));
3553
+ const { value } = await getFromApi({
3554
+ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
3555
+ headers: await resolve(this.config.headers()),
3556
+ successfulResponseHandler: createJsonResponseHandler(gatewaySpendReportResponseSchema),
3557
+ failedResponseHandler: createJsonErrorResponseHandler({
3558
+ errorSchema: any(),
3559
+ errorToMessage: (data) => data
3560
+ }),
3561
+ fetch: this.config.fetch
3562
+ });
3563
+ return value;
3564
+ } catch (error) {
3565
+ throw await asGatewayError(error);
3566
+ }
3567
+ }
3568
+ };
3569
+ var gatewaySpendReportResponseSchema = lazySchema(() => zodSchema(object({ results: array(object({
3570
+ day: string().optional(),
3571
+ hour: string().optional(),
3572
+ user: string().optional(),
3573
+ model: string().optional(),
3574
+ tag: string().optional(),
3575
+ provider: string().optional(),
3576
+ credential_type: _enum(["byok", "system"]).optional(),
3577
+ total_cost: number(),
3578
+ market_cost: number().optional(),
3579
+ input_tokens: number().optional(),
3580
+ output_tokens: number().optional(),
3581
+ cached_input_tokens: number().optional(),
3582
+ cache_creation_input_tokens: number().optional(),
3583
+ reasoning_tokens: number().optional(),
3584
+ request_count: number().optional()
3585
+ }).transform(({ credential_type, total_cost, market_cost, input_tokens, output_tokens, cached_input_tokens, cache_creation_input_tokens, reasoning_tokens, request_count, ...rest }) => ({
3586
+ ...rest,
3587
+ ...credential_type !== undefined ? { credentialType: credential_type } : {},
3588
+ totalCost: total_cost,
3589
+ ...market_cost !== undefined ? { marketCost: market_cost } : {},
3590
+ ...input_tokens !== undefined ? { inputTokens: input_tokens } : {},
3591
+ ...output_tokens !== undefined ? { outputTokens: output_tokens } : {},
3592
+ ...cached_input_tokens !== undefined ? { cachedInputTokens: cached_input_tokens } : {},
3593
+ ...cache_creation_input_tokens !== undefined ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
3594
+ ...reasoning_tokens !== undefined ? { reasoningTokens: reasoning_tokens } : {},
3595
+ ...request_count !== undefined ? { requestCount: request_count } : {}
3596
+ }))) })));
3597
+ var GatewayGenerationInfoFetcher = class {
3598
+ constructor(config) {
3599
+ this.config = config;
3600
+ }
3601
+ async getGenerationInfo(params) {
3602
+ try {
3603
+ const { value } = await getFromApi({
3604
+ url: `${new URL(this.config.baseURL).origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
3605
+ headers: await resolve(this.config.headers()),
3606
+ successfulResponseHandler: createJsonResponseHandler(gatewayGenerationInfoResponseSchema),
3607
+ failedResponseHandler: createJsonErrorResponseHandler({
3608
+ errorSchema: any(),
3609
+ errorToMessage: (data) => data
3610
+ }),
3611
+ fetch: this.config.fetch
3612
+ });
3613
+ return value;
3614
+ } catch (error) {
3615
+ throw await asGatewayError(error);
3616
+ }
3617
+ }
3618
+ };
3619
+ var gatewayGenerationInfoResponseSchema = lazySchema(() => zodSchema(object({ data: object({
3620
+ id: string(),
3621
+ total_cost: number(),
3622
+ upstream_inference_cost: number(),
3623
+ usage: number(),
3624
+ created_at: string(),
3625
+ model: string(),
3626
+ is_byok: boolean(),
3627
+ provider_name: string(),
3628
+ streamed: boolean(),
3629
+ finish_reason: string(),
3630
+ latency: number(),
3631
+ generation_time: number(),
3632
+ native_tokens_prompt: number(),
3633
+ native_tokens_completion: number(),
3634
+ native_tokens_reasoning: number(),
3635
+ native_tokens_cached: number(),
3636
+ native_tokens_cache_creation: number(),
3637
+ billable_web_search_calls: number()
3638
+ }).transform(({ total_cost, upstream_inference_cost, created_at, is_byok, provider_name, finish_reason, generation_time, native_tokens_prompt, native_tokens_completion, native_tokens_reasoning, native_tokens_cached, native_tokens_cache_creation, billable_web_search_calls, ...rest }) => ({
3639
+ ...rest,
3640
+ totalCost: total_cost,
3641
+ upstreamInferenceCost: upstream_inference_cost,
3642
+ createdAt: created_at,
3643
+ isByok: is_byok,
3644
+ providerName: provider_name,
3645
+ finishReason: finish_reason,
3646
+ generationTime: generation_time,
3647
+ promptTokens: native_tokens_prompt,
3648
+ completionTokens: native_tokens_completion,
3649
+ reasoningTokens: native_tokens_reasoning,
3650
+ cachedTokens: native_tokens_cached,
3651
+ cacheCreationTokens: native_tokens_cache_creation,
3652
+ billableWebSearchCalls: billable_web_search_calls
3653
+ })) }).transform(({ data }) => data)));
3654
+ var GatewayLanguageModel = class {
3655
+ constructor(modelId, config) {
3656
+ this.modelId = modelId;
3657
+ this.config = config;
3658
+ this.specificationVersion = "v3";
3659
+ this.supportedUrls = { "*/*": [/.*/] };
3660
+ }
3661
+ get provider() {
3662
+ return this.config.provider;
3663
+ }
3664
+ async getArgs(options) {
3665
+ const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;
3666
+ return {
3667
+ args: this.maybeEncodeFileParts(optionsWithoutSignal),
3668
+ warnings: []
3669
+ };
3670
+ }
3671
+ async doGenerate(options) {
3672
+ const { args, warnings } = await this.getArgs(options);
3673
+ const { abortSignal } = options;
3674
+ const resolvedHeaders = await resolve(this.config.headers());
3675
+ try {
3676
+ const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({
3677
+ url: this.getUrl(),
3678
+ headers: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, false), await resolve(this.config.o11yHeaders)),
3679
+ body: args,
3680
+ successfulResponseHandler: createJsonResponseHandler(any()),
3681
+ failedResponseHandler: createJsonErrorResponseHandler({
3682
+ errorSchema: any(),
3683
+ errorToMessage: (data) => data
3684
+ }),
3685
+ ...abortSignal && { abortSignal },
3686
+ fetch: this.config.fetch
3687
+ });
3688
+ return {
3689
+ ...responseBody,
3690
+ request: { body: args },
3691
+ response: {
3692
+ headers: responseHeaders,
3693
+ body: rawResponse
3694
+ },
3695
+ warnings
3696
+ };
3697
+ } catch (error) {
3698
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
3699
+ }
3700
+ }
3701
+ async doStream(options) {
3702
+ const { args, warnings } = await this.getArgs(options);
3703
+ const { abortSignal } = options;
3704
+ const resolvedHeaders = await resolve(this.config.headers());
3705
+ try {
3706
+ const { value: response, responseHeaders } = await postJsonToApi({
3707
+ url: this.getUrl(),
3708
+ headers: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, true), await resolve(this.config.o11yHeaders)),
3709
+ body: args,
3710
+ successfulResponseHandler: createEventSourceResponseHandler(any()),
3711
+ failedResponseHandler: createJsonErrorResponseHandler({
3712
+ errorSchema: any(),
3713
+ errorToMessage: (data) => data
3714
+ }),
3715
+ ...abortSignal && { abortSignal },
3716
+ fetch: this.config.fetch
3717
+ });
3718
+ return {
3719
+ stream: response.pipeThrough(new TransformStream({
3720
+ start(controller) {
3721
+ if (warnings.length > 0)
3722
+ controller.enqueue({
3723
+ type: "stream-start",
3724
+ warnings
3725
+ });
3726
+ },
3727
+ transform(chunk, controller) {
3728
+ if (chunk.success) {
3729
+ const streamPart = chunk.value;
3730
+ if (streamPart.type === "raw" && !options.includeRawChunks)
3731
+ return;
3732
+ if (streamPart.type === "response-metadata" && streamPart.timestamp && typeof streamPart.timestamp === "string")
3733
+ streamPart.timestamp = new Date(streamPart.timestamp);
3734
+ controller.enqueue(streamPart);
3735
+ } else
3736
+ controller.error(chunk.error);
3737
+ }
3738
+ })),
3739
+ request: { body: args },
3740
+ response: { headers: responseHeaders }
3741
+ };
3742
+ } catch (error) {
3743
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
3744
+ }
3745
+ }
3746
+ isFilePart(part) {
3747
+ return part && typeof part === "object" && "type" in part && part.type === "file";
3748
+ }
3749
+ maybeEncodeFileParts(options) {
3750
+ for (const message of options.prompt)
3751
+ for (const part of message.content)
3752
+ if (this.isFilePart(part)) {
3753
+ const filePart = part;
3754
+ if (filePart.data instanceof Uint8Array) {
3755
+ const buffer = Uint8Array.from(filePart.data);
3756
+ const base64Data = Buffer.from(buffer).toString("base64");
3757
+ filePart.data = new URL(`data:${filePart.mediaType || "application/octet-stream"};base64,${base64Data}`);
3758
+ }
3759
+ }
3760
+ return options;
3761
+ }
3762
+ getUrl() {
3763
+ return `${this.config.baseURL}/language-model`;
3764
+ }
3765
+ getModelConfigHeaders(modelId, streaming) {
3766
+ return {
3767
+ "ai-language-model-specification-version": "3",
3768
+ "ai-language-model-id": modelId,
3769
+ "ai-language-model-streaming": String(streaming)
3770
+ };
3771
+ }
3772
+ };
3773
+ var GatewayEmbeddingModel = class {
3774
+ constructor(modelId, config) {
3775
+ this.modelId = modelId;
3776
+ this.config = config;
3777
+ this.specificationVersion = "v3";
3778
+ this.maxEmbeddingsPerCall = 2048;
3779
+ this.supportsParallelCalls = true;
3780
+ }
3781
+ get provider() {
3782
+ return this.config.provider;
3783
+ }
3784
+ async doEmbed({ values, headers, abortSignal, providerOptions }) {
3785
+ var _a11, _b11;
3786
+ const resolvedHeaders = await resolve(this.config.headers());
3787
+ try {
3788
+ const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
3789
+ url: this.getUrl(),
3790
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
3791
+ body: {
3792
+ values,
3793
+ ...providerOptions ? { providerOptions } : {}
3794
+ },
3795
+ successfulResponseHandler: createJsonResponseHandler(gatewayEmbeddingResponseSchema),
3796
+ failedResponseHandler: createJsonErrorResponseHandler({
3797
+ errorSchema: any(),
3798
+ errorToMessage: (data) => data
3799
+ }),
3800
+ ...abortSignal && { abortSignal },
3801
+ fetch: this.config.fetch
3802
+ });
3803
+ return {
3804
+ embeddings: responseBody.embeddings,
3805
+ usage: (_a11 = responseBody.usage) != null ? _a11 : undefined,
3806
+ providerMetadata: responseBody.providerMetadata,
3807
+ response: {
3808
+ headers: responseHeaders,
3809
+ body: rawValue
3810
+ },
3811
+ warnings: (_b11 = responseBody.warnings) != null ? _b11 : []
3812
+ };
3813
+ } catch (error) {
3814
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
3815
+ }
3816
+ }
3817
+ getUrl() {
3818
+ return `${this.config.baseURL}/embedding-model`;
3819
+ }
3820
+ getModelConfigHeaders() {
3821
+ return {
3822
+ "ai-embedding-model-specification-version": "3",
3823
+ "ai-model-id": this.modelId
3824
+ };
3825
+ }
3826
+ };
3827
+ var gatewayEmbeddingWarningSchema = discriminatedUnion("type", [
3828
+ object({
3829
+ type: literal("unsupported"),
3830
+ feature: string(),
3831
+ details: string().optional()
3832
+ }),
3833
+ object({
3834
+ type: literal("compatibility"),
3835
+ feature: string(),
3836
+ details: string().optional()
3837
+ }),
3838
+ object({
3839
+ type: literal("other"),
3840
+ message: string()
3841
+ })
3842
+ ]);
3843
+ var gatewayEmbeddingResponseSchema = lazySchema(() => zodSchema(object({
3844
+ embeddings: array(array(number())),
3845
+ usage: object({ tokens: number() }).nullish(),
3846
+ warnings: array(gatewayEmbeddingWarningSchema).optional(),
3847
+ providerMetadata: record(string(), record(string(), unknown())).optional()
3848
+ })));
3849
+ function mapGatewayWarnings(warnings) {
3850
+ return (warnings != null ? warnings : []).map((warning) => warning.type === "deprecated" ? {
3851
+ type: "other",
3852
+ message: warning.message
3853
+ } : warning);
3854
+ }
3855
+ var GatewayImageModel = class {
3856
+ constructor(modelId, config) {
3857
+ this.modelId = modelId;
3858
+ this.config = config;
3859
+ this.specificationVersion = "v3";
3860
+ this.maxImagesPerCall = Number.MAX_SAFE_INTEGER;
3861
+ }
3862
+ get provider() {
3863
+ return this.config.provider;
3864
+ }
3865
+ async doGenerate({ prompt, n, size, aspectRatio, seed, files, mask, providerOptions, headers, abortSignal }) {
3866
+ var _a11, _b11, _c;
3867
+ const resolvedHeaders = await resolve(this.config.headers());
3868
+ try {
3869
+ const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
3870
+ url: this.getUrl(),
3871
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
3872
+ body: {
3873
+ prompt,
3874
+ n,
3875
+ ...size && { size },
3876
+ ...aspectRatio && { aspectRatio },
3877
+ ...seed && { seed },
3878
+ ...providerOptions && { providerOptions },
3879
+ ...files && { files: files.map((file) => maybeEncodeImageFile(file)) },
3880
+ ...mask && { mask: maybeEncodeImageFile(mask) }
3881
+ },
3882
+ successfulResponseHandler: createJsonResponseHandler(gatewayImageResponseSchema),
3883
+ failedResponseHandler: createJsonErrorResponseHandler({
3884
+ errorSchema: any(),
3885
+ errorToMessage: (data) => data
3886
+ }),
3887
+ ...abortSignal && { abortSignal },
3888
+ fetch: this.config.fetch
3889
+ });
3890
+ return {
3891
+ images: responseBody.images,
3892
+ warnings: mapGatewayWarnings(responseBody.warnings),
3893
+ providerMetadata: responseBody.providerMetadata,
3894
+ response: {
3895
+ timestamp: /* @__PURE__ */ new Date,
3896
+ modelId: this.modelId,
3897
+ headers: responseHeaders
3898
+ },
3899
+ ...responseBody.usage != null && { usage: {
3900
+ inputTokens: (_a11 = responseBody.usage.inputTokens) != null ? _a11 : undefined,
3901
+ outputTokens: (_b11 = responseBody.usage.outputTokens) != null ? _b11 : undefined,
3902
+ totalTokens: (_c = responseBody.usage.totalTokens) != null ? _c : undefined
3903
+ } }
3904
+ };
3905
+ } catch (error) {
3906
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
3907
+ }
3908
+ }
3909
+ getUrl() {
3910
+ return `${this.config.baseURL}/image-model`;
3911
+ }
3912
+ getModelConfigHeaders() {
3913
+ return {
3914
+ "ai-image-model-specification-version": "3",
3915
+ "ai-model-id": this.modelId
3916
+ };
3917
+ }
3918
+ };
3919
+ function maybeEncodeImageFile(file) {
3920
+ if (file.type === "file" && file.data instanceof Uint8Array)
3921
+ return {
3922
+ ...file,
3923
+ data: convertUint8ArrayToBase64(file.data)
3924
+ };
3925
+ return file;
3926
+ }
3927
+ var providerMetadataEntrySchema = object({ images: array(unknown()).optional() }).catchall(unknown());
3928
+ var gatewayImageWarningSchema = discriminatedUnion("type", [
3929
+ object({
3930
+ type: literal("unsupported"),
3931
+ feature: string(),
3932
+ details: string().optional()
3933
+ }),
3934
+ object({
3935
+ type: literal("compatibility"),
3936
+ feature: string(),
3937
+ details: string().optional()
3938
+ }),
3939
+ object({
3940
+ type: literal("deprecated"),
3941
+ setting: string(),
3942
+ message: string()
3943
+ }),
3944
+ object({
3945
+ type: literal("other"),
3946
+ message: string()
3947
+ })
3948
+ ]);
3949
+ var gatewayImageUsageSchema = object({
3950
+ inputTokens: number().nullish(),
3951
+ outputTokens: number().nullish(),
3952
+ totalTokens: number().nullish()
3953
+ });
3954
+ var gatewayImageResponseSchema = object({
3955
+ images: array(string()),
3956
+ warnings: array(gatewayImageWarningSchema).optional(),
3957
+ providerMetadata: record(string(), providerMetadataEntrySchema).optional(),
3958
+ usage: gatewayImageUsageSchema.optional()
3959
+ });
3960
+ var GatewayVideoModel = class {
3961
+ constructor(modelId, config) {
3962
+ this.modelId = modelId;
3963
+ this.config = config;
3964
+ this.specificationVersion = "v3";
3965
+ this.maxVideosPerCall = Number.MAX_SAFE_INTEGER;
3966
+ }
3967
+ get provider() {
3968
+ return this.config.provider;
3969
+ }
3970
+ async doGenerate({ prompt, n, aspectRatio, resolution, duration, fps, seed, generateAudio, image, frameImages, inputReferences, providerOptions, headers, abortSignal }) {
3971
+ const resolvedHeaders = await resolve(this.config.headers());
3972
+ try {
3973
+ const { responseHeaders, value: responseBody } = await postJsonToApi({
3974
+ url: this.getUrl(),
3975
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders), { accept: "text/event-stream" }),
3976
+ body: {
3977
+ prompt,
3978
+ n,
3979
+ ...aspectRatio && { aspectRatio },
3980
+ ...resolution && { resolution },
3981
+ ...duration && { duration },
3982
+ ...fps && { fps },
3983
+ ...seed && { seed },
3984
+ ...generateAudio !== undefined && { generateAudio },
3985
+ ...providerOptions && { providerOptions },
3986
+ ...image && { image: maybeEncodeVideoFile(image) },
3987
+ ...frameImages && { frameImages: frameImages.map((frame) => ({
3988
+ ...frame,
3989
+ image: maybeEncodeVideoFile(frame.image)
3990
+ })) },
3991
+ ...inputReferences && { inputReferences: inputReferences.map((reference) => maybeEncodeVideoFile(reference)) }
3992
+ },
3993
+ successfulResponseHandler: async ({ response, url, requestBodyValues }) => {
3994
+ if (response.body == null)
3995
+ throw new APICallError2({
3996
+ message: "SSE response body is empty",
3997
+ url,
3998
+ requestBodyValues,
3999
+ statusCode: response.status
4000
+ });
4001
+ const reader = parseJsonEventStream({
4002
+ stream: response.body,
4003
+ schema: gatewayVideoEventSchema
4004
+ }).getReader();
4005
+ const { done, value: parseResult } = await reader.read();
4006
+ reader.releaseLock();
4007
+ if (done || !parseResult)
4008
+ throw new APICallError2({
4009
+ message: "SSE stream ended without a data event",
4010
+ url,
4011
+ requestBodyValues,
4012
+ statusCode: response.status
4013
+ });
4014
+ if (!parseResult.success)
4015
+ throw new APICallError2({
4016
+ message: "Failed to parse video SSE event",
4017
+ cause: parseResult.error,
4018
+ url,
4019
+ requestBodyValues,
4020
+ statusCode: response.status
4021
+ });
4022
+ const event = parseResult.value;
4023
+ if (event.type === "error")
4024
+ throw new APICallError2({
4025
+ message: event.message,
4026
+ statusCode: event.statusCode,
4027
+ url,
4028
+ requestBodyValues,
4029
+ responseHeaders: Object.fromEntries([...response.headers]),
4030
+ responseBody: JSON.stringify(event),
4031
+ data: { error: {
4032
+ message: event.message,
4033
+ type: event.errorType,
4034
+ param: event.param
4035
+ } }
4036
+ });
4037
+ return {
4038
+ value: {
4039
+ videos: event.videos,
4040
+ warnings: event.warnings,
4041
+ providerMetadata: event.providerMetadata
4042
+ },
4043
+ responseHeaders: Object.fromEntries([...response.headers])
4044
+ };
4045
+ },
4046
+ failedResponseHandler: createJsonErrorResponseHandler({
4047
+ errorSchema: any(),
4048
+ errorToMessage: (data) => data
4049
+ }),
4050
+ ...abortSignal && { abortSignal },
4051
+ fetch: this.config.fetch
4052
+ });
4053
+ return {
4054
+ videos: responseBody.videos,
4055
+ warnings: mapGatewayWarnings(responseBody.warnings),
4056
+ providerMetadata: responseBody.providerMetadata,
4057
+ response: {
4058
+ timestamp: /* @__PURE__ */ new Date,
4059
+ modelId: this.modelId,
4060
+ headers: responseHeaders
4061
+ }
4062
+ };
4063
+ } catch (error) {
4064
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
4065
+ }
4066
+ }
4067
+ getUrl() {
4068
+ return `${this.config.baseURL}/video-model`;
4069
+ }
4070
+ getModelConfigHeaders() {
4071
+ return {
4072
+ "ai-video-model-specification-version": "3",
4073
+ "ai-model-id": this.modelId
4074
+ };
4075
+ }
4076
+ };
4077
+ function maybeEncodeVideoFile(file) {
4078
+ if (file.type === "file" && file.data instanceof Uint8Array)
4079
+ return {
4080
+ ...file,
4081
+ data: convertUint8ArrayToBase64(file.data)
4082
+ };
4083
+ return file;
4084
+ }
4085
+ var providerMetadataEntrySchema2 = object({ videos: array(unknown()).optional() }).catchall(unknown());
4086
+ var gatewayVideoDataSchema = union([object({
4087
+ type: literal("url"),
4088
+ url: string(),
4089
+ mediaType: string()
4090
+ }), object({
4091
+ type: literal("base64"),
4092
+ data: string(),
4093
+ mediaType: string()
4094
+ })]);
4095
+ var gatewayVideoWarningSchema = discriminatedUnion("type", [
4096
+ object({
4097
+ type: literal("unsupported"),
4098
+ feature: string(),
4099
+ details: string().optional()
4100
+ }),
4101
+ object({
4102
+ type: literal("compatibility"),
4103
+ feature: string(),
4104
+ details: string().optional()
4105
+ }),
4106
+ object({
4107
+ type: literal("deprecated"),
4108
+ setting: string(),
4109
+ message: string()
4110
+ }),
4111
+ object({
4112
+ type: literal("other"),
4113
+ message: string()
4114
+ })
4115
+ ]);
4116
+ var gatewayVideoEventSchema = discriminatedUnion("type", [object({
4117
+ type: literal("result"),
4118
+ videos: array(gatewayVideoDataSchema),
4119
+ warnings: array(gatewayVideoWarningSchema).optional(),
4120
+ providerMetadata: record(string(), providerMetadataEntrySchema2).optional()
4121
+ }), object({
4122
+ type: literal("error"),
4123
+ message: string(),
4124
+ errorType: string(),
4125
+ statusCode: number(),
4126
+ param: unknown().nullable()
4127
+ })]);
4128
+ var GatewayRerankingModel = class {
4129
+ constructor(modelId, config) {
4130
+ this.modelId = modelId;
4131
+ this.config = config;
4132
+ this.specificationVersion = "v3";
4133
+ }
4134
+ get provider() {
4135
+ return this.config.provider;
4136
+ }
4137
+ async doRerank({ documents, query, topN, headers, abortSignal, providerOptions }) {
4138
+ var _a11;
4139
+ const resolvedHeaders = await resolve(this.config.headers());
4140
+ try {
4141
+ const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
4142
+ url: this.getUrl(),
4143
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
4144
+ body: {
4145
+ documents,
4146
+ query,
4147
+ ...topN != null ? { topN } : {},
4148
+ ...providerOptions ? { providerOptions } : {}
4149
+ },
4150
+ successfulResponseHandler: createJsonResponseHandler(gatewayRerankingResponseSchema),
4151
+ failedResponseHandler: createJsonErrorResponseHandler({
4152
+ errorSchema: any(),
4153
+ errorToMessage: (data) => data
4154
+ }),
4155
+ ...abortSignal && { abortSignal },
4156
+ fetch: this.config.fetch
4157
+ });
4158
+ return {
4159
+ ranking: responseBody.ranking,
4160
+ providerMetadata: responseBody.providerMetadata,
4161
+ response: {
4162
+ headers: responseHeaders,
4163
+ body: rawValue
4164
+ },
4165
+ warnings: (_a11 = responseBody.warnings) != null ? _a11 : []
4166
+ };
4167
+ } catch (error) {
4168
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
4169
+ }
4170
+ }
4171
+ getUrl() {
4172
+ return `${this.config.baseURL}/reranking-model`;
4173
+ }
4174
+ getModelConfigHeaders() {
4175
+ return {
4176
+ "ai-reranking-model-specification-version": "3",
4177
+ "ai-model-id": this.modelId
4178
+ };
4179
+ }
4180
+ };
4181
+ var gatewayRerankingWarningSchema = discriminatedUnion("type", [
4182
+ object({
4183
+ type: literal("unsupported"),
4184
+ feature: string(),
4185
+ details: string().optional()
4186
+ }),
4187
+ object({
4188
+ type: literal("compatibility"),
4189
+ feature: string(),
4190
+ details: string().optional()
4191
+ }),
4192
+ object({
4193
+ type: literal("other"),
4194
+ message: string()
4195
+ })
4196
+ ]);
4197
+ var gatewayRerankingResponseSchema = lazySchema(() => zodSchema(object({
4198
+ ranking: array(object({
4199
+ index: number(),
4200
+ relevanceScore: number()
4201
+ })),
4202
+ warnings: array(gatewayRerankingWarningSchema).optional(),
4203
+ providerMetadata: record(string(), record(string(), unknown())).optional()
4204
+ })));
4205
+ var GatewaySpeechModel = class {
4206
+ constructor(modelId, config) {
4207
+ this.modelId = modelId;
4208
+ this.config = config;
4209
+ this.specificationVersion = "v3";
4210
+ }
4211
+ get provider() {
4212
+ return this.config.provider;
4213
+ }
4214
+ async doGenerate({ text, voice, outputFormat, instructions, speed, language, providerOptions, headers, abortSignal }) {
4215
+ const resolvedHeaders = await resolve(this.config.headers());
4216
+ try {
4217
+ const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
4218
+ url: this.getUrl(),
4219
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
4220
+ body: {
4221
+ text,
4222
+ ...voice && { voice },
4223
+ ...outputFormat && { outputFormat },
4224
+ ...instructions && { instructions },
4225
+ ...speed != null && { speed },
4226
+ ...language && { language },
4227
+ ...providerOptions && { providerOptions }
4228
+ },
4229
+ successfulResponseHandler: createJsonResponseHandler(gatewaySpeechResponseSchema),
4230
+ failedResponseHandler: createJsonErrorResponseHandler({
4231
+ errorSchema: any(),
4232
+ errorToMessage: (data) => data
4233
+ }),
4234
+ ...abortSignal && { abortSignal },
4235
+ fetch: this.config.fetch
4236
+ });
4237
+ return {
4238
+ audio: responseBody.audio,
4239
+ warnings: mapGatewayWarnings(responseBody.warnings),
4240
+ providerMetadata: responseBody.providerMetadata,
4241
+ response: {
4242
+ timestamp: /* @__PURE__ */ new Date,
4243
+ modelId: this.modelId,
4244
+ headers: responseHeaders,
4245
+ body: rawValue
4246
+ }
4247
+ };
4248
+ } catch (error) {
4249
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}));
4250
+ }
4251
+ }
4252
+ getUrl() {
4253
+ return `${this.config.baseURL}/speech-model`;
4254
+ }
4255
+ getModelConfigHeaders() {
4256
+ return {
4257
+ "ai-speech-model-specification-version": "3",
4258
+ "ai-model-id": this.modelId
4259
+ };
4260
+ }
4261
+ };
4262
+ var providerMetadataEntrySchema3 = object({}).catchall(unknown());
4263
+ var gatewaySpeechWarningSchema = discriminatedUnion("type", [
4264
+ object({
4265
+ type: literal("unsupported"),
4266
+ feature: string(),
4267
+ details: string().optional()
4268
+ }),
4269
+ object({
4270
+ type: literal("compatibility"),
4271
+ feature: string(),
4272
+ details: string().optional()
4273
+ }),
4274
+ object({
4275
+ type: literal("deprecated"),
4276
+ setting: string(),
4277
+ message: string()
4278
+ }),
4279
+ object({
4280
+ type: literal("other"),
4281
+ message: string()
4282
+ })
4283
+ ]);
4284
+ var gatewaySpeechResponseSchema = object({
4285
+ audio: string(),
4286
+ warnings: array(gatewaySpeechWarningSchema).optional(),
4287
+ providerMetadata: record(string(), providerMetadataEntrySchema3).optional()
4288
+ });
4289
+ var GatewayTranscriptionModel = class {
4290
+ constructor(modelId, config) {
4291
+ this.modelId = modelId;
4292
+ this.config = config;
4293
+ this.specificationVersion = "v3";
4294
+ }
4295
+ get provider() {
4296
+ return this.config.provider;
4297
+ }
4298
+ async doGenerate({ audio, mediaType, providerOptions, headers, abortSignal }) {
4299
+ var _a11, _b11, _c;
4300
+ const resolvedHeaders = await resolve(this.config.headers());
4301
+ try {
4302
+ const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
4303
+ url: this.getUrl(),
4304
+ headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
4305
+ body: {
4306
+ audio: audio instanceof Uint8Array ? convertUint8ArrayToBase64(audio) : audio,
4307
+ mediaType,
4308
+ ...providerOptions && { providerOptions }
4309
+ },
4310
+ successfulResponseHandler: createJsonResponseHandler(gatewayTranscriptionResponseSchema),
4311
+ failedResponseHandler: createJsonErrorResponseHandler({
4312
+ errorSchema: any(),
4313
+ errorToMessage: (data) => data
4314
+ }),
4315
+ ...abortSignal && { abortSignal },
4316
+ fetch: this.config.fetch
4317
+ });
4318
+ return {
4319
+ text: responseBody.text,
4320
+ segments: (_a11 = responseBody.segments) != null ? _a11 : [],
4321
+ language: (_b11 = responseBody.language) != null ? _b11 : undefined,
4322
+ durationInSeconds: (_c = responseBody.durationInSeconds) != null ? _c : undefined,
4323
+ warnings: mapGatewayWarnings(responseBody.warnings),
4324
+ providerMetadata: responseBody.providerMetadata,
4325
+ response: {
4326
+ timestamp: /* @__PURE__ */ new Date,
4327
+ modelId: this.modelId,
4328
+ headers: responseHeaders,
4329
+ body: rawValue
4330
+ }
4331
+ };
4332
+ } catch (error) {
4333
+ throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}));
4334
+ }
4335
+ }
4336
+ getUrl() {
4337
+ return `${this.config.baseURL}/transcription-model`;
4338
+ }
4339
+ getModelConfigHeaders() {
4340
+ return {
4341
+ "ai-transcription-model-specification-version": "3",
4342
+ "ai-model-id": this.modelId
4343
+ };
4344
+ }
4345
+ };
4346
+ var providerMetadataEntrySchema4 = object({}).catchall(unknown());
4347
+ var gatewayTranscriptionWarningSchema = discriminatedUnion("type", [
4348
+ object({
4349
+ type: literal("unsupported"),
4350
+ feature: string(),
4351
+ details: string().optional()
4352
+ }),
4353
+ object({
4354
+ type: literal("compatibility"),
4355
+ feature: string(),
4356
+ details: string().optional()
4357
+ }),
4358
+ object({
4359
+ type: literal("deprecated"),
4360
+ setting: string(),
4361
+ message: string()
4362
+ }),
4363
+ object({
4364
+ type: literal("other"),
4365
+ message: string()
4366
+ })
4367
+ ]);
4368
+ var gatewayTranscriptionResponseSchema = object({
4369
+ text: string(),
4370
+ segments: array(object({
4371
+ text: string(),
4372
+ startSecond: number(),
4373
+ endSecond: number()
4374
+ })).optional(),
4375
+ language: string().nullish(),
4376
+ durationInSeconds: number().nullish(),
4377
+ warnings: array(gatewayTranscriptionWarningSchema).optional(),
4378
+ providerMetadata: record(string(), providerMetadataEntrySchema4).optional()
4379
+ });
4380
+ var exaSearchToolFactory = createProviderToolFactoryWithOutputSchema({
4381
+ id: "gateway.exa_search",
4382
+ inputSchema: lazySchema(() => zodSchema(object({
4383
+ query: string().describe("Natural-language web search query. This is required."),
4384
+ type: _enum([
4385
+ "auto",
4386
+ "fast",
4387
+ "instant"
4388
+ ]).optional().describe("Search method. Use auto for the default balance of speed and quality."),
4389
+ num_results: number().optional().describe("Maximum number of results to return (1-100, default: 10)."),
4390
+ category: _enum([
4391
+ "company",
4392
+ "people",
4393
+ "research paper",
4394
+ "news",
4395
+ "personal site",
4396
+ "financial report"
4397
+ ]).optional().describe("Optional content category to focus results."),
4398
+ user_location: string().optional().describe("Two-letter ISO country code such as 'US'."),
4399
+ include_domains: array(string()).optional().describe("Only return results from these domains."),
4400
+ exclude_domains: array(string()).optional().describe("Exclude results from these domains."),
4401
+ start_published_date: string().optional().describe("Only return links published after this ISO 8601 date."),
4402
+ end_published_date: string().optional().describe("Only return links published before this ISO 8601 date."),
4403
+ contents: object({
4404
+ text: union([boolean(), object({
4405
+ max_characters: number().optional(),
4406
+ include_html_tags: boolean().optional(),
4407
+ verbosity: _enum([
4408
+ "compact",
4409
+ "standard",
4410
+ "full"
4411
+ ]).optional(),
4412
+ include_sections: array(_enum([
4413
+ "header",
4414
+ "navigation",
4415
+ "banner",
4416
+ "body",
4417
+ "sidebar",
4418
+ "footer",
4419
+ "metadata"
4420
+ ])).optional(),
4421
+ exclude_sections: array(_enum([
4422
+ "header",
4423
+ "navigation",
4424
+ "banner",
4425
+ "body",
4426
+ "sidebar",
4427
+ "footer",
4428
+ "metadata"
4429
+ ])).optional()
4430
+ })]).optional(),
4431
+ highlights: union([boolean(), object({
4432
+ query: string().optional(),
4433
+ max_characters: number().optional()
4434
+ })]).optional(),
4435
+ max_age_hours: number().optional(),
4436
+ livecrawl_timeout: number().optional(),
4437
+ subpages: number().optional(),
4438
+ subpage_target: union([string(), array(string())]).optional(),
4439
+ extras: object({
4440
+ links: number().optional(),
4441
+ image_links: number().optional()
4442
+ }).optional()
4443
+ }).optional().describe("Controls extracted page content and freshness.")
4444
+ }))),
4445
+ outputSchema: lazySchema(() => zodSchema(union([object({
4446
+ requestId: string(),
4447
+ searchType: string().optional(),
4448
+ resolvedSearchType: string().optional(),
4449
+ results: array(object({
4450
+ title: string(),
4451
+ url: string(),
4452
+ id: string(),
4453
+ publishedDate: string().nullable().optional(),
4454
+ author: string().nullable().optional(),
4455
+ image: string().nullable().optional(),
4456
+ favicon: string().nullable().optional(),
4457
+ text: string().optional(),
4458
+ highlights: array(string()).optional(),
4459
+ highlightScores: array(number()).optional(),
4460
+ summary: string().optional(),
4461
+ subpages: array(any()).optional(),
4462
+ extras: object({
4463
+ links: array(string()).optional(),
4464
+ imageLinks: array(string()).optional()
4465
+ }).optional()
4466
+ })),
4467
+ costDollars: object({
4468
+ total: number().optional(),
4469
+ search: record(number()).optional()
4470
+ }).optional()
4471
+ }), object({
4472
+ error: _enum([
4473
+ "api_error",
4474
+ "rate_limit",
4475
+ "timeout",
4476
+ "invalid_input",
4477
+ "configuration_error",
4478
+ "execution_error",
4479
+ "unknown"
4480
+ ]),
4481
+ statusCode: number().optional(),
4482
+ message: string()
4483
+ })])))
4484
+ });
4485
+ var exaSearch = (config = {}) => exaSearchToolFactory(config);
4486
+ var parallelSearchToolFactory = createProviderToolFactoryWithOutputSchema({
4487
+ id: "gateway.parallel_search",
4488
+ inputSchema: lazySchema(() => zodSchema(object({
4489
+ objective: string().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),
4490
+ search_queries: array(string()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),
4491
+ mode: _enum(["one-shot", "agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),
4492
+ max_results: number().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),
4493
+ source_policy: object({
4494
+ include_domains: array(string()).optional().describe("Limit results to these domains. Use plain domain names only — e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."),
4495
+ exclude_domains: array(string()).optional().describe("Exclude results from these domains. Use plain domain names only — e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."),
4496
+ after_date: string().optional().describe("Only include results published after this date. Use an ISO 8601 calendar date formatted YYYY-MM-DD (e.g. 2025-01-01); do not include a time.")
4497
+ }).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),
4498
+ excerpts: object({
4499
+ max_chars_per_result: number().optional().describe("Maximum characters per result."),
4500
+ max_chars_total: number().optional().describe("Maximum total characters across all results.")
4501
+ }).optional().describe("Excerpt configuration for controlling result length."),
4502
+ fetch_policy: object({ max_age_seconds: number().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.") }).optional().describe("Fetch policy for controlling content freshness.")
4503
+ }))),
4504
+ outputSchema: lazySchema(() => zodSchema(union([object({
4505
+ searchId: string(),
4506
+ results: array(object({
4507
+ url: string(),
4508
+ title: string(),
4509
+ excerpt: string(),
4510
+ publishDate: string().nullable().optional(),
4511
+ relevanceScore: number().optional()
4512
+ }))
4513
+ }), object({
4514
+ error: _enum([
4515
+ "api_error",
4516
+ "rate_limit",
4517
+ "timeout",
4518
+ "invalid_input",
4519
+ "configuration_error",
4520
+ "unknown"
4521
+ ]),
4522
+ statusCode: number().optional(),
4523
+ message: string()
4524
+ })])))
4525
+ });
4526
+ var parallelSearch = (config = {}) => parallelSearchToolFactory(config);
4527
+ var perplexitySearchToolFactory = createProviderToolFactoryWithOutputSchema({
4528
+ id: "gateway.perplexity_search",
4529
+ inputSchema: lazySchema(() => zodSchema(object({
4530
+ query: union([string(), array(string())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),
4531
+ max_results: number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),
4532
+ max_tokens_per_page: number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),
4533
+ max_tokens: number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),
4534
+ country: string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),
4535
+ search_domain_filter: array(string()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),
4536
+ search_language_filter: array(string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),
4537
+ search_after_date: string().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),
4538
+ search_before_date: string().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),
4539
+ last_updated_after_filter: string().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),
4540
+ last_updated_before_filter: string().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),
4541
+ search_recency_filter: _enum([
4542
+ "day",
4543
+ "week",
4544
+ "month",
4545
+ "year"
4546
+ ]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")
4547
+ }))),
4548
+ outputSchema: lazySchema(() => zodSchema(union([object({
4549
+ results: array(object({
4550
+ title: string(),
4551
+ url: string(),
4552
+ snippet: string(),
4553
+ date: string().optional(),
4554
+ lastUpdated: string().optional()
4555
+ })),
4556
+ id: string()
4557
+ }), object({
4558
+ error: _enum([
4559
+ "api_error",
4560
+ "rate_limit",
4561
+ "timeout",
4562
+ "invalid_input",
4563
+ "unknown"
4564
+ ]),
4565
+ statusCode: number().optional(),
4566
+ message: string()
4567
+ })])))
4568
+ });
4569
+ var perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);
4570
+ var gatewayTools = {
4571
+ exaSearch,
4572
+ parallelSearch,
4573
+ perplexitySearch
4574
+ };
4575
+ async function getVercelRequestId() {
4576
+ var _a11;
4577
+ return (_a11 = getContext().headers) == null ? undefined : _a11["x-vercel-id"];
4578
+ }
4579
+ var VERSION = "3.0.163";
4580
+ var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
4581
+ function createGatewayProvider(options = {}) {
4582
+ var _a11, _b11;
4583
+ let pendingMetadata = null;
4584
+ let metadataCache = null;
4585
+ const cacheRefreshMillis = (_a11 = options.metadataCacheRefreshMillis) != null ? _a11 : 1000 * 60 * 5;
4586
+ let lastFetchTime = 0;
4587
+ const baseURL = (_b11 = withoutTrailingSlash(options.baseURL)) != null ? _b11 : "https://ai-gateway.vercel.sh/v3/ai";
4588
+ const getHeaders = async () => {
4589
+ try {
4590
+ const auth = await getGatewayAuthToken(options);
4591
+ return withUserAgentSuffix({
4592
+ Authorization: `Bearer ${auth.token}`,
4593
+ "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION,
4594
+ [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,
4595
+ ...options.headers
4596
+ }, `ai-sdk/gateway/${VERSION}`);
4597
+ } catch (error) {
4598
+ throw GatewayAuthenticationError.createContextualError({
4599
+ apiKeyProvided: false,
4600
+ oidcTokenProvided: false,
4601
+ statusCode: 401,
4602
+ cause: error
4603
+ });
4604
+ }
4605
+ };
4606
+ const createO11yHeaders = () => {
4607
+ const deploymentId = loadOptionalSetting({
4608
+ settingValue: undefined,
4609
+ environmentVariableName: "VERCEL_DEPLOYMENT_ID"
4610
+ });
4611
+ const environment = loadOptionalSetting({
4612
+ settingValue: undefined,
4613
+ environmentVariableName: "VERCEL_ENV"
4614
+ });
4615
+ const region = loadOptionalSetting({
4616
+ settingValue: undefined,
4617
+ environmentVariableName: "VERCEL_REGION"
4618
+ });
4619
+ const projectId = loadOptionalSetting({
4620
+ settingValue: undefined,
4621
+ environmentVariableName: "VERCEL_PROJECT_ID"
4622
+ });
4623
+ return async () => {
4624
+ const requestId = await getVercelRequestId();
4625
+ return {
4626
+ ...deploymentId && { "ai-o11y-deployment-id": deploymentId },
4627
+ ...environment && { "ai-o11y-environment": environment },
4628
+ ...region && { "ai-o11y-region": region },
4629
+ ...requestId && { "ai-o11y-request-id": requestId },
4630
+ ...projectId && { "ai-o11y-project-id": projectId }
4631
+ };
4632
+ };
4633
+ };
4634
+ const createLanguageModel = (modelId) => {
4635
+ return new GatewayLanguageModel(modelId, {
4636
+ provider: "gateway",
4637
+ baseURL,
4638
+ headers: getHeaders,
4639
+ fetch: options.fetch,
4640
+ o11yHeaders: createO11yHeaders()
4641
+ });
4642
+ };
4643
+ const getAvailableModels = async () => {
4644
+ var _a12, _b12, _c;
4645
+ const now = (_c = (_b12 = (_a12 = options._internal) == null ? undefined : _a12.currentDate) == null ? undefined : _b12.call(_a12).getTime()) != null ? _c : Date.now();
4646
+ if (!pendingMetadata || now - lastFetchTime > cacheRefreshMillis) {
4647
+ lastFetchTime = now;
4648
+ pendingMetadata = new GatewayFetchMetadata({
4649
+ baseURL,
4650
+ headers: getHeaders,
4651
+ fetch: options.fetch
4652
+ }).getAvailableModels().then((metadata) => {
4653
+ metadataCache = metadata;
4654
+ return metadata;
4655
+ }).catch(async (error) => {
4656
+ throw await asGatewayError(error, await parseAuthMethod(await getHeaders()));
4657
+ });
4658
+ }
4659
+ return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata;
4660
+ };
4661
+ const getCredits = async () => {
4662
+ return new GatewayFetchMetadata({
4663
+ baseURL,
4664
+ headers: getHeaders,
4665
+ fetch: options.fetch
4666
+ }).getCredits().catch(async (error) => {
4667
+ throw await asGatewayError(error, await parseAuthMethod(await getHeaders()));
4668
+ });
4669
+ };
4670
+ const getSpendReport = async (params) => {
4671
+ return new GatewaySpendReport({
4672
+ baseURL,
4673
+ headers: getHeaders,
4674
+ fetch: options.fetch
4675
+ }).getSpendReport(params).catch(async (error) => {
4676
+ throw await asGatewayError(error, await parseAuthMethod(await getHeaders()));
4677
+ });
4678
+ };
4679
+ const getGenerationInfo = async (params) => {
4680
+ return new GatewayGenerationInfoFetcher({
4681
+ baseURL,
4682
+ headers: getHeaders,
4683
+ fetch: options.fetch
4684
+ }).getGenerationInfo(params).catch(async (error) => {
4685
+ throw await asGatewayError(error, await parseAuthMethod(await getHeaders()));
4686
+ });
4687
+ };
4688
+ const provider = function(modelId) {
4689
+ if (new.target)
4690
+ throw new Error("The Gateway Provider model function cannot be called with the new keyword.");
4691
+ return createLanguageModel(modelId);
4692
+ };
4693
+ provider.specificationVersion = "v3";
4694
+ provider.getAvailableModels = getAvailableModels;
4695
+ provider.getCredits = getCredits;
4696
+ provider.getSpendReport = getSpendReport;
4697
+ provider.getGenerationInfo = getGenerationInfo;
4698
+ provider.imageModel = (modelId) => {
4699
+ return new GatewayImageModel(modelId, {
4700
+ provider: "gateway",
4701
+ baseURL,
4702
+ headers: getHeaders,
4703
+ fetch: options.fetch,
4704
+ o11yHeaders: createO11yHeaders()
4705
+ });
4706
+ };
4707
+ provider.languageModel = createLanguageModel;
4708
+ const createEmbeddingModel = (modelId) => {
4709
+ return new GatewayEmbeddingModel(modelId, {
4710
+ provider: "gateway",
4711
+ baseURL,
4712
+ headers: getHeaders,
4713
+ fetch: options.fetch,
4714
+ o11yHeaders: createO11yHeaders()
4715
+ });
4716
+ };
4717
+ provider.embeddingModel = createEmbeddingModel;
4718
+ provider.textEmbeddingModel = createEmbeddingModel;
4719
+ provider.videoModel = (modelId) => {
4720
+ return new GatewayVideoModel(modelId, {
4721
+ provider: "gateway",
4722
+ baseURL,
4723
+ headers: getHeaders,
4724
+ fetch: options.fetch,
4725
+ o11yHeaders: createO11yHeaders()
4726
+ });
4727
+ };
4728
+ const createRerankingModel = (modelId) => {
4729
+ return new GatewayRerankingModel(modelId, {
4730
+ provider: "gateway",
4731
+ baseURL,
4732
+ headers: getHeaders,
4733
+ fetch: options.fetch,
4734
+ o11yHeaders: createO11yHeaders()
4735
+ });
4736
+ };
4737
+ provider.rerankingModel = createRerankingModel;
4738
+ provider.reranking = createRerankingModel;
4739
+ const createSpeechModel = (modelId) => {
4740
+ return new GatewaySpeechModel(modelId, {
4741
+ provider: "gateway",
4742
+ baseURL,
4743
+ headers: getHeaders,
4744
+ fetch: options.fetch,
4745
+ o11yHeaders: createO11yHeaders()
4746
+ });
4747
+ };
4748
+ provider.speechModel = createSpeechModel;
4749
+ provider.speech = createSpeechModel;
4750
+ const createTranscriptionModel = (modelId) => {
4751
+ return new GatewayTranscriptionModel(modelId, {
4752
+ provider: "gateway",
4753
+ baseURL,
4754
+ headers: getHeaders,
4755
+ fetch: options.fetch,
4756
+ o11yHeaders: createO11yHeaders()
4757
+ });
4758
+ };
4759
+ provider.transcriptionModel = createTranscriptionModel;
4760
+ provider.transcription = createTranscriptionModel;
4761
+ provider.chat = provider.languageModel;
4762
+ provider.embedding = provider.embeddingModel;
4763
+ provider.image = provider.imageModel;
4764
+ provider.video = provider.videoModel;
4765
+ provider.tools = gatewayTools;
4766
+ return provider;
4767
+ }
4768
+ var gateway = createGatewayProvider();
4769
+ async function getGatewayAuthToken(options) {
4770
+ const apiKey = loadOptionalSetting({
4771
+ settingValue: options.apiKey,
4772
+ environmentVariableName: "AI_GATEWAY_API_KEY"
4773
+ });
4774
+ if (apiKey)
4775
+ return {
4776
+ token: apiKey,
4777
+ authMethod: "api-key"
4778
+ };
4779
+ return {
4780
+ token: await getVercelOidcToken(),
4781
+ authMethod: "oidc"
4782
+ };
4783
+ }
4784
+
4785
+ export { DelayedPromise2, convertBase64ToUint8Array, convertUint8ArrayToBase64, cancelResponseBody, DownloadError, fetchWithValidatedRedirects, DEFAULT_MAX_DOWNLOAD_SIZE, readResponseWithSizeLimit, createIdGenerator, getErrorMessage$1, isAbortError2, getRuntimeEnvironmentUserAgent, withUserAgentSuffix, isUrlSupported, lazySchema, asSchema2, zodSchema, validateTypes, safeValidateTypes, safeParseJSON, resolve, retryWithExponentialBackoff, executeTool, AISDKError, APICallError2, getErrorMessage, InvalidPromptError, TypeValidationError2, UnsupportedFunctionalityError, GatewayError, GatewayAuthenticationError, createGatewayProvider, gateway };