@openrouter/ai-sdk-provider 1.5.3 → 2.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.
@@ -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/node_modules/@ai-sdk/provider/dist/index.mjs
33
+ // node_modules/.pnpm/@ai-sdk+provider@3.0.0/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,22 +205,42 @@ 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
- _a8 = symbol8;
212
+ var _b8;
213
+ var LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {
214
+ // used in isInstance
215
+ constructor({ message }) {
216
+ super({ name: name7, message });
217
+ this[_a8] = true;
218
+ }
219
+ static isInstance(error) {
220
+ return AISDKError.hasMarker(error, marker8);
221
+ }
222
+ };
202
223
  var name8 = "AI_LoadSettingError";
203
224
  var marker9 = `vercel.ai.error.${name8}`;
204
225
  var symbol9 = Symbol.for(marker9);
205
226
  var _a9;
206
- _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
+ };
207
238
  var name9 = "AI_NoContentGeneratedError";
208
239
  var marker10 = `vercel.ai.error.${name9}`;
209
240
  var symbol10 = Symbol.for(marker10);
210
241
  var _a10;
211
- var NoContentGeneratedError = class extends AISDKError {
242
+ var _b10;
243
+ var NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {
212
244
  // used in isInstance
213
245
  constructor({
214
246
  message = "No content generated."
@@ -220,22 +252,54 @@ var NoContentGeneratedError = class extends AISDKError {
220
252
  return AISDKError.hasMarker(error, marker10);
221
253
  }
222
254
  };
223
- _a10 = symbol10;
224
255
  var name10 = "AI_NoSuchModelError";
225
256
  var marker11 = `vercel.ai.error.${name10}`;
226
257
  var symbol11 = Symbol.for(marker11);
227
258
  var _a11;
228
- _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
+ };
229
276
  var name11 = "AI_TooManyEmbeddingValuesForCallError";
230
277
  var marker12 = `vercel.ai.error.${name11}`;
231
278
  var symbol12 = Symbol.for(marker12);
232
279
  var _a12;
233
- _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
+ };
234
297
  var name12 = "AI_TypeValidationError";
235
298
  var marker13 = `vercel.ai.error.${name12}`;
236
299
  var symbol13 = Symbol.for(marker13);
237
300
  var _a13;
238
- var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
301
+ var _b13;
302
+ var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
239
303
  constructor({ value, cause }) {
240
304
  super({
241
305
  name: name12,
@@ -263,16 +327,15 @@ Error message: ${getErrorMessage(cause)}`,
263
327
  value,
264
328
  cause
265
329
  }) {
266
- 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 });
267
331
  }
268
332
  };
269
- _a13 = symbol13;
270
- var TypeValidationError = _TypeValidationError;
271
333
  var name13 = "AI_UnsupportedFunctionalityError";
272
334
  var marker14 = `vercel.ai.error.${name13}`;
273
335
  var symbol14 = Symbol.for(marker14);
274
336
  var _a14;
275
- var UnsupportedFunctionalityError = class extends AISDKError {
337
+ var _b14;
338
+ var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {
276
339
  constructor({
277
340
  functionality,
278
341
  message = `'${functionality}' functionality not supported.`
@@ -285,9 +348,16 @@ var UnsupportedFunctionalityError = class extends AISDKError {
285
348
  return AISDKError.hasMarker(error, marker14);
286
349
  }
287
350
  };
288
- _a14 = symbol14;
289
351
 
290
- // 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.1_zod@4.3.5/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
291
361
  var ParseError = class extends Error {
292
362
  constructor(message, options) {
293
363
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
@@ -378,7 +448,7 @@ function splitLines(chunk) {
378
448
  const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
379
449
  `, searchIndex);
380
450
  let lineEnd = -1;
381
- 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) {
382
452
  incompleteLine = chunk.slice(searchIndex);
383
453
  break;
384
454
  } else {
@@ -390,7 +460,7 @@ function splitLines(chunk) {
390
460
  return [lines, incompleteLine];
391
461
  }
392
462
 
393
- // 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
394
464
  var EventSourceParserStream = class extends TransformStream {
395
465
  constructor({ onError, onRetry, onComment } = {}) {
396
466
  let parser;
@@ -414,25 +484,7 @@ var EventSourceParserStream = class extends TransformStream {
414
484
  }
415
485
  };
416
486
 
417
- // node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
418
- import * as z4 from "zod/v4";
419
-
420
- // node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Options.js
421
- var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
422
-
423
- // node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/selectParser.js
424
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod";
425
-
426
- // node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
427
- import { ZodFirstPartyTypeKind } from "zod";
428
-
429
- // node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
430
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2 } from "zod";
431
-
432
- // node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
433
- var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
434
-
435
- // node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
487
+ // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.1_zod@4.3.5/node_modules/@ai-sdk/provider-utils/dist/index.mjs
436
488
  function combineHeaders(...headers) {
437
489
  return headers.reduce(
438
490
  (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
@@ -442,6 +494,37 @@ function combineHeaders(...headers) {
442
494
  function extractResponseHeaders(response) {
443
495
  return Object.fromEntries([...response.headers]);
444
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
+ };
445
528
  var createIdGenerator = ({
446
529
  prefix,
447
530
  size = 16,
@@ -496,11 +579,53 @@ function handleFetchError({
496
579
  }
497
580
  return error;
498
581
  }
499
- function removeUndefinedEntries(record) {
500
- return Object.fromEntries(
501
- 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(" ")
502
625
  );
626
+ return Object.fromEntries(normalizedHeaders.entries());
503
627
  }
628
+ var VERSION = true ? "4.0.1" : "0.0.0-test";
504
629
  var suspectProtoRx = /"__proto__"\s*:/;
505
630
  var suspectConstructorRx = /"constructor"\s*:/;
506
631
  function _parse(text) {
@@ -537,34 +662,1195 @@ function filter(obj) {
537
662
  }
538
663
  function secureJsonParse(text) {
539
664
  const { stackTraceLimit } = Error;
540
- Error.stackTraceLimit = 0;
665
+ try {
666
+ Error.stackTraceLimit = 0;
667
+ } catch (e) {
668
+ return _parse(text);
669
+ }
541
670
  try {
542
671
  return _parse(text);
543
672
  } finally {
544
673
  Error.stackTraceLimit = stackTraceLimit;
545
674
  }
546
675
  }
547
- var validatorSymbol = Symbol.for("vercel.ai.validator");
548
- function validator(validate) {
549
- return { [validatorSymbol]: true, validate };
676
+ function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
677
+ if (jsonSchema2.type === "object") {
678
+ jsonSchema2.additionalProperties = false;
679
+ const properties = jsonSchema2.properties;
680
+ if (properties != null) {
681
+ for (const property in properties) {
682
+ properties[property] = addAdditionalPropertiesToJsonSchema(
683
+ properties[property]
684
+ );
685
+ }
686
+ }
687
+ }
688
+ if (jsonSchema2.type === "array" && jsonSchema2.items != null) {
689
+ if (Array.isArray(jsonSchema2.items)) {
690
+ jsonSchema2.items = jsonSchema2.items.map(
691
+ (item) => addAdditionalPropertiesToJsonSchema(item)
692
+ );
693
+ } else {
694
+ jsonSchema2.items = addAdditionalPropertiesToJsonSchema(
695
+ jsonSchema2.items
696
+ );
697
+ }
698
+ }
699
+ return jsonSchema2;
550
700
  }
551
- function isValidator(value) {
552
- return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
701
+ var ignoreOverride = Symbol(
702
+ "Let zodToJsonSchema decide on which parser to use"
703
+ );
704
+ var defaultOptions = {
705
+ name: void 0,
706
+ $refStrategy: "root",
707
+ basePath: ["#"],
708
+ effectStrategy: "input",
709
+ pipeStrategy: "all",
710
+ dateStrategy: "format:date-time",
711
+ mapStrategy: "entries",
712
+ removeAdditionalStrategy: "passthrough",
713
+ allowedAdditionalProperties: true,
714
+ rejectedAdditionalProperties: false,
715
+ definitionPath: "definitions",
716
+ strictUnions: false,
717
+ definitions: {},
718
+ errorMessages: false,
719
+ patternStrategy: "escape",
720
+ applyRegexFlags: false,
721
+ emailStrategy: "format:email",
722
+ base64Strategy: "contentEncoding:base64",
723
+ nameStrategy: "ref"
724
+ };
725
+ var getDefaultOptions = (options) => typeof options === "string" ? __spreadProps(__spreadValues({}, defaultOptions), {
726
+ name: options
727
+ }) : __spreadValues(__spreadValues({}, defaultOptions), options);
728
+ function parseAnyDef() {
729
+ return {};
553
730
  }
554
- function asValidator(value) {
555
- return isValidator(value) ? value : standardSchemaValidator(value);
731
+ function parseArrayDef(def, refs) {
732
+ var _a22, _b22, _c;
733
+ const res = {
734
+ type: "array"
735
+ };
736
+ 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) {
737
+ res.items = parseDef(def.type._def, __spreadProps(__spreadValues({}, refs), {
738
+ currentPath: [...refs.currentPath, "items"]
739
+ }));
740
+ }
741
+ if (def.minLength) {
742
+ res.minItems = def.minLength.value;
743
+ }
744
+ if (def.maxLength) {
745
+ res.maxItems = def.maxLength.value;
746
+ }
747
+ if (def.exactLength) {
748
+ res.minItems = def.exactLength.value;
749
+ res.maxItems = def.exactLength.value;
750
+ }
751
+ return res;
556
752
  }
557
- function standardSchemaValidator(standardSchema) {
558
- return validator(async (value) => {
559
- const result = await standardSchema["~standard"].validate(value);
560
- return result.issues == null ? { success: true, value: result.value } : {
561
- success: false,
562
- error: new TypeValidationError({
563
- value,
564
- cause: result.issues
565
- })
753
+ function parseBigintDef(def) {
754
+ const res = {
755
+ type: "integer",
756
+ format: "int64"
757
+ };
758
+ if (!def.checks) return res;
759
+ for (const check of def.checks) {
760
+ switch (check.kind) {
761
+ case "min":
762
+ if (check.inclusive) {
763
+ res.minimum = check.value;
764
+ } else {
765
+ res.exclusiveMinimum = check.value;
766
+ }
767
+ break;
768
+ case "max":
769
+ if (check.inclusive) {
770
+ res.maximum = check.value;
771
+ } else {
772
+ res.exclusiveMaximum = check.value;
773
+ }
774
+ break;
775
+ case "multipleOf":
776
+ res.multipleOf = check.value;
777
+ break;
778
+ }
779
+ }
780
+ return res;
781
+ }
782
+ function parseBooleanDef() {
783
+ return { type: "boolean" };
784
+ }
785
+ function parseBrandedDef(_def, refs) {
786
+ return parseDef(_def.type._def, refs);
787
+ }
788
+ var parseCatchDef = (def, refs) => {
789
+ return parseDef(def.innerType._def, refs);
790
+ };
791
+ function parseDateDef(def, refs, overrideDateStrategy) {
792
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
793
+ if (Array.isArray(strategy)) {
794
+ return {
795
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
796
+ };
797
+ }
798
+ switch (strategy) {
799
+ case "string":
800
+ case "format:date-time":
801
+ return {
802
+ type: "string",
803
+ format: "date-time"
804
+ };
805
+ case "format:date":
806
+ return {
807
+ type: "string",
808
+ format: "date"
809
+ };
810
+ case "integer":
811
+ return integerDateParser(def);
812
+ }
813
+ }
814
+ var integerDateParser = (def) => {
815
+ const res = {
816
+ type: "integer",
817
+ format: "unix-time"
818
+ };
819
+ for (const check of def.checks) {
820
+ switch (check.kind) {
821
+ case "min":
822
+ res.minimum = check.value;
823
+ break;
824
+ case "max":
825
+ res.maximum = check.value;
826
+ break;
827
+ }
828
+ }
829
+ return res;
830
+ };
831
+ function parseDefaultDef(_def, refs) {
832
+ return __spreadProps(__spreadValues({}, parseDef(_def.innerType._def, refs)), {
833
+ default: _def.defaultValue()
834
+ });
835
+ }
836
+ function parseEffectsDef(_def, refs) {
837
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
838
+ }
839
+ function parseEnumDef(def) {
840
+ return {
841
+ type: "string",
842
+ enum: Array.from(def.values)
843
+ };
844
+ }
845
+ var isJsonSchema7AllOfType = (type) => {
846
+ if ("type" in type && type.type === "string") return false;
847
+ return "allOf" in type;
848
+ };
849
+ function parseIntersectionDef(def, refs) {
850
+ const allOf = [
851
+ parseDef(def.left._def, __spreadProps(__spreadValues({}, refs), {
852
+ currentPath: [...refs.currentPath, "allOf", "0"]
853
+ })),
854
+ parseDef(def.right._def, __spreadProps(__spreadValues({}, refs), {
855
+ currentPath: [...refs.currentPath, "allOf", "1"]
856
+ }))
857
+ ].filter((x) => !!x);
858
+ const mergedAllOf = [];
859
+ allOf.forEach((schema) => {
860
+ if (isJsonSchema7AllOfType(schema)) {
861
+ mergedAllOf.push(...schema.allOf);
862
+ } else {
863
+ let nestedSchema = schema;
864
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
865
+ const _a16 = schema, { additionalProperties } = _a16, rest = __objRest(_a16, ["additionalProperties"]);
866
+ nestedSchema = rest;
867
+ }
868
+ mergedAllOf.push(nestedSchema);
869
+ }
870
+ });
871
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
872
+ }
873
+ function parseLiteralDef(def) {
874
+ const parsedType = typeof def.value;
875
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
876
+ return {
877
+ type: Array.isArray(def.value) ? "array" : "object"
878
+ };
879
+ }
880
+ return {
881
+ type: parsedType === "bigint" ? "integer" : parsedType,
882
+ const: def.value
883
+ };
884
+ }
885
+ var emojiRegex = void 0;
886
+ var zodPatterns = {
887
+ /**
888
+ * `c` was changed to `[cC]` to replicate /i flag
889
+ */
890
+ cuid: /^[cC][^\s-]{8,}$/,
891
+ cuid2: /^[0-9a-z]+$/,
892
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
893
+ /**
894
+ * `a-z` was added to replicate /i flag
895
+ */
896
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
897
+ /**
898
+ * Constructed a valid Unicode RegExp
899
+ *
900
+ * Lazily instantiate since this type of regex isn't supported
901
+ * in all envs (e.g. React Native).
902
+ *
903
+ * See:
904
+ * https://github.com/colinhacks/zod/issues/2433
905
+ * Fix in Zod:
906
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
907
+ */
908
+ emoji: () => {
909
+ if (emojiRegex === void 0) {
910
+ emojiRegex = RegExp(
911
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
912
+ "u"
913
+ );
914
+ }
915
+ return emojiRegex;
916
+ },
917
+ /**
918
+ * Unused
919
+ */
920
+ 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}$/,
921
+ /**
922
+ * Unused
923
+ */
924
+ 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])$/,
925
+ 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])$/,
926
+ /**
927
+ * Unused
928
+ */
929
+ 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})))$/,
930
+ 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])$/,
931
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
932
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
933
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
934
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
935
+ };
936
+ function parseStringDef(def, refs) {
937
+ const res = {
938
+ type: "string"
939
+ };
940
+ if (def.checks) {
941
+ for (const check of def.checks) {
942
+ switch (check.kind) {
943
+ case "min":
944
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
945
+ break;
946
+ case "max":
947
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
948
+ break;
949
+ case "email":
950
+ switch (refs.emailStrategy) {
951
+ case "format:email":
952
+ addFormat(res, "email", check.message, refs);
953
+ break;
954
+ case "format:idn-email":
955
+ addFormat(res, "idn-email", check.message, refs);
956
+ break;
957
+ case "pattern:zod":
958
+ addPattern(res, zodPatterns.email, check.message, refs);
959
+ break;
960
+ }
961
+ break;
962
+ case "url":
963
+ addFormat(res, "uri", check.message, refs);
964
+ break;
965
+ case "uuid":
966
+ addFormat(res, "uuid", check.message, refs);
967
+ break;
968
+ case "regex":
969
+ addPattern(res, check.regex, check.message, refs);
970
+ break;
971
+ case "cuid":
972
+ addPattern(res, zodPatterns.cuid, check.message, refs);
973
+ break;
974
+ case "cuid2":
975
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
976
+ break;
977
+ case "startsWith":
978
+ addPattern(
979
+ res,
980
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
981
+ check.message,
982
+ refs
983
+ );
984
+ break;
985
+ case "endsWith":
986
+ addPattern(
987
+ res,
988
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
989
+ check.message,
990
+ refs
991
+ );
992
+ break;
993
+ case "datetime":
994
+ addFormat(res, "date-time", check.message, refs);
995
+ break;
996
+ case "date":
997
+ addFormat(res, "date", check.message, refs);
998
+ break;
999
+ case "time":
1000
+ addFormat(res, "time", check.message, refs);
1001
+ break;
1002
+ case "duration":
1003
+ addFormat(res, "duration", check.message, refs);
1004
+ break;
1005
+ case "length":
1006
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1007
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1008
+ break;
1009
+ case "includes": {
1010
+ addPattern(
1011
+ res,
1012
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
1013
+ check.message,
1014
+ refs
1015
+ );
1016
+ break;
1017
+ }
1018
+ case "ip": {
1019
+ if (check.version !== "v6") {
1020
+ addFormat(res, "ipv4", check.message, refs);
1021
+ }
1022
+ if (check.version !== "v4") {
1023
+ addFormat(res, "ipv6", check.message, refs);
1024
+ }
1025
+ break;
1026
+ }
1027
+ case "base64url":
1028
+ addPattern(res, zodPatterns.base64url, check.message, refs);
1029
+ break;
1030
+ case "jwt":
1031
+ addPattern(res, zodPatterns.jwt, check.message, refs);
1032
+ break;
1033
+ case "cidr": {
1034
+ if (check.version !== "v6") {
1035
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1036
+ }
1037
+ if (check.version !== "v4") {
1038
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1039
+ }
1040
+ break;
1041
+ }
1042
+ case "emoji":
1043
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
1044
+ break;
1045
+ case "ulid": {
1046
+ addPattern(res, zodPatterns.ulid, check.message, refs);
1047
+ break;
1048
+ }
1049
+ case "base64": {
1050
+ switch (refs.base64Strategy) {
1051
+ case "format:binary": {
1052
+ addFormat(res, "binary", check.message, refs);
1053
+ break;
1054
+ }
1055
+ case "contentEncoding:base64": {
1056
+ res.contentEncoding = "base64";
1057
+ break;
1058
+ }
1059
+ case "pattern:zod": {
1060
+ addPattern(res, zodPatterns.base64, check.message, refs);
1061
+ break;
1062
+ }
1063
+ }
1064
+ break;
1065
+ }
1066
+ case "nanoid": {
1067
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
1068
+ }
1069
+ case "toLowerCase":
1070
+ case "toUpperCase":
1071
+ case "trim":
1072
+ break;
1073
+ default:
1074
+ /* @__PURE__ */ ((_) => {
1075
+ })(check);
1076
+ }
1077
+ }
1078
+ }
1079
+ return res;
1080
+ }
1081
+ function escapeLiteralCheckValue(literal, refs) {
1082
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1083
+ }
1084
+ var ALPHA_NUMERIC = new Set(
1085
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1086
+ );
1087
+ function escapeNonAlphaNumeric(source) {
1088
+ let result = "";
1089
+ for (let i = 0; i < source.length; i++) {
1090
+ if (!ALPHA_NUMERIC.has(source[i])) {
1091
+ result += "\\";
1092
+ }
1093
+ result += source[i];
1094
+ }
1095
+ return result;
1096
+ }
1097
+ function addFormat(schema, value, message, refs) {
1098
+ var _a22;
1099
+ if (schema.format || ((_a22 = schema.anyOf) == null ? void 0 : _a22.some((x) => x.format))) {
1100
+ if (!schema.anyOf) {
1101
+ schema.anyOf = [];
1102
+ }
1103
+ if (schema.format) {
1104
+ schema.anyOf.push({
1105
+ format: schema.format
1106
+ });
1107
+ delete schema.format;
1108
+ }
1109
+ schema.anyOf.push(__spreadValues({
1110
+ format: value
1111
+ }, message && refs.errorMessages && { errorMessage: { format: message } }));
1112
+ } else {
1113
+ schema.format = value;
1114
+ }
1115
+ }
1116
+ function addPattern(schema, regex, message, refs) {
1117
+ var _a22;
1118
+ if (schema.pattern || ((_a22 = schema.allOf) == null ? void 0 : _a22.some((x) => x.pattern))) {
1119
+ if (!schema.allOf) {
1120
+ schema.allOf = [];
1121
+ }
1122
+ if (schema.pattern) {
1123
+ schema.allOf.push({
1124
+ pattern: schema.pattern
1125
+ });
1126
+ delete schema.pattern;
1127
+ }
1128
+ schema.allOf.push(__spreadValues({
1129
+ pattern: stringifyRegExpWithFlags(regex, refs)
1130
+ }, message && refs.errorMessages && { errorMessage: { pattern: message } }));
1131
+ } else {
1132
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
1133
+ }
1134
+ }
1135
+ function stringifyRegExpWithFlags(regex, refs) {
1136
+ var _a22;
1137
+ if (!refs.applyRegexFlags || !regex.flags) {
1138
+ return regex.source;
1139
+ }
1140
+ const flags = {
1141
+ i: regex.flags.includes("i"),
1142
+ // Case-insensitive
1143
+ m: regex.flags.includes("m"),
1144
+ // `^` and `$` matches adjacent to newline characters
1145
+ s: regex.flags.includes("s")
1146
+ // `.` matches newlines
1147
+ };
1148
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1149
+ let pattern = "";
1150
+ let isEscaped = false;
1151
+ let inCharGroup = false;
1152
+ let inCharRange = false;
1153
+ for (let i = 0; i < source.length; i++) {
1154
+ if (isEscaped) {
1155
+ pattern += source[i];
1156
+ isEscaped = false;
1157
+ continue;
1158
+ }
1159
+ if (flags.i) {
1160
+ if (inCharGroup) {
1161
+ if (source[i].match(/[a-z]/)) {
1162
+ if (inCharRange) {
1163
+ pattern += source[i];
1164
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1165
+ inCharRange = false;
1166
+ } else if (source[i + 1] === "-" && ((_a22 = source[i + 2]) == null ? void 0 : _a22.match(/[a-z]/))) {
1167
+ pattern += source[i];
1168
+ inCharRange = true;
1169
+ } else {
1170
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1171
+ }
1172
+ continue;
1173
+ }
1174
+ } else if (source[i].match(/[a-z]/)) {
1175
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1176
+ continue;
1177
+ }
1178
+ }
1179
+ if (flags.m) {
1180
+ if (source[i] === "^") {
1181
+ pattern += `(^|(?<=[\r
1182
+ ]))`;
1183
+ continue;
1184
+ } else if (source[i] === "$") {
1185
+ pattern += `($|(?=[\r
1186
+ ]))`;
1187
+ continue;
1188
+ }
1189
+ }
1190
+ if (flags.s && source[i] === ".") {
1191
+ pattern += inCharGroup ? `${source[i]}\r
1192
+ ` : `[${source[i]}\r
1193
+ ]`;
1194
+ continue;
1195
+ }
1196
+ pattern += source[i];
1197
+ if (source[i] === "\\") {
1198
+ isEscaped = true;
1199
+ } else if (inCharGroup && source[i] === "]") {
1200
+ inCharGroup = false;
1201
+ } else if (!inCharGroup && source[i] === "[") {
1202
+ inCharGroup = true;
1203
+ }
1204
+ }
1205
+ try {
1206
+ new RegExp(pattern);
1207
+ } catch (e) {
1208
+ console.warn(
1209
+ `Could not convert regex pattern at ${refs.currentPath.join(
1210
+ "/"
1211
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1212
+ );
1213
+ return regex.source;
1214
+ }
1215
+ return pattern;
1216
+ }
1217
+ function parseRecordDef(def, refs) {
1218
+ var _a22, _b22, _c, _d, _e, _f;
1219
+ const schema = {
1220
+ type: "object",
1221
+ additionalProperties: (_a22 = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
1222
+ currentPath: [...refs.currentPath, "additionalProperties"]
1223
+ }))) != null ? _a22 : refs.allowedAdditionalProperties
1224
+ };
1225
+ if (((_b22 = def.keyType) == null ? void 0 : _b22._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1226
+ const _a16 = parseStringDef(def.keyType._def, refs), { type } = _a16, keyType = __objRest(_a16, ["type"]);
1227
+ return __spreadProps(__spreadValues({}, schema), {
1228
+ propertyNames: keyType
1229
+ });
1230
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1231
+ return __spreadProps(__spreadValues({}, schema), {
1232
+ propertyNames: {
1233
+ enum: def.keyType._def.values
1234
+ }
1235
+ });
1236
+ } 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)) {
1237
+ const _b16 = parseBrandedDef(
1238
+ def.keyType._def,
1239
+ refs
1240
+ ), { type } = _b16, keyType = __objRest(_b16, ["type"]);
1241
+ return __spreadProps(__spreadValues({}, schema), {
1242
+ propertyNames: keyType
1243
+ });
1244
+ }
1245
+ return schema;
1246
+ }
1247
+ function parseMapDef(def, refs) {
1248
+ if (refs.mapStrategy === "record") {
1249
+ return parseRecordDef(def, refs);
1250
+ }
1251
+ const keys = parseDef(def.keyType._def, __spreadProps(__spreadValues({}, refs), {
1252
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1253
+ })) || parseAnyDef();
1254
+ const values = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
1255
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1256
+ })) || parseAnyDef();
1257
+ return {
1258
+ type: "array",
1259
+ maxItems: 125,
1260
+ items: {
1261
+ type: "array",
1262
+ items: [keys, values],
1263
+ minItems: 2,
1264
+ maxItems: 2
1265
+ }
1266
+ };
1267
+ }
1268
+ function parseNativeEnumDef(def) {
1269
+ const object = def.values;
1270
+ const actualKeys = Object.keys(def.values).filter((key) => {
1271
+ return typeof object[object[key]] !== "number";
1272
+ });
1273
+ const actualValues = actualKeys.map((key) => object[key]);
1274
+ const parsedTypes = Array.from(
1275
+ new Set(actualValues.map((values) => typeof values))
1276
+ );
1277
+ return {
1278
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1279
+ enum: actualValues
1280
+ };
1281
+ }
1282
+ function parseNeverDef() {
1283
+ return { not: parseAnyDef() };
1284
+ }
1285
+ function parseNullDef() {
1286
+ return {
1287
+ type: "null"
1288
+ };
1289
+ }
1290
+ var primitiveMappings = {
1291
+ ZodString: "string",
1292
+ ZodNumber: "number",
1293
+ ZodBigInt: "integer",
1294
+ ZodBoolean: "boolean",
1295
+ ZodNull: "null"
1296
+ };
1297
+ function parseUnionDef(def, refs) {
1298
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1299
+ if (options.every(
1300
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1301
+ )) {
1302
+ const types = options.reduce((types2, x) => {
1303
+ const type = primitiveMappings[x._def.typeName];
1304
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1305
+ }, []);
1306
+ return {
1307
+ type: types.length > 1 ? types : types[0]
566
1308
  };
1309
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1310
+ const types = options.reduce(
1311
+ (acc, x) => {
1312
+ const type = typeof x._def.value;
1313
+ switch (type) {
1314
+ case "string":
1315
+ case "number":
1316
+ case "boolean":
1317
+ return [...acc, type];
1318
+ case "bigint":
1319
+ return [...acc, "integer"];
1320
+ case "object":
1321
+ if (x._def.value === null) return [...acc, "null"];
1322
+ case "symbol":
1323
+ case "undefined":
1324
+ case "function":
1325
+ default:
1326
+ return acc;
1327
+ }
1328
+ },
1329
+ []
1330
+ );
1331
+ if (types.length === options.length) {
1332
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1333
+ return {
1334
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1335
+ enum: options.reduce(
1336
+ (acc, x) => {
1337
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1338
+ },
1339
+ []
1340
+ )
1341
+ };
1342
+ }
1343
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1344
+ return {
1345
+ type: "string",
1346
+ enum: options.reduce(
1347
+ (acc, x) => [
1348
+ ...acc,
1349
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1350
+ ],
1351
+ []
1352
+ )
1353
+ };
1354
+ }
1355
+ return asAnyOf(def, refs);
1356
+ }
1357
+ var asAnyOf = (def, refs) => {
1358
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1359
+ (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), {
1360
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1361
+ }))
1362
+ ).filter(
1363
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1364
+ );
1365
+ return anyOf.length ? { anyOf } : void 0;
1366
+ };
1367
+ function parseNullableDef(def, refs) {
1368
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1369
+ def.innerType._def.typeName
1370
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1371
+ return {
1372
+ type: [
1373
+ primitiveMappings[def.innerType._def.typeName],
1374
+ "null"
1375
+ ]
1376
+ };
1377
+ }
1378
+ const base = parseDef(def.innerType._def, __spreadProps(__spreadValues({}, refs), {
1379
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1380
+ }));
1381
+ return base && { anyOf: [base, { type: "null" }] };
1382
+ }
1383
+ function parseNumberDef(def) {
1384
+ const res = {
1385
+ type: "number"
1386
+ };
1387
+ if (!def.checks) return res;
1388
+ for (const check of def.checks) {
1389
+ switch (check.kind) {
1390
+ case "int":
1391
+ res.type = "integer";
1392
+ break;
1393
+ case "min":
1394
+ if (check.inclusive) {
1395
+ res.minimum = check.value;
1396
+ } else {
1397
+ res.exclusiveMinimum = check.value;
1398
+ }
1399
+ break;
1400
+ case "max":
1401
+ if (check.inclusive) {
1402
+ res.maximum = check.value;
1403
+ } else {
1404
+ res.exclusiveMaximum = check.value;
1405
+ }
1406
+ break;
1407
+ case "multipleOf":
1408
+ res.multipleOf = check.value;
1409
+ break;
1410
+ }
1411
+ }
1412
+ return res;
1413
+ }
1414
+ function parseObjectDef(def, refs) {
1415
+ const result = {
1416
+ type: "object",
1417
+ properties: {}
1418
+ };
1419
+ const required = [];
1420
+ const shape = def.shape();
1421
+ for (const propName in shape) {
1422
+ let propDef = shape[propName];
1423
+ if (propDef === void 0 || propDef._def === void 0) {
1424
+ continue;
1425
+ }
1426
+ const propOptional = safeIsOptional(propDef);
1427
+ const parsedDef = parseDef(propDef._def, __spreadProps(__spreadValues({}, refs), {
1428
+ currentPath: [...refs.currentPath, "properties", propName],
1429
+ propertyPath: [...refs.currentPath, "properties", propName]
1430
+ }));
1431
+ if (parsedDef === void 0) {
1432
+ continue;
1433
+ }
1434
+ result.properties[propName] = parsedDef;
1435
+ if (!propOptional) {
1436
+ required.push(propName);
1437
+ }
1438
+ }
1439
+ if (required.length) {
1440
+ result.required = required;
1441
+ }
1442
+ const additionalProperties = decideAdditionalProperties(def, refs);
1443
+ if (additionalProperties !== void 0) {
1444
+ result.additionalProperties = additionalProperties;
1445
+ }
1446
+ return result;
1447
+ }
1448
+ function decideAdditionalProperties(def, refs) {
1449
+ if (def.catchall._def.typeName !== "ZodNever") {
1450
+ return parseDef(def.catchall._def, __spreadProps(__spreadValues({}, refs), {
1451
+ currentPath: [...refs.currentPath, "additionalProperties"]
1452
+ }));
1453
+ }
1454
+ switch (def.unknownKeys) {
1455
+ case "passthrough":
1456
+ return refs.allowedAdditionalProperties;
1457
+ case "strict":
1458
+ return refs.rejectedAdditionalProperties;
1459
+ case "strip":
1460
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1461
+ }
1462
+ }
1463
+ function safeIsOptional(schema) {
1464
+ try {
1465
+ return schema.isOptional();
1466
+ } catch (e) {
1467
+ return true;
1468
+ }
1469
+ }
1470
+ var parseOptionalDef = (def, refs) => {
1471
+ var _a22;
1472
+ if (refs.currentPath.toString() === ((_a22 = refs.propertyPath) == null ? void 0 : _a22.toString())) {
1473
+ return parseDef(def.innerType._def, refs);
1474
+ }
1475
+ const innerSchema = parseDef(def.innerType._def, __spreadProps(__spreadValues({}, refs), {
1476
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1477
+ }));
1478
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1479
+ };
1480
+ var parsePipelineDef = (def, refs) => {
1481
+ if (refs.pipeStrategy === "input") {
1482
+ return parseDef(def.in._def, refs);
1483
+ } else if (refs.pipeStrategy === "output") {
1484
+ return parseDef(def.out._def, refs);
1485
+ }
1486
+ const a = parseDef(def.in._def, __spreadProps(__spreadValues({}, refs), {
1487
+ currentPath: [...refs.currentPath, "allOf", "0"]
1488
+ }));
1489
+ const b = parseDef(def.out._def, __spreadProps(__spreadValues({}, refs), {
1490
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1491
+ }));
1492
+ return {
1493
+ allOf: [a, b].filter((x) => x !== void 0)
1494
+ };
1495
+ };
1496
+ function parsePromiseDef(def, refs) {
1497
+ return parseDef(def.type._def, refs);
1498
+ }
1499
+ function parseSetDef(def, refs) {
1500
+ const items = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
1501
+ currentPath: [...refs.currentPath, "items"]
1502
+ }));
1503
+ const schema = {
1504
+ type: "array",
1505
+ uniqueItems: true,
1506
+ items
1507
+ };
1508
+ if (def.minSize) {
1509
+ schema.minItems = def.minSize.value;
1510
+ }
1511
+ if (def.maxSize) {
1512
+ schema.maxItems = def.maxSize.value;
1513
+ }
1514
+ return schema;
1515
+ }
1516
+ function parseTupleDef(def, refs) {
1517
+ if (def.rest) {
1518
+ return {
1519
+ type: "array",
1520
+ minItems: def.items.length,
1521
+ items: def.items.map(
1522
+ (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), {
1523
+ currentPath: [...refs.currentPath, "items", `${i}`]
1524
+ }))
1525
+ ).reduce(
1526
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1527
+ []
1528
+ ),
1529
+ additionalItems: parseDef(def.rest._def, __spreadProps(__spreadValues({}, refs), {
1530
+ currentPath: [...refs.currentPath, "additionalItems"]
1531
+ }))
1532
+ };
1533
+ } else {
1534
+ return {
1535
+ type: "array",
1536
+ minItems: def.items.length,
1537
+ maxItems: def.items.length,
1538
+ items: def.items.map(
1539
+ (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), {
1540
+ currentPath: [...refs.currentPath, "items", `${i}`]
1541
+ }))
1542
+ ).reduce(
1543
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1544
+ []
1545
+ )
1546
+ };
1547
+ }
1548
+ }
1549
+ function parseUndefinedDef() {
1550
+ return {
1551
+ not: parseAnyDef()
1552
+ };
1553
+ }
1554
+ function parseUnknownDef() {
1555
+ return parseAnyDef();
1556
+ }
1557
+ var parseReadonlyDef = (def, refs) => {
1558
+ return parseDef(def.innerType._def, refs);
1559
+ };
1560
+ var selectParser = (def, typeName, refs) => {
1561
+ switch (typeName) {
1562
+ case ZodFirstPartyTypeKind3.ZodString:
1563
+ return parseStringDef(def, refs);
1564
+ case ZodFirstPartyTypeKind3.ZodNumber:
1565
+ return parseNumberDef(def);
1566
+ case ZodFirstPartyTypeKind3.ZodObject:
1567
+ return parseObjectDef(def, refs);
1568
+ case ZodFirstPartyTypeKind3.ZodBigInt:
1569
+ return parseBigintDef(def);
1570
+ case ZodFirstPartyTypeKind3.ZodBoolean:
1571
+ return parseBooleanDef();
1572
+ case ZodFirstPartyTypeKind3.ZodDate:
1573
+ return parseDateDef(def, refs);
1574
+ case ZodFirstPartyTypeKind3.ZodUndefined:
1575
+ return parseUndefinedDef();
1576
+ case ZodFirstPartyTypeKind3.ZodNull:
1577
+ return parseNullDef();
1578
+ case ZodFirstPartyTypeKind3.ZodArray:
1579
+ return parseArrayDef(def, refs);
1580
+ case ZodFirstPartyTypeKind3.ZodUnion:
1581
+ case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1582
+ return parseUnionDef(def, refs);
1583
+ case ZodFirstPartyTypeKind3.ZodIntersection:
1584
+ return parseIntersectionDef(def, refs);
1585
+ case ZodFirstPartyTypeKind3.ZodTuple:
1586
+ return parseTupleDef(def, refs);
1587
+ case ZodFirstPartyTypeKind3.ZodRecord:
1588
+ return parseRecordDef(def, refs);
1589
+ case ZodFirstPartyTypeKind3.ZodLiteral:
1590
+ return parseLiteralDef(def);
1591
+ case ZodFirstPartyTypeKind3.ZodEnum:
1592
+ return parseEnumDef(def);
1593
+ case ZodFirstPartyTypeKind3.ZodNativeEnum:
1594
+ return parseNativeEnumDef(def);
1595
+ case ZodFirstPartyTypeKind3.ZodNullable:
1596
+ return parseNullableDef(def, refs);
1597
+ case ZodFirstPartyTypeKind3.ZodOptional:
1598
+ return parseOptionalDef(def, refs);
1599
+ case ZodFirstPartyTypeKind3.ZodMap:
1600
+ return parseMapDef(def, refs);
1601
+ case ZodFirstPartyTypeKind3.ZodSet:
1602
+ return parseSetDef(def, refs);
1603
+ case ZodFirstPartyTypeKind3.ZodLazy:
1604
+ return () => def.getter()._def;
1605
+ case ZodFirstPartyTypeKind3.ZodPromise:
1606
+ return parsePromiseDef(def, refs);
1607
+ case ZodFirstPartyTypeKind3.ZodNaN:
1608
+ case ZodFirstPartyTypeKind3.ZodNever:
1609
+ return parseNeverDef();
1610
+ case ZodFirstPartyTypeKind3.ZodEffects:
1611
+ return parseEffectsDef(def, refs);
1612
+ case ZodFirstPartyTypeKind3.ZodAny:
1613
+ return parseAnyDef();
1614
+ case ZodFirstPartyTypeKind3.ZodUnknown:
1615
+ return parseUnknownDef();
1616
+ case ZodFirstPartyTypeKind3.ZodDefault:
1617
+ return parseDefaultDef(def, refs);
1618
+ case ZodFirstPartyTypeKind3.ZodBranded:
1619
+ return parseBrandedDef(def, refs);
1620
+ case ZodFirstPartyTypeKind3.ZodReadonly:
1621
+ return parseReadonlyDef(def, refs);
1622
+ case ZodFirstPartyTypeKind3.ZodCatch:
1623
+ return parseCatchDef(def, refs);
1624
+ case ZodFirstPartyTypeKind3.ZodPipeline:
1625
+ return parsePipelineDef(def, refs);
1626
+ case ZodFirstPartyTypeKind3.ZodFunction:
1627
+ case ZodFirstPartyTypeKind3.ZodVoid:
1628
+ case ZodFirstPartyTypeKind3.ZodSymbol:
1629
+ return void 0;
1630
+ default:
1631
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
1632
+ }
1633
+ };
1634
+ var getRelativePath = (pathA, pathB) => {
1635
+ let i = 0;
1636
+ for (; i < pathA.length && i < pathB.length; i++) {
1637
+ if (pathA[i] !== pathB[i]) break;
1638
+ }
1639
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1640
+ };
1641
+ function parseDef(def, refs, forceResolution = false) {
1642
+ var _a22;
1643
+ const seenItem = refs.seen.get(def);
1644
+ if (refs.override) {
1645
+ const overrideResult = (_a22 = refs.override) == null ? void 0 : _a22.call(
1646
+ refs,
1647
+ def,
1648
+ refs,
1649
+ seenItem,
1650
+ forceResolution
1651
+ );
1652
+ if (overrideResult !== ignoreOverride) {
1653
+ return overrideResult;
1654
+ }
1655
+ }
1656
+ if (seenItem && !forceResolution) {
1657
+ const seenSchema = get$ref(seenItem, refs);
1658
+ if (seenSchema !== void 0) {
1659
+ return seenSchema;
1660
+ }
1661
+ }
1662
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1663
+ refs.seen.set(def, newItem);
1664
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1665
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1666
+ if (jsonSchema2) {
1667
+ addMeta(def, refs, jsonSchema2);
1668
+ }
1669
+ if (refs.postProcess) {
1670
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1671
+ newItem.jsonSchema = jsonSchema2;
1672
+ return postProcessResult;
1673
+ }
1674
+ newItem.jsonSchema = jsonSchema2;
1675
+ return jsonSchema2;
1676
+ }
1677
+ var get$ref = (item, refs) => {
1678
+ switch (refs.$refStrategy) {
1679
+ case "root":
1680
+ return { $ref: item.path.join("/") };
1681
+ case "relative":
1682
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1683
+ case "none":
1684
+ case "seen": {
1685
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1686
+ console.warn(
1687
+ `Recursive reference detected at ${refs.currentPath.join(
1688
+ "/"
1689
+ )}! Defaulting to any`
1690
+ );
1691
+ return parseAnyDef();
1692
+ }
1693
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1694
+ }
1695
+ }
1696
+ };
1697
+ var addMeta = (def, refs, jsonSchema2) => {
1698
+ if (def.description) {
1699
+ jsonSchema2.description = def.description;
1700
+ }
1701
+ return jsonSchema2;
1702
+ };
1703
+ var getRefs = (options) => {
1704
+ const _options = getDefaultOptions(options);
1705
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1706
+ return __spreadProps(__spreadValues({}, _options), {
1707
+ currentPath,
1708
+ propertyPath: void 0,
1709
+ seen: new Map(
1710
+ Object.entries(_options.definitions).map(([name22, def]) => [
1711
+ def._def,
1712
+ {
1713
+ def: def._def,
1714
+ path: [..._options.basePath, _options.definitionPath, name22],
1715
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1716
+ jsonSchema: void 0
1717
+ }
1718
+ ])
1719
+ )
567
1720
  });
1721
+ };
1722
+ var zod3ToJsonSchema = (schema, options) => {
1723
+ var _a22;
1724
+ const refs = getRefs(options);
1725
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1726
+ (acc, [name32, schema2]) => {
1727
+ var _a32;
1728
+ return __spreadProps(__spreadValues({}, acc), {
1729
+ [name32]: (_a32 = parseDef(
1730
+ schema2._def,
1731
+ __spreadProps(__spreadValues({}, refs), {
1732
+ currentPath: [...refs.basePath, refs.definitionPath, name32]
1733
+ }),
1734
+ true
1735
+ )) != null ? _a32 : parseAnyDef()
1736
+ });
1737
+ },
1738
+ {}
1739
+ ) : void 0;
1740
+ const name22 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1741
+ const main = (_a22 = parseDef(
1742
+ schema._def,
1743
+ name22 === void 0 ? refs : __spreadProps(__spreadValues({}, refs), {
1744
+ currentPath: [...refs.basePath, refs.definitionPath, name22]
1745
+ }),
1746
+ false
1747
+ )) != null ? _a22 : parseAnyDef();
1748
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1749
+ if (title !== void 0) {
1750
+ main.title = title;
1751
+ }
1752
+ const combined = name22 === void 0 ? definitions ? __spreadProps(__spreadValues({}, main), {
1753
+ [refs.definitionPath]: definitions
1754
+ }) : main : {
1755
+ $ref: [
1756
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1757
+ refs.definitionPath,
1758
+ name22
1759
+ ].join("/"),
1760
+ [refs.definitionPath]: __spreadProps(__spreadValues({}, definitions), {
1761
+ [name22]: main
1762
+ })
1763
+ };
1764
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1765
+ return combined;
1766
+ };
1767
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
1768
+ function jsonSchema(jsonSchema2, {
1769
+ validate
1770
+ } = {}) {
1771
+ return {
1772
+ [schemaSymbol]: true,
1773
+ _type: void 0,
1774
+ // should never be used directly
1775
+ get jsonSchema() {
1776
+ if (typeof jsonSchema2 === "function") {
1777
+ jsonSchema2 = jsonSchema2();
1778
+ }
1779
+ return jsonSchema2;
1780
+ },
1781
+ validate
1782
+ };
1783
+ }
1784
+ function isSchema(value) {
1785
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
1786
+ }
1787
+ function asSchema(schema) {
1788
+ return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
1789
+ }
1790
+ function standardSchema(standardSchema2) {
1791
+ return jsonSchema(
1792
+ () => standardSchema2["~standard"].jsonSchema.input({
1793
+ target: "draft-07"
1794
+ }),
1795
+ {
1796
+ validate: async (value) => {
1797
+ const result = await standardSchema2["~standard"].validate(value);
1798
+ return "value" in result ? { success: true, value: result.value } : {
1799
+ success: false,
1800
+ error: new TypeValidationError({
1801
+ value,
1802
+ cause: result.issues
1803
+ })
1804
+ };
1805
+ }
1806
+ }
1807
+ );
1808
+ }
1809
+ function zod3Schema(zodSchema2, options) {
1810
+ var _a22;
1811
+ const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
1812
+ return jsonSchema(
1813
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1814
+ () => zod3ToJsonSchema(zodSchema2, {
1815
+ $refStrategy: useReferences ? "root" : "none"
1816
+ }),
1817
+ {
1818
+ validate: async (value) => {
1819
+ const result = await zodSchema2.safeParseAsync(value);
1820
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1821
+ }
1822
+ }
1823
+ );
1824
+ }
1825
+ function zod4Schema(zodSchema2, options) {
1826
+ var _a22;
1827
+ const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
1828
+ return jsonSchema(
1829
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1830
+ () => addAdditionalPropertiesToJsonSchema(
1831
+ z4.toJSONSchema(zodSchema2, {
1832
+ target: "draft-7",
1833
+ io: "input",
1834
+ reused: useReferences ? "ref" : "inline"
1835
+ })
1836
+ ),
1837
+ {
1838
+ validate: async (value) => {
1839
+ const result = await z4.safeParseAsync(zodSchema2, value);
1840
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1841
+ }
1842
+ }
1843
+ );
1844
+ }
1845
+ function isZod4Schema(zodSchema2) {
1846
+ return "_zod" in zodSchema2;
1847
+ }
1848
+ function zodSchema(zodSchema2, options) {
1849
+ if (isZod4Schema(zodSchema2)) {
1850
+ return zod4Schema(zodSchema2, options);
1851
+ } else {
1852
+ return zod3Schema(zodSchema2, options);
1853
+ }
568
1854
  }
569
1855
  async function validateTypes({
570
1856
  value,
@@ -580,12 +1866,12 @@ async function safeValidateTypes({
580
1866
  value,
581
1867
  schema
582
1868
  }) {
583
- const validator2 = asValidator(schema);
1869
+ const actualSchema = asSchema(schema);
584
1870
  try {
585
- if (validator2.validate == null) {
1871
+ if (actualSchema.validate == null) {
586
1872
  return { success: true, value, rawValue: value };
587
1873
  }
588
- const result = await validator2.validate(value);
1874
+ const result = await actualSchema.validate(value);
589
1875
  if (result.success) {
590
1876
  return { success: true, value: result.value, rawValue: value };
591
1877
  }
@@ -668,7 +1954,7 @@ var postJsonToApi = async ({
668
1954
  failedResponseHandler,
669
1955
  successfulResponseHandler,
670
1956
  abortSignal,
671
- fetch
1957
+ fetch: fetch2
672
1958
  }) => postToApi({
673
1959
  url,
674
1960
  headers: __spreadValues({
@@ -681,7 +1967,7 @@ var postJsonToApi = async ({
681
1967
  failedResponseHandler,
682
1968
  successfulResponseHandler,
683
1969
  abortSignal,
684
- fetch
1970
+ fetch: fetch2
685
1971
  });
686
1972
  var postToApi = async ({
687
1973
  url,
@@ -690,12 +1976,16 @@ var postToApi = async ({
690
1976
  successfulResponseHandler,
691
1977
  failedResponseHandler,
692
1978
  abortSignal,
693
- fetch = getOriginalFetch2()
1979
+ fetch: fetch2 = getOriginalFetch2()
694
1980
  }) => {
695
1981
  try {
696
- const response = await fetch(url, {
1982
+ const response = await fetch2(url, {
697
1983
  method: "POST",
698
- headers: removeUndefinedEntries(headers),
1984
+ headers: withUserAgentSuffix(
1985
+ headers,
1986
+ `ai-sdk/provider-utils/${VERSION}`,
1987
+ getRuntimeEnvironmentUserAgent()
1988
+ ),
699
1989
  body: body.content,
700
1990
  signal: abortSignal
701
1991
  });
@@ -839,15 +2129,6 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
839
2129
  rawValue: parsedResult.rawValue
840
2130
  };
841
2131
  };
842
- var schemaSymbol = Symbol.for("vercel.ai.schema");
843
- var { btoa, atob } = globalThis;
844
- function convertUint8ArrayToBase64(array) {
845
- let latin1string = "";
846
- for (let i = 0; i < array.length; i++) {
847
- latin1string += String.fromCodePoint(array[i]);
848
- }
849
- return btoa(latin1string);
850
- }
851
2132
 
852
2133
  // src/schemas/reasoning-details.ts
853
2134
  import { z } from "zod/v4";
@@ -975,7 +2256,7 @@ var OpenRouterProviderOptionsSchema = z3.object({
975
2256
  }).optional();
976
2257
 
977
2258
  // src/utils/map-finish-reason.ts
978
- function mapOpenRouterFinishReason(finishReason) {
2259
+ function mapToUnified(finishReason) {
979
2260
  switch (finishReason) {
980
2261
  case "stop":
981
2262
  return "stop";
@@ -987,9 +2268,18 @@ function mapOpenRouterFinishReason(finishReason) {
987
2268
  case "tool_calls":
988
2269
  return "tool-calls";
989
2270
  default:
990
- return "unknown";
2271
+ return "other";
991
2272
  }
992
2273
  }
2274
+ function mapOpenRouterFinishReason(finishReason) {
2275
+ return {
2276
+ unified: mapToUnified(finishReason),
2277
+ raw: finishReason != null ? finishReason : void 0
2278
+ };
2279
+ }
2280
+ function createFinishReason(unified, raw) {
2281
+ return { unified, raw };
2282
+ }
993
2283
 
994
2284
  // src/types/openrouter-chat-completions-input.ts
995
2285
  var OPENROUTER_AUDIO_FORMATS = [
@@ -1022,10 +2312,10 @@ function getFileUrl({
1022
2312
  part,
1023
2313
  defaultMediaType
1024
2314
  }) {
1025
- var _a15, _b;
2315
+ var _a16, _b16;
1026
2316
  if (part.data instanceof Uint8Array) {
1027
2317
  const base64 = convertUint8ArrayToBase64(part.data);
1028
- return `data:${(_a15 = part.mediaType) != null ? _a15 : defaultMediaType};base64,${base64}`;
2318
+ return `data:${(_a16 = part.mediaType) != null ? _a16 : defaultMediaType};base64,${base64}`;
1029
2319
  }
1030
2320
  const stringUrl = part.data.toString();
1031
2321
  if (isUrl({
@@ -1034,12 +2324,12 @@ function getFileUrl({
1034
2324
  })) {
1035
2325
  return stringUrl;
1036
2326
  }
1037
- return stringUrl.startsWith("data:") ? stringUrl : `data:${(_b = part.mediaType) != null ? _b : defaultMediaType};base64,${stringUrl}`;
2327
+ return stringUrl.startsWith("data:") ? stringUrl : `data:${(_b16 = part.mediaType) != null ? _b16 : defaultMediaType};base64,${stringUrl}`;
1038
2328
  }
1039
2329
  function getMediaType(dataUrl, defaultMediaType) {
1040
- var _a15;
2330
+ var _a16;
1041
2331
  const match = dataUrl.match(/^data:([^;]+)/);
1042
- return match ? (_a15 = match[1]) != null ? _a15 : defaultMediaType : defaultMediaType;
2332
+ return match ? (_a16 = match[1]) != null ? _a16 : defaultMediaType : defaultMediaType;
1043
2333
  }
1044
2334
  function getBase64FromDataUrl(dataUrl) {
1045
2335
  const match = dataUrl.match(/^data:[^;]*;base64,(.+)$/);
@@ -1114,13 +2404,13 @@ Learn more: https://openrouter.ai/docs/features/multimodal/audio`
1114
2404
 
1115
2405
  // src/chat/convert-to-openrouter-chat-messages.ts
1116
2406
  function getCacheControl(providerMetadata) {
1117
- var _a15, _b, _c;
2407
+ var _a16, _b16, _c;
1118
2408
  const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
1119
2409
  const openrouter = providerMetadata == null ? void 0 : providerMetadata.openrouter;
1120
- return (_c = (_b = (_a15 = openrouter == null ? void 0 : openrouter.cacheControl) != null ? _a15 : openrouter == null ? void 0 : openrouter.cache_control) != null ? _b : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
2410
+ return (_c = (_b16 = (_a16 = openrouter == null ? void 0 : openrouter.cacheControl) != null ? _a16 : openrouter == null ? void 0 : openrouter.cache_control) != null ? _b16 : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
1121
2411
  }
1122
2412
  function convertToOpenRouterChatMessages(prompt) {
1123
- var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2413
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j;
1124
2414
  const messages = [];
1125
2415
  for (const { role, content, providerOptions } of prompt) {
1126
2416
  switch (role) {
@@ -1133,8 +2423,8 @@ function convertToOpenRouterChatMessages(prompt) {
1133
2423
  break;
1134
2424
  }
1135
2425
  case "user": {
1136
- if (content.length === 1 && ((_a15 = content[0]) == null ? void 0 : _a15.type) === "text") {
1137
- const cacheControl = (_b = getCacheControl(providerOptions)) != null ? _b : getCacheControl(content[0].providerOptions);
2426
+ if (content.length === 1 && ((_a16 = content[0]) == null ? void 0 : _a16.type) === "text") {
2427
+ const cacheControl = (_b16 = getCacheControl(providerOptions)) != null ? _b16 : getCacheControl(content[0].providerOptions);
1138
2428
  const contentWithCacheControl = cacheControl ? [
1139
2429
  {
1140
2430
  type: "text",
@@ -1151,8 +2441,8 @@ function convertToOpenRouterChatMessages(prompt) {
1151
2441
  const messageCacheControl = getCacheControl(providerOptions);
1152
2442
  const contentParts = content.map(
1153
2443
  (part) => {
1154
- var _a16, _b2, _c2, _d2, _e2, _f2, _g2;
1155
- const cacheControl = (_a16 = getCacheControl(part.providerOptions)) != null ? _a16 : messageCacheControl;
2444
+ var _a17, _b17, _c2, _d2, _e2, _f2, _g2;
2445
+ const cacheControl = (_a17 = getCacheControl(part.providerOptions)) != null ? _a17 : messageCacheControl;
1156
2446
  switch (part.type) {
1157
2447
  case "text":
1158
2448
  return {
@@ -1162,7 +2452,7 @@ function convertToOpenRouterChatMessages(prompt) {
1162
2452
  cache_control: cacheControl
1163
2453
  };
1164
2454
  case "file": {
1165
- if ((_b2 = part.mediaType) == null ? void 0 : _b2.startsWith("image/")) {
2455
+ if ((_b17 = part.mediaType) == null ? void 0 : _b17.startsWith("image/")) {
1166
2456
  const url = getFileUrl({
1167
2457
  part,
1168
2458
  defaultMediaType: "image/jpeg"
@@ -1289,6 +2579,9 @@ function convertToOpenRouterChatMessages(prompt) {
1289
2579
  }
1290
2580
  case "tool": {
1291
2581
  for (const toolResponse of content) {
2582
+ if (toolResponse.type === "tool-approval-response") {
2583
+ continue;
2584
+ }
1292
2585
  const content2 = getToolResultContent(toolResponse);
1293
2586
  messages.push({
1294
2587
  role: "tool",
@@ -1307,7 +2600,18 @@ function convertToOpenRouterChatMessages(prompt) {
1307
2600
  return messages;
1308
2601
  }
1309
2602
  function getToolResultContent(input) {
1310
- return input.output.type === "text" ? input.output.value : JSON.stringify(input.output.value);
2603
+ var _a16;
2604
+ switch (input.output.type) {
2605
+ case "text":
2606
+ case "error-text":
2607
+ return input.output.value;
2608
+ case "json":
2609
+ case "error-json":
2610
+ case "content":
2611
+ return JSON.stringify(input.output.value);
2612
+ case "execution-denied":
2613
+ return (_a16 = input.output.reason) != null ? _a16 : "Tool execution denied";
2614
+ }
1311
2615
  }
1312
2616
 
1313
2617
  // src/chat/get-tool-choice.ts
@@ -1550,7 +2854,7 @@ var OpenRouterStreamChatCompletionChunkSchema = z7.union([
1550
2854
  // src/chat/index.ts
1551
2855
  var OpenRouterChatLanguageModel = class {
1552
2856
  constructor(modelId, settings, config) {
1553
- this.specificationVersion = "v2";
2857
+ this.specificationVersion = "v3";
1554
2858
  this.provider = "openrouter";
1555
2859
  this.defaultObjectGenerationMode = "tool";
1556
2860
  this.supportsImageUrls = true;
@@ -1580,7 +2884,7 @@ var OpenRouterChatLanguageModel = class {
1580
2884
  tools,
1581
2885
  toolChoice
1582
2886
  }) {
1583
- var _a15;
2887
+ var _a16;
1584
2888
  const baseArgs = __spreadValues(__spreadValues({
1585
2889
  // model id:
1586
2890
  model: this.modelId,
@@ -1604,7 +2908,7 @@ var OpenRouterChatLanguageModel = class {
1604
2908
  json_schema: __spreadValues({
1605
2909
  schema: responseFormat.schema,
1606
2910
  strict: true,
1607
- name: (_a15 = responseFormat.name) != null ? _a15 : "response"
2911
+ name: (_a16 = responseFormat.name) != null ? _a16 : "response"
1608
2912
  }, responseFormat.description && {
1609
2913
  description: responseFormat.description
1610
2914
  })
@@ -1643,7 +2947,7 @@ var OpenRouterChatLanguageModel = class {
1643
2947
  return baseArgs;
1644
2948
  }
1645
2949
  async doGenerate(options) {
1646
- var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w;
2950
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w;
1647
2951
  const providerOptions = options.providerOptions || {};
1648
2952
  const openrouterOptions = providerOptions.openrouter || {};
1649
2953
  const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
@@ -1683,19 +2987,31 @@ var OpenRouterChatLanguageModel = class {
1683
2987
  });
1684
2988
  }
1685
2989
  const usageInfo = response.usage ? {
1686
- inputTokens: (_a15 = response.usage.prompt_tokens) != null ? _a15 : 0,
1687
- outputTokens: (_b = response.usage.completion_tokens) != null ? _b : 0,
1688
- totalTokens: ((_c = response.usage.prompt_tokens) != null ? _c : 0) + ((_d = response.usage.completion_tokens) != null ? _d : 0),
1689
- reasoningTokens: (_f = (_e = response.usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0,
1690
- cachedInputTokens: (_h = (_g = response.usage.prompt_tokens_details) == null ? void 0 : _g.cached_tokens) != null ? _h : 0
2990
+ inputTokens: {
2991
+ total: (_a16 = response.usage.prompt_tokens) != null ? _a16 : 0,
2992
+ noCache: void 0,
2993
+ cacheRead: (_c = (_b16 = response.usage.prompt_tokens_details) == null ? void 0 : _b16.cached_tokens) != null ? _c : void 0,
2994
+ cacheWrite: void 0
2995
+ },
2996
+ outputTokens: {
2997
+ total: (_d = response.usage.completion_tokens) != null ? _d : 0,
2998
+ text: void 0,
2999
+ reasoning: (_f = (_e = response.usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : void 0
3000
+ }
1691
3001
  } : {
1692
- inputTokens: 0,
1693
- outputTokens: 0,
1694
- totalTokens: 0,
1695
- reasoningTokens: 0,
1696
- cachedInputTokens: 0
3002
+ inputTokens: {
3003
+ total: 0,
3004
+ noCache: void 0,
3005
+ cacheRead: void 0,
3006
+ cacheWrite: void 0
3007
+ },
3008
+ outputTokens: {
3009
+ total: 0,
3010
+ text: void 0,
3011
+ reasoning: void 0
3012
+ }
1697
3013
  };
1698
- const reasoningDetails = (_i = choice.message.reasoning_details) != null ? _i : [];
3014
+ const reasoningDetails = (_g = choice.message.reasoning_details) != null ? _g : [];
1699
3015
  const reasoning = reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
1700
3016
  switch (detail.type) {
1701
3017
  case "reasoning.text" /* Text */: {
@@ -1763,7 +3079,7 @@ var OpenRouterChatLanguageModel = class {
1763
3079
  for (const toolCall of choice.message.tool_calls) {
1764
3080
  content.push({
1765
3081
  type: "tool-call",
1766
- toolCallId: (_j = toolCall.id) != null ? _j : generateId(),
3082
+ toolCallId: (_h = toolCall.id) != null ? _h : generateId(),
1767
3083
  toolName: toolCall.function.name,
1768
3084
  input: toolCall.function.arguments,
1769
3085
  providerMetadata: {
@@ -1801,7 +3117,7 @@ var OpenRouterChatLanguageModel = class {
1801
3117
  }
1802
3118
  }
1803
3119
  }
1804
- const fileAnnotations = (_k = choice.message.annotations) == null ? void 0 : _k.filter(
3120
+ const fileAnnotations = (_i = choice.message.annotations) == null ? void 0 : _i.filter(
1805
3121
  (a) => a.type === "file"
1806
3122
  );
1807
3123
  const hasToolCalls = choice.message.tool_calls && choice.message.tool_calls.length > 0;
@@ -1809,7 +3125,7 @@ var OpenRouterChatLanguageModel = class {
1809
3125
  (d) => d.type === "reasoning.encrypted" /* Encrypted */ && d.data
1810
3126
  );
1811
3127
  const shouldOverrideFinishReason = hasToolCalls && hasEncryptedReasoning && choice.finish_reason === "stop";
1812
- const effectiveFinishReason = shouldOverrideFinishReason ? "tool-calls" : mapOpenRouterFinishReason(choice.finish_reason);
3128
+ const effectiveFinishReason = shouldOverrideFinishReason ? createFinishReason("tool-calls", (_j = choice.finish_reason) != null ? _j : void 0) : mapOpenRouterFinishReason(choice.finish_reason);
1813
3129
  return {
1814
3130
  content,
1815
3131
  finishReason: effectiveFinishReason,
@@ -1817,13 +3133,13 @@ var OpenRouterChatLanguageModel = class {
1817
3133
  warnings: [],
1818
3134
  providerMetadata: {
1819
3135
  openrouter: OpenRouterProviderMetadataSchema.parse({
1820
- provider: (_l = response.provider) != null ? _l : "",
1821
- reasoning_details: (_m = choice.message.reasoning_details) != null ? _m : [],
3136
+ provider: (_k = response.provider) != null ? _k : "",
3137
+ reasoning_details: (_l = choice.message.reasoning_details) != null ? _l : [],
1822
3138
  annotations: fileAnnotations && fileAnnotations.length > 0 ? fileAnnotations : void 0,
1823
3139
  usage: __spreadValues(__spreadValues(__spreadValues({
1824
- promptTokens: (_n = usageInfo.inputTokens) != null ? _n : 0,
1825
- completionTokens: (_o = usageInfo.outputTokens) != null ? _o : 0,
1826
- totalTokens: (_p = usageInfo.totalTokens) != null ? _p : 0,
3140
+ promptTokens: (_m = usageInfo.inputTokens.total) != null ? _m : 0,
3141
+ completionTokens: (_n = usageInfo.outputTokens.total) != null ? _n : 0,
3142
+ totalTokens: ((_o = usageInfo.inputTokens.total) != null ? _o : 0) + ((_p = usageInfo.outputTokens.total) != null ? _p : 0),
1827
3143
  cost: (_q = response.usage) == null ? void 0 : _q.cost
1828
3144
  }, ((_s = (_r = response.usage) == null ? void 0 : _r.prompt_tokens_details) == null ? void 0 : _s.cached_tokens) != null ? {
1829
3145
  promptTokensDetails: {
@@ -1849,7 +3165,7 @@ var OpenRouterChatLanguageModel = class {
1849
3165
  };
1850
3166
  }
1851
3167
  async doStream(options) {
1852
- var _a15;
3168
+ var _a16;
1853
3169
  const providerOptions = options.providerOptions || {};
1854
3170
  const openrouterOptions = providerOptions.openrouter || {};
1855
3171
  const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
@@ -1864,7 +3180,7 @@ var OpenRouterChatLanguageModel = class {
1864
3180
  // only include stream_options when in strict compatibility mode:
1865
3181
  stream_options: this.config.compatibility === "strict" ? __spreadValues({
1866
3182
  include_usage: true
1867
- }, ((_a15 = this.settings.usage) == null ? void 0 : _a15.include) ? { include_usage: true } : {}) : void 0
3183
+ }, ((_a16 = this.settings.usage) == null ? void 0 : _a16.include) ? { include_usage: true } : {}) : void 0
1868
3184
  }),
1869
3185
  failedResponseHandler: openrouterFailedResponseHandler,
1870
3186
  successfulResponseHandler: createEventSourceResponseHandler(
@@ -1874,13 +3190,19 @@ var OpenRouterChatLanguageModel = class {
1874
3190
  fetch: this.config.fetch
1875
3191
  });
1876
3192
  const toolCalls = [];
1877
- let finishReason = "other";
3193
+ let finishReason = createFinishReason("other");
1878
3194
  const usage = {
1879
- inputTokens: Number.NaN,
1880
- outputTokens: Number.NaN,
1881
- totalTokens: Number.NaN,
1882
- reasoningTokens: Number.NaN,
1883
- cachedInputTokens: Number.NaN
3195
+ inputTokens: {
3196
+ total: void 0,
3197
+ noCache: void 0,
3198
+ cacheRead: void 0,
3199
+ cacheWrite: void 0
3200
+ },
3201
+ outputTokens: {
3202
+ total: void 0,
3203
+ text: void 0,
3204
+ reasoning: void 0
3205
+ }
1884
3206
  };
1885
3207
  const openrouterUsage = {};
1886
3208
  const accumulatedReasoningDetails = [];
@@ -1895,15 +3217,15 @@ var OpenRouterChatLanguageModel = class {
1895
3217
  stream: response.pipeThrough(
1896
3218
  new TransformStream({
1897
3219
  transform(chunk, controller) {
1898
- var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
3220
+ var _a17, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
1899
3221
  if (!chunk.success) {
1900
- finishReason = "error";
3222
+ finishReason = createFinishReason("error");
1901
3223
  controller.enqueue({ type: "error", error: chunk.error });
1902
3224
  return;
1903
3225
  }
1904
3226
  const value = chunk.value;
1905
3227
  if ("error" in value) {
1906
- finishReason = "error";
3228
+ finishReason = createFinishReason("error");
1907
3229
  controller.enqueue({ type: "error", error: value.error });
1908
3230
  return;
1909
3231
  }
@@ -1924,21 +3246,20 @@ var OpenRouterChatLanguageModel = class {
1924
3246
  });
1925
3247
  }
1926
3248
  if (value.usage != null) {
1927
- usage.inputTokens = value.usage.prompt_tokens;
1928
- usage.outputTokens = value.usage.completion_tokens;
1929
- usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
3249
+ usage.inputTokens.total = value.usage.prompt_tokens;
3250
+ usage.outputTokens.total = value.usage.completion_tokens;
1930
3251
  openrouterUsage.promptTokens = value.usage.prompt_tokens;
1931
3252
  if (value.usage.prompt_tokens_details) {
1932
- const cachedInputTokens = (_a16 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a16 : 0;
1933
- usage.cachedInputTokens = cachedInputTokens;
3253
+ const cachedInputTokens = (_a17 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a17 : 0;
3254
+ usage.inputTokens.cacheRead = cachedInputTokens;
1934
3255
  openrouterUsage.promptTokensDetails = {
1935
3256
  cachedTokens: cachedInputTokens
1936
3257
  };
1937
3258
  }
1938
3259
  openrouterUsage.completionTokens = value.usage.completion_tokens;
1939
3260
  if (value.usage.completion_tokens_details) {
1940
- const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
1941
- usage.reasoningTokens = reasoningTokens;
3261
+ const reasoningTokens = (_b16 = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b16 : 0;
3262
+ usage.outputTokens.reasoning = reasoningTokens;
1942
3263
  openrouterUsage.completionTokensDetails = {
1943
3264
  reasoningTokens
1944
3265
  };
@@ -2197,20 +3518,20 @@ var OpenRouterChatLanguageModel = class {
2197
3518
  }
2198
3519
  },
2199
3520
  flush(controller) {
2200
- var _a16;
3521
+ var _a17;
2201
3522
  const hasToolCalls = toolCalls.length > 0;
2202
3523
  const hasEncryptedReasoning = accumulatedReasoningDetails.some(
2203
3524
  (d) => d.type === "reasoning.encrypted" /* Encrypted */ && d.data
2204
3525
  );
2205
- if (hasToolCalls && hasEncryptedReasoning && finishReason === "stop") {
2206
- finishReason = "tool-calls";
3526
+ if (hasToolCalls && hasEncryptedReasoning && finishReason.unified === "stop") {
3527
+ finishReason = createFinishReason("tool-calls", finishReason.raw);
2207
3528
  }
2208
- if (finishReason === "tool-calls") {
3529
+ if (finishReason.unified === "tool-calls") {
2209
3530
  for (const toolCall of toolCalls) {
2210
3531
  if (toolCall && !toolCall.sent) {
2211
3532
  controller.enqueue({
2212
3533
  type: "tool-call",
2213
- toolCallId: (_a16 = toolCall.id) != null ? _a16 : generateId(),
3534
+ toolCallId: (_a17 = toolCall.id) != null ? _a17 : generateId(),
2214
3535
  toolName: toolCall.function.name,
2215
3536
  // Coerce invalid arguments to an empty JSON object
2216
3537
  input: isParsableJson(toolCall.function.arguments) ? toolCall.function.arguments : "{}",
@@ -2411,7 +3732,7 @@ var OpenRouterCompletionChunkSchema = z8.union([
2411
3732
  // src/completion/index.ts
2412
3733
  var OpenRouterCompletionLanguageModel = class {
2413
3734
  constructor(modelId, settings, config) {
2414
- this.specificationVersion = "v2";
3735
+ this.specificationVersion = "v3";
2415
3736
  this.provider = "openrouter";
2416
3737
  this.supportsImageUrls = true;
2417
3738
  this.supportedUrls = {
@@ -2482,7 +3803,7 @@ var OpenRouterCompletionLanguageModel = class {
2482
3803
  }, this.config.extraBody), this.settings.extraBody);
2483
3804
  }
2484
3805
  async doGenerate(options) {
2485
- var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
3806
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k;
2486
3807
  const providerOptions = options.providerOptions || {};
2487
3808
  const openrouterOptions = providerOptions.openrouter || {};
2488
3809
  const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
@@ -2524,16 +3845,22 @@ var OpenRouterCompletionLanguageModel = class {
2524
3845
  content: [
2525
3846
  {
2526
3847
  type: "text",
2527
- text: (_a15 = choice.text) != null ? _a15 : ""
3848
+ text: (_a16 = choice.text) != null ? _a16 : ""
2528
3849
  }
2529
3850
  ],
2530
3851
  finishReason: mapOpenRouterFinishReason(choice.finish_reason),
2531
3852
  usage: {
2532
- inputTokens: (_c = (_b = response.usage) == null ? void 0 : _b.prompt_tokens) != null ? _c : 0,
2533
- outputTokens: (_e = (_d = response.usage) == null ? void 0 : _d.completion_tokens) != null ? _e : 0,
2534
- 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),
2535
- reasoningTokens: (_l = (_k = (_j = response.usage) == null ? void 0 : _j.completion_tokens_details) == null ? void 0 : _k.reasoning_tokens) != null ? _l : 0,
2536
- cachedInputTokens: (_o = (_n = (_m = response.usage) == null ? void 0 : _m.prompt_tokens_details) == null ? void 0 : _n.cached_tokens) != null ? _o : 0
3853
+ inputTokens: {
3854
+ total: (_c = (_b16 = response.usage) == null ? void 0 : _b16.prompt_tokens) != null ? _c : 0,
3855
+ noCache: void 0,
3856
+ cacheRead: (_f = (_e = (_d = response.usage) == null ? void 0 : _d.prompt_tokens_details) == null ? void 0 : _e.cached_tokens) != null ? _f : void 0,
3857
+ cacheWrite: void 0
3858
+ },
3859
+ outputTokens: {
3860
+ total: (_h = (_g = response.usage) == null ? void 0 : _g.completion_tokens) != null ? _h : 0,
3861
+ text: void 0,
3862
+ reasoning: (_k = (_j = (_i = response.usage) == null ? void 0 : _i.completion_tokens_details) == null ? void 0 : _j.reasoning_tokens) != null ? _k : void 0
3863
+ }
2537
3864
  },
2538
3865
  warnings: [],
2539
3866
  response: {
@@ -2563,47 +3890,52 @@ var OpenRouterCompletionLanguageModel = class {
2563
3890
  abortSignal: options.abortSignal,
2564
3891
  fetch: this.config.fetch
2565
3892
  });
2566
- let finishReason = "other";
3893
+ let finishReason = createFinishReason("other");
2567
3894
  const usage = {
2568
- inputTokens: Number.NaN,
2569
- outputTokens: Number.NaN,
2570
- totalTokens: Number.NaN,
2571
- reasoningTokens: Number.NaN,
2572
- cachedInputTokens: Number.NaN
3895
+ inputTokens: {
3896
+ total: void 0,
3897
+ noCache: void 0,
3898
+ cacheRead: void 0,
3899
+ cacheWrite: void 0
3900
+ },
3901
+ outputTokens: {
3902
+ total: void 0,
3903
+ text: void 0,
3904
+ reasoning: void 0
3905
+ }
2573
3906
  };
2574
3907
  const openrouterUsage = {};
2575
3908
  return {
2576
3909
  stream: response.pipeThrough(
2577
3910
  new TransformStream({
2578
3911
  transform(chunk, controller) {
2579
- var _a15, _b, _c;
3912
+ var _a16, _b16, _c;
2580
3913
  if (!chunk.success) {
2581
- finishReason = "error";
3914
+ finishReason = createFinishReason("error");
2582
3915
  controller.enqueue({ type: "error", error: chunk.error });
2583
3916
  return;
2584
3917
  }
2585
3918
  const value = chunk.value;
2586
3919
  if ("error" in value) {
2587
- finishReason = "error";
3920
+ finishReason = createFinishReason("error");
2588
3921
  controller.enqueue({ type: "error", error: value.error });
2589
3922
  return;
2590
3923
  }
2591
3924
  if (value.usage != null) {
2592
- usage.inputTokens = value.usage.prompt_tokens;
2593
- usage.outputTokens = value.usage.completion_tokens;
2594
- usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
3925
+ usage.inputTokens.total = value.usage.prompt_tokens;
3926
+ usage.outputTokens.total = value.usage.completion_tokens;
2595
3927
  openrouterUsage.promptTokens = value.usage.prompt_tokens;
2596
3928
  if (value.usage.prompt_tokens_details) {
2597
- const cachedInputTokens = (_a15 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a15 : 0;
2598
- usage.cachedInputTokens = cachedInputTokens;
3929
+ const cachedInputTokens = (_a16 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a16 : 0;
3930
+ usage.inputTokens.cacheRead = cachedInputTokens;
2599
3931
  openrouterUsage.promptTokensDetails = {
2600
3932
  cachedTokens: cachedInputTokens
2601
3933
  };
2602
3934
  }
2603
3935
  openrouterUsage.completionTokens = value.usage.completion_tokens;
2604
3936
  if (value.usage.completion_tokens_details) {
2605
- const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
2606
- usage.reasoningTokens = reasoningTokens;
3937
+ const reasoningTokens = (_b16 = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b16 : 0;
3938
+ usage.outputTokens.reasoning = reasoningTokens;
2607
3939
  openrouterUsage.completionTokensDetails = {
2608
3940
  reasoningTokens
2609
3941
  };