@openrouter/ai-sdk-provider 1.5.4 → 2.0.1

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/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,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,17 +220,27 @@ 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
- var NoContentGeneratedError = class extends AISDKError {
242
+ var _b10;
243
+ var NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {
222
244
  // used in isInstance
223
245
  constructor({
224
246
  message = "No content generated."
@@ -230,22 +252,54 @@ var NoContentGeneratedError = class extends AISDKError {
230
252
  return AISDKError.hasMarker(error, marker10);
231
253
  }
232
254
  };
233
- _a10 = symbol10;
234
255
  var name10 = "AI_NoSuchModelError";
235
256
  var marker11 = `vercel.ai.error.${name10}`;
236
257
  var symbol11 = Symbol.for(marker11);
237
258
  var _a11;
238
- _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
+ };
239
276
  var name11 = "AI_TooManyEmbeddingValuesForCallError";
240
277
  var marker12 = `vercel.ai.error.${name11}`;
241
278
  var symbol12 = Symbol.for(marker12);
242
279
  var _a12;
243
- _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
+ };
244
297
  var name12 = "AI_TypeValidationError";
245
298
  var marker13 = `vercel.ai.error.${name12}`;
246
299
  var symbol13 = Symbol.for(marker13);
247
300
  var _a13;
248
- var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
301
+ var _b13;
302
+ var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
249
303
  constructor({ value, cause }) {
250
304
  super({
251
305
  name: name12,
@@ -273,16 +327,15 @@ Error message: ${getErrorMessage(cause)}`,
273
327
  value,
274
328
  cause
275
329
  }) {
276
- 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 });
277
331
  }
278
332
  };
279
- _a13 = symbol13;
280
- var TypeValidationError = _TypeValidationError;
281
333
  var name13 = "AI_UnsupportedFunctionalityError";
282
334
  var marker14 = `vercel.ai.error.${name13}`;
283
335
  var symbol14 = Symbol.for(marker14);
284
336
  var _a14;
285
- var UnsupportedFunctionalityError = class extends AISDKError {
337
+ var _b14;
338
+ var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {
286
339
  constructor({
287
340
  functionality,
288
341
  message = `'${functionality}' functionality not supported.`
@@ -295,9 +348,16 @@ var UnsupportedFunctionalityError = class extends AISDKError {
295
348
  return AISDKError.hasMarker(error, marker14);
296
349
  }
297
350
  };
298
- _a14 = symbol14;
299
351
 
300
- // 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
301
361
  var ParseError = class extends Error {
302
362
  constructor(message, options) {
303
363
  super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
@@ -388,7 +448,7 @@ function splitLines(chunk) {
388
448
  const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
389
449
  `, searchIndex);
390
450
  let lineEnd = -1;
391
- 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) {
392
452
  incompleteLine = chunk.slice(searchIndex);
393
453
  break;
394
454
  } else {
@@ -400,7 +460,7 @@ function splitLines(chunk) {
400
460
  return [lines, incompleteLine];
401
461
  }
402
462
 
403
- // 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
404
464
  var EventSourceParserStream = class extends TransformStream {
405
465
  constructor({ onError, onRetry, onComment } = {}) {
406
466
  let parser;
@@ -424,25 +484,7 @@ var EventSourceParserStream = class extends TransformStream {
424
484
  }
425
485
  };
426
486
 
427
- // node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
428
- import * as z4 from "zod/v4";
429
-
430
- // node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Options.js
431
- var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
432
-
433
- // node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/selectParser.js
434
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod";
435
-
436
- // 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
437
- import { ZodFirstPartyTypeKind } from "zod";
438
-
439
- // 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
440
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2 } from "zod";
441
-
442
- // 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
443
- var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
444
-
445
- // 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
446
488
  function combineHeaders(...headers) {
447
489
  return headers.reduce(
448
490
  (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
@@ -452,6 +494,37 @@ function combineHeaders(...headers) {
452
494
  function extractResponseHeaders(response) {
453
495
  return Object.fromEntries([...response.headers]);
454
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
+ };
455
528
  var createIdGenerator = ({
456
529
  prefix,
457
530
  size = 16,
@@ -506,11 +579,53 @@ function handleFetchError({
506
579
  }
507
580
  return error;
508
581
  }
509
- function removeUndefinedEntries(record) {
510
- return Object.fromEntries(
511
- 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(" ")
512
625
  );
626
+ return Object.fromEntries(normalizedHeaders.entries());
513
627
  }
628
+ var VERSION = true ? "4.0.1" : "0.0.0-test";
514
629
  function loadApiKey({
515
630
  apiKey,
516
631
  environmentVariableName,
@@ -579,34 +694,1195 @@ function filter(obj) {
579
694
  }
580
695
  function secureJsonParse(text) {
581
696
  const { stackTraceLimit } = Error;
582
- Error.stackTraceLimit = 0;
697
+ try {
698
+ Error.stackTraceLimit = 0;
699
+ } catch (e) {
700
+ return _parse(text);
701
+ }
583
702
  try {
584
703
  return _parse(text);
585
704
  } finally {
586
705
  Error.stackTraceLimit = stackTraceLimit;
587
706
  }
588
707
  }
589
- var validatorSymbol = Symbol.for("vercel.ai.validator");
590
- function validator(validate) {
591
- return { [validatorSymbol]: true, validate };
708
+ function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
709
+ if (jsonSchema2.type === "object") {
710
+ jsonSchema2.additionalProperties = false;
711
+ const properties = jsonSchema2.properties;
712
+ if (properties != null) {
713
+ for (const property in properties) {
714
+ properties[property] = addAdditionalPropertiesToJsonSchema(
715
+ properties[property]
716
+ );
717
+ }
718
+ }
719
+ }
720
+ if (jsonSchema2.type === "array" && jsonSchema2.items != null) {
721
+ if (Array.isArray(jsonSchema2.items)) {
722
+ jsonSchema2.items = jsonSchema2.items.map(
723
+ (item) => addAdditionalPropertiesToJsonSchema(item)
724
+ );
725
+ } else {
726
+ jsonSchema2.items = addAdditionalPropertiesToJsonSchema(
727
+ jsonSchema2.items
728
+ );
729
+ }
730
+ }
731
+ return jsonSchema2;
732
+ }
733
+ var ignoreOverride = Symbol(
734
+ "Let zodToJsonSchema decide on which parser to use"
735
+ );
736
+ var defaultOptions = {
737
+ name: void 0,
738
+ $refStrategy: "root",
739
+ basePath: ["#"],
740
+ effectStrategy: "input",
741
+ pipeStrategy: "all",
742
+ dateStrategy: "format:date-time",
743
+ mapStrategy: "entries",
744
+ removeAdditionalStrategy: "passthrough",
745
+ allowedAdditionalProperties: true,
746
+ rejectedAdditionalProperties: false,
747
+ definitionPath: "definitions",
748
+ strictUnions: false,
749
+ definitions: {},
750
+ errorMessages: false,
751
+ patternStrategy: "escape",
752
+ applyRegexFlags: false,
753
+ emailStrategy: "format:email",
754
+ base64Strategy: "contentEncoding:base64",
755
+ nameStrategy: "ref"
756
+ };
757
+ var getDefaultOptions = (options) => typeof options === "string" ? __spreadProps(__spreadValues({}, defaultOptions), {
758
+ name: options
759
+ }) : __spreadValues(__spreadValues({}, defaultOptions), options);
760
+ function parseAnyDef() {
761
+ return {};
762
+ }
763
+ function parseArrayDef(def, refs) {
764
+ var _a22, _b22, _c;
765
+ const res = {
766
+ type: "array"
767
+ };
768
+ 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) {
769
+ res.items = parseDef(def.type._def, __spreadProps(__spreadValues({}, refs), {
770
+ currentPath: [...refs.currentPath, "items"]
771
+ }));
772
+ }
773
+ if (def.minLength) {
774
+ res.minItems = def.minLength.value;
775
+ }
776
+ if (def.maxLength) {
777
+ res.maxItems = def.maxLength.value;
778
+ }
779
+ if (def.exactLength) {
780
+ res.minItems = def.exactLength.value;
781
+ res.maxItems = def.exactLength.value;
782
+ }
783
+ return res;
784
+ }
785
+ function parseBigintDef(def) {
786
+ const res = {
787
+ type: "integer",
788
+ format: "int64"
789
+ };
790
+ if (!def.checks) return res;
791
+ for (const check of def.checks) {
792
+ switch (check.kind) {
793
+ case "min":
794
+ if (check.inclusive) {
795
+ res.minimum = check.value;
796
+ } else {
797
+ res.exclusiveMinimum = check.value;
798
+ }
799
+ break;
800
+ case "max":
801
+ if (check.inclusive) {
802
+ res.maximum = check.value;
803
+ } else {
804
+ res.exclusiveMaximum = check.value;
805
+ }
806
+ break;
807
+ case "multipleOf":
808
+ res.multipleOf = check.value;
809
+ break;
810
+ }
811
+ }
812
+ return res;
592
813
  }
593
- function isValidator(value) {
594
- return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
814
+ function parseBooleanDef() {
815
+ return { type: "boolean" };
595
816
  }
596
- function asValidator(value) {
597
- return isValidator(value) ? value : standardSchemaValidator(value);
817
+ function parseBrandedDef(_def, refs) {
818
+ return parseDef(_def.type._def, refs);
598
819
  }
599
- function standardSchemaValidator(standardSchema) {
600
- return validator(async (value) => {
601
- const result = await standardSchema["~standard"].validate(value);
602
- return result.issues == null ? { success: true, value: result.value } : {
603
- success: false,
604
- error: new TypeValidationError({
605
- value,
606
- cause: result.issues
607
- })
820
+ var parseCatchDef = (def, refs) => {
821
+ return parseDef(def.innerType._def, refs);
822
+ };
823
+ function parseDateDef(def, refs, overrideDateStrategy) {
824
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
825
+ if (Array.isArray(strategy)) {
826
+ return {
827
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
608
828
  };
829
+ }
830
+ switch (strategy) {
831
+ case "string":
832
+ case "format:date-time":
833
+ return {
834
+ type: "string",
835
+ format: "date-time"
836
+ };
837
+ case "format:date":
838
+ return {
839
+ type: "string",
840
+ format: "date"
841
+ };
842
+ case "integer":
843
+ return integerDateParser(def);
844
+ }
845
+ }
846
+ var integerDateParser = (def) => {
847
+ const res = {
848
+ type: "integer",
849
+ format: "unix-time"
850
+ };
851
+ for (const check of def.checks) {
852
+ switch (check.kind) {
853
+ case "min":
854
+ res.minimum = check.value;
855
+ break;
856
+ case "max":
857
+ res.maximum = check.value;
858
+ break;
859
+ }
860
+ }
861
+ return res;
862
+ };
863
+ function parseDefaultDef(_def, refs) {
864
+ return __spreadProps(__spreadValues({}, parseDef(_def.innerType._def, refs)), {
865
+ default: _def.defaultValue()
866
+ });
867
+ }
868
+ function parseEffectsDef(_def, refs) {
869
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
870
+ }
871
+ function parseEnumDef(def) {
872
+ return {
873
+ type: "string",
874
+ enum: Array.from(def.values)
875
+ };
876
+ }
877
+ var isJsonSchema7AllOfType = (type) => {
878
+ if ("type" in type && type.type === "string") return false;
879
+ return "allOf" in type;
880
+ };
881
+ function parseIntersectionDef(def, refs) {
882
+ const allOf = [
883
+ parseDef(def.left._def, __spreadProps(__spreadValues({}, refs), {
884
+ currentPath: [...refs.currentPath, "allOf", "0"]
885
+ })),
886
+ parseDef(def.right._def, __spreadProps(__spreadValues({}, refs), {
887
+ currentPath: [...refs.currentPath, "allOf", "1"]
888
+ }))
889
+ ].filter((x) => !!x);
890
+ const mergedAllOf = [];
891
+ allOf.forEach((schema) => {
892
+ if (isJsonSchema7AllOfType(schema)) {
893
+ mergedAllOf.push(...schema.allOf);
894
+ } else {
895
+ let nestedSchema = schema;
896
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
897
+ const _a16 = schema, { additionalProperties } = _a16, rest = __objRest(_a16, ["additionalProperties"]);
898
+ nestedSchema = rest;
899
+ }
900
+ mergedAllOf.push(nestedSchema);
901
+ }
609
902
  });
903
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
904
+ }
905
+ function parseLiteralDef(def) {
906
+ const parsedType = typeof def.value;
907
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
908
+ return {
909
+ type: Array.isArray(def.value) ? "array" : "object"
910
+ };
911
+ }
912
+ return {
913
+ type: parsedType === "bigint" ? "integer" : parsedType,
914
+ const: def.value
915
+ };
916
+ }
917
+ var emojiRegex = void 0;
918
+ var zodPatterns = {
919
+ /**
920
+ * `c` was changed to `[cC]` to replicate /i flag
921
+ */
922
+ cuid: /^[cC][^\s-]{8,}$/,
923
+ cuid2: /^[0-9a-z]+$/,
924
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
925
+ /**
926
+ * `a-z` was added to replicate /i flag
927
+ */
928
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
929
+ /**
930
+ * Constructed a valid Unicode RegExp
931
+ *
932
+ * Lazily instantiate since this type of regex isn't supported
933
+ * in all envs (e.g. React Native).
934
+ *
935
+ * See:
936
+ * https://github.com/colinhacks/zod/issues/2433
937
+ * Fix in Zod:
938
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
939
+ */
940
+ emoji: () => {
941
+ if (emojiRegex === void 0) {
942
+ emojiRegex = RegExp(
943
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
944
+ "u"
945
+ );
946
+ }
947
+ return emojiRegex;
948
+ },
949
+ /**
950
+ * Unused
951
+ */
952
+ 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}$/,
953
+ /**
954
+ * Unused
955
+ */
956
+ 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])$/,
957
+ 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])$/,
958
+ /**
959
+ * Unused
960
+ */
961
+ 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})))$/,
962
+ 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])$/,
963
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
964
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
965
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
966
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
967
+ };
968
+ function parseStringDef(def, refs) {
969
+ const res = {
970
+ type: "string"
971
+ };
972
+ if (def.checks) {
973
+ for (const check of def.checks) {
974
+ switch (check.kind) {
975
+ case "min":
976
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
977
+ break;
978
+ case "max":
979
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
980
+ break;
981
+ case "email":
982
+ switch (refs.emailStrategy) {
983
+ case "format:email":
984
+ addFormat(res, "email", check.message, refs);
985
+ break;
986
+ case "format:idn-email":
987
+ addFormat(res, "idn-email", check.message, refs);
988
+ break;
989
+ case "pattern:zod":
990
+ addPattern(res, zodPatterns.email, check.message, refs);
991
+ break;
992
+ }
993
+ break;
994
+ case "url":
995
+ addFormat(res, "uri", check.message, refs);
996
+ break;
997
+ case "uuid":
998
+ addFormat(res, "uuid", check.message, refs);
999
+ break;
1000
+ case "regex":
1001
+ addPattern(res, check.regex, check.message, refs);
1002
+ break;
1003
+ case "cuid":
1004
+ addPattern(res, zodPatterns.cuid, check.message, refs);
1005
+ break;
1006
+ case "cuid2":
1007
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
1008
+ break;
1009
+ case "startsWith":
1010
+ addPattern(
1011
+ res,
1012
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
1013
+ check.message,
1014
+ refs
1015
+ );
1016
+ break;
1017
+ case "endsWith":
1018
+ addPattern(
1019
+ res,
1020
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
1021
+ check.message,
1022
+ refs
1023
+ );
1024
+ break;
1025
+ case "datetime":
1026
+ addFormat(res, "date-time", check.message, refs);
1027
+ break;
1028
+ case "date":
1029
+ addFormat(res, "date", check.message, refs);
1030
+ break;
1031
+ case "time":
1032
+ addFormat(res, "time", check.message, refs);
1033
+ break;
1034
+ case "duration":
1035
+ addFormat(res, "duration", check.message, refs);
1036
+ break;
1037
+ case "length":
1038
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1039
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1040
+ break;
1041
+ case "includes": {
1042
+ addPattern(
1043
+ res,
1044
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
1045
+ check.message,
1046
+ refs
1047
+ );
1048
+ break;
1049
+ }
1050
+ case "ip": {
1051
+ if (check.version !== "v6") {
1052
+ addFormat(res, "ipv4", check.message, refs);
1053
+ }
1054
+ if (check.version !== "v4") {
1055
+ addFormat(res, "ipv6", check.message, refs);
1056
+ }
1057
+ break;
1058
+ }
1059
+ case "base64url":
1060
+ addPattern(res, zodPatterns.base64url, check.message, refs);
1061
+ break;
1062
+ case "jwt":
1063
+ addPattern(res, zodPatterns.jwt, check.message, refs);
1064
+ break;
1065
+ case "cidr": {
1066
+ if (check.version !== "v6") {
1067
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1068
+ }
1069
+ if (check.version !== "v4") {
1070
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1071
+ }
1072
+ break;
1073
+ }
1074
+ case "emoji":
1075
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
1076
+ break;
1077
+ case "ulid": {
1078
+ addPattern(res, zodPatterns.ulid, check.message, refs);
1079
+ break;
1080
+ }
1081
+ case "base64": {
1082
+ switch (refs.base64Strategy) {
1083
+ case "format:binary": {
1084
+ addFormat(res, "binary", check.message, refs);
1085
+ break;
1086
+ }
1087
+ case "contentEncoding:base64": {
1088
+ res.contentEncoding = "base64";
1089
+ break;
1090
+ }
1091
+ case "pattern:zod": {
1092
+ addPattern(res, zodPatterns.base64, check.message, refs);
1093
+ break;
1094
+ }
1095
+ }
1096
+ break;
1097
+ }
1098
+ case "nanoid": {
1099
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
1100
+ }
1101
+ case "toLowerCase":
1102
+ case "toUpperCase":
1103
+ case "trim":
1104
+ break;
1105
+ default:
1106
+ /* @__PURE__ */ ((_) => {
1107
+ })(check);
1108
+ }
1109
+ }
1110
+ }
1111
+ return res;
1112
+ }
1113
+ function escapeLiteralCheckValue(literal, refs) {
1114
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1115
+ }
1116
+ var ALPHA_NUMERIC = new Set(
1117
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1118
+ );
1119
+ function escapeNonAlphaNumeric(source) {
1120
+ let result = "";
1121
+ for (let i = 0; i < source.length; i++) {
1122
+ if (!ALPHA_NUMERIC.has(source[i])) {
1123
+ result += "\\";
1124
+ }
1125
+ result += source[i];
1126
+ }
1127
+ return result;
1128
+ }
1129
+ function addFormat(schema, value, message, refs) {
1130
+ var _a22;
1131
+ if (schema.format || ((_a22 = schema.anyOf) == null ? void 0 : _a22.some((x) => x.format))) {
1132
+ if (!schema.anyOf) {
1133
+ schema.anyOf = [];
1134
+ }
1135
+ if (schema.format) {
1136
+ schema.anyOf.push({
1137
+ format: schema.format
1138
+ });
1139
+ delete schema.format;
1140
+ }
1141
+ schema.anyOf.push(__spreadValues({
1142
+ format: value
1143
+ }, message && refs.errorMessages && { errorMessage: { format: message } }));
1144
+ } else {
1145
+ schema.format = value;
1146
+ }
1147
+ }
1148
+ function addPattern(schema, regex, message, refs) {
1149
+ var _a22;
1150
+ if (schema.pattern || ((_a22 = schema.allOf) == null ? void 0 : _a22.some((x) => x.pattern))) {
1151
+ if (!schema.allOf) {
1152
+ schema.allOf = [];
1153
+ }
1154
+ if (schema.pattern) {
1155
+ schema.allOf.push({
1156
+ pattern: schema.pattern
1157
+ });
1158
+ delete schema.pattern;
1159
+ }
1160
+ schema.allOf.push(__spreadValues({
1161
+ pattern: stringifyRegExpWithFlags(regex, refs)
1162
+ }, message && refs.errorMessages && { errorMessage: { pattern: message } }));
1163
+ } else {
1164
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
1165
+ }
1166
+ }
1167
+ function stringifyRegExpWithFlags(regex, refs) {
1168
+ var _a22;
1169
+ if (!refs.applyRegexFlags || !regex.flags) {
1170
+ return regex.source;
1171
+ }
1172
+ const flags = {
1173
+ i: regex.flags.includes("i"),
1174
+ // Case-insensitive
1175
+ m: regex.flags.includes("m"),
1176
+ // `^` and `$` matches adjacent to newline characters
1177
+ s: regex.flags.includes("s")
1178
+ // `.` matches newlines
1179
+ };
1180
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1181
+ let pattern = "";
1182
+ let isEscaped = false;
1183
+ let inCharGroup = false;
1184
+ let inCharRange = false;
1185
+ for (let i = 0; i < source.length; i++) {
1186
+ if (isEscaped) {
1187
+ pattern += source[i];
1188
+ isEscaped = false;
1189
+ continue;
1190
+ }
1191
+ if (flags.i) {
1192
+ if (inCharGroup) {
1193
+ if (source[i].match(/[a-z]/)) {
1194
+ if (inCharRange) {
1195
+ pattern += source[i];
1196
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1197
+ inCharRange = false;
1198
+ } else if (source[i + 1] === "-" && ((_a22 = source[i + 2]) == null ? void 0 : _a22.match(/[a-z]/))) {
1199
+ pattern += source[i];
1200
+ inCharRange = true;
1201
+ } else {
1202
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1203
+ }
1204
+ continue;
1205
+ }
1206
+ } else if (source[i].match(/[a-z]/)) {
1207
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1208
+ continue;
1209
+ }
1210
+ }
1211
+ if (flags.m) {
1212
+ if (source[i] === "^") {
1213
+ pattern += `(^|(?<=[\r
1214
+ ]))`;
1215
+ continue;
1216
+ } else if (source[i] === "$") {
1217
+ pattern += `($|(?=[\r
1218
+ ]))`;
1219
+ continue;
1220
+ }
1221
+ }
1222
+ if (flags.s && source[i] === ".") {
1223
+ pattern += inCharGroup ? `${source[i]}\r
1224
+ ` : `[${source[i]}\r
1225
+ ]`;
1226
+ continue;
1227
+ }
1228
+ pattern += source[i];
1229
+ if (source[i] === "\\") {
1230
+ isEscaped = true;
1231
+ } else if (inCharGroup && source[i] === "]") {
1232
+ inCharGroup = false;
1233
+ } else if (!inCharGroup && source[i] === "[") {
1234
+ inCharGroup = true;
1235
+ }
1236
+ }
1237
+ try {
1238
+ new RegExp(pattern);
1239
+ } catch (e) {
1240
+ console.warn(
1241
+ `Could not convert regex pattern at ${refs.currentPath.join(
1242
+ "/"
1243
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1244
+ );
1245
+ return regex.source;
1246
+ }
1247
+ return pattern;
1248
+ }
1249
+ function parseRecordDef(def, refs) {
1250
+ var _a22, _b22, _c, _d, _e, _f;
1251
+ const schema = {
1252
+ type: "object",
1253
+ additionalProperties: (_a22 = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
1254
+ currentPath: [...refs.currentPath, "additionalProperties"]
1255
+ }))) != null ? _a22 : refs.allowedAdditionalProperties
1256
+ };
1257
+ if (((_b22 = def.keyType) == null ? void 0 : _b22._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1258
+ const _a16 = parseStringDef(def.keyType._def, refs), { type } = _a16, keyType = __objRest(_a16, ["type"]);
1259
+ return __spreadProps(__spreadValues({}, schema), {
1260
+ propertyNames: keyType
1261
+ });
1262
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1263
+ return __spreadProps(__spreadValues({}, schema), {
1264
+ propertyNames: {
1265
+ enum: def.keyType._def.values
1266
+ }
1267
+ });
1268
+ } 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)) {
1269
+ const _b16 = parseBrandedDef(
1270
+ def.keyType._def,
1271
+ refs
1272
+ ), { type } = _b16, keyType = __objRest(_b16, ["type"]);
1273
+ return __spreadProps(__spreadValues({}, schema), {
1274
+ propertyNames: keyType
1275
+ });
1276
+ }
1277
+ return schema;
1278
+ }
1279
+ function parseMapDef(def, refs) {
1280
+ if (refs.mapStrategy === "record") {
1281
+ return parseRecordDef(def, refs);
1282
+ }
1283
+ const keys = parseDef(def.keyType._def, __spreadProps(__spreadValues({}, refs), {
1284
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1285
+ })) || parseAnyDef();
1286
+ const values = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
1287
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1288
+ })) || parseAnyDef();
1289
+ return {
1290
+ type: "array",
1291
+ maxItems: 125,
1292
+ items: {
1293
+ type: "array",
1294
+ items: [keys, values],
1295
+ minItems: 2,
1296
+ maxItems: 2
1297
+ }
1298
+ };
1299
+ }
1300
+ function parseNativeEnumDef(def) {
1301
+ const object = def.values;
1302
+ const actualKeys = Object.keys(def.values).filter((key) => {
1303
+ return typeof object[object[key]] !== "number";
1304
+ });
1305
+ const actualValues = actualKeys.map((key) => object[key]);
1306
+ const parsedTypes = Array.from(
1307
+ new Set(actualValues.map((values) => typeof values))
1308
+ );
1309
+ return {
1310
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1311
+ enum: actualValues
1312
+ };
1313
+ }
1314
+ function parseNeverDef() {
1315
+ return { not: parseAnyDef() };
1316
+ }
1317
+ function parseNullDef() {
1318
+ return {
1319
+ type: "null"
1320
+ };
1321
+ }
1322
+ var primitiveMappings = {
1323
+ ZodString: "string",
1324
+ ZodNumber: "number",
1325
+ ZodBigInt: "integer",
1326
+ ZodBoolean: "boolean",
1327
+ ZodNull: "null"
1328
+ };
1329
+ function parseUnionDef(def, refs) {
1330
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1331
+ if (options.every(
1332
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1333
+ )) {
1334
+ const types = options.reduce((types2, x) => {
1335
+ const type = primitiveMappings[x._def.typeName];
1336
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1337
+ }, []);
1338
+ return {
1339
+ type: types.length > 1 ? types : types[0]
1340
+ };
1341
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1342
+ const types = options.reduce(
1343
+ (acc, x) => {
1344
+ const type = typeof x._def.value;
1345
+ switch (type) {
1346
+ case "string":
1347
+ case "number":
1348
+ case "boolean":
1349
+ return [...acc, type];
1350
+ case "bigint":
1351
+ return [...acc, "integer"];
1352
+ case "object":
1353
+ if (x._def.value === null) return [...acc, "null"];
1354
+ case "symbol":
1355
+ case "undefined":
1356
+ case "function":
1357
+ default:
1358
+ return acc;
1359
+ }
1360
+ },
1361
+ []
1362
+ );
1363
+ if (types.length === options.length) {
1364
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1365
+ return {
1366
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1367
+ enum: options.reduce(
1368
+ (acc, x) => {
1369
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1370
+ },
1371
+ []
1372
+ )
1373
+ };
1374
+ }
1375
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1376
+ return {
1377
+ type: "string",
1378
+ enum: options.reduce(
1379
+ (acc, x) => [
1380
+ ...acc,
1381
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1382
+ ],
1383
+ []
1384
+ )
1385
+ };
1386
+ }
1387
+ return asAnyOf(def, refs);
1388
+ }
1389
+ var asAnyOf = (def, refs) => {
1390
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1391
+ (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), {
1392
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1393
+ }))
1394
+ ).filter(
1395
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1396
+ );
1397
+ return anyOf.length ? { anyOf } : void 0;
1398
+ };
1399
+ function parseNullableDef(def, refs) {
1400
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1401
+ def.innerType._def.typeName
1402
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1403
+ return {
1404
+ type: [
1405
+ primitiveMappings[def.innerType._def.typeName],
1406
+ "null"
1407
+ ]
1408
+ };
1409
+ }
1410
+ const base = parseDef(def.innerType._def, __spreadProps(__spreadValues({}, refs), {
1411
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1412
+ }));
1413
+ return base && { anyOf: [base, { type: "null" }] };
1414
+ }
1415
+ function parseNumberDef(def) {
1416
+ const res = {
1417
+ type: "number"
1418
+ };
1419
+ if (!def.checks) return res;
1420
+ for (const check of def.checks) {
1421
+ switch (check.kind) {
1422
+ case "int":
1423
+ res.type = "integer";
1424
+ break;
1425
+ case "min":
1426
+ if (check.inclusive) {
1427
+ res.minimum = check.value;
1428
+ } else {
1429
+ res.exclusiveMinimum = check.value;
1430
+ }
1431
+ break;
1432
+ case "max":
1433
+ if (check.inclusive) {
1434
+ res.maximum = check.value;
1435
+ } else {
1436
+ res.exclusiveMaximum = check.value;
1437
+ }
1438
+ break;
1439
+ case "multipleOf":
1440
+ res.multipleOf = check.value;
1441
+ break;
1442
+ }
1443
+ }
1444
+ return res;
1445
+ }
1446
+ function parseObjectDef(def, refs) {
1447
+ const result = {
1448
+ type: "object",
1449
+ properties: {}
1450
+ };
1451
+ const required = [];
1452
+ const shape = def.shape();
1453
+ for (const propName in shape) {
1454
+ let propDef = shape[propName];
1455
+ if (propDef === void 0 || propDef._def === void 0) {
1456
+ continue;
1457
+ }
1458
+ const propOptional = safeIsOptional(propDef);
1459
+ const parsedDef = parseDef(propDef._def, __spreadProps(__spreadValues({}, refs), {
1460
+ currentPath: [...refs.currentPath, "properties", propName],
1461
+ propertyPath: [...refs.currentPath, "properties", propName]
1462
+ }));
1463
+ if (parsedDef === void 0) {
1464
+ continue;
1465
+ }
1466
+ result.properties[propName] = parsedDef;
1467
+ if (!propOptional) {
1468
+ required.push(propName);
1469
+ }
1470
+ }
1471
+ if (required.length) {
1472
+ result.required = required;
1473
+ }
1474
+ const additionalProperties = decideAdditionalProperties(def, refs);
1475
+ if (additionalProperties !== void 0) {
1476
+ result.additionalProperties = additionalProperties;
1477
+ }
1478
+ return result;
1479
+ }
1480
+ function decideAdditionalProperties(def, refs) {
1481
+ if (def.catchall._def.typeName !== "ZodNever") {
1482
+ return parseDef(def.catchall._def, __spreadProps(__spreadValues({}, refs), {
1483
+ currentPath: [...refs.currentPath, "additionalProperties"]
1484
+ }));
1485
+ }
1486
+ switch (def.unknownKeys) {
1487
+ case "passthrough":
1488
+ return refs.allowedAdditionalProperties;
1489
+ case "strict":
1490
+ return refs.rejectedAdditionalProperties;
1491
+ case "strip":
1492
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1493
+ }
1494
+ }
1495
+ function safeIsOptional(schema) {
1496
+ try {
1497
+ return schema.isOptional();
1498
+ } catch (e) {
1499
+ return true;
1500
+ }
1501
+ }
1502
+ var parseOptionalDef = (def, refs) => {
1503
+ var _a22;
1504
+ if (refs.currentPath.toString() === ((_a22 = refs.propertyPath) == null ? void 0 : _a22.toString())) {
1505
+ return parseDef(def.innerType._def, refs);
1506
+ }
1507
+ const innerSchema = parseDef(def.innerType._def, __spreadProps(__spreadValues({}, refs), {
1508
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1509
+ }));
1510
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1511
+ };
1512
+ var parsePipelineDef = (def, refs) => {
1513
+ if (refs.pipeStrategy === "input") {
1514
+ return parseDef(def.in._def, refs);
1515
+ } else if (refs.pipeStrategy === "output") {
1516
+ return parseDef(def.out._def, refs);
1517
+ }
1518
+ const a = parseDef(def.in._def, __spreadProps(__spreadValues({}, refs), {
1519
+ currentPath: [...refs.currentPath, "allOf", "0"]
1520
+ }));
1521
+ const b = parseDef(def.out._def, __spreadProps(__spreadValues({}, refs), {
1522
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1523
+ }));
1524
+ return {
1525
+ allOf: [a, b].filter((x) => x !== void 0)
1526
+ };
1527
+ };
1528
+ function parsePromiseDef(def, refs) {
1529
+ return parseDef(def.type._def, refs);
1530
+ }
1531
+ function parseSetDef(def, refs) {
1532
+ const items = parseDef(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
1533
+ currentPath: [...refs.currentPath, "items"]
1534
+ }));
1535
+ const schema = {
1536
+ type: "array",
1537
+ uniqueItems: true,
1538
+ items
1539
+ };
1540
+ if (def.minSize) {
1541
+ schema.minItems = def.minSize.value;
1542
+ }
1543
+ if (def.maxSize) {
1544
+ schema.maxItems = def.maxSize.value;
1545
+ }
1546
+ return schema;
1547
+ }
1548
+ function parseTupleDef(def, refs) {
1549
+ if (def.rest) {
1550
+ return {
1551
+ type: "array",
1552
+ minItems: def.items.length,
1553
+ items: def.items.map(
1554
+ (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), {
1555
+ currentPath: [...refs.currentPath, "items", `${i}`]
1556
+ }))
1557
+ ).reduce(
1558
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1559
+ []
1560
+ ),
1561
+ additionalItems: parseDef(def.rest._def, __spreadProps(__spreadValues({}, refs), {
1562
+ currentPath: [...refs.currentPath, "additionalItems"]
1563
+ }))
1564
+ };
1565
+ } else {
1566
+ return {
1567
+ type: "array",
1568
+ minItems: def.items.length,
1569
+ maxItems: def.items.length,
1570
+ items: def.items.map(
1571
+ (x, i) => parseDef(x._def, __spreadProps(__spreadValues({}, refs), {
1572
+ currentPath: [...refs.currentPath, "items", `${i}`]
1573
+ }))
1574
+ ).reduce(
1575
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1576
+ []
1577
+ )
1578
+ };
1579
+ }
1580
+ }
1581
+ function parseUndefinedDef() {
1582
+ return {
1583
+ not: parseAnyDef()
1584
+ };
1585
+ }
1586
+ function parseUnknownDef() {
1587
+ return parseAnyDef();
1588
+ }
1589
+ var parseReadonlyDef = (def, refs) => {
1590
+ return parseDef(def.innerType._def, refs);
1591
+ };
1592
+ var selectParser = (def, typeName, refs) => {
1593
+ switch (typeName) {
1594
+ case ZodFirstPartyTypeKind3.ZodString:
1595
+ return parseStringDef(def, refs);
1596
+ case ZodFirstPartyTypeKind3.ZodNumber:
1597
+ return parseNumberDef(def);
1598
+ case ZodFirstPartyTypeKind3.ZodObject:
1599
+ return parseObjectDef(def, refs);
1600
+ case ZodFirstPartyTypeKind3.ZodBigInt:
1601
+ return parseBigintDef(def);
1602
+ case ZodFirstPartyTypeKind3.ZodBoolean:
1603
+ return parseBooleanDef();
1604
+ case ZodFirstPartyTypeKind3.ZodDate:
1605
+ return parseDateDef(def, refs);
1606
+ case ZodFirstPartyTypeKind3.ZodUndefined:
1607
+ return parseUndefinedDef();
1608
+ case ZodFirstPartyTypeKind3.ZodNull:
1609
+ return parseNullDef();
1610
+ case ZodFirstPartyTypeKind3.ZodArray:
1611
+ return parseArrayDef(def, refs);
1612
+ case ZodFirstPartyTypeKind3.ZodUnion:
1613
+ case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1614
+ return parseUnionDef(def, refs);
1615
+ case ZodFirstPartyTypeKind3.ZodIntersection:
1616
+ return parseIntersectionDef(def, refs);
1617
+ case ZodFirstPartyTypeKind3.ZodTuple:
1618
+ return parseTupleDef(def, refs);
1619
+ case ZodFirstPartyTypeKind3.ZodRecord:
1620
+ return parseRecordDef(def, refs);
1621
+ case ZodFirstPartyTypeKind3.ZodLiteral:
1622
+ return parseLiteralDef(def);
1623
+ case ZodFirstPartyTypeKind3.ZodEnum:
1624
+ return parseEnumDef(def);
1625
+ case ZodFirstPartyTypeKind3.ZodNativeEnum:
1626
+ return parseNativeEnumDef(def);
1627
+ case ZodFirstPartyTypeKind3.ZodNullable:
1628
+ return parseNullableDef(def, refs);
1629
+ case ZodFirstPartyTypeKind3.ZodOptional:
1630
+ return parseOptionalDef(def, refs);
1631
+ case ZodFirstPartyTypeKind3.ZodMap:
1632
+ return parseMapDef(def, refs);
1633
+ case ZodFirstPartyTypeKind3.ZodSet:
1634
+ return parseSetDef(def, refs);
1635
+ case ZodFirstPartyTypeKind3.ZodLazy:
1636
+ return () => def.getter()._def;
1637
+ case ZodFirstPartyTypeKind3.ZodPromise:
1638
+ return parsePromiseDef(def, refs);
1639
+ case ZodFirstPartyTypeKind3.ZodNaN:
1640
+ case ZodFirstPartyTypeKind3.ZodNever:
1641
+ return parseNeverDef();
1642
+ case ZodFirstPartyTypeKind3.ZodEffects:
1643
+ return parseEffectsDef(def, refs);
1644
+ case ZodFirstPartyTypeKind3.ZodAny:
1645
+ return parseAnyDef();
1646
+ case ZodFirstPartyTypeKind3.ZodUnknown:
1647
+ return parseUnknownDef();
1648
+ case ZodFirstPartyTypeKind3.ZodDefault:
1649
+ return parseDefaultDef(def, refs);
1650
+ case ZodFirstPartyTypeKind3.ZodBranded:
1651
+ return parseBrandedDef(def, refs);
1652
+ case ZodFirstPartyTypeKind3.ZodReadonly:
1653
+ return parseReadonlyDef(def, refs);
1654
+ case ZodFirstPartyTypeKind3.ZodCatch:
1655
+ return parseCatchDef(def, refs);
1656
+ case ZodFirstPartyTypeKind3.ZodPipeline:
1657
+ return parsePipelineDef(def, refs);
1658
+ case ZodFirstPartyTypeKind3.ZodFunction:
1659
+ case ZodFirstPartyTypeKind3.ZodVoid:
1660
+ case ZodFirstPartyTypeKind3.ZodSymbol:
1661
+ return void 0;
1662
+ default:
1663
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
1664
+ }
1665
+ };
1666
+ var getRelativePath = (pathA, pathB) => {
1667
+ let i = 0;
1668
+ for (; i < pathA.length && i < pathB.length; i++) {
1669
+ if (pathA[i] !== pathB[i]) break;
1670
+ }
1671
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1672
+ };
1673
+ function parseDef(def, refs, forceResolution = false) {
1674
+ var _a22;
1675
+ const seenItem = refs.seen.get(def);
1676
+ if (refs.override) {
1677
+ const overrideResult = (_a22 = refs.override) == null ? void 0 : _a22.call(
1678
+ refs,
1679
+ def,
1680
+ refs,
1681
+ seenItem,
1682
+ forceResolution
1683
+ );
1684
+ if (overrideResult !== ignoreOverride) {
1685
+ return overrideResult;
1686
+ }
1687
+ }
1688
+ if (seenItem && !forceResolution) {
1689
+ const seenSchema = get$ref(seenItem, refs);
1690
+ if (seenSchema !== void 0) {
1691
+ return seenSchema;
1692
+ }
1693
+ }
1694
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1695
+ refs.seen.set(def, newItem);
1696
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1697
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1698
+ if (jsonSchema2) {
1699
+ addMeta(def, refs, jsonSchema2);
1700
+ }
1701
+ if (refs.postProcess) {
1702
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1703
+ newItem.jsonSchema = jsonSchema2;
1704
+ return postProcessResult;
1705
+ }
1706
+ newItem.jsonSchema = jsonSchema2;
1707
+ return jsonSchema2;
1708
+ }
1709
+ var get$ref = (item, refs) => {
1710
+ switch (refs.$refStrategy) {
1711
+ case "root":
1712
+ return { $ref: item.path.join("/") };
1713
+ case "relative":
1714
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1715
+ case "none":
1716
+ case "seen": {
1717
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1718
+ console.warn(
1719
+ `Recursive reference detected at ${refs.currentPath.join(
1720
+ "/"
1721
+ )}! Defaulting to any`
1722
+ );
1723
+ return parseAnyDef();
1724
+ }
1725
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1726
+ }
1727
+ }
1728
+ };
1729
+ var addMeta = (def, refs, jsonSchema2) => {
1730
+ if (def.description) {
1731
+ jsonSchema2.description = def.description;
1732
+ }
1733
+ return jsonSchema2;
1734
+ };
1735
+ var getRefs = (options) => {
1736
+ const _options = getDefaultOptions(options);
1737
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1738
+ return __spreadProps(__spreadValues({}, _options), {
1739
+ currentPath,
1740
+ propertyPath: void 0,
1741
+ seen: new Map(
1742
+ Object.entries(_options.definitions).map(([name22, def]) => [
1743
+ def._def,
1744
+ {
1745
+ def: def._def,
1746
+ path: [..._options.basePath, _options.definitionPath, name22],
1747
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1748
+ jsonSchema: void 0
1749
+ }
1750
+ ])
1751
+ )
1752
+ });
1753
+ };
1754
+ var zod3ToJsonSchema = (schema, options) => {
1755
+ var _a22;
1756
+ const refs = getRefs(options);
1757
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1758
+ (acc, [name32, schema2]) => {
1759
+ var _a32;
1760
+ return __spreadProps(__spreadValues({}, acc), {
1761
+ [name32]: (_a32 = parseDef(
1762
+ schema2._def,
1763
+ __spreadProps(__spreadValues({}, refs), {
1764
+ currentPath: [...refs.basePath, refs.definitionPath, name32]
1765
+ }),
1766
+ true
1767
+ )) != null ? _a32 : parseAnyDef()
1768
+ });
1769
+ },
1770
+ {}
1771
+ ) : void 0;
1772
+ const name22 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1773
+ const main = (_a22 = parseDef(
1774
+ schema._def,
1775
+ name22 === void 0 ? refs : __spreadProps(__spreadValues({}, refs), {
1776
+ currentPath: [...refs.basePath, refs.definitionPath, name22]
1777
+ }),
1778
+ false
1779
+ )) != null ? _a22 : parseAnyDef();
1780
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1781
+ if (title !== void 0) {
1782
+ main.title = title;
1783
+ }
1784
+ const combined = name22 === void 0 ? definitions ? __spreadProps(__spreadValues({}, main), {
1785
+ [refs.definitionPath]: definitions
1786
+ }) : main : {
1787
+ $ref: [
1788
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1789
+ refs.definitionPath,
1790
+ name22
1791
+ ].join("/"),
1792
+ [refs.definitionPath]: __spreadProps(__spreadValues({}, definitions), {
1793
+ [name22]: main
1794
+ })
1795
+ };
1796
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1797
+ return combined;
1798
+ };
1799
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
1800
+ function jsonSchema(jsonSchema2, {
1801
+ validate
1802
+ } = {}) {
1803
+ return {
1804
+ [schemaSymbol]: true,
1805
+ _type: void 0,
1806
+ // should never be used directly
1807
+ get jsonSchema() {
1808
+ if (typeof jsonSchema2 === "function") {
1809
+ jsonSchema2 = jsonSchema2();
1810
+ }
1811
+ return jsonSchema2;
1812
+ },
1813
+ validate
1814
+ };
1815
+ }
1816
+ function isSchema(value) {
1817
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
1818
+ }
1819
+ function asSchema(schema) {
1820
+ return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
1821
+ }
1822
+ function standardSchema(standardSchema2) {
1823
+ return jsonSchema(
1824
+ () => standardSchema2["~standard"].jsonSchema.input({
1825
+ target: "draft-07"
1826
+ }),
1827
+ {
1828
+ validate: async (value) => {
1829
+ const result = await standardSchema2["~standard"].validate(value);
1830
+ return "value" in result ? { success: true, value: result.value } : {
1831
+ success: false,
1832
+ error: new TypeValidationError({
1833
+ value,
1834
+ cause: result.issues
1835
+ })
1836
+ };
1837
+ }
1838
+ }
1839
+ );
1840
+ }
1841
+ function zod3Schema(zodSchema2, options) {
1842
+ var _a22;
1843
+ const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
1844
+ return jsonSchema(
1845
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1846
+ () => zod3ToJsonSchema(zodSchema2, {
1847
+ $refStrategy: useReferences ? "root" : "none"
1848
+ }),
1849
+ {
1850
+ validate: async (value) => {
1851
+ const result = await zodSchema2.safeParseAsync(value);
1852
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1853
+ }
1854
+ }
1855
+ );
1856
+ }
1857
+ function zod4Schema(zodSchema2, options) {
1858
+ var _a22;
1859
+ const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
1860
+ return jsonSchema(
1861
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1862
+ () => addAdditionalPropertiesToJsonSchema(
1863
+ z4.toJSONSchema(zodSchema2, {
1864
+ target: "draft-7",
1865
+ io: "input",
1866
+ reused: useReferences ? "ref" : "inline"
1867
+ })
1868
+ ),
1869
+ {
1870
+ validate: async (value) => {
1871
+ const result = await z4.safeParseAsync(zodSchema2, value);
1872
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1873
+ }
1874
+ }
1875
+ );
1876
+ }
1877
+ function isZod4Schema(zodSchema2) {
1878
+ return "_zod" in zodSchema2;
1879
+ }
1880
+ function zodSchema(zodSchema2, options) {
1881
+ if (isZod4Schema(zodSchema2)) {
1882
+ return zod4Schema(zodSchema2, options);
1883
+ } else {
1884
+ return zod3Schema(zodSchema2, options);
1885
+ }
610
1886
  }
611
1887
  async function validateTypes({
612
1888
  value,
@@ -622,12 +1898,12 @@ async function safeValidateTypes({
622
1898
  value,
623
1899
  schema
624
1900
  }) {
625
- const validator2 = asValidator(schema);
1901
+ const actualSchema = asSchema(schema);
626
1902
  try {
627
- if (validator2.validate == null) {
1903
+ if (actualSchema.validate == null) {
628
1904
  return { success: true, value, rawValue: value };
629
1905
  }
630
- const result = await validator2.validate(value);
1906
+ const result = await actualSchema.validate(value);
631
1907
  if (result.success) {
632
1908
  return { success: true, value: result.value, rawValue: value };
633
1909
  }
@@ -710,7 +1986,7 @@ var postJsonToApi = async ({
710
1986
  failedResponseHandler,
711
1987
  successfulResponseHandler,
712
1988
  abortSignal,
713
- fetch
1989
+ fetch: fetch2
714
1990
  }) => postToApi({
715
1991
  url,
716
1992
  headers: __spreadValues({
@@ -723,7 +1999,7 @@ var postJsonToApi = async ({
723
1999
  failedResponseHandler,
724
2000
  successfulResponseHandler,
725
2001
  abortSignal,
726
- fetch
2002
+ fetch: fetch2
727
2003
  });
728
2004
  var postToApi = async ({
729
2005
  url,
@@ -732,12 +2008,16 @@ var postToApi = async ({
732
2008
  successfulResponseHandler,
733
2009
  failedResponseHandler,
734
2010
  abortSignal,
735
- fetch = getOriginalFetch2()
2011
+ fetch: fetch2 = getOriginalFetch2()
736
2012
  }) => {
737
2013
  try {
738
- const response = await fetch(url, {
2014
+ const response = await fetch2(url, {
739
2015
  method: "POST",
740
- headers: removeUndefinedEntries(headers),
2016
+ headers: withUserAgentSuffix(
2017
+ headers,
2018
+ `ai-sdk/provider-utils/${VERSION}`,
2019
+ getRuntimeEnvironmentUserAgent()
2020
+ ),
741
2021
  body: body.content,
742
2022
  signal: abortSignal
743
2023
  });
@@ -881,15 +2161,6 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
881
2161
  rawValue: parsedResult.rawValue
882
2162
  };
883
2163
  };
884
- var schemaSymbol = Symbol.for("vercel.ai.schema");
885
- var { btoa, atob } = globalThis;
886
- function convertUint8ArrayToBase64(array) {
887
- let latin1string = "";
888
- for (let i = 0; i < array.length; i++) {
889
- latin1string += String.fromCodePoint(array[i]);
890
- }
891
- return btoa(latin1string);
892
- }
893
2164
  function withoutTrailingSlash(url) {
894
2165
  return url == null ? void 0 : url.replace(/\/$/, "");
895
2166
  }
@@ -1020,7 +2291,7 @@ var OpenRouterProviderOptionsSchema = z3.object({
1020
2291
  }).optional();
1021
2292
 
1022
2293
  // src/utils/map-finish-reason.ts
1023
- function mapOpenRouterFinishReason(finishReason) {
2294
+ function mapToUnified(finishReason) {
1024
2295
  switch (finishReason) {
1025
2296
  case "stop":
1026
2297
  return "stop";
@@ -1032,9 +2303,18 @@ function mapOpenRouterFinishReason(finishReason) {
1032
2303
  case "tool_calls":
1033
2304
  return "tool-calls";
1034
2305
  default:
1035
- return "unknown";
2306
+ return "other";
1036
2307
  }
1037
2308
  }
2309
+ function mapOpenRouterFinishReason(finishReason) {
2310
+ return {
2311
+ unified: mapToUnified(finishReason),
2312
+ raw: finishReason != null ? finishReason : void 0
2313
+ };
2314
+ }
2315
+ function createFinishReason(unified, raw) {
2316
+ return { unified, raw };
2317
+ }
1038
2318
 
1039
2319
  // src/types/openrouter-chat-completions-input.ts
1040
2320
  var OPENROUTER_AUDIO_FORMATS = [
@@ -1067,10 +2347,10 @@ function getFileUrl({
1067
2347
  part,
1068
2348
  defaultMediaType
1069
2349
  }) {
1070
- var _a15, _b;
2350
+ var _a16, _b16;
1071
2351
  if (part.data instanceof Uint8Array) {
1072
2352
  const base64 = convertUint8ArrayToBase64(part.data);
1073
- return `data:${(_a15 = part.mediaType) != null ? _a15 : defaultMediaType};base64,${base64}`;
2353
+ return `data:${(_a16 = part.mediaType) != null ? _a16 : defaultMediaType};base64,${base64}`;
1074
2354
  }
1075
2355
  const stringUrl = part.data.toString();
1076
2356
  if (isUrl({
@@ -1079,12 +2359,12 @@ function getFileUrl({
1079
2359
  })) {
1080
2360
  return stringUrl;
1081
2361
  }
1082
- return stringUrl.startsWith("data:") ? stringUrl : `data:${(_b = part.mediaType) != null ? _b : defaultMediaType};base64,${stringUrl}`;
2362
+ return stringUrl.startsWith("data:") ? stringUrl : `data:${(_b16 = part.mediaType) != null ? _b16 : defaultMediaType};base64,${stringUrl}`;
1083
2363
  }
1084
2364
  function getMediaType(dataUrl, defaultMediaType) {
1085
- var _a15;
2365
+ var _a16;
1086
2366
  const match = dataUrl.match(/^data:([^;]+)/);
1087
- return match ? (_a15 = match[1]) != null ? _a15 : defaultMediaType : defaultMediaType;
2367
+ return match ? (_a16 = match[1]) != null ? _a16 : defaultMediaType : defaultMediaType;
1088
2368
  }
1089
2369
  function getBase64FromDataUrl(dataUrl) {
1090
2370
  const match = dataUrl.match(/^data:[^;]*;base64,(.+)$/);
@@ -1159,13 +2439,13 @@ Learn more: https://openrouter.ai/docs/features/multimodal/audio`
1159
2439
 
1160
2440
  // src/chat/convert-to-openrouter-chat-messages.ts
1161
2441
  function getCacheControl(providerMetadata) {
1162
- var _a15, _b, _c;
2442
+ var _a16, _b16, _c;
1163
2443
  const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
1164
2444
  const openrouter2 = providerMetadata == null ? void 0 : providerMetadata.openrouter;
1165
- return (_c = (_b = (_a15 = openrouter2 == null ? void 0 : openrouter2.cacheControl) != null ? _a15 : openrouter2 == null ? void 0 : openrouter2.cache_control) != null ? _b : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
2445
+ return (_c = (_b16 = (_a16 = openrouter2 == null ? void 0 : openrouter2.cacheControl) != null ? _a16 : openrouter2 == null ? void 0 : openrouter2.cache_control) != null ? _b16 : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
1166
2446
  }
1167
2447
  function convertToOpenRouterChatMessages(prompt) {
1168
- var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2448
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j;
1169
2449
  const messages = [];
1170
2450
  for (const { role, content, providerOptions } of prompt) {
1171
2451
  switch (role) {
@@ -1178,8 +2458,8 @@ function convertToOpenRouterChatMessages(prompt) {
1178
2458
  break;
1179
2459
  }
1180
2460
  case "user": {
1181
- if (content.length === 1 && ((_a15 = content[0]) == null ? void 0 : _a15.type) === "text") {
1182
- const cacheControl = (_b = getCacheControl(providerOptions)) != null ? _b : getCacheControl(content[0].providerOptions);
2461
+ if (content.length === 1 && ((_a16 = content[0]) == null ? void 0 : _a16.type) === "text") {
2462
+ const cacheControl = (_b16 = getCacheControl(providerOptions)) != null ? _b16 : getCacheControl(content[0].providerOptions);
1183
2463
  const contentWithCacheControl = cacheControl ? [
1184
2464
  {
1185
2465
  type: "text",
@@ -1196,8 +2476,8 @@ function convertToOpenRouterChatMessages(prompt) {
1196
2476
  const messageCacheControl = getCacheControl(providerOptions);
1197
2477
  const contentParts = content.map(
1198
2478
  (part) => {
1199
- var _a16, _b2, _c2, _d2, _e2, _f2, _g2;
1200
- const cacheControl = (_a16 = getCacheControl(part.providerOptions)) != null ? _a16 : messageCacheControl;
2479
+ var _a17, _b17, _c2, _d2, _e2, _f2, _g2;
2480
+ const cacheControl = (_a17 = getCacheControl(part.providerOptions)) != null ? _a17 : messageCacheControl;
1201
2481
  switch (part.type) {
1202
2482
  case "text":
1203
2483
  return {
@@ -1207,7 +2487,7 @@ function convertToOpenRouterChatMessages(prompt) {
1207
2487
  cache_control: cacheControl
1208
2488
  };
1209
2489
  case "file": {
1210
- if ((_b2 = part.mediaType) == null ? void 0 : _b2.startsWith("image/")) {
2490
+ if ((_b17 = part.mediaType) == null ? void 0 : _b17.startsWith("image/")) {
1211
2491
  const url = getFileUrl({
1212
2492
  part,
1213
2493
  defaultMediaType: "image/jpeg"
@@ -1334,6 +2614,9 @@ function convertToOpenRouterChatMessages(prompt) {
1334
2614
  }
1335
2615
  case "tool": {
1336
2616
  for (const toolResponse of content) {
2617
+ if (toolResponse.type === "tool-approval-response") {
2618
+ continue;
2619
+ }
1337
2620
  const content2 = getToolResultContent(toolResponse);
1338
2621
  messages.push({
1339
2622
  role: "tool",
@@ -1352,7 +2635,18 @@ function convertToOpenRouterChatMessages(prompt) {
1352
2635
  return messages;
1353
2636
  }
1354
2637
  function getToolResultContent(input) {
1355
- return input.output.type === "text" ? input.output.value : JSON.stringify(input.output.value);
2638
+ var _a16;
2639
+ switch (input.output.type) {
2640
+ case "text":
2641
+ case "error-text":
2642
+ return input.output.value;
2643
+ case "json":
2644
+ case "error-json":
2645
+ case "content":
2646
+ return JSON.stringify(input.output.value);
2647
+ case "execution-denied":
2648
+ return (_a16 = input.output.reason) != null ? _a16 : "Tool execution denied";
2649
+ }
1356
2650
  }
1357
2651
 
1358
2652
  // src/chat/get-tool-choice.ts
@@ -1595,7 +2889,7 @@ var OpenRouterStreamChatCompletionChunkSchema = z7.union([
1595
2889
  // src/chat/index.ts
1596
2890
  var OpenRouterChatLanguageModel = class {
1597
2891
  constructor(modelId, settings, config) {
1598
- this.specificationVersion = "v2";
2892
+ this.specificationVersion = "v3";
1599
2893
  this.provider = "openrouter";
1600
2894
  this.defaultObjectGenerationMode = "tool";
1601
2895
  this.supportsImageUrls = true;
@@ -1625,7 +2919,7 @@ var OpenRouterChatLanguageModel = class {
1625
2919
  tools,
1626
2920
  toolChoice
1627
2921
  }) {
1628
- var _a15;
2922
+ var _a16;
1629
2923
  const baseArgs = __spreadValues(__spreadValues({
1630
2924
  // model id:
1631
2925
  model: this.modelId,
@@ -1649,7 +2943,7 @@ var OpenRouterChatLanguageModel = class {
1649
2943
  json_schema: __spreadValues({
1650
2944
  schema: responseFormat.schema,
1651
2945
  strict: true,
1652
- name: (_a15 = responseFormat.name) != null ? _a15 : "response"
2946
+ name: (_a16 = responseFormat.name) != null ? _a16 : "response"
1653
2947
  }, responseFormat.description && {
1654
2948
  description: responseFormat.description
1655
2949
  })
@@ -1688,7 +2982,7 @@ var OpenRouterChatLanguageModel = class {
1688
2982
  return baseArgs;
1689
2983
  }
1690
2984
  async doGenerate(options) {
1691
- var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w;
2985
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w;
1692
2986
  const providerOptions = options.providerOptions || {};
1693
2987
  const openrouterOptions = providerOptions.openrouter || {};
1694
2988
  const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
@@ -1728,19 +3022,31 @@ var OpenRouterChatLanguageModel = class {
1728
3022
  });
1729
3023
  }
1730
3024
  const usageInfo = response.usage ? {
1731
- inputTokens: (_a15 = response.usage.prompt_tokens) != null ? _a15 : 0,
1732
- outputTokens: (_b = response.usage.completion_tokens) != null ? _b : 0,
1733
- totalTokens: ((_c = response.usage.prompt_tokens) != null ? _c : 0) + ((_d = response.usage.completion_tokens) != null ? _d : 0),
1734
- reasoningTokens: (_f = (_e = response.usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0,
1735
- cachedInputTokens: (_h = (_g = response.usage.prompt_tokens_details) == null ? void 0 : _g.cached_tokens) != null ? _h : 0
3025
+ inputTokens: {
3026
+ total: (_a16 = response.usage.prompt_tokens) != null ? _a16 : 0,
3027
+ noCache: void 0,
3028
+ cacheRead: (_c = (_b16 = response.usage.prompt_tokens_details) == null ? void 0 : _b16.cached_tokens) != null ? _c : void 0,
3029
+ cacheWrite: void 0
3030
+ },
3031
+ outputTokens: {
3032
+ total: (_d = response.usage.completion_tokens) != null ? _d : 0,
3033
+ text: void 0,
3034
+ reasoning: (_f = (_e = response.usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : void 0
3035
+ }
1736
3036
  } : {
1737
- inputTokens: 0,
1738
- outputTokens: 0,
1739
- totalTokens: 0,
1740
- reasoningTokens: 0,
1741
- cachedInputTokens: 0
3037
+ inputTokens: {
3038
+ total: 0,
3039
+ noCache: void 0,
3040
+ cacheRead: void 0,
3041
+ cacheWrite: void 0
3042
+ },
3043
+ outputTokens: {
3044
+ total: 0,
3045
+ text: void 0,
3046
+ reasoning: void 0
3047
+ }
1742
3048
  };
1743
- const reasoningDetails = (_i = choice.message.reasoning_details) != null ? _i : [];
3049
+ const reasoningDetails = (_g = choice.message.reasoning_details) != null ? _g : [];
1744
3050
  const reasoning = reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
1745
3051
  switch (detail.type) {
1746
3052
  case "reasoning.text" /* Text */: {
@@ -1808,7 +3114,7 @@ var OpenRouterChatLanguageModel = class {
1808
3114
  for (const toolCall of choice.message.tool_calls) {
1809
3115
  content.push({
1810
3116
  type: "tool-call",
1811
- toolCallId: (_j = toolCall.id) != null ? _j : generateId(),
3117
+ toolCallId: (_h = toolCall.id) != null ? _h : generateId(),
1812
3118
  toolName: toolCall.function.name,
1813
3119
  input: toolCall.function.arguments,
1814
3120
  providerMetadata: {
@@ -1846,7 +3152,7 @@ var OpenRouterChatLanguageModel = class {
1846
3152
  }
1847
3153
  }
1848
3154
  }
1849
- const fileAnnotations = (_k = choice.message.annotations) == null ? void 0 : _k.filter(
3155
+ const fileAnnotations = (_i = choice.message.annotations) == null ? void 0 : _i.filter(
1850
3156
  (a) => a.type === "file"
1851
3157
  );
1852
3158
  const hasToolCalls = choice.message.tool_calls && choice.message.tool_calls.length > 0;
@@ -1854,7 +3160,7 @@ var OpenRouterChatLanguageModel = class {
1854
3160
  (d) => d.type === "reasoning.encrypted" /* Encrypted */ && d.data
1855
3161
  );
1856
3162
  const shouldOverrideFinishReason = hasToolCalls && hasEncryptedReasoning && choice.finish_reason === "stop";
1857
- const effectiveFinishReason = shouldOverrideFinishReason ? "tool-calls" : mapOpenRouterFinishReason(choice.finish_reason);
3163
+ const effectiveFinishReason = shouldOverrideFinishReason ? createFinishReason("tool-calls", (_j = choice.finish_reason) != null ? _j : void 0) : mapOpenRouterFinishReason(choice.finish_reason);
1858
3164
  return {
1859
3165
  content,
1860
3166
  finishReason: effectiveFinishReason,
@@ -1862,13 +3168,13 @@ var OpenRouterChatLanguageModel = class {
1862
3168
  warnings: [],
1863
3169
  providerMetadata: {
1864
3170
  openrouter: OpenRouterProviderMetadataSchema.parse({
1865
- provider: (_l = response.provider) != null ? _l : "",
1866
- reasoning_details: (_m = choice.message.reasoning_details) != null ? _m : [],
3171
+ provider: (_k = response.provider) != null ? _k : "",
3172
+ reasoning_details: (_l = choice.message.reasoning_details) != null ? _l : [],
1867
3173
  annotations: fileAnnotations && fileAnnotations.length > 0 ? fileAnnotations : void 0,
1868
3174
  usage: __spreadValues(__spreadValues(__spreadValues({
1869
- promptTokens: (_n = usageInfo.inputTokens) != null ? _n : 0,
1870
- completionTokens: (_o = usageInfo.outputTokens) != null ? _o : 0,
1871
- totalTokens: (_p = usageInfo.totalTokens) != null ? _p : 0,
3175
+ promptTokens: (_m = usageInfo.inputTokens.total) != null ? _m : 0,
3176
+ completionTokens: (_n = usageInfo.outputTokens.total) != null ? _n : 0,
3177
+ totalTokens: ((_o = usageInfo.inputTokens.total) != null ? _o : 0) + ((_p = usageInfo.outputTokens.total) != null ? _p : 0),
1872
3178
  cost: (_q = response.usage) == null ? void 0 : _q.cost
1873
3179
  }, ((_s = (_r = response.usage) == null ? void 0 : _r.prompt_tokens_details) == null ? void 0 : _s.cached_tokens) != null ? {
1874
3180
  promptTokensDetails: {
@@ -1894,7 +3200,7 @@ var OpenRouterChatLanguageModel = class {
1894
3200
  };
1895
3201
  }
1896
3202
  async doStream(options) {
1897
- var _a15;
3203
+ var _a16;
1898
3204
  const providerOptions = options.providerOptions || {};
1899
3205
  const openrouterOptions = providerOptions.openrouter || {};
1900
3206
  const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
@@ -1909,7 +3215,7 @@ var OpenRouterChatLanguageModel = class {
1909
3215
  // only include stream_options when in strict compatibility mode:
1910
3216
  stream_options: this.config.compatibility === "strict" ? __spreadValues({
1911
3217
  include_usage: true
1912
- }, ((_a15 = this.settings.usage) == null ? void 0 : _a15.include) ? { include_usage: true } : {}) : void 0
3218
+ }, ((_a16 = this.settings.usage) == null ? void 0 : _a16.include) ? { include_usage: true } : {}) : void 0
1913
3219
  }),
1914
3220
  failedResponseHandler: openrouterFailedResponseHandler,
1915
3221
  successfulResponseHandler: createEventSourceResponseHandler(
@@ -1919,13 +3225,19 @@ var OpenRouterChatLanguageModel = class {
1919
3225
  fetch: this.config.fetch
1920
3226
  });
1921
3227
  const toolCalls = [];
1922
- let finishReason = "other";
3228
+ let finishReason = createFinishReason("other");
1923
3229
  const usage = {
1924
- inputTokens: Number.NaN,
1925
- outputTokens: Number.NaN,
1926
- totalTokens: Number.NaN,
1927
- reasoningTokens: Number.NaN,
1928
- cachedInputTokens: Number.NaN
3230
+ inputTokens: {
3231
+ total: void 0,
3232
+ noCache: void 0,
3233
+ cacheRead: void 0,
3234
+ cacheWrite: void 0
3235
+ },
3236
+ outputTokens: {
3237
+ total: void 0,
3238
+ text: void 0,
3239
+ reasoning: void 0
3240
+ }
1929
3241
  };
1930
3242
  const openrouterUsage = {};
1931
3243
  const accumulatedReasoningDetails = [];
@@ -1940,15 +3252,15 @@ var OpenRouterChatLanguageModel = class {
1940
3252
  stream: response.pipeThrough(
1941
3253
  new TransformStream({
1942
3254
  transform(chunk, controller) {
1943
- var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
3255
+ var _a17, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
1944
3256
  if (!chunk.success) {
1945
- finishReason = "error";
3257
+ finishReason = createFinishReason("error");
1946
3258
  controller.enqueue({ type: "error", error: chunk.error });
1947
3259
  return;
1948
3260
  }
1949
3261
  const value = chunk.value;
1950
3262
  if ("error" in value) {
1951
- finishReason = "error";
3263
+ finishReason = createFinishReason("error");
1952
3264
  controller.enqueue({ type: "error", error: value.error });
1953
3265
  return;
1954
3266
  }
@@ -1969,21 +3281,20 @@ var OpenRouterChatLanguageModel = class {
1969
3281
  });
1970
3282
  }
1971
3283
  if (value.usage != null) {
1972
- usage.inputTokens = value.usage.prompt_tokens;
1973
- usage.outputTokens = value.usage.completion_tokens;
1974
- usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
3284
+ usage.inputTokens.total = value.usage.prompt_tokens;
3285
+ usage.outputTokens.total = value.usage.completion_tokens;
1975
3286
  openrouterUsage.promptTokens = value.usage.prompt_tokens;
1976
3287
  if (value.usage.prompt_tokens_details) {
1977
- const cachedInputTokens = (_a16 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a16 : 0;
1978
- usage.cachedInputTokens = cachedInputTokens;
3288
+ const cachedInputTokens = (_a17 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a17 : 0;
3289
+ usage.inputTokens.cacheRead = cachedInputTokens;
1979
3290
  openrouterUsage.promptTokensDetails = {
1980
3291
  cachedTokens: cachedInputTokens
1981
3292
  };
1982
3293
  }
1983
3294
  openrouterUsage.completionTokens = value.usage.completion_tokens;
1984
3295
  if (value.usage.completion_tokens_details) {
1985
- const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
1986
- usage.reasoningTokens = reasoningTokens;
3296
+ const reasoningTokens = (_b16 = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b16 : 0;
3297
+ usage.outputTokens.reasoning = reasoningTokens;
1987
3298
  openrouterUsage.completionTokensDetails = {
1988
3299
  reasoningTokens
1989
3300
  };
@@ -2242,20 +3553,20 @@ var OpenRouterChatLanguageModel = class {
2242
3553
  }
2243
3554
  },
2244
3555
  flush(controller) {
2245
- var _a16;
3556
+ var _a17;
2246
3557
  const hasToolCalls = toolCalls.length > 0;
2247
3558
  const hasEncryptedReasoning = accumulatedReasoningDetails.some(
2248
3559
  (d) => d.type === "reasoning.encrypted" /* Encrypted */ && d.data
2249
3560
  );
2250
- if (hasToolCalls && hasEncryptedReasoning && finishReason === "stop") {
2251
- finishReason = "tool-calls";
3561
+ if (hasToolCalls && hasEncryptedReasoning && finishReason.unified === "stop") {
3562
+ finishReason = createFinishReason("tool-calls", finishReason.raw);
2252
3563
  }
2253
- if (finishReason === "tool-calls") {
3564
+ if (finishReason.unified === "tool-calls") {
2254
3565
  for (const toolCall of toolCalls) {
2255
3566
  if (toolCall && !toolCall.sent) {
2256
3567
  controller.enqueue({
2257
3568
  type: "tool-call",
2258
- toolCallId: (_a16 = toolCall.id) != null ? _a16 : generateId(),
3569
+ toolCallId: (_a17 = toolCall.id) != null ? _a17 : generateId(),
2259
3570
  toolName: toolCall.function.name,
2260
3571
  // Coerce invalid arguments to an empty JSON object
2261
3572
  input: isParsableJson(toolCall.function.arguments) ? toolCall.function.arguments : "{}",
@@ -2456,7 +3767,7 @@ var OpenRouterCompletionChunkSchema = z8.union([
2456
3767
  // src/completion/index.ts
2457
3768
  var OpenRouterCompletionLanguageModel = class {
2458
3769
  constructor(modelId, settings, config) {
2459
- this.specificationVersion = "v2";
3770
+ this.specificationVersion = "v3";
2460
3771
  this.provider = "openrouter";
2461
3772
  this.supportsImageUrls = true;
2462
3773
  this.supportedUrls = {
@@ -2527,7 +3838,7 @@ var OpenRouterCompletionLanguageModel = class {
2527
3838
  }, this.config.extraBody), this.settings.extraBody);
2528
3839
  }
2529
3840
  async doGenerate(options) {
2530
- var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
3841
+ var _a16, _b16, _c, _d, _e, _f, _g, _h, _i, _j, _k;
2531
3842
  const providerOptions = options.providerOptions || {};
2532
3843
  const openrouterOptions = providerOptions.openrouter || {};
2533
3844
  const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
@@ -2569,16 +3880,22 @@ var OpenRouterCompletionLanguageModel = class {
2569
3880
  content: [
2570
3881
  {
2571
3882
  type: "text",
2572
- text: (_a15 = choice.text) != null ? _a15 : ""
3883
+ text: (_a16 = choice.text) != null ? _a16 : ""
2573
3884
  }
2574
3885
  ],
2575
3886
  finishReason: mapOpenRouterFinishReason(choice.finish_reason),
2576
3887
  usage: {
2577
- inputTokens: (_c = (_b = response.usage) == null ? void 0 : _b.prompt_tokens) != null ? _c : 0,
2578
- outputTokens: (_e = (_d = response.usage) == null ? void 0 : _d.completion_tokens) != null ? _e : 0,
2579
- 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),
2580
- reasoningTokens: (_l = (_k = (_j = response.usage) == null ? void 0 : _j.completion_tokens_details) == null ? void 0 : _k.reasoning_tokens) != null ? _l : 0,
2581
- cachedInputTokens: (_o = (_n = (_m = response.usage) == null ? void 0 : _m.prompt_tokens_details) == null ? void 0 : _n.cached_tokens) != null ? _o : 0
3888
+ inputTokens: {
3889
+ total: (_c = (_b16 = response.usage) == null ? void 0 : _b16.prompt_tokens) != null ? _c : 0,
3890
+ noCache: void 0,
3891
+ cacheRead: (_f = (_e = (_d = response.usage) == null ? void 0 : _d.prompt_tokens_details) == null ? void 0 : _e.cached_tokens) != null ? _f : void 0,
3892
+ cacheWrite: void 0
3893
+ },
3894
+ outputTokens: {
3895
+ total: (_h = (_g = response.usage) == null ? void 0 : _g.completion_tokens) != null ? _h : 0,
3896
+ text: void 0,
3897
+ reasoning: (_k = (_j = (_i = response.usage) == null ? void 0 : _i.completion_tokens_details) == null ? void 0 : _j.reasoning_tokens) != null ? _k : void 0
3898
+ }
2582
3899
  },
2583
3900
  warnings: [],
2584
3901
  response: {
@@ -2608,47 +3925,52 @@ var OpenRouterCompletionLanguageModel = class {
2608
3925
  abortSignal: options.abortSignal,
2609
3926
  fetch: this.config.fetch
2610
3927
  });
2611
- let finishReason = "other";
3928
+ let finishReason = createFinishReason("other");
2612
3929
  const usage = {
2613
- inputTokens: Number.NaN,
2614
- outputTokens: Number.NaN,
2615
- totalTokens: Number.NaN,
2616
- reasoningTokens: Number.NaN,
2617
- cachedInputTokens: Number.NaN
3930
+ inputTokens: {
3931
+ total: void 0,
3932
+ noCache: void 0,
3933
+ cacheRead: void 0,
3934
+ cacheWrite: void 0
3935
+ },
3936
+ outputTokens: {
3937
+ total: void 0,
3938
+ text: void 0,
3939
+ reasoning: void 0
3940
+ }
2618
3941
  };
2619
3942
  const openrouterUsage = {};
2620
3943
  return {
2621
3944
  stream: response.pipeThrough(
2622
3945
  new TransformStream({
2623
3946
  transform(chunk, controller) {
2624
- var _a15, _b, _c;
3947
+ var _a16, _b16, _c;
2625
3948
  if (!chunk.success) {
2626
- finishReason = "error";
3949
+ finishReason = createFinishReason("error");
2627
3950
  controller.enqueue({ type: "error", error: chunk.error });
2628
3951
  return;
2629
3952
  }
2630
3953
  const value = chunk.value;
2631
3954
  if ("error" in value) {
2632
- finishReason = "error";
3955
+ finishReason = createFinishReason("error");
2633
3956
  controller.enqueue({ type: "error", error: value.error });
2634
3957
  return;
2635
3958
  }
2636
3959
  if (value.usage != null) {
2637
- usage.inputTokens = value.usage.prompt_tokens;
2638
- usage.outputTokens = value.usage.completion_tokens;
2639
- usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
3960
+ usage.inputTokens.total = value.usage.prompt_tokens;
3961
+ usage.outputTokens.total = value.usage.completion_tokens;
2640
3962
  openrouterUsage.promptTokens = value.usage.prompt_tokens;
2641
3963
  if (value.usage.prompt_tokens_details) {
2642
- const cachedInputTokens = (_a15 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a15 : 0;
2643
- usage.cachedInputTokens = cachedInputTokens;
3964
+ const cachedInputTokens = (_a16 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a16 : 0;
3965
+ usage.inputTokens.cacheRead = cachedInputTokens;
2644
3966
  openrouterUsage.promptTokensDetails = {
2645
3967
  cachedTokens: cachedInputTokens
2646
3968
  };
2647
3969
  }
2648
3970
  openrouterUsage.completionTokens = value.usage.completion_tokens;
2649
3971
  if (value.usage.completion_tokens_details) {
2650
- const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
2651
- usage.reasoningTokens = reasoningTokens;
3972
+ const reasoningTokens = (_b16 = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b16 : 0;
3973
+ usage.outputTokens.reasoning = reasoningTokens;
2652
3974
  openrouterUsage.completionTokensDetails = {
2653
3975
  reasoningTokens
2654
3976
  };
@@ -2718,7 +4040,7 @@ var OpenRouterEmbeddingResponseSchema = z9.object({
2718
4040
  // src/embedding/index.ts
2719
4041
  var OpenRouterEmbeddingModel = class {
2720
4042
  constructor(modelId, settings, config) {
2721
- this.specificationVersion = "v2";
4043
+ this.specificationVersion = "v3";
2722
4044
  this.provider = "openrouter";
2723
4045
  this.maxEmbeddingsPerCall = void 0;
2724
4046
  this.supportsParallelCalls = true;
@@ -2727,7 +4049,7 @@ var OpenRouterEmbeddingModel = class {
2727
4049
  this.config = config;
2728
4050
  }
2729
4051
  async doEmbed(options) {
2730
- var _a15;
4052
+ var _a16;
2731
4053
  const { values, abortSignal, headers } = options;
2732
4054
  const args = __spreadValues(__spreadValues({
2733
4055
  model: this.modelId,
@@ -2752,7 +4074,7 @@ var OpenRouterEmbeddingModel = class {
2752
4074
  return {
2753
4075
  embeddings: responseValue.data.map((item) => item.embedding),
2754
4076
  usage: responseValue.usage ? { tokens: responseValue.usage.prompt_tokens } : void 0,
2755
- providerMetadata: ((_a15 = responseValue.usage) == null ? void 0 : _a15.cost) ? {
4077
+ providerMetadata: ((_a16 = responseValue.usage) == null ? void 0 : _a16.cost) ? {
2756
4078
  openrouter: {
2757
4079
  usage: {
2758
4080
  cost: responseValue.usage.cost
@@ -2762,7 +4084,8 @@ var OpenRouterEmbeddingModel = class {
2762
4084
  response: {
2763
4085
  headers: responseHeaders,
2764
4086
  body: responseValue
2765
- }
4087
+ },
4088
+ warnings: []
2766
4089
  };
2767
4090
  }
2768
4091
  };
@@ -2773,8 +4096,8 @@ var OpenRouter = class {
2773
4096
  * Creates a new OpenRouter provider instance.
2774
4097
  */
2775
4098
  constructor(options = {}) {
2776
- var _a15, _b;
2777
- this.baseURL = (_b = withoutTrailingSlash((_a15 = options.baseURL) != null ? _a15 : options.baseUrl)) != null ? _b : "https://openrouter.ai/api/v1";
4099
+ var _a16, _b16;
4100
+ this.baseURL = (_b16 = withoutTrailingSlash((_a16 = options.baseURL) != null ? _a16 : options.baseUrl)) != null ? _b16 : "https://openrouter.ai/api/v1";
2778
4101
  this.apiKey = options.apiKey;
2779
4102
  this.headers = options.headers;
2780
4103
  this.api_keys = options.api_keys;
@@ -2825,15 +4148,15 @@ var OpenRouter = class {
2825
4148
  };
2826
4149
 
2827
4150
  // src/utils/remove-undefined.ts
2828
- function removeUndefinedEntries2(record) {
4151
+ function removeUndefinedEntries(record) {
2829
4152
  return Object.fromEntries(
2830
4153
  Object.entries(record).filter(([, value]) => value !== null)
2831
4154
  );
2832
4155
  }
2833
4156
 
2834
4157
  // src/utils/with-user-agent-suffix.ts
2835
- function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
2836
- const cleanedHeaders = removeUndefinedEntries2(
4158
+ function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
4159
+ const cleanedHeaders = removeUndefinedEntries(
2837
4160
  headers != null ? headers : {}
2838
4161
  );
2839
4162
  const currentUserAgentHeader = cleanedHeaders["user-agent"] || "";
@@ -2844,14 +4167,14 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
2844
4167
  }
2845
4168
 
2846
4169
  // src/version.ts
2847
- var VERSION = false ? "0.0.0-test" : "1.5.4";
4170
+ var VERSION2 = false ? "0.0.0-test" : "2.0.1";
2848
4171
 
2849
4172
  // src/provider.ts
2850
4173
  function createOpenRouter(options = {}) {
2851
- var _a15, _b, _c;
2852
- const baseURL = (_b = withoutTrailingSlash((_a15 = options.baseURL) != null ? _a15 : options.baseUrl)) != null ? _b : "https://openrouter.ai/api/v1";
4174
+ var _a16, _b16, _c;
4175
+ const baseURL = (_b16 = withoutTrailingSlash((_a16 = options.baseURL) != null ? _a16 : options.baseUrl)) != null ? _b16 : "https://openrouter.ai/api/v1";
2853
4176
  const compatibility = (_c = options.compatibility) != null ? _c : "compatible";
2854
- const getHeaders = () => withUserAgentSuffix(
4177
+ const getHeaders = () => withUserAgentSuffix2(
2855
4178
  __spreadValues(__spreadValues({
2856
4179
  Authorization: `Bearer ${loadApiKey({
2857
4180
  apiKey: options.apiKey,
@@ -2861,7 +4184,7 @@ function createOpenRouter(options = {}) {
2861
4184
  }, options.headers), options.api_keys && Object.keys(options.api_keys).length > 0 && {
2862
4185
  "X-Provider-API-Keys": JSON.stringify(options.api_keys)
2863
4186
  }),
2864
- `ai-sdk/openrouter/${VERSION}`
4187
+ `ai-sdk/openrouter/${VERSION2}`
2865
4188
  );
2866
4189
  const createChatModel = (modelId, settings = {}) => new OpenRouterChatLanguageModel(modelId, settings, {
2867
4190
  provider: "openrouter.chat",