@llmgateway/ai-sdk-provider 2.5.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -17,12 +17,25 @@ var __spreadValues = (a, b) => {
17
17
  return a;
18
18
  };
19
19
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
30
+ return target;
31
+ };
20
32
 
21
- // node_modules/.pnpm/@ai-sdk+provider@2.0.0-beta.1/node_modules/@ai-sdk/provider/dist/index.mjs
33
+ // node_modules/.pnpm/@ai-sdk+provider@3.0.2/node_modules/@ai-sdk/provider/dist/index.mjs
22
34
  var marker = "vercel.ai.error";
23
35
  var symbol = Symbol.for(marker);
24
36
  var _a;
25
- var _AISDKError = class _AISDKError2 extends Error {
37
+ var _b;
38
+ var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {
26
39
  /**
27
40
  * Creates an AI SDK Error.
28
41
  *
@@ -32,13 +45,13 @@ var _AISDKError = class _AISDKError2 extends Error {
32
45
  * @param {unknown} [params.cause] - The underlying cause of the error.
33
46
  */
34
47
  constructor({
35
- name: name14,
48
+ name: name142,
36
49
  message,
37
50
  cause
38
51
  }) {
39
52
  super(message);
40
53
  this[_a] = true;
41
- this.name = name14;
54
+ this.name = name142;
42
55
  this.cause = cause;
43
56
  }
44
57
  /**
@@ -47,20 +60,19 @@ var _AISDKError = class _AISDKError2 extends Error {
47
60
  * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
48
61
  */
49
62
  static isInstance(error) {
50
- return _AISDKError2.hasMarker(error, marker);
63
+ return _AISDKError.hasMarker(error, marker);
51
64
  }
52
- static hasMarker(error, marker15) {
53
- const markerSymbol = Symbol.for(marker15);
65
+ static hasMarker(error, marker152) {
66
+ const markerSymbol = Symbol.for(marker152);
54
67
  return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
55
68
  }
56
69
  };
57
- _a = symbol;
58
- var AISDKError = _AISDKError;
59
70
  var name = "AI_APICallError";
60
71
  var marker2 = `vercel.ai.error.${name}`;
61
72
  var symbol2 = Symbol.for(marker2);
62
73
  var _a2;
63
- var APICallError = class extends AISDKError {
74
+ var _b2;
75
+ var APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {
64
76
  constructor({
65
77
  message,
66
78
  url,
@@ -90,12 +102,12 @@ var APICallError = class extends AISDKError {
90
102
  return AISDKError.hasMarker(error, marker2);
91
103
  }
92
104
  };
93
- _a2 = symbol2;
94
105
  var name2 = "AI_EmptyResponseBodyError";
95
106
  var marker3 = `vercel.ai.error.${name2}`;
96
107
  var symbol3 = Symbol.for(marker3);
97
108
  var _a3;
98
- var EmptyResponseBodyError = class extends AISDKError {
109
+ var _b3;
110
+ var EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {
99
111
  // used in isInstance
100
112
  constructor({ message = "Empty response body" } = {}) {
101
113
  super({ name: name2, message });
@@ -105,7 +117,6 @@ var EmptyResponseBodyError = class extends AISDKError {
105
117
  return AISDKError.hasMarker(error, marker3);
106
118
  }
107
119
  };
108
- _a3 = symbol3;
109
120
  function getErrorMessage(error) {
110
121
  if (error == null) {
111
122
  return "unknown error";
@@ -122,7 +133,8 @@ var name3 = "AI_InvalidArgumentError";
122
133
  var marker4 = `vercel.ai.error.${name3}`;
123
134
  var symbol4 = Symbol.for(marker4);
124
135
  var _a4;
125
- var InvalidArgumentError = class extends AISDKError {
136
+ var _b4;
137
+ var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {
126
138
  constructor({
127
139
  message,
128
140
  cause,
@@ -136,12 +148,12 @@ var InvalidArgumentError = class extends AISDKError {
136
148
  return AISDKError.hasMarker(error, marker4);
137
149
  }
138
150
  };
139
- _a4 = symbol4;
140
151
  var name4 = "AI_InvalidPromptError";
141
152
  var marker5 = `vercel.ai.error.${name4}`;
142
153
  var symbol5 = Symbol.for(marker5);
143
154
  var _a5;
144
- var InvalidPromptError = class extends AISDKError {
155
+ var _b5;
156
+ var InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {
145
157
  constructor({
146
158
  prompt,
147
159
  message,
@@ -155,12 +167,12 @@ var InvalidPromptError = class extends AISDKError {
155
167
  return AISDKError.hasMarker(error, marker5);
156
168
  }
157
169
  };
158
- _a5 = symbol5;
159
170
  var name5 = "AI_InvalidResponseDataError";
160
171
  var marker6 = `vercel.ai.error.${name5}`;
161
172
  var symbol6 = Symbol.for(marker6);
162
173
  var _a6;
163
- var InvalidResponseDataError = class extends AISDKError {
174
+ var _b6;
175
+ var InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {
164
176
  constructor({
165
177
  data,
166
178
  message = `Invalid response data: ${JSON.stringify(data)}.`
@@ -173,12 +185,12 @@ var InvalidResponseDataError = class extends AISDKError {
173
185
  return AISDKError.hasMarker(error, marker6);
174
186
  }
175
187
  };
176
- _a6 = symbol6;
177
188
  var name6 = "AI_JSONParseError";
178
189
  var marker7 = `vercel.ai.error.${name6}`;
179
190
  var symbol7 = Symbol.for(marker7);
180
191
  var _a7;
181
- var JSONParseError = class extends AISDKError {
192
+ var _b7;
193
+ var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {
182
194
  constructor({ text, cause }) {
183
195
  super({
184
196
  name: name6,
@@ -193,12 +205,12 @@ Error message: ${getErrorMessage(cause)}`,
193
205
  return AISDKError.hasMarker(error, marker7);
194
206
  }
195
207
  };
196
- _a7 = symbol7;
197
208
  var name7 = "AI_LoadAPIKeyError";
198
209
  var marker8 = `vercel.ai.error.${name7}`;
199
210
  var symbol8 = Symbol.for(marker8);
200
211
  var _a8;
201
- var LoadAPIKeyError = class extends AISDKError {
212
+ var _b8;
213
+ var LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {
202
214
  // used in isInstance
203
215
  constructor({ message }) {
204
216
  super({ name: name7, message });
@@ -208,32 +220,86 @@ var LoadAPIKeyError = class extends AISDKError {
208
220
  return AISDKError.hasMarker(error, marker8);
209
221
  }
210
222
  };
211
- _a8 = symbol8;
212
223
  var name8 = "AI_LoadSettingError";
213
224
  var marker9 = `vercel.ai.error.${name8}`;
214
225
  var symbol9 = Symbol.for(marker9);
215
226
  var _a9;
216
- _a9 = symbol9;
227
+ var _b9;
228
+ var LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {
229
+ // used in isInstance
230
+ constructor({ message }) {
231
+ super({ name: name8, message });
232
+ this[_a9] = true;
233
+ }
234
+ static isInstance(error) {
235
+ return AISDKError.hasMarker(error, marker9);
236
+ }
237
+ };
217
238
  var name9 = "AI_NoContentGeneratedError";
218
239
  var marker10 = `vercel.ai.error.${name9}`;
219
240
  var symbol10 = Symbol.for(marker10);
220
241
  var _a10;
221
- _a10 = symbol10;
242
+ var _b10;
243
+ var NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {
244
+ // used in isInstance
245
+ constructor({
246
+ message = "No content generated."
247
+ } = {}) {
248
+ super({ name: name9, message });
249
+ this[_a10] = true;
250
+ }
251
+ static isInstance(error) {
252
+ return AISDKError.hasMarker(error, marker10);
253
+ }
254
+ };
222
255
  var name10 = "AI_NoSuchModelError";
223
256
  var marker11 = `vercel.ai.error.${name10}`;
224
257
  var symbol11 = Symbol.for(marker11);
225
258
  var _a11;
226
- _a11 = symbol11;
259
+ var _b11;
260
+ var NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {
261
+ constructor({
262
+ errorName = name10,
263
+ modelId,
264
+ modelType,
265
+ message = `No such ${modelType}: ${modelId}`
266
+ }) {
267
+ super({ name: errorName, message });
268
+ this[_a11] = true;
269
+ this.modelId = modelId;
270
+ this.modelType = modelType;
271
+ }
272
+ static isInstance(error) {
273
+ return AISDKError.hasMarker(error, marker11);
274
+ }
275
+ };
227
276
  var name11 = "AI_TooManyEmbeddingValuesForCallError";
228
277
  var marker12 = `vercel.ai.error.${name11}`;
229
278
  var symbol12 = Symbol.for(marker12);
230
279
  var _a12;
231
- _a12 = symbol12;
280
+ var _b12;
281
+ var TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {
282
+ constructor(options) {
283
+ super({
284
+ name: name11,
285
+ 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.`
286
+ });
287
+ this[_a12] = true;
288
+ this.provider = options.provider;
289
+ this.modelId = options.modelId;
290
+ this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
291
+ this.values = options.values;
292
+ }
293
+ static isInstance(error) {
294
+ return AISDKError.hasMarker(error, marker12);
295
+ }
296
+ };
232
297
  var name12 = "AI_TypeValidationError";
233
298
  var marker13 = `vercel.ai.error.${name12}`;
234
299
  var symbol13 = Symbol.for(marker13);
235
300
  var _a13;
236
- var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
301
+ var _b13;
302
+ var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
237
303
  constructor({ value, cause }) {
238
304
  super({
239
305
  name: name12,
@@ -261,16 +327,15 @@ Error message: ${getErrorMessage(cause)}`,
261
327
  value,
262
328
  cause
263
329
  }) {
264
- return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
330
+ return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
265
331
  }
266
332
  };
267
- _a13 = symbol13;
268
- var TypeValidationError = _TypeValidationError;
269
333
  var name13 = "AI_UnsupportedFunctionalityError";
270
334
  var marker14 = `vercel.ai.error.${name13}`;
271
335
  var symbol14 = Symbol.for(marker14);
272
336
  var _a14;
273
- var UnsupportedFunctionalityError = class extends AISDKError {
337
+ var _b14;
338
+ var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {
274
339
  constructor({
275
340
  functionality,
276
341
  message = `'${functionality}' functionality not supported.`
@@ -283,9 +348,16 @@ var UnsupportedFunctionalityError = class extends AISDKError {
283
348
  return AISDKError.hasMarker(error, marker14);
284
349
  }
285
350
  };
286
- _a14 = symbol14;
287
351
 
288
- // node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/dist/index.js
352
+ // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.4_zod@3.25.34/node_modules/@ai-sdk/provider-utils/dist/index.mjs
353
+ import * as z4 from "zod/v4";
354
+ import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
355
+ import { ZodFirstPartyTypeKind } from "zod/v3";
356
+ import {
357
+ ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2
358
+ } from "zod/v3";
359
+
360
+ // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js
289
361
  var ParseError = class extends Error {
290
362
  constructor(message, options) {
291
363
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
@@ -376,7 +448,7 @@ function splitLines(chunk) {
376
448
  const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
377
449
  `, searchIndex);
378
450
  let lineEnd = -1;
379
- if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
451
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
380
452
  incompleteLine = chunk.slice(searchIndex);
381
453
  break;
382
454
  } else {
@@ -388,7 +460,7 @@ function splitLines(chunk) {
388
460
  return [lines, incompleteLine];
389
461
  }
390
462
 
391
- // node_modules/.pnpm/eventsource-parser@3.0.3/node_modules/eventsource-parser/dist/stream.js
463
+ // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js
392
464
  var EventSourceParserStream = class extends TransformStream {
393
465
  constructor({ onError, onRetry, onComment } = {}) {
394
466
  let parser;
@@ -412,28 +484,7 @@ var EventSourceParserStream = class extends TransformStream {
412
484
  }
413
485
  };
414
486
 
415
- // node_modules/.pnpm/@ai-sdk+provider-utils@3.0.0-beta.5_zod@3.25.34/node_modules/@ai-sdk/provider-utils/dist/index.mjs
416
- import * as z4 from "zod/v4";
417
-
418
- // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.34/node_modules/zod-to-json-schema/dist/esm/Options.js
419
- var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
420
-
421
- // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.34/node_modules/zod-to-json-schema/dist/esm/selectParser.js
422
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod";
423
-
424
- // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.34/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
425
- import { ZodFirstPartyTypeKind } from "zod";
426
-
427
- // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.34/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
428
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2 } from "zod";
429
-
430
- // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.34/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
431
- var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
432
-
433
- // node_modules/.pnpm/zod-to-json-schema@3.24.5_zod@3.25.34/node_modules/zod-to-json-schema/dist/esm/parsers/object.js
434
- import { ZodOptional } from "zod";
435
-
436
- // node_modules/.pnpm/@ai-sdk+provider-utils@3.0.0-beta.5_zod@3.25.34/node_modules/@ai-sdk/provider-utils/dist/index.mjs
487
+ // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.4_zod@3.25.34/node_modules/@ai-sdk/provider-utils/dist/index.mjs
437
488
  function combineHeaders(...headers) {
438
489
  return headers.reduce(
439
490
  (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
@@ -443,6 +494,37 @@ function combineHeaders(...headers) {
443
494
  function extractResponseHeaders(response) {
444
495
  return Object.fromEntries([...response.headers]);
445
496
  }
497
+ var { btoa, atob } = globalThis;
498
+ function convertUint8ArrayToBase64(array) {
499
+ let latin1string = "";
500
+ for (let i = 0; i < array.length; i++) {
501
+ latin1string += String.fromCodePoint(array[i]);
502
+ }
503
+ return btoa(latin1string);
504
+ }
505
+ var name14 = "AI_DownloadError";
506
+ var marker15 = `vercel.ai.error.${name14}`;
507
+ var symbol15 = Symbol.for(marker15);
508
+ var _a15;
509
+ var _b15;
510
+ var DownloadError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) {
511
+ constructor({
512
+ url,
513
+ statusCode,
514
+ statusText,
515
+ cause,
516
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
517
+ }) {
518
+ super({ name: name14, message, cause });
519
+ this[_a15] = true;
520
+ this.url = url;
521
+ this.statusCode = statusCode;
522
+ this.statusText = statusText;
523
+ }
524
+ static isInstance(error) {
525
+ return AISDKError.hasMarker(error, marker15);
526
+ }
527
+ };
446
528
  var createIdGenerator = ({
447
529
  prefix,
448
530
  size = 16,
@@ -470,7 +552,7 @@ var createIdGenerator = ({
470
552
  };
471
553
  var generateId = createIdGenerator();
472
554
  function isAbortError(error) {
473
- return error instanceof Error && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
555
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
474
556
  error.name === "TimeoutError");
475
557
  }
476
558
  var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
@@ -497,11 +579,53 @@ function handleFetchError({
497
579
  }
498
580
  return error;
499
581
  }
500
- function removeUndefinedEntries(record) {
501
- return Object.fromEntries(
502
- Object.entries(record).filter(([_key, value]) => value != null)
582
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
583
+ var _a22, _b22, _c;
584
+ if (globalThisAny.window) {
585
+ return `runtime/browser`;
586
+ }
587
+ if ((_a22 = globalThisAny.navigator) == null ? void 0 : _a22.userAgent) {
588
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
589
+ }
590
+ if ((_c = (_b22 = globalThisAny.process) == null ? void 0 : _b22.versions) == null ? void 0 : _c.node) {
591
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
592
+ }
593
+ if (globalThisAny.EdgeRuntime) {
594
+ return `runtime/vercel-edge`;
595
+ }
596
+ return "runtime/unknown";
597
+ }
598
+ function normalizeHeaders(headers) {
599
+ if (headers == null) {
600
+ return {};
601
+ }
602
+ const normalized = {};
603
+ if (headers instanceof Headers) {
604
+ headers.forEach((value, key) => {
605
+ normalized[key.toLowerCase()] = value;
606
+ });
607
+ } else {
608
+ if (!Array.isArray(headers)) {
609
+ headers = Object.entries(headers);
610
+ }
611
+ for (const [key, value] of headers) {
612
+ if (value != null) {
613
+ normalized[key.toLowerCase()] = value;
614
+ }
615
+ }
616
+ }
617
+ return normalized;
618
+ }
619
+ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
620
+ const normalizedHeaders = new Headers(normalizeHeaders(headers));
621
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
622
+ normalizedHeaders.set(
623
+ "user-agent",
624
+ [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
503
625
  );
626
+ return Object.fromEntries(normalizedHeaders.entries());
504
627
  }
628
+ var VERSION = true ? "4.0.4" : "0.0.0-test";
505
629
  function loadApiKey({
506
630
  apiKey,
507
631
  environmentVariableName,
@@ -570,35 +694,1205 @@ function filter(obj) {
570
694
  }
571
695
  function secureJsonParse(text) {
572
696
  const { stackTraceLimit } = Error;
573
- Error.stackTraceLimit = 0;
697
+ try {
698
+ Error.stackTraceLimit = 0;
699
+ } catch (e) {
700
+ return _parse(text);
701
+ }
574
702
  try {
575
703
  return _parse(text);
576
704
  } finally {
577
705
  Error.stackTraceLimit = stackTraceLimit;
578
706
  }
579
707
  }
580
- var validatorSymbol = Symbol.for("vercel.ai.validator");
581
- function validator(validate) {
582
- return { [validatorSymbol]: true, validate };
708
+ function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
709
+ if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
710
+ jsonSchema2.additionalProperties = false;
711
+ const { properties } = jsonSchema2;
712
+ if (properties != null) {
713
+ for (const key of Object.keys(properties)) {
714
+ properties[key] = visit(properties[key]);
715
+ }
716
+ }
717
+ }
718
+ if (jsonSchema2.items != null) {
719
+ jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
720
+ }
721
+ if (jsonSchema2.anyOf != null) {
722
+ jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
723
+ }
724
+ if (jsonSchema2.allOf != null) {
725
+ jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
726
+ }
727
+ if (jsonSchema2.oneOf != null) {
728
+ jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
729
+ }
730
+ const { definitions } = jsonSchema2;
731
+ if (definitions != null) {
732
+ for (const key of Object.keys(definitions)) {
733
+ definitions[key] = visit(definitions[key]);
734
+ }
735
+ }
736
+ return jsonSchema2;
583
737
  }
584
- function isValidator(value) {
585
- return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
738
+ function visit(def) {
739
+ if (typeof def === "boolean") return def;
740
+ return addAdditionalPropertiesToJsonSchema(def);
586
741
  }
587
- function asValidator(value) {
588
- return isValidator(value) ? value : standardSchemaValidator(value);
742
+ var ignoreOverride = Symbol(
743
+ "Let zodToJsonSchema decide on which parser to use"
744
+ );
745
+ var defaultOptions = {
746
+ name: void 0,
747
+ $refStrategy: "root",
748
+ basePath: ["#"],
749
+ effectStrategy: "input",
750
+ pipeStrategy: "all",
751
+ dateStrategy: "format:date-time",
752
+ mapStrategy: "entries",
753
+ removeAdditionalStrategy: "passthrough",
754
+ allowedAdditionalProperties: true,
755
+ rejectedAdditionalProperties: false,
756
+ definitionPath: "definitions",
757
+ strictUnions: false,
758
+ definitions: {},
759
+ errorMessages: false,
760
+ patternStrategy: "escape",
761
+ applyRegexFlags: false,
762
+ emailStrategy: "format:email",
763
+ base64Strategy: "contentEncoding:base64",
764
+ nameStrategy: "ref"
765
+ };
766
+ var getDefaultOptions = (options) => typeof options === "string" ? __spreadProps(__spreadValues({}, defaultOptions), {
767
+ name: options
768
+ }) : __spreadValues(__spreadValues({}, defaultOptions), options);
769
+ function parseAnyDef() {
770
+ return {};
589
771
  }
590
- function standardSchemaValidator(standardSchema) {
591
- return validator(async (value) => {
592
- const result = await standardSchema["~standard"].validate(value);
593
- return result.issues == null ? { success: true, value: result.value } : {
594
- success: false,
595
- error: new TypeValidationError({
596
- value,
597
- cause: result.issues
598
- })
772
+ function parseArrayDef(def, refs) {
773
+ var _a22, _b22, _c;
774
+ const res = {
775
+ type: "array"
776
+ };
777
+ if (((_a22 = def.type) == null ? void 0 : _a22._def) && ((_c = (_b22 = def.type) == null ? void 0 : _b22._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
778
+ res.items = parseDef(def.type._def, __spreadProps(__spreadValues({}, refs), {
779
+ currentPath: [...refs.currentPath, "items"]
780
+ }));
781
+ }
782
+ if (def.minLength) {
783
+ res.minItems = def.minLength.value;
784
+ }
785
+ if (def.maxLength) {
786
+ res.maxItems = def.maxLength.value;
787
+ }
788
+ if (def.exactLength) {
789
+ res.minItems = def.exactLength.value;
790
+ res.maxItems = def.exactLength.value;
791
+ }
792
+ return res;
793
+ }
794
+ function parseBigintDef(def) {
795
+ const res = {
796
+ type: "integer",
797
+ format: "int64"
798
+ };
799
+ if (!def.checks) return res;
800
+ for (const check of def.checks) {
801
+ switch (check.kind) {
802
+ case "min":
803
+ if (check.inclusive) {
804
+ res.minimum = check.value;
805
+ } else {
806
+ res.exclusiveMinimum = check.value;
807
+ }
808
+ break;
809
+ case "max":
810
+ if (check.inclusive) {
811
+ res.maximum = check.value;
812
+ } else {
813
+ res.exclusiveMaximum = check.value;
814
+ }
815
+ break;
816
+ case "multipleOf":
817
+ res.multipleOf = check.value;
818
+ break;
819
+ }
820
+ }
821
+ return res;
822
+ }
823
+ function parseBooleanDef() {
824
+ return { type: "boolean" };
825
+ }
826
+ function parseBrandedDef(_def, refs) {
827
+ return parseDef(_def.type._def, refs);
828
+ }
829
+ var parseCatchDef = (def, refs) => {
830
+ return parseDef(def.innerType._def, refs);
831
+ };
832
+ function parseDateDef(def, refs, overrideDateStrategy) {
833
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
834
+ if (Array.isArray(strategy)) {
835
+ return {
836
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
599
837
  };
838
+ }
839
+ switch (strategy) {
840
+ case "string":
841
+ case "format:date-time":
842
+ return {
843
+ type: "string",
844
+ format: "date-time"
845
+ };
846
+ case "format:date":
847
+ return {
848
+ type: "string",
849
+ format: "date"
850
+ };
851
+ case "integer":
852
+ return integerDateParser(def);
853
+ }
854
+ }
855
+ var integerDateParser = (def) => {
856
+ const res = {
857
+ type: "integer",
858
+ format: "unix-time"
859
+ };
860
+ for (const check of def.checks) {
861
+ switch (check.kind) {
862
+ case "min":
863
+ res.minimum = check.value;
864
+ break;
865
+ case "max":
866
+ res.maximum = check.value;
867
+ break;
868
+ }
869
+ }
870
+ return res;
871
+ };
872
+ function parseDefaultDef(_def, refs) {
873
+ return __spreadProps(__spreadValues({}, parseDef(_def.innerType._def, refs)), {
874
+ default: _def.defaultValue()
600
875
  });
601
876
  }
877
+ function parseEffectsDef(_def, refs) {
878
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
879
+ }
880
+ function parseEnumDef(def) {
881
+ return {
882
+ type: "string",
883
+ enum: Array.from(def.values)
884
+ };
885
+ }
886
+ var isJsonSchema7AllOfType = (type) => {
887
+ if ("type" in type && type.type === "string") return false;
888
+ return "allOf" in type;
889
+ };
890
+ function parseIntersectionDef(def, refs) {
891
+ const allOf = [
892
+ parseDef(def.left._def, __spreadProps(__spreadValues({}, refs), {
893
+ currentPath: [...refs.currentPath, "allOf", "0"]
894
+ })),
895
+ parseDef(def.right._def, __spreadProps(__spreadValues({}, refs), {
896
+ currentPath: [...refs.currentPath, "allOf", "1"]
897
+ }))
898
+ ].filter((x) => !!x);
899
+ const mergedAllOf = [];
900
+ allOf.forEach((schema) => {
901
+ if (isJsonSchema7AllOfType(schema)) {
902
+ mergedAllOf.push(...schema.allOf);
903
+ } else {
904
+ let nestedSchema = schema;
905
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
906
+ const _a16 = schema, { additionalProperties } = _a16, rest = __objRest(_a16, ["additionalProperties"]);
907
+ nestedSchema = rest;
908
+ }
909
+ mergedAllOf.push(nestedSchema);
910
+ }
911
+ });
912
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
913
+ }
914
+ function parseLiteralDef(def) {
915
+ const parsedType = typeof def.value;
916
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
917
+ return {
918
+ type: Array.isArray(def.value) ? "array" : "object"
919
+ };
920
+ }
921
+ return {
922
+ type: parsedType === "bigint" ? "integer" : parsedType,
923
+ const: def.value
924
+ };
925
+ }
926
+ var emojiRegex = void 0;
927
+ var zodPatterns = {
928
+ /**
929
+ * `c` was changed to `[cC]` to replicate /i flag
930
+ */
931
+ cuid: /^[cC][^\s-]{8,}$/,
932
+ cuid2: /^[0-9a-z]+$/,
933
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
934
+ /**
935
+ * `a-z` was added to replicate /i flag
936
+ */
937
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
938
+ /**
939
+ * Constructed a valid Unicode RegExp
940
+ *
941
+ * Lazily instantiate since this type of regex isn't supported
942
+ * in all envs (e.g. React Native).
943
+ *
944
+ * See:
945
+ * https://github.com/colinhacks/zod/issues/2433
946
+ * Fix in Zod:
947
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
948
+ */
949
+ emoji: () => {
950
+ if (emojiRegex === void 0) {
951
+ emojiRegex = RegExp(
952
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
953
+ "u"
954
+ );
955
+ }
956
+ return emojiRegex;
957
+ },
958
+ /**
959
+ * Unused
960
+ */
961
+ 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}$/,
962
+ /**
963
+ * Unused
964
+ */
965
+ 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])$/,
966
+ 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])$/,
967
+ /**
968
+ * Unused
969
+ */
970
+ 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})))$/,
971
+ 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])$/,
972
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
973
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
974
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
975
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
976
+ };
977
+ function parseStringDef(def, refs) {
978
+ const res = {
979
+ type: "string"
980
+ };
981
+ if (def.checks) {
982
+ for (const check of def.checks) {
983
+ switch (check.kind) {
984
+ case "min":
985
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
986
+ break;
987
+ case "max":
988
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
989
+ break;
990
+ case "email":
991
+ switch (refs.emailStrategy) {
992
+ case "format:email":
993
+ addFormat(res, "email", check.message, refs);
994
+ break;
995
+ case "format:idn-email":
996
+ addFormat(res, "idn-email", check.message, refs);
997
+ break;
998
+ case "pattern:zod":
999
+ addPattern(res, zodPatterns.email, check.message, refs);
1000
+ break;
1001
+ }
1002
+ break;
1003
+ case "url":
1004
+ addFormat(res, "uri", check.message, refs);
1005
+ break;
1006
+ case "uuid":
1007
+ addFormat(res, "uuid", check.message, refs);
1008
+ break;
1009
+ case "regex":
1010
+ addPattern(res, check.regex, check.message, refs);
1011
+ break;
1012
+ case "cuid":
1013
+ addPattern(res, zodPatterns.cuid, check.message, refs);
1014
+ break;
1015
+ case "cuid2":
1016
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
1017
+ break;
1018
+ case "startsWith":
1019
+ addPattern(
1020
+ res,
1021
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
1022
+ check.message,
1023
+ refs
1024
+ );
1025
+ break;
1026
+ case "endsWith":
1027
+ addPattern(
1028
+ res,
1029
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
1030
+ check.message,
1031
+ refs
1032
+ );
1033
+ break;
1034
+ case "datetime":
1035
+ addFormat(res, "date-time", check.message, refs);
1036
+ break;
1037
+ case "date":
1038
+ addFormat(res, "date", check.message, refs);
1039
+ break;
1040
+ case "time":
1041
+ addFormat(res, "time", check.message, refs);
1042
+ break;
1043
+ case "duration":
1044
+ addFormat(res, "duration", check.message, refs);
1045
+ break;
1046
+ case "length":
1047
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1048
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1049
+ break;
1050
+ case "includes": {
1051
+ addPattern(
1052
+ res,
1053
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
1054
+ check.message,
1055
+ refs
1056
+ );
1057
+ break;
1058
+ }
1059
+ case "ip": {
1060
+ if (check.version !== "v6") {
1061
+ addFormat(res, "ipv4", check.message, refs);
1062
+ }
1063
+ if (check.version !== "v4") {
1064
+ addFormat(res, "ipv6", check.message, refs);
1065
+ }
1066
+ break;
1067
+ }
1068
+ case "base64url":
1069
+ addPattern(res, zodPatterns.base64url, check.message, refs);
1070
+ break;
1071
+ case "jwt":
1072
+ addPattern(res, zodPatterns.jwt, check.message, refs);
1073
+ break;
1074
+ case "cidr": {
1075
+ if (check.version !== "v6") {
1076
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1077
+ }
1078
+ if (check.version !== "v4") {
1079
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1080
+ }
1081
+ break;
1082
+ }
1083
+ case "emoji":
1084
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
1085
+ break;
1086
+ case "ulid": {
1087
+ addPattern(res, zodPatterns.ulid, check.message, refs);
1088
+ break;
1089
+ }
1090
+ case "base64": {
1091
+ switch (refs.base64Strategy) {
1092
+ case "format:binary": {
1093
+ addFormat(res, "binary", check.message, refs);
1094
+ break;
1095
+ }
1096
+ case "contentEncoding:base64": {
1097
+ res.contentEncoding = "base64";
1098
+ break;
1099
+ }
1100
+ case "pattern:zod": {
1101
+ addPattern(res, zodPatterns.base64, check.message, refs);
1102
+ break;
1103
+ }
1104
+ }
1105
+ break;
1106
+ }
1107
+ case "nanoid": {
1108
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
1109
+ }
1110
+ case "toLowerCase":
1111
+ case "toUpperCase":
1112
+ case "trim":
1113
+ break;
1114
+ default:
1115
+ /* @__PURE__ */ ((_) => {
1116
+ })(check);
1117
+ }
1118
+ }
1119
+ }
1120
+ return res;
1121
+ }
1122
+ function escapeLiteralCheckValue(literal, refs) {
1123
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1124
+ }
1125
+ var ALPHA_NUMERIC = new Set(
1126
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1127
+ );
1128
+ function escapeNonAlphaNumeric(source) {
1129
+ let result = "";
1130
+ for (let i = 0; i < source.length; i++) {
1131
+ if (!ALPHA_NUMERIC.has(source[i])) {
1132
+ result += "\\";
1133
+ }
1134
+ result += source[i];
1135
+ }
1136
+ return result;
1137
+ }
1138
+ function addFormat(schema, value, message, refs) {
1139
+ var _a22;
1140
+ if (schema.format || ((_a22 = schema.anyOf) == null ? void 0 : _a22.some((x) => x.format))) {
1141
+ if (!schema.anyOf) {
1142
+ schema.anyOf = [];
1143
+ }
1144
+ if (schema.format) {
1145
+ schema.anyOf.push({
1146
+ format: schema.format
1147
+ });
1148
+ delete schema.format;
1149
+ }
1150
+ schema.anyOf.push(__spreadValues({
1151
+ format: value
1152
+ }, message && refs.errorMessages && { errorMessage: { format: message } }));
1153
+ } else {
1154
+ schema.format = value;
1155
+ }
1156
+ }
1157
+ function addPattern(schema, regex, message, refs) {
1158
+ var _a22;
1159
+ if (schema.pattern || ((_a22 = schema.allOf) == null ? void 0 : _a22.some((x) => x.pattern))) {
1160
+ if (!schema.allOf) {
1161
+ schema.allOf = [];
1162
+ }
1163
+ if (schema.pattern) {
1164
+ schema.allOf.push({
1165
+ pattern: schema.pattern
1166
+ });
1167
+ delete schema.pattern;
1168
+ }
1169
+ schema.allOf.push(__spreadValues({
1170
+ pattern: stringifyRegExpWithFlags(regex, refs)
1171
+ }, message && refs.errorMessages && { errorMessage: { pattern: message } }));
1172
+ } else {
1173
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
1174
+ }
1175
+ }
1176
+ function stringifyRegExpWithFlags(regex, refs) {
1177
+ var _a22;
1178
+ if (!refs.applyRegexFlags || !regex.flags) {
1179
+ return regex.source;
1180
+ }
1181
+ const flags = {
1182
+ i: regex.flags.includes("i"),
1183
+ // Case-insensitive
1184
+ m: regex.flags.includes("m"),
1185
+ // `^` and `$` matches adjacent to newline characters
1186
+ s: regex.flags.includes("s")
1187
+ // `.` matches newlines
1188
+ };
1189
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1190
+ let pattern = "";
1191
+ let isEscaped = false;
1192
+ let inCharGroup = false;
1193
+ let inCharRange = false;
1194
+ for (let i = 0; i < source.length; i++) {
1195
+ if (isEscaped) {
1196
+ pattern += source[i];
1197
+ isEscaped = false;
1198
+ continue;
1199
+ }
1200
+ if (flags.i) {
1201
+ if (inCharGroup) {
1202
+ if (source[i].match(/[a-z]/)) {
1203
+ if (inCharRange) {
1204
+ pattern += source[i];
1205
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1206
+ inCharRange = false;
1207
+ } else if (source[i + 1] === "-" && ((_a22 = source[i + 2]) == null ? void 0 : _a22.match(/[a-z]/))) {
1208
+ pattern += source[i];
1209
+ inCharRange = true;
1210
+ } else {
1211
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1212
+ }
1213
+ continue;
1214
+ }
1215
+ } else if (source[i].match(/[a-z]/)) {
1216
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1217
+ continue;
1218
+ }
1219
+ }
1220
+ if (flags.m) {
1221
+ if (source[i] === "^") {
1222
+ pattern += `(^|(?<=[\r
1223
+ ]))`;
1224
+ continue;
1225
+ } else if (source[i] === "$") {
1226
+ pattern += `($|(?=[\r
1227
+ ]))`;
1228
+ continue;
1229
+ }
1230
+ }
1231
+ if (flags.s && source[i] === ".") {
1232
+ pattern += inCharGroup ? `${source[i]}\r
1233
+ ` : `[${source[i]}\r
1234
+ ]`;
1235
+ continue;
1236
+ }
1237
+ pattern += source[i];
1238
+ if (source[i] === "\\") {
1239
+ isEscaped = true;
1240
+ } else if (inCharGroup && source[i] === "]") {
1241
+ inCharGroup = false;
1242
+ } else if (!inCharGroup && source[i] === "[") {
1243
+ inCharGroup = true;
1244
+ }
1245
+ }
1246
+ try {
1247
+ new RegExp(pattern);
1248
+ } catch (e) {
1249
+ console.warn(
1250
+ `Could not convert regex pattern at ${refs.currentPath.join(
1251
+ "/"
1252
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1253
+ );
1254
+ return regex.source;
1255
+ }
1256
+ return pattern;
1257
+ }
1258
+ function parseRecordDef(def, refs) {
1259
+ var _a22, _b22, _c, _d, _e, _f;
1260
+ const schema = {
1261
+ type: "object",
1262
+ additionalProperties: (_a22 = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
1263
+ currentPath: [...refs.currentPath, "additionalProperties"]
1264
+ }))) != null ? _a22 : refs.allowedAdditionalProperties
1265
+ };
1266
+ if (((_b22 = def.keyType) == null ? void 0 : _b22._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1267
+ const _a16 = parseStringDef(def.keyType._def, refs), { type } = _a16, keyType = __objRest(_a16, ["type"]);
1268
+ return __spreadProps(__spreadValues({}, schema), {
1269
+ propertyNames: keyType
1270
+ });
1271
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1272
+ return __spreadProps(__spreadValues({}, schema), {
1273
+ propertyNames: {
1274
+ enum: def.keyType._def.values
1275
+ }
1276
+ });
1277
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1278
+ const _b16 = parseBrandedDef(
1279
+ def.keyType._def,
1280
+ refs
1281
+ ), { type } = _b16, keyType = __objRest(_b16, ["type"]);
1282
+ return __spreadProps(__spreadValues({}, schema), {
1283
+ propertyNames: keyType
1284
+ });
1285
+ }
1286
+ return schema;
1287
+ }
1288
+ function parseMapDef(def, refs) {
1289
+ if (refs.mapStrategy === "record") {
1290
+ return parseRecordDef(def, refs);
1291
+ }
1292
+ const keys = parseDef(def.keyType._def, __spreadProps(__spreadValues({}, refs), {
1293
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1294
+ })) || parseAnyDef();
1295
+ const values = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
1296
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1297
+ })) || parseAnyDef();
1298
+ return {
1299
+ type: "array",
1300
+ maxItems: 125,
1301
+ items: {
1302
+ type: "array",
1303
+ items: [keys, values],
1304
+ minItems: 2,
1305
+ maxItems: 2
1306
+ }
1307
+ };
1308
+ }
1309
+ function parseNativeEnumDef(def) {
1310
+ const object = def.values;
1311
+ const actualKeys = Object.keys(def.values).filter((key) => {
1312
+ return typeof object[object[key]] !== "number";
1313
+ });
1314
+ const actualValues = actualKeys.map((key) => object[key]);
1315
+ const parsedTypes = Array.from(
1316
+ new Set(actualValues.map((values) => typeof values))
1317
+ );
1318
+ return {
1319
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1320
+ enum: actualValues
1321
+ };
1322
+ }
1323
+ function parseNeverDef() {
1324
+ return { not: parseAnyDef() };
1325
+ }
1326
+ function parseNullDef() {
1327
+ return {
1328
+ type: "null"
1329
+ };
1330
+ }
1331
+ var primitiveMappings = {
1332
+ ZodString: "string",
1333
+ ZodNumber: "number",
1334
+ ZodBigInt: "integer",
1335
+ ZodBoolean: "boolean",
1336
+ ZodNull: "null"
1337
+ };
1338
+ function parseUnionDef(def, refs) {
1339
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1340
+ if (options.every(
1341
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1342
+ )) {
1343
+ const types = options.reduce((types2, x) => {
1344
+ const type = primitiveMappings[x._def.typeName];
1345
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1346
+ }, []);
1347
+ return {
1348
+ type: types.length > 1 ? types : types[0]
1349
+ };
1350
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1351
+ const types = options.reduce(
1352
+ (acc, x) => {
1353
+ const type = typeof x._def.value;
1354
+ switch (type) {
1355
+ case "string":
1356
+ case "number":
1357
+ case "boolean":
1358
+ return [...acc, type];
1359
+ case "bigint":
1360
+ return [...acc, "integer"];
1361
+ case "object":
1362
+ if (x._def.value === null) return [...acc, "null"];
1363
+ case "symbol":
1364
+ case "undefined":
1365
+ case "function":
1366
+ default:
1367
+ return acc;
1368
+ }
1369
+ },
1370
+ []
1371
+ );
1372
+ if (types.length === options.length) {
1373
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1374
+ return {
1375
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1376
+ enum: options.reduce(
1377
+ (acc, x) => {
1378
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1379
+ },
1380
+ []
1381
+ )
1382
+ };
1383
+ }
1384
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1385
+ return {
1386
+ type: "string",
1387
+ enum: options.reduce(
1388
+ (acc, x) => [
1389
+ ...acc,
1390
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1391
+ ],
1392
+ []
1393
+ )
1394
+ };
1395
+ }
1396
+ return asAnyOf(def, refs);
1397
+ }
1398
+ var asAnyOf = (def, refs) => {
1399
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1400
+ (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), {
1401
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1402
+ }))
1403
+ ).filter(
1404
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1405
+ );
1406
+ return anyOf.length ? { anyOf } : void 0;
1407
+ };
1408
+ function parseNullableDef(def, refs) {
1409
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1410
+ def.innerType._def.typeName
1411
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1412
+ return {
1413
+ type: [
1414
+ primitiveMappings[def.innerType._def.typeName],
1415
+ "null"
1416
+ ]
1417
+ };
1418
+ }
1419
+ const base = parseDef(def.innerType._def, __spreadProps(__spreadValues({}, refs), {
1420
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1421
+ }));
1422
+ return base && { anyOf: [base, { type: "null" }] };
1423
+ }
1424
+ function parseNumberDef(def) {
1425
+ const res = {
1426
+ type: "number"
1427
+ };
1428
+ if (!def.checks) return res;
1429
+ for (const check of def.checks) {
1430
+ switch (check.kind) {
1431
+ case "int":
1432
+ res.type = "integer";
1433
+ break;
1434
+ case "min":
1435
+ if (check.inclusive) {
1436
+ res.minimum = check.value;
1437
+ } else {
1438
+ res.exclusiveMinimum = check.value;
1439
+ }
1440
+ break;
1441
+ case "max":
1442
+ if (check.inclusive) {
1443
+ res.maximum = check.value;
1444
+ } else {
1445
+ res.exclusiveMaximum = check.value;
1446
+ }
1447
+ break;
1448
+ case "multipleOf":
1449
+ res.multipleOf = check.value;
1450
+ break;
1451
+ }
1452
+ }
1453
+ return res;
1454
+ }
1455
+ function parseObjectDef(def, refs) {
1456
+ const result = {
1457
+ type: "object",
1458
+ properties: {}
1459
+ };
1460
+ const required = [];
1461
+ const shape = def.shape();
1462
+ for (const propName in shape) {
1463
+ let propDef = shape[propName];
1464
+ if (propDef === void 0 || propDef._def === void 0) {
1465
+ continue;
1466
+ }
1467
+ const propOptional = safeIsOptional(propDef);
1468
+ const parsedDef = parseDef(propDef._def, __spreadProps(__spreadValues({}, refs), {
1469
+ currentPath: [...refs.currentPath, "properties", propName],
1470
+ propertyPath: [...refs.currentPath, "properties", propName]
1471
+ }));
1472
+ if (parsedDef === void 0) {
1473
+ continue;
1474
+ }
1475
+ result.properties[propName] = parsedDef;
1476
+ if (!propOptional) {
1477
+ required.push(propName);
1478
+ }
1479
+ }
1480
+ if (required.length) {
1481
+ result.required = required;
1482
+ }
1483
+ const additionalProperties = decideAdditionalProperties(def, refs);
1484
+ if (additionalProperties !== void 0) {
1485
+ result.additionalProperties = additionalProperties;
1486
+ }
1487
+ return result;
1488
+ }
1489
+ function decideAdditionalProperties(def, refs) {
1490
+ if (def.catchall._def.typeName !== "ZodNever") {
1491
+ return parseDef(def.catchall._def, __spreadProps(__spreadValues({}, refs), {
1492
+ currentPath: [...refs.currentPath, "additionalProperties"]
1493
+ }));
1494
+ }
1495
+ switch (def.unknownKeys) {
1496
+ case "passthrough":
1497
+ return refs.allowedAdditionalProperties;
1498
+ case "strict":
1499
+ return refs.rejectedAdditionalProperties;
1500
+ case "strip":
1501
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1502
+ }
1503
+ }
1504
+ function safeIsOptional(schema) {
1505
+ try {
1506
+ return schema.isOptional();
1507
+ } catch (e) {
1508
+ return true;
1509
+ }
1510
+ }
1511
+ var parseOptionalDef = (def, refs) => {
1512
+ var _a22;
1513
+ if (refs.currentPath.toString() === ((_a22 = refs.propertyPath) == null ? void 0 : _a22.toString())) {
1514
+ return parseDef(def.innerType._def, refs);
1515
+ }
1516
+ const innerSchema = parseDef(def.innerType._def, __spreadProps(__spreadValues({}, refs), {
1517
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1518
+ }));
1519
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1520
+ };
1521
+ var parsePipelineDef = (def, refs) => {
1522
+ if (refs.pipeStrategy === "input") {
1523
+ return parseDef(def.in._def, refs);
1524
+ } else if (refs.pipeStrategy === "output") {
1525
+ return parseDef(def.out._def, refs);
1526
+ }
1527
+ const a = parseDef(def.in._def, __spreadProps(__spreadValues({}, refs), {
1528
+ currentPath: [...refs.currentPath, "allOf", "0"]
1529
+ }));
1530
+ const b = parseDef(def.out._def, __spreadProps(__spreadValues({}, refs), {
1531
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1532
+ }));
1533
+ return {
1534
+ allOf: [a, b].filter((x) => x !== void 0)
1535
+ };
1536
+ };
1537
+ function parsePromiseDef(def, refs) {
1538
+ return parseDef(def.type._def, refs);
1539
+ }
1540
+ function parseSetDef(def, refs) {
1541
+ const items = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
1542
+ currentPath: [...refs.currentPath, "items"]
1543
+ }));
1544
+ const schema = {
1545
+ type: "array",
1546
+ uniqueItems: true,
1547
+ items
1548
+ };
1549
+ if (def.minSize) {
1550
+ schema.minItems = def.minSize.value;
1551
+ }
1552
+ if (def.maxSize) {
1553
+ schema.maxItems = def.maxSize.value;
1554
+ }
1555
+ return schema;
1556
+ }
1557
+ function parseTupleDef(def, refs) {
1558
+ if (def.rest) {
1559
+ return {
1560
+ type: "array",
1561
+ minItems: def.items.length,
1562
+ items: def.items.map(
1563
+ (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), {
1564
+ currentPath: [...refs.currentPath, "items", `${i}`]
1565
+ }))
1566
+ ).reduce(
1567
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1568
+ []
1569
+ ),
1570
+ additionalItems: parseDef(def.rest._def, __spreadProps(__spreadValues({}, refs), {
1571
+ currentPath: [...refs.currentPath, "additionalItems"]
1572
+ }))
1573
+ };
1574
+ } else {
1575
+ return {
1576
+ type: "array",
1577
+ minItems: def.items.length,
1578
+ maxItems: def.items.length,
1579
+ items: def.items.map(
1580
+ (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), {
1581
+ currentPath: [...refs.currentPath, "items", `${i}`]
1582
+ }))
1583
+ ).reduce(
1584
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1585
+ []
1586
+ )
1587
+ };
1588
+ }
1589
+ }
1590
+ function parseUndefinedDef() {
1591
+ return {
1592
+ not: parseAnyDef()
1593
+ };
1594
+ }
1595
+ function parseUnknownDef() {
1596
+ return parseAnyDef();
1597
+ }
1598
+ var parseReadonlyDef = (def, refs) => {
1599
+ return parseDef(def.innerType._def, refs);
1600
+ };
1601
+ var selectParser = (def, typeName, refs) => {
1602
+ switch (typeName) {
1603
+ case ZodFirstPartyTypeKind3.ZodString:
1604
+ return parseStringDef(def, refs);
1605
+ case ZodFirstPartyTypeKind3.ZodNumber:
1606
+ return parseNumberDef(def);
1607
+ case ZodFirstPartyTypeKind3.ZodObject:
1608
+ return parseObjectDef(def, refs);
1609
+ case ZodFirstPartyTypeKind3.ZodBigInt:
1610
+ return parseBigintDef(def);
1611
+ case ZodFirstPartyTypeKind3.ZodBoolean:
1612
+ return parseBooleanDef();
1613
+ case ZodFirstPartyTypeKind3.ZodDate:
1614
+ return parseDateDef(def, refs);
1615
+ case ZodFirstPartyTypeKind3.ZodUndefined:
1616
+ return parseUndefinedDef();
1617
+ case ZodFirstPartyTypeKind3.ZodNull:
1618
+ return parseNullDef();
1619
+ case ZodFirstPartyTypeKind3.ZodArray:
1620
+ return parseArrayDef(def, refs);
1621
+ case ZodFirstPartyTypeKind3.ZodUnion:
1622
+ case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1623
+ return parseUnionDef(def, refs);
1624
+ case ZodFirstPartyTypeKind3.ZodIntersection:
1625
+ return parseIntersectionDef(def, refs);
1626
+ case ZodFirstPartyTypeKind3.ZodTuple:
1627
+ return parseTupleDef(def, refs);
1628
+ case ZodFirstPartyTypeKind3.ZodRecord:
1629
+ return parseRecordDef(def, refs);
1630
+ case ZodFirstPartyTypeKind3.ZodLiteral:
1631
+ return parseLiteralDef(def);
1632
+ case ZodFirstPartyTypeKind3.ZodEnum:
1633
+ return parseEnumDef(def);
1634
+ case ZodFirstPartyTypeKind3.ZodNativeEnum:
1635
+ return parseNativeEnumDef(def);
1636
+ case ZodFirstPartyTypeKind3.ZodNullable:
1637
+ return parseNullableDef(def, refs);
1638
+ case ZodFirstPartyTypeKind3.ZodOptional:
1639
+ return parseOptionalDef(def, refs);
1640
+ case ZodFirstPartyTypeKind3.ZodMap:
1641
+ return parseMapDef(def, refs);
1642
+ case ZodFirstPartyTypeKind3.ZodSet:
1643
+ return parseSetDef(def, refs);
1644
+ case ZodFirstPartyTypeKind3.ZodLazy:
1645
+ return () => def.getter()._def;
1646
+ case ZodFirstPartyTypeKind3.ZodPromise:
1647
+ return parsePromiseDef(def, refs);
1648
+ case ZodFirstPartyTypeKind3.ZodNaN:
1649
+ case ZodFirstPartyTypeKind3.ZodNever:
1650
+ return parseNeverDef();
1651
+ case ZodFirstPartyTypeKind3.ZodEffects:
1652
+ return parseEffectsDef(def, refs);
1653
+ case ZodFirstPartyTypeKind3.ZodAny:
1654
+ return parseAnyDef();
1655
+ case ZodFirstPartyTypeKind3.ZodUnknown:
1656
+ return parseUnknownDef();
1657
+ case ZodFirstPartyTypeKind3.ZodDefault:
1658
+ return parseDefaultDef(def, refs);
1659
+ case ZodFirstPartyTypeKind3.ZodBranded:
1660
+ return parseBrandedDef(def, refs);
1661
+ case ZodFirstPartyTypeKind3.ZodReadonly:
1662
+ return parseReadonlyDef(def, refs);
1663
+ case ZodFirstPartyTypeKind3.ZodCatch:
1664
+ return parseCatchDef(def, refs);
1665
+ case ZodFirstPartyTypeKind3.ZodPipeline:
1666
+ return parsePipelineDef(def, refs);
1667
+ case ZodFirstPartyTypeKind3.ZodFunction:
1668
+ case ZodFirstPartyTypeKind3.ZodVoid:
1669
+ case ZodFirstPartyTypeKind3.ZodSymbol:
1670
+ return void 0;
1671
+ default:
1672
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
1673
+ }
1674
+ };
1675
+ var getRelativePath = (pathA, pathB) => {
1676
+ let i = 0;
1677
+ for (; i < pathA.length && i < pathB.length; i++) {
1678
+ if (pathA[i] !== pathB[i]) break;
1679
+ }
1680
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1681
+ };
1682
+ function parseDef(def, refs, forceResolution = false) {
1683
+ var _a22;
1684
+ const seenItem = refs.seen.get(def);
1685
+ if (refs.override) {
1686
+ const overrideResult = (_a22 = refs.override) == null ? void 0 : _a22.call(
1687
+ refs,
1688
+ def,
1689
+ refs,
1690
+ seenItem,
1691
+ forceResolution
1692
+ );
1693
+ if (overrideResult !== ignoreOverride) {
1694
+ return overrideResult;
1695
+ }
1696
+ }
1697
+ if (seenItem && !forceResolution) {
1698
+ const seenSchema = get$ref(seenItem, refs);
1699
+ if (seenSchema !== void 0) {
1700
+ return seenSchema;
1701
+ }
1702
+ }
1703
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1704
+ refs.seen.set(def, newItem);
1705
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1706
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1707
+ if (jsonSchema2) {
1708
+ addMeta(def, refs, jsonSchema2);
1709
+ }
1710
+ if (refs.postProcess) {
1711
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1712
+ newItem.jsonSchema = jsonSchema2;
1713
+ return postProcessResult;
1714
+ }
1715
+ newItem.jsonSchema = jsonSchema2;
1716
+ return jsonSchema2;
1717
+ }
1718
+ var get$ref = (item, refs) => {
1719
+ switch (refs.$refStrategy) {
1720
+ case "root":
1721
+ return { $ref: item.path.join("/") };
1722
+ case "relative":
1723
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1724
+ case "none":
1725
+ case "seen": {
1726
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1727
+ console.warn(
1728
+ `Recursive reference detected at ${refs.currentPath.join(
1729
+ "/"
1730
+ )}! Defaulting to any`
1731
+ );
1732
+ return parseAnyDef();
1733
+ }
1734
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1735
+ }
1736
+ }
1737
+ };
1738
+ var addMeta = (def, refs, jsonSchema2) => {
1739
+ if (def.description) {
1740
+ jsonSchema2.description = def.description;
1741
+ }
1742
+ return jsonSchema2;
1743
+ };
1744
+ var getRefs = (options) => {
1745
+ const _options = getDefaultOptions(options);
1746
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1747
+ return __spreadProps(__spreadValues({}, _options), {
1748
+ currentPath,
1749
+ propertyPath: void 0,
1750
+ seen: new Map(
1751
+ Object.entries(_options.definitions).map(([name22, def]) => [
1752
+ def._def,
1753
+ {
1754
+ def: def._def,
1755
+ path: [..._options.basePath, _options.definitionPath, name22],
1756
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1757
+ jsonSchema: void 0
1758
+ }
1759
+ ])
1760
+ )
1761
+ });
1762
+ };
1763
+ var zod3ToJsonSchema = (schema, options) => {
1764
+ var _a22;
1765
+ const refs = getRefs(options);
1766
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1767
+ (acc, [name32, schema2]) => {
1768
+ var _a32;
1769
+ return __spreadProps(__spreadValues({}, acc), {
1770
+ [name32]: (_a32 = parseDef(
1771
+ schema2._def,
1772
+ __spreadProps(__spreadValues({}, refs), {
1773
+ currentPath: [...refs.basePath, refs.definitionPath, name32]
1774
+ }),
1775
+ true
1776
+ )) != null ? _a32 : parseAnyDef()
1777
+ });
1778
+ },
1779
+ {}
1780
+ ) : void 0;
1781
+ const name22 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1782
+ const main = (_a22 = parseDef(
1783
+ schema._def,
1784
+ name22 === void 0 ? refs : __spreadProps(__spreadValues({}, refs), {
1785
+ currentPath: [...refs.basePath, refs.definitionPath, name22]
1786
+ }),
1787
+ false
1788
+ )) != null ? _a22 : parseAnyDef();
1789
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1790
+ if (title !== void 0) {
1791
+ main.title = title;
1792
+ }
1793
+ const combined = name22 === void 0 ? definitions ? __spreadProps(__spreadValues({}, main), {
1794
+ [refs.definitionPath]: definitions
1795
+ }) : main : {
1796
+ $ref: [
1797
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1798
+ refs.definitionPath,
1799
+ name22
1800
+ ].join("/"),
1801
+ [refs.definitionPath]: __spreadProps(__spreadValues({}, definitions), {
1802
+ [name22]: main
1803
+ })
1804
+ };
1805
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1806
+ return combined;
1807
+ };
1808
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
1809
+ function jsonSchema(jsonSchema2, {
1810
+ validate
1811
+ } = {}) {
1812
+ return {
1813
+ [schemaSymbol]: true,
1814
+ _type: void 0,
1815
+ // should never be used directly
1816
+ get jsonSchema() {
1817
+ if (typeof jsonSchema2 === "function") {
1818
+ jsonSchema2 = jsonSchema2();
1819
+ }
1820
+ return jsonSchema2;
1821
+ },
1822
+ validate
1823
+ };
1824
+ }
1825
+ function isSchema(value) {
1826
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
1827
+ }
1828
+ function asSchema(schema) {
1829
+ return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
1830
+ }
1831
+ function standardSchema(standardSchema2) {
1832
+ return jsonSchema(
1833
+ () => standardSchema2["~standard"].jsonSchema.input({
1834
+ target: "draft-07"
1835
+ }),
1836
+ {
1837
+ validate: async (value) => {
1838
+ const result = await standardSchema2["~standard"].validate(value);
1839
+ return "value" in result ? { success: true, value: result.value } : {
1840
+ success: false,
1841
+ error: new TypeValidationError({
1842
+ value,
1843
+ cause: result.issues
1844
+ })
1845
+ };
1846
+ }
1847
+ }
1848
+ );
1849
+ }
1850
+ function zod3Schema(zodSchema2, options) {
1851
+ var _a22;
1852
+ const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
1853
+ return jsonSchema(
1854
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1855
+ () => zod3ToJsonSchema(zodSchema2, {
1856
+ $refStrategy: useReferences ? "root" : "none"
1857
+ }),
1858
+ {
1859
+ validate: async (value) => {
1860
+ const result = await zodSchema2.safeParseAsync(value);
1861
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1862
+ }
1863
+ }
1864
+ );
1865
+ }
1866
+ function zod4Schema(zodSchema2, options) {
1867
+ var _a22;
1868
+ const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
1869
+ return jsonSchema(
1870
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1871
+ () => addAdditionalPropertiesToJsonSchema(
1872
+ z4.toJSONSchema(zodSchema2, {
1873
+ target: "draft-7",
1874
+ io: "input",
1875
+ reused: useReferences ? "ref" : "inline"
1876
+ })
1877
+ ),
1878
+ {
1879
+ validate: async (value) => {
1880
+ const result = await z4.safeParseAsync(zodSchema2, value);
1881
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1882
+ }
1883
+ }
1884
+ );
1885
+ }
1886
+ function isZod4Schema(zodSchema2) {
1887
+ return "_zod" in zodSchema2;
1888
+ }
1889
+ function zodSchema(zodSchema2, options) {
1890
+ if (isZod4Schema(zodSchema2)) {
1891
+ return zod4Schema(zodSchema2, options);
1892
+ } else {
1893
+ return zod3Schema(zodSchema2, options);
1894
+ }
1895
+ }
602
1896
  async function validateTypes({
603
1897
  value,
604
1898
  schema
@@ -613,12 +1907,12 @@ async function safeValidateTypes({
613
1907
  value,
614
1908
  schema
615
1909
  }) {
616
- const validator2 = asValidator(schema);
1910
+ const actualSchema = asSchema(schema);
617
1911
  try {
618
- if (validator2.validate == null) {
1912
+ if (actualSchema.validate == null) {
619
1913
  return { success: true, value, rawValue: value };
620
1914
  }
621
- const result = await validator2.validate(value);
1915
+ const result = await actualSchema.validate(value);
622
1916
  if (result.success) {
623
1917
  return { success: true, value: result.value, rawValue: value };
624
1918
  }
@@ -701,7 +1995,7 @@ var postJsonToApi = async ({
701
1995
  failedResponseHandler,
702
1996
  successfulResponseHandler,
703
1997
  abortSignal,
704
- fetch
1998
+ fetch: fetch2
705
1999
  }) => postToApi({
706
2000
  url,
707
2001
  headers: __spreadValues({
@@ -714,7 +2008,7 @@ var postJsonToApi = async ({
714
2008
  failedResponseHandler,
715
2009
  successfulResponseHandler,
716
2010
  abortSignal,
717
- fetch
2011
+ fetch: fetch2
718
2012
  });
719
2013
  var postToApi = async ({
720
2014
  url,
@@ -723,12 +2017,16 @@ var postToApi = async ({
723
2017
  successfulResponseHandler,
724
2018
  failedResponseHandler,
725
2019
  abortSignal,
726
- fetch = getOriginalFetch2()
2020
+ fetch: fetch2 = getOriginalFetch2()
727
2021
  }) => {
728
2022
  try {
729
- const response = await fetch(url, {
2023
+ const response = await fetch2(url, {
730
2024
  method: "POST",
731
- headers: removeUndefinedEntries(headers),
2025
+ headers: withUserAgentSuffix(
2026
+ headers,
2027
+ `ai-sdk/provider-utils/${VERSION}`,
2028
+ getRuntimeEnvironmentUserAgent()
2029
+ ),
732
2030
  body: body.content,
733
2031
  signal: abortSignal
734
2032
  });
@@ -872,15 +2170,6 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
872
2170
  rawValue: parsedResult.rawValue
873
2171
  };
874
2172
  };
875
- var schemaSymbol = Symbol.for("vercel.ai.schema");
876
- var { btoa, atob } = globalThis;
877
- function convertUint8ArrayToBase64(array) {
878
- let latin1string = "";
879
- for (let i = 0; i < array.length; i++) {
880
- latin1string += String.fromCodePoint(array[i]);
881
- }
882
- return btoa(latin1string);
883
- }
884
2173
  function withoutTrailingSlash(url) {
885
2174
  return url == null ? void 0 : url.replace(/\/$/, "");
886
2175
  }
@@ -961,10 +2250,10 @@ function getFileUrl({
961
2250
  part,
962
2251
  defaultMediaType
963
2252
  }) {
964
- var _a15, _b;
2253
+ var _a16, _b16;
965
2254
  if (part.data instanceof Uint8Array) {
966
2255
  const base64 = convertUint8ArrayToBase64(part.data);
967
- return `data:${(_a15 = part.mediaType) != null ? _a15 : defaultMediaType};base64,${base64}`;
2256
+ return `data:${(_a16 = part.mediaType) != null ? _a16 : defaultMediaType};base64,${base64}`;
968
2257
  }
969
2258
  const stringUrl = part.data.toString();
970
2259
  if (isUrl({
@@ -973,12 +2262,12 @@ function getFileUrl({
973
2262
  })) {
974
2263
  return stringUrl;
975
2264
  }
976
- return stringUrl.startsWith("data:") ? stringUrl : `data:${(_b = part.mediaType) != null ? _b : defaultMediaType};base64,${stringUrl}`;
2265
+ return stringUrl.startsWith("data:") ? stringUrl : `data:${(_b16 = part.mediaType) != null ? _b16 : defaultMediaType};base64,${stringUrl}`;
977
2266
  }
978
2267
  function getMediaType(dataUrl, defaultMediaType) {
979
- var _a15;
2268
+ var _a16;
980
2269
  const match = dataUrl.match(/^data:([^;]+)/);
981
- return match ? (_a15 = match[1]) != null ? _a15 : defaultMediaType : defaultMediaType;
2270
+ return match ? (_a16 = match[1]) != null ? _a16 : defaultMediaType : defaultMediaType;
982
2271
  }
983
2272
  function getBase64FromDataUrl(dataUrl) {
984
2273
  const match = dataUrl.match(/^data:[^;]*;base64,(.+)$/);
@@ -986,14 +2275,14 @@ function getBase64FromDataUrl(dataUrl) {
986
2275
  }
987
2276
 
988
2277
  // src/chat/convert-to-llmgateway-chat-messages.ts
989
- function getCacheControl(providerMetadata) {
990
- var _a15, _b, _c;
991
- const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
992
- const llmgateway2 = providerMetadata == null ? void 0 : providerMetadata.llmgateway;
993
- return (_c = (_b = (_a15 = llmgateway2 == null ? void 0 : llmgateway2.cacheControl) != null ? _a15 : llmgateway2 == null ? void 0 : llmgateway2.cache_control) != null ? _b : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
2278
+ function getCacheControl(providerOptions) {
2279
+ var _a16, _b16, _c;
2280
+ const anthropic = providerOptions == null ? void 0 : providerOptions.anthropic;
2281
+ const llmgateway2 = providerOptions == null ? void 0 : providerOptions.llmgateway;
2282
+ return (_c = (_b16 = (_a16 = llmgateway2 == null ? void 0 : llmgateway2.cacheControl) != null ? _a16 : llmgateway2 == null ? void 0 : llmgateway2.cache_control) != null ? _b16 : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
994
2283
  }
995
2284
  function convertToLLMGatewayChatMessages(prompt) {
996
- var _a15, _b, _c;
2285
+ var _a16, _b16, _c;
997
2286
  const messages = [];
998
2287
  for (const { role, content, providerOptions } of prompt) {
999
2288
  switch (role) {
@@ -1006,8 +2295,8 @@ function convertToLLMGatewayChatMessages(prompt) {
1006
2295
  break;
1007
2296
  }
1008
2297
  case "user": {
1009
- if (content.length === 1 && ((_a15 = content[0]) == null ? void 0 : _a15.type) === "text") {
1010
- const cacheControl = (_b = getCacheControl(providerOptions)) != null ? _b : getCacheControl(content[0].providerOptions);
2298
+ if (content.length === 1 && ((_a16 = content[0]) == null ? void 0 : _a16.type) === "text") {
2299
+ const cacheControl = (_b16 = getCacheControl(providerOptions)) != null ? _b16 : getCacheControl(content[0].providerOptions);
1011
2300
  const contentWithCacheControl = cacheControl ? [
1012
2301
  {
1013
2302
  type: "text",
@@ -1024,8 +2313,8 @@ function convertToLLMGatewayChatMessages(prompt) {
1024
2313
  const messageCacheControl = getCacheControl(providerOptions);
1025
2314
  const contentParts = content.map(
1026
2315
  (part) => {
1027
- var _a16, _b2, _c2, _d, _e, _f;
1028
- const cacheControl = (_a16 = getCacheControl(part.providerOptions)) != null ? _a16 : messageCacheControl;
2316
+ var _a17, _b17, _c2, _d, _e, _f;
2317
+ const cacheControl = (_a17 = getCacheControl(part.providerOptions)) != null ? _a17 : messageCacheControl;
1029
2318
  switch (part.type) {
1030
2319
  case "text":
1031
2320
  return {
@@ -1035,7 +2324,7 @@ function convertToLLMGatewayChatMessages(prompt) {
1035
2324
  cache_control: cacheControl
1036
2325
  };
1037
2326
  case "file": {
1038
- if ((_b2 = part.mediaType) == null ? void 0 : _b2.startsWith("image/")) {
2327
+ if ((_b17 = part.mediaType) == null ? void 0 : _b17.startsWith("image/")) {
1039
2328
  const url = getFileUrl({
1040
2329
  part,
1041
2330
  defaultMediaType: "image/jpeg"
@@ -1134,7 +2423,7 @@ function convertToLLMGatewayChatMessages(prompt) {
1134
2423
  role: "assistant",
1135
2424
  content: text,
1136
2425
  tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
1137
- reasoning: reasoning || void 0,
2426
+ reasoningText: reasoning || void 0,
1138
2427
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
1139
2428
  cache_control: getCacheControl(providerOptions)
1140
2429
  });
@@ -1239,6 +2528,7 @@ var LLMGatewayNonStreamChatCompletionResponseSchema = LLMGatewayChatCompletionBa
1239
2528
  role: z6.literal("assistant"),
1240
2529
  content: z6.string().nullable().optional(),
1241
2530
  reasoning: z6.string().nullable().optional(),
2531
+ reasoningText: z6.string().nullable().optional(),
1242
2532
  reasoning_details: ReasoningDetailArraySchema.nullish(),
1243
2533
  images: ImageResponseArraySchema.nullish(),
1244
2534
  tool_calls: z6.array(
@@ -1279,6 +2569,7 @@ var LLMGatewayStreamChatCompletionChunkSchema = z6.union([
1279
2569
  role: z6.enum(["assistant"]).optional(),
1280
2570
  content: z6.string().nullish(),
1281
2571
  reasoning: z6.string().nullish().optional(),
2572
+ reasoningText: z6.string().nullish().optional(),
1282
2573
  reasoning_details: ReasoningDetailArraySchema.nullish(),
1283
2574
  images: ImageResponseArraySchema.nullish(),
1284
2575
  tool_calls: z6.array(
@@ -1371,7 +2662,7 @@ var LLMGatewayChatLanguageModel = class {
1371
2662
  messages: convertToLLMGatewayChatMessages(prompt),
1372
2663
  // LLMGateway specific settings:
1373
2664
  include_reasoning: this.settings.includeReasoning,
1374
- reasoning: this.settings.reasoning,
2665
+ reasoningText: this.settings.reasoningText,
1375
2666
  usage: this.settings.usage
1376
2667
  }, this.config.extraBody), this.settings.extraBody);
1377
2668
  if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
@@ -1398,7 +2689,7 @@ var LLMGatewayChatLanguageModel = class {
1398
2689
  function: {
1399
2690
  name: tool.name,
1400
2691
  description: tool.type,
1401
- parameters: tool.inputSchema
2692
+ inputSchema: tool.inputSchema
1402
2693
  }
1403
2694
  }));
1404
2695
  return __spreadProps(__spreadValues({}, baseArgs), {
@@ -1409,10 +2700,11 @@ var LLMGatewayChatLanguageModel = class {
1409
2700
  return baseArgs;
1410
2701
  }
1411
2702
  async doGenerate(options) {
1412
- var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w;
2703
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
1413
2704
  const providerOptions = options.providerOptions || {};
1414
2705
  const llmgatewayOptions = providerOptions.llmgateway || {};
1415
2706
  const args = __spreadValues(__spreadValues({}, this.getArgs(options)), llmgatewayOptions);
2707
+ const includeUsageAccounting = ((_a16 = args.usage) == null ? void 0 : _a16.include) === true;
1416
2708
  const { value: response, responseHeaders } = await postJsonToApi({
1417
2709
  url: this.config.url({
1418
2710
  path: "/chat/completions",
@@ -1432,11 +2724,11 @@ var LLMGatewayChatLanguageModel = class {
1432
2724
  throw new Error("No choice in response");
1433
2725
  }
1434
2726
  const usageInfo = response.usage ? {
1435
- inputTokens: (_a15 = response.usage.prompt_tokens) != null ? _a15 : 0,
1436
- outputTokens: (_b = response.usage.completion_tokens) != null ? _b : 0,
1437
- totalTokens: ((_c = response.usage.prompt_tokens) != null ? _c : 0) + ((_d = response.usage.completion_tokens) != null ? _d : 0),
1438
- reasoningTokens: (_f = (_e = response.usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0,
1439
- cachedInputTokens: (_h = (_g = response.usage.prompt_tokens_details) == null ? void 0 : _g.cached_tokens) != null ? _h : 0
2727
+ inputTokens: (_b16 = response.usage.prompt_tokens) != null ? _b16 : 0,
2728
+ outputTokens: (_c = response.usage.completion_tokens) != null ? _c : 0,
2729
+ totalTokens: ((_d = response.usage.prompt_tokens) != null ? _d : 0) + ((_e = response.usage.completion_tokens) != null ? _e : 0),
2730
+ reasoningTokens: (_g = (_f = response.usage.completion_tokens_details) == null ? void 0 : _f.reasoning_tokens) != null ? _g : 0,
2731
+ cachedInputTokens: (_i = (_h = response.usage.prompt_tokens_details) == null ? void 0 : _h.cached_tokens) != null ? _i : 0
1440
2732
  } : {
1441
2733
  inputTokens: 0,
1442
2734
  outputTokens: 0,
@@ -1444,7 +2736,7 @@ var LLMGatewayChatLanguageModel = class {
1444
2736
  reasoningTokens: 0,
1445
2737
  cachedInputTokens: 0
1446
2738
  };
1447
- const reasoningDetails = (_i = choice.message.reasoning_details) != null ? _i : [];
2739
+ const reasoningDetails = (_j = choice.message.reasoning_details) != null ? _j : [];
1448
2740
  const reasoning = reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
1449
2741
  switch (detail.type) {
1450
2742
  case "reasoning.text" /* Text */: {
@@ -1482,10 +2774,10 @@ var LLMGatewayChatLanguageModel = class {
1482
2774
  return null;
1483
2775
  }).filter(
1484
2776
  (p) => p !== null
1485
- ) : choice.message.reasoning ? [
2777
+ ) : choice.message.reasoningText ? [
1486
2778
  {
1487
2779
  type: "reasoning",
1488
- text: choice.message.reasoning
2780
+ text: choice.message.reasoningText
1489
2781
  }
1490
2782
  ] : [];
1491
2783
  const content = [];
@@ -1500,7 +2792,7 @@ var LLMGatewayChatLanguageModel = class {
1500
2792
  for (const toolCall of choice.message.tool_calls) {
1501
2793
  content.push({
1502
2794
  type: "tool-call",
1503
- toolCallId: (_j = toolCall.id) != null ? _j : generateId(),
2795
+ toolCallId: (_k = toolCall.id) != null ? _k : generateId(),
1504
2796
  toolName: toolCall.function.name,
1505
2797
  input: toolCall.function.arguments
1506
2798
  });
@@ -1525,7 +2817,7 @@ var LLMGatewayChatLanguageModel = class {
1525
2817
  url: annotation.url_citation.url,
1526
2818
  title: annotation.url_citation.title,
1527
2819
  providerMetadata: {
1528
- openrouter: {
2820
+ llmgateway: {
1529
2821
  content: annotation.url_citation.content || ""
1530
2822
  }
1531
2823
  }
@@ -1538,25 +2830,25 @@ var LLMGatewayChatLanguageModel = class {
1538
2830
  finishReason: mapLLMGatewayFinishReason(choice.finish_reason),
1539
2831
  usage: usageInfo,
1540
2832
  warnings: [],
1541
- providerMetadata: {
2833
+ providerMetadata: includeUsageAccounting ? {
1542
2834
  llmgateway: {
1543
2835
  usage: {
1544
- promptTokens: (_k = usageInfo.inputTokens) != null ? _k : 0,
1545
- completionTokens: (_l = usageInfo.outputTokens) != null ? _l : 0,
1546
- totalTokens: (_m = usageInfo.totalTokens) != null ? _m : 0,
1547
- cost: (_n = response.usage) == null ? void 0 : _n.cost,
2836
+ promptTokens: (_l = usageInfo.inputTokens) != null ? _l : 0,
2837
+ completionTokens: (_m = usageInfo.outputTokens) != null ? _m : 0,
2838
+ totalTokens: (_n = usageInfo.totalTokens) != null ? _n : 0,
2839
+ cost: (_o = response.usage) == null ? void 0 : _o.cost,
1548
2840
  promptTokensDetails: {
1549
- cachedTokens: (_q = (_p = (_o = response.usage) == null ? void 0 : _o.prompt_tokens_details) == null ? void 0 : _p.cached_tokens) != null ? _q : 0
2841
+ cachedTokens: (_r = (_q = (_p = response.usage) == null ? void 0 : _p.prompt_tokens_details) == null ? void 0 : _q.cached_tokens) != null ? _r : 0
1550
2842
  },
1551
2843
  completionTokensDetails: {
1552
- reasoningTokens: (_t = (_s = (_r = response.usage) == null ? void 0 : _r.completion_tokens_details) == null ? void 0 : _s.reasoning_tokens) != null ? _t : 0
2844
+ reasoningTokens: (_u = (_t = (_s = response.usage) == null ? void 0 : _s.completion_tokens_details) == null ? void 0 : _t.reasoning_tokens) != null ? _u : 0
1553
2845
  },
1554
2846
  costDetails: {
1555
- upstreamInferenceCost: (_w = (_v = (_u = response.usage) == null ? void 0 : _u.cost_details) == null ? void 0 : _v.upstream_inference_cost) != null ? _w : 0
2847
+ upstreamInferenceCost: (_x = (_w = (_v = response.usage) == null ? void 0 : _v.cost_details) == null ? void 0 : _w.upstream_inference_cost) != null ? _x : 0
1556
2848
  }
1557
2849
  }
1558
2850
  }
1559
- },
2851
+ } : void 0,
1560
2852
  request: { body: args },
1561
2853
  response: {
1562
2854
  id: response.id,
@@ -1566,7 +2858,6 @@ var LLMGatewayChatLanguageModel = class {
1566
2858
  };
1567
2859
  }
1568
2860
  async doStream(options) {
1569
- var _a15;
1570
2861
  const providerOptions = options.providerOptions || {};
1571
2862
  const llmgatewayOptions = providerOptions.llmgateway || {};
1572
2863
  const args = __spreadValues(__spreadValues({}, this.getArgs(options)), llmgatewayOptions);
@@ -1579,9 +2870,7 @@ var LLMGatewayChatLanguageModel = class {
1579
2870
  body: __spreadProps(__spreadValues({}, args), {
1580
2871
  stream: true,
1581
2872
  // only include stream_options when in strict compatibility mode:
1582
- stream_options: this.config.compatibility === "strict" ? __spreadValues({
1583
- include_usage: true
1584
- }, ((_a15 = this.settings.usage) == null ? void 0 : _a15.include) ? { include_usage: true } : {}) : void 0
2873
+ stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
1585
2874
  }),
1586
2875
  failedResponseHandler: llmgatewayFailedResponseHandler,
1587
2876
  successfulResponseHandler: createEventSourceResponseHandler(
@@ -1609,7 +2898,7 @@ var LLMGatewayChatLanguageModel = class {
1609
2898
  stream: response.pipeThrough(
1610
2899
  new TransformStream({
1611
2900
  transform(chunk, controller) {
1612
- var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
2901
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
1613
2902
  if (!chunk.success) {
1614
2903
  finishReason = "error";
1615
2904
  controller.enqueue({ type: "error", error: chunk.error });
@@ -1648,7 +2937,7 @@ var LLMGatewayChatLanguageModel = class {
1648
2937
  }
1649
2938
  llmgatewayUsage.completionTokens = value.usage.completion_tokens;
1650
2939
  if (value.usage.completion_tokens_details) {
1651
- const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
2940
+ const reasoningTokens = (_b16 = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b16 : 0;
1652
2941
  usage.reasoningTokens = reasoningTokens;
1653
2942
  llmgatewayUsage.completionTokensDetails = {
1654
2943
  reasoningTokens
@@ -1707,8 +2996,10 @@ var LLMGatewayChatLanguageModel = class {
1707
2996
  }
1708
2997
  }
1709
2998
  }
1710
- } else if (delta.reasoning != null) {
1711
- emitReasoningChunk(delta.reasoning);
2999
+ } else if (delta.reasoningText != null || "reasoning" in delta && typeof delta.reasoning === "string") {
3000
+ emitReasoningChunk(
3001
+ (_d = (_c = delta.reasoningText) != null ? _c : "reasoning" in delta && typeof delta.reasoning === "string" ? delta.reasoning : void 0) != null ? _d : ""
3002
+ );
1712
3003
  }
1713
3004
  if (delta.content != null) {
1714
3005
  if (!textStarted) {
@@ -1727,7 +3018,7 @@ var LLMGatewayChatLanguageModel = class {
1727
3018
  }
1728
3019
  if (delta.tool_calls != null) {
1729
3020
  for (const toolCallDelta of delta.tool_calls) {
1730
- const index = (_c = toolCallDelta.index) != null ? _c : toolCalls.length - 1;
3021
+ const index = (_e = toolCallDelta.index) != null ? _e : toolCalls.length - 1;
1731
3022
  if (toolCalls[index] == null) {
1732
3023
  if (toolCallDelta.type !== "function") {
1733
3024
  throw new InvalidResponseDataError({
@@ -1741,7 +3032,7 @@ var LLMGatewayChatLanguageModel = class {
1741
3032
  message: `Expected 'id' to be a string.`
1742
3033
  });
1743
3034
  }
1744
- if (((_d = toolCallDelta.function) == null ? void 0 : _d.name) == null) {
3035
+ if (((_f = toolCallDelta.function) == null ? void 0 : _f.name) == null) {
1745
3036
  throw new InvalidResponseDataError({
1746
3037
  data: toolCallDelta,
1747
3038
  message: `Expected 'function.name' to be a string.`
@@ -1752,7 +3043,7 @@ var LLMGatewayChatLanguageModel = class {
1752
3043
  type: "function",
1753
3044
  function: {
1754
3045
  name: toolCallDelta.function.name,
1755
- arguments: (_e = toolCallDelta.function.arguments) != null ? _e : ""
3046
+ arguments: (_g = toolCallDelta.function.arguments) != null ? _g : ""
1756
3047
  },
1757
3048
  inputStarted: false,
1758
3049
  sent: false
@@ -1761,7 +3052,7 @@ var LLMGatewayChatLanguageModel = class {
1761
3052
  if (toolCall2 == null) {
1762
3053
  throw new Error("Tool call is missing");
1763
3054
  }
1764
- if (((_f = toolCall2.function) == null ? void 0 : _f.name) != null && ((_g = toolCall2.function) == null ? void 0 : _g.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
3055
+ if (((_h = toolCall2.function) == null ? void 0 : _h.name) != null && ((_i = toolCall2.function) == null ? void 0 : _i.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
1765
3056
  toolCall2.inputStarted = true;
1766
3057
  controller.enqueue({
1767
3058
  type: "tool-input-start",
@@ -1799,18 +3090,18 @@ var LLMGatewayChatLanguageModel = class {
1799
3090
  toolName: toolCall.function.name
1800
3091
  });
1801
3092
  }
1802
- if (((_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null) {
1803
- toolCall.function.arguments += (_j = (_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null ? _j : "";
3093
+ if (((_j = toolCallDelta.function) == null ? void 0 : _j.arguments) != null) {
3094
+ toolCall.function.arguments += (_l = (_k = toolCallDelta.function) == null ? void 0 : _k.arguments) != null ? _l : "";
1804
3095
  }
1805
3096
  controller.enqueue({
1806
3097
  type: "tool-input-delta",
1807
3098
  id: toolCall.id,
1808
- delta: (_k = toolCallDelta.function.arguments) != null ? _k : ""
3099
+ delta: (_m = toolCallDelta.function.arguments) != null ? _m : ""
1809
3100
  });
1810
- if (((_l = toolCall.function) == null ? void 0 : _l.name) != null && ((_m = toolCall.function) == null ? void 0 : _m.arguments) != null && isParsableJson(toolCall.function.arguments)) {
3101
+ if (((_n = toolCall.function) == null ? void 0 : _n.name) != null && ((_o = toolCall.function) == null ? void 0 : _o.arguments) != null && isParsableJson(toolCall.function.arguments)) {
1811
3102
  controller.enqueue({
1812
3103
  type: "tool-call",
1813
- toolCallId: (_n = toolCall.id) != null ? _n : generateId(),
3104
+ toolCallId: (_p = toolCall.id) != null ? _p : generateId(),
1814
3105
  toolName: toolCall.function.name,
1815
3106
  input: toolCall.function.arguments
1816
3107
  });
@@ -1988,7 +3279,7 @@ var LLMGatewayCompletionChunkSchema = z7.union([
1988
3279
  choices: z7.array(
1989
3280
  z7.object({
1990
3281
  text: z7.string(),
1991
- reasoning: z7.string().nullish().optional(),
3282
+ reasoningText: z7.string().nullish().optional(),
1992
3283
  reasoning_details: ReasoningDetailArraySchema.nullish(),
1993
3284
  finish_reason: z7.string().nullish(),
1994
3285
  index: z7.number().nullish(),
@@ -2084,11 +3375,11 @@ var LLMGatewayCompletionLanguageModel = class {
2084
3375
  prompt: completionPrompt,
2085
3376
  // LLMGateway specific settings:
2086
3377
  include_reasoning: this.settings.includeReasoning,
2087
- reasoning: this.settings.reasoning
3378
+ reasoningText: this.settings.reasoningText
2088
3379
  }, this.config.extraBody), this.settings.extraBody);
2089
3380
  }
2090
3381
  async doGenerate(options) {
2091
- var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
3382
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
2092
3383
  const providerOptions = options.providerOptions || {};
2093
3384
  const llmgatewayOptions = providerOptions.llmgateway || {};
2094
3385
  const args = __spreadValues(__spreadValues({}, this.getArgs(options)), llmgatewayOptions);
@@ -2117,12 +3408,12 @@ var LLMGatewayCompletionLanguageModel = class {
2117
3408
  content: [
2118
3409
  {
2119
3410
  type: "text",
2120
- text: (_a15 = choice.text) != null ? _a15 : ""
3411
+ text: (_a16 = choice.text) != null ? _a16 : ""
2121
3412
  }
2122
3413
  ],
2123
3414
  finishReason: mapLLMGatewayFinishReason(choice.finish_reason),
2124
3415
  usage: {
2125
- inputTokens: (_c = (_b = response.usage) == null ? void 0 : _b.prompt_tokens) != null ? _c : 0,
3416
+ inputTokens: (_c = (_b16 = response.usage) == null ? void 0 : _b16.prompt_tokens) != null ? _c : 0,
2126
3417
  outputTokens: (_e = (_d = response.usage) == null ? void 0 : _d.completion_tokens) != null ? _e : 0,
2127
3418
  totalTokens: ((_g = (_f = response.usage) == null ? void 0 : _f.prompt_tokens) != null ? _g : 0) + ((_i = (_h = response.usage) == null ? void 0 : _h.completion_tokens) != null ? _i : 0),
2128
3419
  reasoningTokens: (_l = (_k = (_j = response.usage) == null ? void 0 : _j.completion_tokens_details) == null ? void 0 : _k.reasoning_tokens) != null ? _l : 0,
@@ -2169,7 +3460,7 @@ var LLMGatewayCompletionLanguageModel = class {
2169
3460
  stream: response.pipeThrough(
2170
3461
  new TransformStream({
2171
3462
  transform(chunk, controller) {
2172
- var _a15, _b;
3463
+ var _a16, _b16;
2173
3464
  if (!chunk.success) {
2174
3465
  finishReason = "error";
2175
3466
  controller.enqueue({ type: "error", error: chunk.error });
@@ -2187,7 +3478,7 @@ var LLMGatewayCompletionLanguageModel = class {
2187
3478
  usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
2188
3479
  llmgatewayUsage.promptTokens = value.usage.prompt_tokens;
2189
3480
  if (value.usage.prompt_tokens_details) {
2190
- const cachedInputTokens = (_a15 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a15 : 0;
3481
+ const cachedInputTokens = (_a16 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a16 : 0;
2191
3482
  usage.cachedInputTokens = cachedInputTokens;
2192
3483
  llmgatewayUsage.promptTokensDetails = {
2193
3484
  cachedTokens: cachedInputTokens
@@ -2195,7 +3486,7 @@ var LLMGatewayCompletionLanguageModel = class {
2195
3486
  }
2196
3487
  llmgatewayUsage.completionTokens = value.usage.completion_tokens;
2197
3488
  if (value.usage.completion_tokens_details) {
2198
- const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
3489
+ const reasoningTokens = (_b16 = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b16 : 0;
2199
3490
  usage.reasoningTokens = reasoningTokens;
2200
3491
  llmgatewayUsage.completionTokensDetails = {
2201
3492
  reasoningTokens
@@ -2243,8 +3534,8 @@ var LLMGateway = class {
2243
3534
  * Creates a new LLMGateway provider instance.
2244
3535
  */
2245
3536
  constructor(options = {}) {
2246
- var _a15, _b;
2247
- this.baseURL = (_b = withoutTrailingSlash((_a15 = options.baseURL) != null ? _a15 : options.baseUrl)) != null ? _b : "https://api.llmgateway.io/v1";
3537
+ var _a16, _b16;
3538
+ this.baseURL = (_b16 = withoutTrailingSlash((_a16 = options.baseURL) != null ? _a16 : options.baseUrl)) != null ? _b16 : "https://api.llmgateway.io/v1";
2248
3539
  this.apiKey = options.apiKey;
2249
3540
  this.headers = options.headers;
2250
3541
  }
@@ -2280,8 +3571,8 @@ var LLMGateway = class {
2280
3571
 
2281
3572
  // src/provider.ts
2282
3573
  function createLLMGateway(options = {}) {
2283
- var _a15, _b, _c, _d;
2284
- const baseURL = (_c = (_b = withoutTrailingSlash((_a15 = options.baseURL) != null ? _a15 : options.baseUrl)) != null ? _b : process.env.LLM_GATEWAY_API_BASE) != null ? _c : "https://api.llmgateway.io/v1";
3574
+ var _a16, _b16, _c, _d;
3575
+ const baseURL = (_c = (_b16 = withoutTrailingSlash((_a16 = options.baseURL) != null ? _a16 : options.baseUrl)) != null ? _b16 : process.env.LLM_GATEWAY_API_BASE) != null ? _c : "https://api.llmgateway.io/v1";
2285
3576
  const compatibility = (_d = options.compatibility) != null ? _d : "compatible";
2286
3577
  const getHeaders = () => __spreadValues({
2287
3578
  Authorization: `Bearer ${loadApiKey({