@mastra/schema-compat 0.0.0-safe-stringify-telemetry-20251205024938 → 0.0.0-scorers-logs-20251208093427

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.cjs CHANGED
@@ -2,16 +2,3577 @@
2
2
 
3
3
  var chunk5WM4A32G_cjs = require('./chunk-5WM4A32G.cjs');
4
4
  var zod = require('zod');
5
- var ai = require('ai');
6
5
  var zodFromJsonSchema = require('zod-from-json-schema');
7
6
  var zodFromJsonSchemaV3 = require('zod-from-json-schema-v3');
7
+ var v3 = require('zod/v3');
8
8
  var v4 = require('zod/v4');
9
9
 
10
- function convertZodSchemaToAISDKSchema(zodSchema, target = "jsonSchema7") {
11
- const jsonSchemaToUse = chunk5WM4A32G_cjs.zodToJsonSchema(zodSchema, target);
12
- return ai.jsonSchema(jsonSchemaToUse, {
10
+ // ../_ai-sdk-v4/dist/chunk-EDUQOWHB.js
11
+ var __create = Object.create;
12
+ var __defProp = Object.defineProperty;
13
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
+ var __getOwnPropNames = Object.getOwnPropertyNames;
15
+ var __getProtoOf = Object.getPrototypeOf;
16
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
17
+ var __commonJS = (cb, mod) => function __require() {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ __defProp(target, "default", { value: mod, enumerable: true }),
34
+ mod
35
+ ));
36
+ var require_secure_json_parse = __commonJS({
37
+ "../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports, module) {
38
+ var hasBuffer = typeof Buffer !== "undefined";
39
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
40
+ var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
41
+ function _parse(text2, reviver, options) {
42
+ if (options == null) {
43
+ if (reviver !== null && typeof reviver === "object") {
44
+ options = reviver;
45
+ reviver = void 0;
46
+ }
47
+ }
48
+ if (hasBuffer && Buffer.isBuffer(text2)) {
49
+ text2 = text2.toString();
50
+ }
51
+ if (text2 && text2.charCodeAt(0) === 65279) {
52
+ text2 = text2.slice(1);
53
+ }
54
+ const obj = JSON.parse(text2, reviver);
55
+ if (obj === null || typeof obj !== "object") {
56
+ return obj;
57
+ }
58
+ const protoAction = options && options.protoAction || "error";
59
+ const constructorAction = options && options.constructorAction || "error";
60
+ if (protoAction === "ignore" && constructorAction === "ignore") {
61
+ return obj;
62
+ }
63
+ if (protoAction !== "ignore" && constructorAction !== "ignore") {
64
+ if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) {
65
+ return obj;
66
+ }
67
+ } else if (protoAction !== "ignore" && constructorAction === "ignore") {
68
+ if (suspectProtoRx.test(text2) === false) {
69
+ return obj;
70
+ }
71
+ } else {
72
+ if (suspectConstructorRx.test(text2) === false) {
73
+ return obj;
74
+ }
75
+ }
76
+ return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
77
+ }
78
+ function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
79
+ let next = [obj];
80
+ while (next.length) {
81
+ const nodes = next;
82
+ next = [];
83
+ for (const node of nodes) {
84
+ if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
85
+ if (safe === true) {
86
+ return null;
87
+ } else if (protoAction === "error") {
88
+ throw new SyntaxError("Object contains forbidden prototype property");
89
+ }
90
+ delete node.__proto__;
91
+ }
92
+ if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
93
+ if (safe === true) {
94
+ return null;
95
+ } else if (constructorAction === "error") {
96
+ throw new SyntaxError("Object contains forbidden prototype property");
97
+ }
98
+ delete node.constructor;
99
+ }
100
+ for (const key in node) {
101
+ const value = node[key];
102
+ if (value && typeof value === "object") {
103
+ next.push(value);
104
+ }
105
+ }
106
+ }
107
+ }
108
+ return obj;
109
+ }
110
+ function parse(text2, reviver, options) {
111
+ const stackTraceLimit = Error.stackTraceLimit;
112
+ Error.stackTraceLimit = 0;
113
+ try {
114
+ return _parse(text2, reviver, options);
115
+ } finally {
116
+ Error.stackTraceLimit = stackTraceLimit;
117
+ }
118
+ }
119
+ function safeParse(text2, reviver) {
120
+ const stackTraceLimit = Error.stackTraceLimit;
121
+ Error.stackTraceLimit = 0;
122
+ try {
123
+ return _parse(text2, reviver, { safe: true });
124
+ } catch (_e) {
125
+ return null;
126
+ } finally {
127
+ Error.stackTraceLimit = stackTraceLimit;
128
+ }
129
+ }
130
+ module.exports = parse;
131
+ module.exports.default = parse;
132
+ module.exports.parse = parse;
133
+ module.exports.safeParse = safeParse;
134
+ module.exports.scan = filter;
135
+ }
136
+ });
137
+ var marker = "vercel.ai.error";
138
+ var symbol = Symbol.for(marker);
139
+ var _a;
140
+ var _AISDKError = class _AISDKError2 extends Error {
141
+ /**
142
+ * Creates an AI SDK Error.
143
+ *
144
+ * @param {Object} params - The parameters for creating the error.
145
+ * @param {string} params.name - The name of the error.
146
+ * @param {string} params.message - The error message.
147
+ * @param {unknown} [params.cause] - The underlying cause of the error.
148
+ */
149
+ constructor({
150
+ name: name142,
151
+ message,
152
+ cause
153
+ }) {
154
+ super(message);
155
+ this[_a] = true;
156
+ this.name = name142;
157
+ this.cause = cause;
158
+ }
159
+ /**
160
+ * Checks if the given error is an AI SDK Error.
161
+ * @param {unknown} error - The error to check.
162
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
163
+ */
164
+ static isInstance(error) {
165
+ return _AISDKError2.hasMarker(error, marker);
166
+ }
167
+ static hasMarker(error, marker15) {
168
+ const markerSymbol = Symbol.for(marker15);
169
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
170
+ }
171
+ };
172
+ _a = symbol;
173
+ var AISDKError = _AISDKError;
174
+ function getErrorMessage(error) {
175
+ if (error == null) {
176
+ return "unknown error";
177
+ }
178
+ if (typeof error === "string") {
179
+ return error;
180
+ }
181
+ if (error instanceof Error) {
182
+ return error.message;
183
+ }
184
+ return JSON.stringify(error);
185
+ }
186
+ var name3 = "AI_InvalidArgumentError";
187
+ var marker4 = `vercel.ai.error.${name3}`;
188
+ var symbol4 = Symbol.for(marker4);
189
+ var _a4;
190
+ var InvalidArgumentError = class extends AISDKError {
191
+ constructor({
192
+ message,
193
+ cause,
194
+ argument
195
+ }) {
196
+ super({ name: name3, message, cause });
197
+ this[_a4] = true;
198
+ this.argument = argument;
199
+ }
200
+ static isInstance(error) {
201
+ return AISDKError.hasMarker(error, marker4);
202
+ }
203
+ };
204
+ _a4 = symbol4;
205
+ var name6 = "AI_JSONParseError";
206
+ var marker7 = `vercel.ai.error.${name6}`;
207
+ var symbol7 = Symbol.for(marker7);
208
+ var _a7;
209
+ var JSONParseError = class extends AISDKError {
210
+ constructor({ text: text2, cause }) {
211
+ super({
212
+ name: name6,
213
+ message: `JSON parsing failed: Text: ${text2}.
214
+ Error message: ${getErrorMessage(cause)}`,
215
+ cause
216
+ });
217
+ this[_a7] = true;
218
+ this.text = text2;
219
+ }
220
+ static isInstance(error) {
221
+ return AISDKError.hasMarker(error, marker7);
222
+ }
223
+ };
224
+ _a7 = symbol7;
225
+ var name12 = "AI_TypeValidationError";
226
+ var marker13 = `vercel.ai.error.${name12}`;
227
+ var symbol13 = Symbol.for(marker13);
228
+ var _a13;
229
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
230
+ constructor({ value, cause }) {
231
+ super({
232
+ name: name12,
233
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
234
+ Error message: ${getErrorMessage(cause)}`,
235
+ cause
236
+ });
237
+ this[_a13] = true;
238
+ this.value = value;
239
+ }
240
+ static isInstance(error) {
241
+ return AISDKError.hasMarker(error, marker13);
242
+ }
243
+ /**
244
+ * Wraps an error into a TypeValidationError.
245
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
246
+ * Otherwise, it creates a new TypeValidationError.
247
+ *
248
+ * @param {Object} params - The parameters for wrapping the error.
249
+ * @param {unknown} params.value - The value that failed validation.
250
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
251
+ * @returns {TypeValidationError} A TypeValidationError instance.
252
+ */
253
+ static wrap({
254
+ value,
255
+ cause
256
+ }) {
257
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
258
+ }
259
+ };
260
+ _a13 = symbol13;
261
+ var TypeValidationError = _TypeValidationError;
262
+ var customAlphabet = (alphabet, defaultSize = 21) => {
263
+ return (size = defaultSize) => {
264
+ let id = "";
265
+ let i = size | 0;
266
+ while (i--) {
267
+ id += alphabet[Math.random() * alphabet.length | 0];
268
+ }
269
+ return id;
270
+ };
271
+ };
272
+ var import_secure_json_parse = __toESM(require_secure_json_parse());
273
+ function convertAsyncIteratorToReadableStream(iterator) {
274
+ return new ReadableStream({
275
+ /**
276
+ * Called when the consumer wants to pull more data from the stream.
277
+ *
278
+ * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.
279
+ * @returns {Promise<void>}
280
+ */
281
+ async pull(controller) {
282
+ try {
283
+ const { value, done } = await iterator.next();
284
+ if (done) {
285
+ controller.close();
286
+ } else {
287
+ controller.enqueue(value);
288
+ }
289
+ } catch (error) {
290
+ controller.error(error);
291
+ }
292
+ },
293
+ /**
294
+ * Called when the consumer cancels the stream.
295
+ */
296
+ cancel() {
297
+ }
298
+ });
299
+ }
300
+ var createIdGenerator = ({
301
+ prefix,
302
+ size: defaultSize = 16,
303
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
304
+ separator = "-"
305
+ } = {}) => {
306
+ const generator = customAlphabet(alphabet, defaultSize);
307
+ if (prefix == null) {
308
+ return generator;
309
+ }
310
+ if (alphabet.includes(separator)) {
311
+ throw new InvalidArgumentError({
312
+ argument: "separator",
313
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
314
+ });
315
+ }
316
+ return (size) => `${prefix}${separator}${generator(size)}`;
317
+ };
318
+ createIdGenerator();
319
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
320
+ function validator(validate) {
321
+ return { [validatorSymbol]: true, validate };
322
+ }
323
+ function isValidator(value) {
324
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
325
+ }
326
+ function asValidator(value) {
327
+ return isValidator(value) ? value : zodValidator(value);
328
+ }
329
+ function zodValidator(zodSchema2) {
330
+ return validator((value) => {
331
+ const result = zodSchema2.safeParse(value);
332
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
333
+ });
334
+ }
335
+ function safeValidateTypes({
336
+ value,
337
+ schema
338
+ }) {
339
+ const validator2 = asValidator(schema);
340
+ try {
341
+ if (validator2.validate == null) {
342
+ return { success: true, value };
343
+ }
344
+ const result = validator2.validate(value);
345
+ if (result.success) {
346
+ return result;
347
+ }
348
+ return {
349
+ success: false,
350
+ error: TypeValidationError.wrap({ value, cause: result.error })
351
+ };
352
+ } catch (error) {
353
+ return {
354
+ success: false,
355
+ error: TypeValidationError.wrap({ value, cause: error })
356
+ };
357
+ }
358
+ }
359
+ function safeParseJSON({
360
+ text: text2,
361
+ schema
362
+ }) {
363
+ try {
364
+ const value = import_secure_json_parse.default.parse(text2);
365
+ if (schema == null) {
366
+ return { success: true, value, rawValue: value };
367
+ }
368
+ const validationResult = safeValidateTypes({ value, schema });
369
+ return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
370
+ } catch (error) {
371
+ return {
372
+ success: false,
373
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text: text2, cause: error })
374
+ };
375
+ }
376
+ }
377
+ var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
378
+ var defaultOptions = {
379
+ name: void 0,
380
+ $refStrategy: "root",
381
+ basePath: ["#"],
382
+ effectStrategy: "input",
383
+ pipeStrategy: "all",
384
+ dateStrategy: "format:date-time",
385
+ mapStrategy: "entries",
386
+ removeAdditionalStrategy: "passthrough",
387
+ allowedAdditionalProperties: true,
388
+ rejectedAdditionalProperties: false,
389
+ definitionPath: "definitions",
390
+ target: "jsonSchema7",
391
+ strictUnions: false,
392
+ definitions: {},
393
+ errorMessages: false,
394
+ markdownDescription: false,
395
+ patternStrategy: "escape",
396
+ applyRegexFlags: false,
397
+ emailStrategy: "format:email",
398
+ base64Strategy: "contentEncoding:base64",
399
+ nameStrategy: "ref",
400
+ openAiAnyTypeName: "OpenAiAnyType"
401
+ };
402
+ var getDefaultOptions = (options) => typeof options === "string" ? {
403
+ ...defaultOptions,
404
+ name: options
405
+ } : {
406
+ ...defaultOptions,
407
+ ...options
408
+ };
409
+ var getRefs = (options) => {
410
+ const _options = getDefaultOptions(options);
411
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
412
+ return {
413
+ ..._options,
414
+ flags: { hasReferencedOpenAiAnyType: false },
415
+ currentPath,
416
+ propertyPath: void 0,
417
+ seen: new Map(Object.entries(_options.definitions).map(([name17, def]) => [
418
+ def._def,
419
+ {
420
+ def: def._def,
421
+ path: [..._options.basePath, _options.definitionPath, name17],
422
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
423
+ jsonSchema: void 0
424
+ }
425
+ ]))
426
+ };
427
+ };
428
+ function addErrorMessage(res, key, errorMessage, refs) {
429
+ if (!refs?.errorMessages)
430
+ return;
431
+ if (errorMessage) {
432
+ res.errorMessage = {
433
+ ...res.errorMessage,
434
+ [key]: errorMessage
435
+ };
436
+ }
437
+ }
438
+ function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
439
+ res[key] = value;
440
+ addErrorMessage(res, key, errorMessage, refs);
441
+ }
442
+ var getRelativePath = (pathA, pathB) => {
443
+ let i = 0;
444
+ for (; i < pathA.length && i < pathB.length; i++) {
445
+ if (pathA[i] !== pathB[i])
446
+ break;
447
+ }
448
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
449
+ };
450
+ function parseAnyDef(refs) {
451
+ if (refs.target !== "openAi") {
452
+ return {};
453
+ }
454
+ const anyDefinitionPath = [
455
+ ...refs.basePath,
456
+ refs.definitionPath,
457
+ refs.openAiAnyTypeName
458
+ ];
459
+ refs.flags.hasReferencedOpenAiAnyType = true;
460
+ return {
461
+ $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/")
462
+ };
463
+ }
464
+ function parseArrayDef(def, refs) {
465
+ const res = {
466
+ type: "array"
467
+ };
468
+ if (def.type?._def && def.type?._def?.typeName !== v3.ZodFirstPartyTypeKind.ZodAny) {
469
+ res.items = parseDef(def.type._def, {
470
+ ...refs,
471
+ currentPath: [...refs.currentPath, "items"]
472
+ });
473
+ }
474
+ if (def.minLength) {
475
+ setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
476
+ }
477
+ if (def.maxLength) {
478
+ setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
479
+ }
480
+ if (def.exactLength) {
481
+ setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
482
+ setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
483
+ }
484
+ return res;
485
+ }
486
+ function parseBigintDef(def, refs) {
487
+ const res = {
488
+ type: "integer",
489
+ format: "int64"
490
+ };
491
+ if (!def.checks)
492
+ return res;
493
+ for (const check of def.checks) {
494
+ switch (check.kind) {
495
+ case "min":
496
+ if (refs.target === "jsonSchema7") {
497
+ if (check.inclusive) {
498
+ setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
499
+ } else {
500
+ setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
501
+ }
502
+ } else {
503
+ if (!check.inclusive) {
504
+ res.exclusiveMinimum = true;
505
+ }
506
+ setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
507
+ }
508
+ break;
509
+ case "max":
510
+ if (refs.target === "jsonSchema7") {
511
+ if (check.inclusive) {
512
+ setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
513
+ } else {
514
+ setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
515
+ }
516
+ } else {
517
+ if (!check.inclusive) {
518
+ res.exclusiveMaximum = true;
519
+ }
520
+ setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
521
+ }
522
+ break;
523
+ case "multipleOf":
524
+ setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
525
+ break;
526
+ }
527
+ }
528
+ return res;
529
+ }
530
+ function parseBooleanDef() {
531
+ return {
532
+ type: "boolean"
533
+ };
534
+ }
535
+ function parseBrandedDef(_def, refs) {
536
+ return parseDef(_def.type._def, refs);
537
+ }
538
+ var parseCatchDef = (def, refs) => {
539
+ return parseDef(def.innerType._def, refs);
540
+ };
541
+ function parseDateDef(def, refs, overrideDateStrategy) {
542
+ const strategy = overrideDateStrategy ?? refs.dateStrategy;
543
+ if (Array.isArray(strategy)) {
544
+ return {
545
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
546
+ };
547
+ }
548
+ switch (strategy) {
549
+ case "string":
550
+ case "format:date-time":
551
+ return {
552
+ type: "string",
553
+ format: "date-time"
554
+ };
555
+ case "format:date":
556
+ return {
557
+ type: "string",
558
+ format: "date"
559
+ };
560
+ case "integer":
561
+ return integerDateParser(def, refs);
562
+ }
563
+ }
564
+ var integerDateParser = (def, refs) => {
565
+ const res = {
566
+ type: "integer",
567
+ format: "unix-time"
568
+ };
569
+ if (refs.target === "openApi3") {
570
+ return res;
571
+ }
572
+ for (const check of def.checks) {
573
+ switch (check.kind) {
574
+ case "min":
575
+ setResponseValueAndErrors(
576
+ res,
577
+ "minimum",
578
+ check.value,
579
+ // This is in milliseconds
580
+ check.message,
581
+ refs
582
+ );
583
+ break;
584
+ case "max":
585
+ setResponseValueAndErrors(
586
+ res,
587
+ "maximum",
588
+ check.value,
589
+ // This is in milliseconds
590
+ check.message,
591
+ refs
592
+ );
593
+ break;
594
+ }
595
+ }
596
+ return res;
597
+ };
598
+ function parseDefaultDef(_def, refs) {
599
+ return {
600
+ ...parseDef(_def.innerType._def, refs),
601
+ default: _def.defaultValue()
602
+ };
603
+ }
604
+ function parseEffectsDef(_def, refs) {
605
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs);
606
+ }
607
+ function parseEnumDef(def) {
608
+ return {
609
+ type: "string",
610
+ enum: Array.from(def.values)
611
+ };
612
+ }
613
+ var isJsonSchema7AllOfType = (type) => {
614
+ if ("type" in type && type.type === "string")
615
+ return false;
616
+ return "allOf" in type;
617
+ };
618
+ function parseIntersectionDef(def, refs) {
619
+ const allOf = [
620
+ parseDef(def.left._def, {
621
+ ...refs,
622
+ currentPath: [...refs.currentPath, "allOf", "0"]
623
+ }),
624
+ parseDef(def.right._def, {
625
+ ...refs,
626
+ currentPath: [...refs.currentPath, "allOf", "1"]
627
+ })
628
+ ].filter((x) => !!x);
629
+ let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
630
+ const mergedAllOf = [];
631
+ allOf.forEach((schema) => {
632
+ if (isJsonSchema7AllOfType(schema)) {
633
+ mergedAllOf.push(...schema.allOf);
634
+ if (schema.unevaluatedProperties === void 0) {
635
+ unevaluatedProperties = void 0;
636
+ }
637
+ } else {
638
+ let nestedSchema = schema;
639
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
640
+ const { additionalProperties, ...rest } = schema;
641
+ nestedSchema = rest;
642
+ } else {
643
+ unevaluatedProperties = void 0;
644
+ }
645
+ mergedAllOf.push(nestedSchema);
646
+ }
647
+ });
648
+ return mergedAllOf.length ? {
649
+ allOf: mergedAllOf,
650
+ ...unevaluatedProperties
651
+ } : void 0;
652
+ }
653
+ function parseLiteralDef(def, refs) {
654
+ const parsedType = typeof def.value;
655
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
656
+ return {
657
+ type: Array.isArray(def.value) ? "array" : "object"
658
+ };
659
+ }
660
+ if (refs.target === "openApi3") {
661
+ return {
662
+ type: parsedType === "bigint" ? "integer" : parsedType,
663
+ enum: [def.value]
664
+ };
665
+ }
666
+ return {
667
+ type: parsedType === "bigint" ? "integer" : parsedType,
668
+ const: def.value
669
+ };
670
+ }
671
+ var emojiRegex = void 0;
672
+ var zodPatterns = {
673
+ /**
674
+ * `c` was changed to `[cC]` to replicate /i flag
675
+ */
676
+ cuid: /^[cC][^\s-]{8,}$/,
677
+ cuid2: /^[0-9a-z]+$/,
678
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
679
+ /**
680
+ * `a-z` was added to replicate /i flag
681
+ */
682
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
683
+ /**
684
+ * Constructed a valid Unicode RegExp
685
+ *
686
+ * Lazily instantiate since this type of regex isn't supported
687
+ * in all envs (e.g. React Native).
688
+ *
689
+ * See:
690
+ * https://github.com/colinhacks/zod/issues/2433
691
+ * Fix in Zod:
692
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
693
+ */
694
+ emoji: () => {
695
+ if (emojiRegex === void 0) {
696
+ emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
697
+ }
698
+ return emojiRegex;
699
+ },
700
+ /**
701
+ * Unused
702
+ */
703
+ 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}$/,
704
+ /**
705
+ * Unused
706
+ */
707
+ 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])$/,
708
+ 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])$/,
709
+ /**
710
+ * Unused
711
+ */
712
+ 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})))$/,
713
+ 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])$/,
714
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
715
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
716
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
717
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
718
+ };
719
+ function parseStringDef(def, refs) {
720
+ const res = {
721
+ type: "string"
722
+ };
723
+ if (def.checks) {
724
+ for (const check of def.checks) {
725
+ switch (check.kind) {
726
+ case "min":
727
+ setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
728
+ break;
729
+ case "max":
730
+ setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
731
+ break;
732
+ case "email":
733
+ switch (refs.emailStrategy) {
734
+ case "format:email":
735
+ addFormat(res, "email", check.message, refs);
736
+ break;
737
+ case "format:idn-email":
738
+ addFormat(res, "idn-email", check.message, refs);
739
+ break;
740
+ case "pattern:zod":
741
+ addPattern(res, zodPatterns.email, check.message, refs);
742
+ break;
743
+ }
744
+ break;
745
+ case "url":
746
+ addFormat(res, "uri", check.message, refs);
747
+ break;
748
+ case "uuid":
749
+ addFormat(res, "uuid", check.message, refs);
750
+ break;
751
+ case "regex":
752
+ addPattern(res, check.regex, check.message, refs);
753
+ break;
754
+ case "cuid":
755
+ addPattern(res, zodPatterns.cuid, check.message, refs);
756
+ break;
757
+ case "cuid2":
758
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
759
+ break;
760
+ case "startsWith":
761
+ addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
762
+ break;
763
+ case "endsWith":
764
+ addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
765
+ break;
766
+ case "datetime":
767
+ addFormat(res, "date-time", check.message, refs);
768
+ break;
769
+ case "date":
770
+ addFormat(res, "date", check.message, refs);
771
+ break;
772
+ case "time":
773
+ addFormat(res, "time", check.message, refs);
774
+ break;
775
+ case "duration":
776
+ addFormat(res, "duration", check.message, refs);
777
+ break;
778
+ case "length":
779
+ setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
780
+ setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
781
+ break;
782
+ case "includes": {
783
+ addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
784
+ break;
785
+ }
786
+ case "ip": {
787
+ if (check.version !== "v6") {
788
+ addFormat(res, "ipv4", check.message, refs);
789
+ }
790
+ if (check.version !== "v4") {
791
+ addFormat(res, "ipv6", check.message, refs);
792
+ }
793
+ break;
794
+ }
795
+ case "base64url":
796
+ addPattern(res, zodPatterns.base64url, check.message, refs);
797
+ break;
798
+ case "jwt":
799
+ addPattern(res, zodPatterns.jwt, check.message, refs);
800
+ break;
801
+ case "cidr": {
802
+ if (check.version !== "v6") {
803
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
804
+ }
805
+ if (check.version !== "v4") {
806
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
807
+ }
808
+ break;
809
+ }
810
+ case "emoji":
811
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
812
+ break;
813
+ case "ulid": {
814
+ addPattern(res, zodPatterns.ulid, check.message, refs);
815
+ break;
816
+ }
817
+ case "base64": {
818
+ switch (refs.base64Strategy) {
819
+ case "format:binary": {
820
+ addFormat(res, "binary", check.message, refs);
821
+ break;
822
+ }
823
+ case "contentEncoding:base64": {
824
+ setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
825
+ break;
826
+ }
827
+ case "pattern:zod": {
828
+ addPattern(res, zodPatterns.base64, check.message, refs);
829
+ break;
830
+ }
831
+ }
832
+ break;
833
+ }
834
+ case "nanoid": {
835
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
836
+ }
837
+ }
838
+ }
839
+ }
840
+ return res;
841
+ }
842
+ function escapeLiteralCheckValue(literal, refs) {
843
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
844
+ }
845
+ var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
846
+ function escapeNonAlphaNumeric(source) {
847
+ let result = "";
848
+ for (let i = 0; i < source.length; i++) {
849
+ if (!ALPHA_NUMERIC.has(source[i])) {
850
+ result += "\\";
851
+ }
852
+ result += source[i];
853
+ }
854
+ return result;
855
+ }
856
+ function addFormat(schema, value, message, refs) {
857
+ if (schema.format || schema.anyOf?.some((x) => x.format)) {
858
+ if (!schema.anyOf) {
859
+ schema.anyOf = [];
860
+ }
861
+ if (schema.format) {
862
+ schema.anyOf.push({
863
+ format: schema.format,
864
+ ...schema.errorMessage && refs.errorMessages && {
865
+ errorMessage: { format: schema.errorMessage.format }
866
+ }
867
+ });
868
+ delete schema.format;
869
+ if (schema.errorMessage) {
870
+ delete schema.errorMessage.format;
871
+ if (Object.keys(schema.errorMessage).length === 0) {
872
+ delete schema.errorMessage;
873
+ }
874
+ }
875
+ }
876
+ schema.anyOf.push({
877
+ format: value,
878
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
879
+ });
880
+ } else {
881
+ setResponseValueAndErrors(schema, "format", value, message, refs);
882
+ }
883
+ }
884
+ function addPattern(schema, regex, message, refs) {
885
+ if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
886
+ if (!schema.allOf) {
887
+ schema.allOf = [];
888
+ }
889
+ if (schema.pattern) {
890
+ schema.allOf.push({
891
+ pattern: schema.pattern,
892
+ ...schema.errorMessage && refs.errorMessages && {
893
+ errorMessage: { pattern: schema.errorMessage.pattern }
894
+ }
895
+ });
896
+ delete schema.pattern;
897
+ if (schema.errorMessage) {
898
+ delete schema.errorMessage.pattern;
899
+ if (Object.keys(schema.errorMessage).length === 0) {
900
+ delete schema.errorMessage;
901
+ }
902
+ }
903
+ }
904
+ schema.allOf.push({
905
+ pattern: stringifyRegExpWithFlags(regex, refs),
906
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
907
+ });
908
+ } else {
909
+ setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
910
+ }
911
+ }
912
+ function stringifyRegExpWithFlags(regex, refs) {
913
+ if (!refs.applyRegexFlags || !regex.flags) {
914
+ return regex.source;
915
+ }
916
+ const flags = {
917
+ i: regex.flags.includes("i"),
918
+ m: regex.flags.includes("m"),
919
+ s: regex.flags.includes("s")
920
+ // `.` matches newlines
921
+ };
922
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
923
+ let pattern = "";
924
+ let isEscaped = false;
925
+ let inCharGroup = false;
926
+ let inCharRange = false;
927
+ for (let i = 0; i < source.length; i++) {
928
+ if (isEscaped) {
929
+ pattern += source[i];
930
+ isEscaped = false;
931
+ continue;
932
+ }
933
+ if (flags.i) {
934
+ if (inCharGroup) {
935
+ if (source[i].match(/[a-z]/)) {
936
+ if (inCharRange) {
937
+ pattern += source[i];
938
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
939
+ inCharRange = false;
940
+ } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
941
+ pattern += source[i];
942
+ inCharRange = true;
943
+ } else {
944
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
945
+ }
946
+ continue;
947
+ }
948
+ } else if (source[i].match(/[a-z]/)) {
949
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
950
+ continue;
951
+ }
952
+ }
953
+ if (flags.m) {
954
+ if (source[i] === "^") {
955
+ pattern += `(^|(?<=[\r
956
+ ]))`;
957
+ continue;
958
+ } else if (source[i] === "$") {
959
+ pattern += `($|(?=[\r
960
+ ]))`;
961
+ continue;
962
+ }
963
+ }
964
+ if (flags.s && source[i] === ".") {
965
+ pattern += inCharGroup ? `${source[i]}\r
966
+ ` : `[${source[i]}\r
967
+ ]`;
968
+ continue;
969
+ }
970
+ pattern += source[i];
971
+ if (source[i] === "\\") {
972
+ isEscaped = true;
973
+ } else if (inCharGroup && source[i] === "]") {
974
+ inCharGroup = false;
975
+ } else if (!inCharGroup && source[i] === "[") {
976
+ inCharGroup = true;
977
+ }
978
+ }
979
+ return pattern;
980
+ }
981
+ function parseRecordDef(def, refs) {
982
+ if (refs.target === "openAi") {
983
+ console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
984
+ }
985
+ if (refs.target === "openApi3" && def.keyType?._def.typeName === v3.ZodFirstPartyTypeKind.ZodEnum) {
986
+ return {
987
+ type: "object",
988
+ required: def.keyType._def.values,
989
+ properties: def.keyType._def.values.reduce((acc, key) => ({
990
+ ...acc,
991
+ [key]: parseDef(def.valueType._def, {
992
+ ...refs,
993
+ currentPath: [...refs.currentPath, "properties", key]
994
+ }) ?? parseAnyDef(refs)
995
+ }), {}),
996
+ additionalProperties: refs.rejectedAdditionalProperties
997
+ };
998
+ }
999
+ const schema = {
1000
+ type: "object",
1001
+ additionalProperties: parseDef(def.valueType._def, {
1002
+ ...refs,
1003
+ currentPath: [...refs.currentPath, "additionalProperties"]
1004
+ }) ?? refs.allowedAdditionalProperties
1005
+ };
1006
+ if (refs.target === "openApi3") {
1007
+ return schema;
1008
+ }
1009
+ if (def.keyType?._def.typeName === v3.ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
1010
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1011
+ return {
1012
+ ...schema,
1013
+ propertyNames: keyType
1014
+ };
1015
+ } else if (def.keyType?._def.typeName === v3.ZodFirstPartyTypeKind.ZodEnum) {
1016
+ return {
1017
+ ...schema,
1018
+ propertyNames: {
1019
+ enum: def.keyType._def.values
1020
+ }
1021
+ };
1022
+ } else if (def.keyType?._def.typeName === v3.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === v3.ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
1023
+ const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
1024
+ return {
1025
+ ...schema,
1026
+ propertyNames: keyType
1027
+ };
1028
+ }
1029
+ return schema;
1030
+ }
1031
+ function parseMapDef(def, refs) {
1032
+ if (refs.mapStrategy === "record") {
1033
+ return parseRecordDef(def, refs);
1034
+ }
1035
+ const keys = parseDef(def.keyType._def, {
1036
+ ...refs,
1037
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1038
+ }) || parseAnyDef(refs);
1039
+ const values = parseDef(def.valueType._def, {
1040
+ ...refs,
1041
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1042
+ }) || parseAnyDef(refs);
1043
+ return {
1044
+ type: "array",
1045
+ maxItems: 125,
1046
+ items: {
1047
+ type: "array",
1048
+ items: [keys, values],
1049
+ minItems: 2,
1050
+ maxItems: 2
1051
+ }
1052
+ };
1053
+ }
1054
+ function parseNativeEnumDef(def) {
1055
+ const object2 = def.values;
1056
+ const actualKeys = Object.keys(def.values).filter((key) => {
1057
+ return typeof object2[object2[key]] !== "number";
1058
+ });
1059
+ const actualValues = actualKeys.map((key) => object2[key]);
1060
+ const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
1061
+ return {
1062
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1063
+ enum: actualValues
1064
+ };
1065
+ }
1066
+ function parseNeverDef(refs) {
1067
+ return refs.target === "openAi" ? void 0 : {
1068
+ not: parseAnyDef({
1069
+ ...refs,
1070
+ currentPath: [...refs.currentPath, "not"]
1071
+ })
1072
+ };
1073
+ }
1074
+ function parseNullDef(refs) {
1075
+ return refs.target === "openApi3" ? {
1076
+ enum: ["null"],
1077
+ nullable: true
1078
+ } : {
1079
+ type: "null"
1080
+ };
1081
+ }
1082
+ var primitiveMappings = {
1083
+ ZodString: "string",
1084
+ ZodNumber: "number",
1085
+ ZodBigInt: "integer",
1086
+ ZodBoolean: "boolean",
1087
+ ZodNull: "null"
1088
+ };
1089
+ function parseUnionDef(def, refs) {
1090
+ if (refs.target === "openApi3")
1091
+ return asAnyOf(def, refs);
1092
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1093
+ if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
1094
+ const types = options.reduce((types2, x) => {
1095
+ const type = primitiveMappings[x._def.typeName];
1096
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1097
+ }, []);
1098
+ return {
1099
+ type: types.length > 1 ? types : types[0]
1100
+ };
1101
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1102
+ const types = options.reduce((acc, x) => {
1103
+ const type = typeof x._def.value;
1104
+ switch (type) {
1105
+ case "string":
1106
+ case "number":
1107
+ case "boolean":
1108
+ return [...acc, type];
1109
+ case "bigint":
1110
+ return [...acc, "integer"];
1111
+ case "object":
1112
+ if (x._def.value === null)
1113
+ return [...acc, "null"];
1114
+ case "symbol":
1115
+ case "undefined":
1116
+ case "function":
1117
+ default:
1118
+ return acc;
1119
+ }
1120
+ }, []);
1121
+ if (types.length === options.length) {
1122
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1123
+ return {
1124
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1125
+ enum: options.reduce((acc, x) => {
1126
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1127
+ }, [])
1128
+ };
1129
+ }
1130
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1131
+ return {
1132
+ type: "string",
1133
+ enum: options.reduce((acc, x) => [
1134
+ ...acc,
1135
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1136
+ ], [])
1137
+ };
1138
+ }
1139
+ return asAnyOf(def, refs);
1140
+ }
1141
+ var asAnyOf = (def, refs) => {
1142
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
1143
+ ...refs,
1144
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1145
+ })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
1146
+ return anyOf.length ? { anyOf } : void 0;
1147
+ };
1148
+ function parseNullableDef(def, refs) {
1149
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1150
+ if (refs.target === "openApi3") {
1151
+ return {
1152
+ type: primitiveMappings[def.innerType._def.typeName],
1153
+ nullable: true
1154
+ };
1155
+ }
1156
+ return {
1157
+ type: [
1158
+ primitiveMappings[def.innerType._def.typeName],
1159
+ "null"
1160
+ ]
1161
+ };
1162
+ }
1163
+ if (refs.target === "openApi3") {
1164
+ const base2 = parseDef(def.innerType._def, {
1165
+ ...refs,
1166
+ currentPath: [...refs.currentPath]
1167
+ });
1168
+ if (base2 && "$ref" in base2)
1169
+ return { allOf: [base2], nullable: true };
1170
+ return base2 && { ...base2, nullable: true };
1171
+ }
1172
+ const base = parseDef(def.innerType._def, {
1173
+ ...refs,
1174
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1175
+ });
1176
+ return base && { anyOf: [base, { type: "null" }] };
1177
+ }
1178
+ function parseNumberDef(def, refs) {
1179
+ const res = {
1180
+ type: "number"
1181
+ };
1182
+ if (!def.checks)
1183
+ return res;
1184
+ for (const check of def.checks) {
1185
+ switch (check.kind) {
1186
+ case "int":
1187
+ res.type = "integer";
1188
+ addErrorMessage(res, "type", check.message, refs);
1189
+ break;
1190
+ case "min":
1191
+ if (refs.target === "jsonSchema7") {
1192
+ if (check.inclusive) {
1193
+ setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
1194
+ } else {
1195
+ setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
1196
+ }
1197
+ } else {
1198
+ if (!check.inclusive) {
1199
+ res.exclusiveMinimum = true;
1200
+ }
1201
+ setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
1202
+ }
1203
+ break;
1204
+ case "max":
1205
+ if (refs.target === "jsonSchema7") {
1206
+ if (check.inclusive) {
1207
+ setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
1208
+ } else {
1209
+ setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
1210
+ }
1211
+ } else {
1212
+ if (!check.inclusive) {
1213
+ res.exclusiveMaximum = true;
1214
+ }
1215
+ setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
1216
+ }
1217
+ break;
1218
+ case "multipleOf":
1219
+ setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
1220
+ break;
1221
+ }
1222
+ }
1223
+ return res;
1224
+ }
1225
+ function parseObjectDef(def, refs) {
1226
+ const forceOptionalIntoNullable = refs.target === "openAi";
1227
+ const result = {
1228
+ type: "object",
1229
+ properties: {}
1230
+ };
1231
+ const required = [];
1232
+ const shape = def.shape();
1233
+ for (const propName in shape) {
1234
+ let propDef = shape[propName];
1235
+ if (propDef === void 0 || propDef._def === void 0) {
1236
+ continue;
1237
+ }
1238
+ let propOptional = safeIsOptional(propDef);
1239
+ if (propOptional && forceOptionalIntoNullable) {
1240
+ if (propDef._def.typeName === "ZodOptional") {
1241
+ propDef = propDef._def.innerType;
1242
+ }
1243
+ if (!propDef.isNullable()) {
1244
+ propDef = propDef.nullable();
1245
+ }
1246
+ propOptional = false;
1247
+ }
1248
+ const parsedDef = parseDef(propDef._def, {
1249
+ ...refs,
1250
+ currentPath: [...refs.currentPath, "properties", propName],
1251
+ propertyPath: [...refs.currentPath, "properties", propName]
1252
+ });
1253
+ if (parsedDef === void 0) {
1254
+ continue;
1255
+ }
1256
+ result.properties[propName] = parsedDef;
1257
+ if (!propOptional) {
1258
+ required.push(propName);
1259
+ }
1260
+ }
1261
+ if (required.length) {
1262
+ result.required = required;
1263
+ }
1264
+ const additionalProperties = decideAdditionalProperties(def, refs);
1265
+ if (additionalProperties !== void 0) {
1266
+ result.additionalProperties = additionalProperties;
1267
+ }
1268
+ return result;
1269
+ }
1270
+ function decideAdditionalProperties(def, refs) {
1271
+ if (def.catchall._def.typeName !== "ZodNever") {
1272
+ return parseDef(def.catchall._def, {
1273
+ ...refs,
1274
+ currentPath: [...refs.currentPath, "additionalProperties"]
1275
+ });
1276
+ }
1277
+ switch (def.unknownKeys) {
1278
+ case "passthrough":
1279
+ return refs.allowedAdditionalProperties;
1280
+ case "strict":
1281
+ return refs.rejectedAdditionalProperties;
1282
+ case "strip":
1283
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1284
+ }
1285
+ }
1286
+ function safeIsOptional(schema) {
1287
+ try {
1288
+ return schema.isOptional();
1289
+ } catch {
1290
+ return true;
1291
+ }
1292
+ }
1293
+ var parseOptionalDef = (def, refs) => {
1294
+ if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
1295
+ return parseDef(def.innerType._def, refs);
1296
+ }
1297
+ const innerSchema = parseDef(def.innerType._def, {
1298
+ ...refs,
1299
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1300
+ });
1301
+ return innerSchema ? {
1302
+ anyOf: [
1303
+ {
1304
+ not: parseAnyDef(refs)
1305
+ },
1306
+ innerSchema
1307
+ ]
1308
+ } : parseAnyDef(refs);
1309
+ };
1310
+ var parsePipelineDef = (def, refs) => {
1311
+ if (refs.pipeStrategy === "input") {
1312
+ return parseDef(def.in._def, refs);
1313
+ } else if (refs.pipeStrategy === "output") {
1314
+ return parseDef(def.out._def, refs);
1315
+ }
1316
+ const a = parseDef(def.in._def, {
1317
+ ...refs,
1318
+ currentPath: [...refs.currentPath, "allOf", "0"]
1319
+ });
1320
+ const b = parseDef(def.out._def, {
1321
+ ...refs,
1322
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1323
+ });
1324
+ return {
1325
+ allOf: [a, b].filter((x) => x !== void 0)
1326
+ };
1327
+ };
1328
+ function parsePromiseDef(def, refs) {
1329
+ return parseDef(def.type._def, refs);
1330
+ }
1331
+ function parseSetDef(def, refs) {
1332
+ const items = parseDef(def.valueType._def, {
1333
+ ...refs,
1334
+ currentPath: [...refs.currentPath, "items"]
1335
+ });
1336
+ const schema = {
1337
+ type: "array",
1338
+ uniqueItems: true,
1339
+ items
1340
+ };
1341
+ if (def.minSize) {
1342
+ setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
1343
+ }
1344
+ if (def.maxSize) {
1345
+ setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
1346
+ }
1347
+ return schema;
1348
+ }
1349
+ function parseTupleDef(def, refs) {
1350
+ if (def.rest) {
1351
+ return {
1352
+ type: "array",
1353
+ minItems: def.items.length,
1354
+ items: def.items.map((x, i) => parseDef(x._def, {
1355
+ ...refs,
1356
+ currentPath: [...refs.currentPath, "items", `${i}`]
1357
+ })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
1358
+ additionalItems: parseDef(def.rest._def, {
1359
+ ...refs,
1360
+ currentPath: [...refs.currentPath, "additionalItems"]
1361
+ })
1362
+ };
1363
+ } else {
1364
+ return {
1365
+ type: "array",
1366
+ minItems: def.items.length,
1367
+ maxItems: def.items.length,
1368
+ items: def.items.map((x, i) => parseDef(x._def, {
1369
+ ...refs,
1370
+ currentPath: [...refs.currentPath, "items", `${i}`]
1371
+ })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
1372
+ };
1373
+ }
1374
+ }
1375
+ function parseUndefinedDef(refs) {
1376
+ return {
1377
+ not: parseAnyDef(refs)
1378
+ };
1379
+ }
1380
+ function parseUnknownDef(refs) {
1381
+ return parseAnyDef(refs);
1382
+ }
1383
+ var parseReadonlyDef = (def, refs) => {
1384
+ return parseDef(def.innerType._def, refs);
1385
+ };
1386
+ var selectParser = (def, typeName, refs) => {
1387
+ switch (typeName) {
1388
+ case v3.ZodFirstPartyTypeKind.ZodString:
1389
+ return parseStringDef(def, refs);
1390
+ case v3.ZodFirstPartyTypeKind.ZodNumber:
1391
+ return parseNumberDef(def, refs);
1392
+ case v3.ZodFirstPartyTypeKind.ZodObject:
1393
+ return parseObjectDef(def, refs);
1394
+ case v3.ZodFirstPartyTypeKind.ZodBigInt:
1395
+ return parseBigintDef(def, refs);
1396
+ case v3.ZodFirstPartyTypeKind.ZodBoolean:
1397
+ return parseBooleanDef();
1398
+ case v3.ZodFirstPartyTypeKind.ZodDate:
1399
+ return parseDateDef(def, refs);
1400
+ case v3.ZodFirstPartyTypeKind.ZodUndefined:
1401
+ return parseUndefinedDef(refs);
1402
+ case v3.ZodFirstPartyTypeKind.ZodNull:
1403
+ return parseNullDef(refs);
1404
+ case v3.ZodFirstPartyTypeKind.ZodArray:
1405
+ return parseArrayDef(def, refs);
1406
+ case v3.ZodFirstPartyTypeKind.ZodUnion:
1407
+ case v3.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
1408
+ return parseUnionDef(def, refs);
1409
+ case v3.ZodFirstPartyTypeKind.ZodIntersection:
1410
+ return parseIntersectionDef(def, refs);
1411
+ case v3.ZodFirstPartyTypeKind.ZodTuple:
1412
+ return parseTupleDef(def, refs);
1413
+ case v3.ZodFirstPartyTypeKind.ZodRecord:
1414
+ return parseRecordDef(def, refs);
1415
+ case v3.ZodFirstPartyTypeKind.ZodLiteral:
1416
+ return parseLiteralDef(def, refs);
1417
+ case v3.ZodFirstPartyTypeKind.ZodEnum:
1418
+ return parseEnumDef(def);
1419
+ case v3.ZodFirstPartyTypeKind.ZodNativeEnum:
1420
+ return parseNativeEnumDef(def);
1421
+ case v3.ZodFirstPartyTypeKind.ZodNullable:
1422
+ return parseNullableDef(def, refs);
1423
+ case v3.ZodFirstPartyTypeKind.ZodOptional:
1424
+ return parseOptionalDef(def, refs);
1425
+ case v3.ZodFirstPartyTypeKind.ZodMap:
1426
+ return parseMapDef(def, refs);
1427
+ case v3.ZodFirstPartyTypeKind.ZodSet:
1428
+ return parseSetDef(def, refs);
1429
+ case v3.ZodFirstPartyTypeKind.ZodLazy:
1430
+ return () => def.getter()._def;
1431
+ case v3.ZodFirstPartyTypeKind.ZodPromise:
1432
+ return parsePromiseDef(def, refs);
1433
+ case v3.ZodFirstPartyTypeKind.ZodNaN:
1434
+ case v3.ZodFirstPartyTypeKind.ZodNever:
1435
+ return parseNeverDef(refs);
1436
+ case v3.ZodFirstPartyTypeKind.ZodEffects:
1437
+ return parseEffectsDef(def, refs);
1438
+ case v3.ZodFirstPartyTypeKind.ZodAny:
1439
+ return parseAnyDef(refs);
1440
+ case v3.ZodFirstPartyTypeKind.ZodUnknown:
1441
+ return parseUnknownDef(refs);
1442
+ case v3.ZodFirstPartyTypeKind.ZodDefault:
1443
+ return parseDefaultDef(def, refs);
1444
+ case v3.ZodFirstPartyTypeKind.ZodBranded:
1445
+ return parseBrandedDef(def, refs);
1446
+ case v3.ZodFirstPartyTypeKind.ZodReadonly:
1447
+ return parseReadonlyDef(def, refs);
1448
+ case v3.ZodFirstPartyTypeKind.ZodCatch:
1449
+ return parseCatchDef(def, refs);
1450
+ case v3.ZodFirstPartyTypeKind.ZodPipeline:
1451
+ return parsePipelineDef(def, refs);
1452
+ case v3.ZodFirstPartyTypeKind.ZodFunction:
1453
+ case v3.ZodFirstPartyTypeKind.ZodVoid:
1454
+ case v3.ZodFirstPartyTypeKind.ZodSymbol:
1455
+ return void 0;
1456
+ default:
1457
+ return /* @__PURE__ */ ((_) => void 0)();
1458
+ }
1459
+ };
1460
+ function parseDef(def, refs, forceResolution = false) {
1461
+ const seenItem = refs.seen.get(def);
1462
+ if (refs.override) {
1463
+ const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
1464
+ if (overrideResult !== ignoreOverride) {
1465
+ return overrideResult;
1466
+ }
1467
+ }
1468
+ if (seenItem && !forceResolution) {
1469
+ const seenSchema = get$ref(seenItem, refs);
1470
+ if (seenSchema !== void 0) {
1471
+ return seenSchema;
1472
+ }
1473
+ }
1474
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1475
+ refs.seen.set(def, newItem);
1476
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1477
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1478
+ if (jsonSchema2) {
1479
+ addMeta(def, refs, jsonSchema2);
1480
+ }
1481
+ if (refs.postProcess) {
1482
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1483
+ newItem.jsonSchema = jsonSchema2;
1484
+ return postProcessResult;
1485
+ }
1486
+ newItem.jsonSchema = jsonSchema2;
1487
+ return jsonSchema2;
1488
+ }
1489
+ var get$ref = (item, refs) => {
1490
+ switch (refs.$refStrategy) {
1491
+ case "root":
1492
+ return { $ref: item.path.join("/") };
1493
+ case "relative":
1494
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1495
+ case "none":
1496
+ case "seen": {
1497
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1498
+ console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
1499
+ return parseAnyDef(refs);
1500
+ }
1501
+ return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0;
1502
+ }
1503
+ }
1504
+ };
1505
+ var addMeta = (def, refs, jsonSchema2) => {
1506
+ if (def.description) {
1507
+ jsonSchema2.description = def.description;
1508
+ if (refs.markdownDescription) {
1509
+ jsonSchema2.markdownDescription = def.description;
1510
+ }
1511
+ }
1512
+ return jsonSchema2;
1513
+ };
1514
+ var zodToJsonSchema2 = (schema, options) => {
1515
+ const refs = getRefs(options);
1516
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name18, schema2]) => ({
1517
+ ...acc,
1518
+ [name18]: parseDef(schema2._def, {
1519
+ ...refs,
1520
+ currentPath: [...refs.basePath, refs.definitionPath, name18]
1521
+ }, true) ?? parseAnyDef(refs)
1522
+ }), {}) : void 0;
1523
+ const name17 = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
1524
+ const main = parseDef(schema._def, name17 === void 0 ? refs : {
1525
+ ...refs,
1526
+ currentPath: [...refs.basePath, refs.definitionPath, name17]
1527
+ }, false) ?? parseAnyDef(refs);
1528
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1529
+ if (title !== void 0) {
1530
+ main.title = title;
1531
+ }
1532
+ if (refs.flags.hasReferencedOpenAiAnyType) {
1533
+ if (!definitions) {
1534
+ definitions = {};
1535
+ }
1536
+ if (!definitions[refs.openAiAnyTypeName]) {
1537
+ definitions[refs.openAiAnyTypeName] = {
1538
+ // Skipping "object" as no properties can be defined and additionalProperties must be "false"
1539
+ type: ["string", "number", "integer", "boolean", "array", "null"],
1540
+ items: {
1541
+ $ref: refs.$refStrategy === "relative" ? "1" : [
1542
+ ...refs.basePath,
1543
+ refs.definitionPath,
1544
+ refs.openAiAnyTypeName
1545
+ ].join("/")
1546
+ }
1547
+ };
1548
+ }
1549
+ }
1550
+ const combined = name17 === void 0 ? definitions ? {
1551
+ ...main,
1552
+ [refs.definitionPath]: definitions
1553
+ } : main : {
1554
+ $ref: [
1555
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1556
+ refs.definitionPath,
1557
+ name17
1558
+ ].join("/"),
1559
+ [refs.definitionPath]: {
1560
+ ...definitions,
1561
+ [name17]: main
1562
+ }
1563
+ };
1564
+ if (refs.target === "jsonSchema7") {
1565
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1566
+ } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
1567
+ combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
1568
+ }
1569
+ if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {
1570
+ console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
1571
+ }
1572
+ return combined;
1573
+ };
1574
+ var esm_default = zodToJsonSchema2;
1575
+ function fixJson(input) {
1576
+ const stack = ["ROOT"];
1577
+ let lastValidIndex = -1;
1578
+ let literalStart = null;
1579
+ function processValueStart(char, i, swapState) {
1580
+ {
1581
+ switch (char) {
1582
+ case '"': {
1583
+ lastValidIndex = i;
1584
+ stack.pop();
1585
+ stack.push(swapState);
1586
+ stack.push("INSIDE_STRING");
1587
+ break;
1588
+ }
1589
+ case "f":
1590
+ case "t":
1591
+ case "n": {
1592
+ lastValidIndex = i;
1593
+ literalStart = i;
1594
+ stack.pop();
1595
+ stack.push(swapState);
1596
+ stack.push("INSIDE_LITERAL");
1597
+ break;
1598
+ }
1599
+ case "-": {
1600
+ stack.pop();
1601
+ stack.push(swapState);
1602
+ stack.push("INSIDE_NUMBER");
1603
+ break;
1604
+ }
1605
+ case "0":
1606
+ case "1":
1607
+ case "2":
1608
+ case "3":
1609
+ case "4":
1610
+ case "5":
1611
+ case "6":
1612
+ case "7":
1613
+ case "8":
1614
+ case "9": {
1615
+ lastValidIndex = i;
1616
+ stack.pop();
1617
+ stack.push(swapState);
1618
+ stack.push("INSIDE_NUMBER");
1619
+ break;
1620
+ }
1621
+ case "{": {
1622
+ lastValidIndex = i;
1623
+ stack.pop();
1624
+ stack.push(swapState);
1625
+ stack.push("INSIDE_OBJECT_START");
1626
+ break;
1627
+ }
1628
+ case "[": {
1629
+ lastValidIndex = i;
1630
+ stack.pop();
1631
+ stack.push(swapState);
1632
+ stack.push("INSIDE_ARRAY_START");
1633
+ break;
1634
+ }
1635
+ }
1636
+ }
1637
+ }
1638
+ function processAfterObjectValue(char, i) {
1639
+ switch (char) {
1640
+ case ",": {
1641
+ stack.pop();
1642
+ stack.push("INSIDE_OBJECT_AFTER_COMMA");
1643
+ break;
1644
+ }
1645
+ case "}": {
1646
+ lastValidIndex = i;
1647
+ stack.pop();
1648
+ break;
1649
+ }
1650
+ }
1651
+ }
1652
+ function processAfterArrayValue(char, i) {
1653
+ switch (char) {
1654
+ case ",": {
1655
+ stack.pop();
1656
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
1657
+ break;
1658
+ }
1659
+ case "]": {
1660
+ lastValidIndex = i;
1661
+ stack.pop();
1662
+ break;
1663
+ }
1664
+ }
1665
+ }
1666
+ for (let i = 0; i < input.length; i++) {
1667
+ const char = input[i];
1668
+ const currentState = stack[stack.length - 1];
1669
+ switch (currentState) {
1670
+ case "ROOT":
1671
+ processValueStart(char, i, "FINISH");
1672
+ break;
1673
+ case "INSIDE_OBJECT_START": {
1674
+ switch (char) {
1675
+ case '"': {
1676
+ stack.pop();
1677
+ stack.push("INSIDE_OBJECT_KEY");
1678
+ break;
1679
+ }
1680
+ case "}": {
1681
+ lastValidIndex = i;
1682
+ stack.pop();
1683
+ break;
1684
+ }
1685
+ }
1686
+ break;
1687
+ }
1688
+ case "INSIDE_OBJECT_AFTER_COMMA": {
1689
+ switch (char) {
1690
+ case '"': {
1691
+ stack.pop();
1692
+ stack.push("INSIDE_OBJECT_KEY");
1693
+ break;
1694
+ }
1695
+ }
1696
+ break;
1697
+ }
1698
+ case "INSIDE_OBJECT_KEY": {
1699
+ switch (char) {
1700
+ case '"': {
1701
+ stack.pop();
1702
+ stack.push("INSIDE_OBJECT_AFTER_KEY");
1703
+ break;
1704
+ }
1705
+ }
1706
+ break;
1707
+ }
1708
+ case "INSIDE_OBJECT_AFTER_KEY": {
1709
+ switch (char) {
1710
+ case ":": {
1711
+ stack.pop();
1712
+ stack.push("INSIDE_OBJECT_BEFORE_VALUE");
1713
+ break;
1714
+ }
1715
+ }
1716
+ break;
1717
+ }
1718
+ case "INSIDE_OBJECT_BEFORE_VALUE": {
1719
+ processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
1720
+ break;
1721
+ }
1722
+ case "INSIDE_OBJECT_AFTER_VALUE": {
1723
+ processAfterObjectValue(char, i);
1724
+ break;
1725
+ }
1726
+ case "INSIDE_STRING": {
1727
+ switch (char) {
1728
+ case '"': {
1729
+ stack.pop();
1730
+ lastValidIndex = i;
1731
+ break;
1732
+ }
1733
+ case "\\": {
1734
+ stack.push("INSIDE_STRING_ESCAPE");
1735
+ break;
1736
+ }
1737
+ default: {
1738
+ lastValidIndex = i;
1739
+ }
1740
+ }
1741
+ break;
1742
+ }
1743
+ case "INSIDE_ARRAY_START": {
1744
+ switch (char) {
1745
+ case "]": {
1746
+ lastValidIndex = i;
1747
+ stack.pop();
1748
+ break;
1749
+ }
1750
+ default: {
1751
+ lastValidIndex = i;
1752
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
1753
+ break;
1754
+ }
1755
+ }
1756
+ break;
1757
+ }
1758
+ case "INSIDE_ARRAY_AFTER_VALUE": {
1759
+ switch (char) {
1760
+ case ",": {
1761
+ stack.pop();
1762
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
1763
+ break;
1764
+ }
1765
+ case "]": {
1766
+ lastValidIndex = i;
1767
+ stack.pop();
1768
+ break;
1769
+ }
1770
+ default: {
1771
+ lastValidIndex = i;
1772
+ break;
1773
+ }
1774
+ }
1775
+ break;
1776
+ }
1777
+ case "INSIDE_ARRAY_AFTER_COMMA": {
1778
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
1779
+ break;
1780
+ }
1781
+ case "INSIDE_STRING_ESCAPE": {
1782
+ stack.pop();
1783
+ lastValidIndex = i;
1784
+ break;
1785
+ }
1786
+ case "INSIDE_NUMBER": {
1787
+ switch (char) {
1788
+ case "0":
1789
+ case "1":
1790
+ case "2":
1791
+ case "3":
1792
+ case "4":
1793
+ case "5":
1794
+ case "6":
1795
+ case "7":
1796
+ case "8":
1797
+ case "9": {
1798
+ lastValidIndex = i;
1799
+ break;
1800
+ }
1801
+ case "e":
1802
+ case "E":
1803
+ case "-":
1804
+ case ".": {
1805
+ break;
1806
+ }
1807
+ case ",": {
1808
+ stack.pop();
1809
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1810
+ processAfterArrayValue(char, i);
1811
+ }
1812
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
1813
+ processAfterObjectValue(char, i);
1814
+ }
1815
+ break;
1816
+ }
1817
+ case "}": {
1818
+ stack.pop();
1819
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
1820
+ processAfterObjectValue(char, i);
1821
+ }
1822
+ break;
1823
+ }
1824
+ case "]": {
1825
+ stack.pop();
1826
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1827
+ processAfterArrayValue(char, i);
1828
+ }
1829
+ break;
1830
+ }
1831
+ default: {
1832
+ stack.pop();
1833
+ break;
1834
+ }
1835
+ }
1836
+ break;
1837
+ }
1838
+ case "INSIDE_LITERAL": {
1839
+ const partialLiteral = input.substring(literalStart, i + 1);
1840
+ if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
1841
+ stack.pop();
1842
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
1843
+ processAfterObjectValue(char, i);
1844
+ } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1845
+ processAfterArrayValue(char, i);
1846
+ }
1847
+ } else {
1848
+ lastValidIndex = i;
1849
+ }
1850
+ break;
1851
+ }
1852
+ }
1853
+ }
1854
+ let result = input.slice(0, lastValidIndex + 1);
1855
+ for (let i = stack.length - 1; i >= 0; i--) {
1856
+ const state = stack[i];
1857
+ switch (state) {
1858
+ case "INSIDE_STRING": {
1859
+ result += '"';
1860
+ break;
1861
+ }
1862
+ case "INSIDE_OBJECT_KEY":
1863
+ case "INSIDE_OBJECT_AFTER_KEY":
1864
+ case "INSIDE_OBJECT_AFTER_COMMA":
1865
+ case "INSIDE_OBJECT_START":
1866
+ case "INSIDE_OBJECT_BEFORE_VALUE":
1867
+ case "INSIDE_OBJECT_AFTER_VALUE": {
1868
+ result += "}";
1869
+ break;
1870
+ }
1871
+ case "INSIDE_ARRAY_START":
1872
+ case "INSIDE_ARRAY_AFTER_COMMA":
1873
+ case "INSIDE_ARRAY_AFTER_VALUE": {
1874
+ result += "]";
1875
+ break;
1876
+ }
1877
+ case "INSIDE_LITERAL": {
1878
+ const partialLiteral = input.substring(literalStart, input.length);
1879
+ if ("true".startsWith(partialLiteral)) {
1880
+ result += "true".slice(partialLiteral.length);
1881
+ } else if ("false".startsWith(partialLiteral)) {
1882
+ result += "false".slice(partialLiteral.length);
1883
+ } else if ("null".startsWith(partialLiteral)) {
1884
+ result += "null".slice(partialLiteral.length);
1885
+ }
1886
+ }
1887
+ }
1888
+ }
1889
+ return result;
1890
+ }
1891
+ function parsePartialJson(jsonText) {
1892
+ if (jsonText === void 0) {
1893
+ return { value: void 0, state: "undefined-input" };
1894
+ }
1895
+ let result = safeParseJSON({ text: jsonText });
1896
+ if (result.success) {
1897
+ return { value: result.value, state: "successful-parse" };
1898
+ }
1899
+ result = safeParseJSON({ text: fixJson(jsonText) });
1900
+ if (result.success) {
1901
+ return { value: result.value, state: "repaired-parse" };
1902
+ }
1903
+ return { value: void 0, state: "failed-parse" };
1904
+ }
1905
+ var textStreamPart2 = {
1906
+ code: "0",
1907
+ name: "text",
1908
+ parse: (value) => {
1909
+ if (typeof value !== "string") {
1910
+ throw new Error('"text" parts expect a string value.');
1911
+ }
1912
+ return { type: "text", value };
1913
+ }
1914
+ };
1915
+ var dataStreamPart = {
1916
+ code: "2",
1917
+ name: "data",
1918
+ parse: (value) => {
1919
+ if (!Array.isArray(value)) {
1920
+ throw new Error('"data" parts expect an array value.');
1921
+ }
1922
+ return { type: "data", value };
1923
+ }
1924
+ };
1925
+ var errorStreamPart2 = {
1926
+ code: "3",
1927
+ name: "error",
1928
+ parse: (value) => {
1929
+ if (typeof value !== "string") {
1930
+ throw new Error('"error" parts expect a string value.');
1931
+ }
1932
+ return { type: "error", value };
1933
+ }
1934
+ };
1935
+ var messageAnnotationsStreamPart = {
1936
+ code: "8",
1937
+ name: "message_annotations",
1938
+ parse: (value) => {
1939
+ if (!Array.isArray(value)) {
1940
+ throw new Error('"message_annotations" parts expect an array value.');
1941
+ }
1942
+ return { type: "message_annotations", value };
1943
+ }
1944
+ };
1945
+ var toolCallStreamPart = {
1946
+ code: "9",
1947
+ name: "tool_call",
1948
+ parse: (value) => {
1949
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object") {
1950
+ throw new Error(
1951
+ '"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.'
1952
+ );
1953
+ }
1954
+ return {
1955
+ type: "tool_call",
1956
+ value
1957
+ };
1958
+ }
1959
+ };
1960
+ var toolResultStreamPart = {
1961
+ code: "a",
1962
+ name: "tool_result",
1963
+ parse: (value) => {
1964
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("result" in value)) {
1965
+ throw new Error(
1966
+ '"tool_result" parts expect an object with a "toolCallId" and a "result" property.'
1967
+ );
1968
+ }
1969
+ return {
1970
+ type: "tool_result",
1971
+ value
1972
+ };
1973
+ }
1974
+ };
1975
+ var toolCallStreamingStartStreamPart = {
1976
+ code: "b",
1977
+ name: "tool_call_streaming_start",
1978
+ parse: (value) => {
1979
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string") {
1980
+ throw new Error(
1981
+ '"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.'
1982
+ );
1983
+ }
1984
+ return {
1985
+ type: "tool_call_streaming_start",
1986
+ value
1987
+ };
1988
+ }
1989
+ };
1990
+ var toolCallDeltaStreamPart = {
1991
+ code: "c",
1992
+ name: "tool_call_delta",
1993
+ parse: (value) => {
1994
+ if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("argsTextDelta" in value) || typeof value.argsTextDelta !== "string") {
1995
+ throw new Error(
1996
+ '"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.'
1997
+ );
1998
+ }
1999
+ return {
2000
+ type: "tool_call_delta",
2001
+ value
2002
+ };
2003
+ }
2004
+ };
2005
+ var finishMessageStreamPart = {
2006
+ code: "d",
2007
+ name: "finish_message",
2008
+ parse: (value) => {
2009
+ if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
2010
+ throw new Error(
2011
+ '"finish_message" parts expect an object with a "finishReason" property.'
2012
+ );
2013
+ }
2014
+ const result = {
2015
+ finishReason: value.finishReason
2016
+ };
2017
+ if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
2018
+ result.usage = {
2019
+ promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
2020
+ completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
2021
+ };
2022
+ }
2023
+ return {
2024
+ type: "finish_message",
2025
+ value: result
2026
+ };
2027
+ }
2028
+ };
2029
+ var finishStepStreamPart = {
2030
+ code: "e",
2031
+ name: "finish_step",
2032
+ parse: (value) => {
2033
+ if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
2034
+ throw new Error(
2035
+ '"finish_step" parts expect an object with a "finishReason" property.'
2036
+ );
2037
+ }
2038
+ const result = {
2039
+ finishReason: value.finishReason,
2040
+ isContinued: false
2041
+ };
2042
+ if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
2043
+ result.usage = {
2044
+ promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
2045
+ completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
2046
+ };
2047
+ }
2048
+ if ("isContinued" in value && typeof value.isContinued === "boolean") {
2049
+ result.isContinued = value.isContinued;
2050
+ }
2051
+ return {
2052
+ type: "finish_step",
2053
+ value: result
2054
+ };
2055
+ }
2056
+ };
2057
+ var startStepStreamPart = {
2058
+ code: "f",
2059
+ name: "start_step",
2060
+ parse: (value) => {
2061
+ if (value == null || typeof value !== "object" || !("messageId" in value) || typeof value.messageId !== "string") {
2062
+ throw new Error(
2063
+ '"start_step" parts expect an object with an "id" property.'
2064
+ );
2065
+ }
2066
+ return {
2067
+ type: "start_step",
2068
+ value: {
2069
+ messageId: value.messageId
2070
+ }
2071
+ };
2072
+ }
2073
+ };
2074
+ var reasoningStreamPart = {
2075
+ code: "g",
2076
+ name: "reasoning",
2077
+ parse: (value) => {
2078
+ if (typeof value !== "string") {
2079
+ throw new Error('"reasoning" parts expect a string value.');
2080
+ }
2081
+ return { type: "reasoning", value };
2082
+ }
2083
+ };
2084
+ var sourcePart = {
2085
+ code: "h",
2086
+ name: "source",
2087
+ parse: (value) => {
2088
+ if (value == null || typeof value !== "object") {
2089
+ throw new Error('"source" parts expect a Source object.');
2090
+ }
2091
+ return {
2092
+ type: "source",
2093
+ value
2094
+ };
2095
+ }
2096
+ };
2097
+ var redactedReasoningStreamPart = {
2098
+ code: "i",
2099
+ name: "redacted_reasoning",
2100
+ parse: (value) => {
2101
+ if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string") {
2102
+ throw new Error(
2103
+ '"redacted_reasoning" parts expect an object with a "data" property.'
2104
+ );
2105
+ }
2106
+ return { type: "redacted_reasoning", value: { data: value.data } };
2107
+ }
2108
+ };
2109
+ var reasoningSignatureStreamPart = {
2110
+ code: "j",
2111
+ name: "reasoning_signature",
2112
+ parse: (value) => {
2113
+ if (value == null || typeof value !== "object" || !("signature" in value) || typeof value.signature !== "string") {
2114
+ throw new Error(
2115
+ '"reasoning_signature" parts expect an object with a "signature" property.'
2116
+ );
2117
+ }
2118
+ return {
2119
+ type: "reasoning_signature",
2120
+ value: { signature: value.signature }
2121
+ };
2122
+ }
2123
+ };
2124
+ var fileStreamPart = {
2125
+ code: "k",
2126
+ name: "file",
2127
+ parse: (value) => {
2128
+ if (value == null || typeof value !== "object" || !("data" in value) || typeof value.data !== "string" || !("mimeType" in value) || typeof value.mimeType !== "string") {
2129
+ throw new Error(
2130
+ '"file" parts expect an object with a "data" and "mimeType" property.'
2131
+ );
2132
+ }
2133
+ return { type: "file", value };
2134
+ }
2135
+ };
2136
+ var dataStreamParts = [
2137
+ textStreamPart2,
2138
+ dataStreamPart,
2139
+ errorStreamPart2,
2140
+ messageAnnotationsStreamPart,
2141
+ toolCallStreamPart,
2142
+ toolResultStreamPart,
2143
+ toolCallStreamingStartStreamPart,
2144
+ toolCallDeltaStreamPart,
2145
+ finishMessageStreamPart,
2146
+ finishStepStreamPart,
2147
+ startStepStreamPart,
2148
+ reasoningStreamPart,
2149
+ sourcePart,
2150
+ redactedReasoningStreamPart,
2151
+ reasoningSignatureStreamPart,
2152
+ fileStreamPart
2153
+ ];
2154
+ Object.fromEntries(
2155
+ dataStreamParts.map((part) => [part.code, part])
2156
+ );
2157
+ Object.fromEntries(
2158
+ dataStreamParts.map((part) => [part.name, part.code])
2159
+ );
2160
+ function formatDataStreamPart(type, value) {
2161
+ const streamPart = dataStreamParts.find((part) => part.name === type);
2162
+ if (!streamPart) {
2163
+ throw new Error(`Invalid stream part type: ${type}`);
2164
+ }
2165
+ return `${streamPart.code}:${JSON.stringify(value)}
2166
+ `;
2167
+ }
2168
+ function zodSchema(zodSchema2, options) {
2169
+ var _a17;
2170
+ const useReferences = (_a17 = void 0) != null ? _a17 : false;
2171
+ return jsonSchema(
2172
+ esm_default(zodSchema2, {
2173
+ $refStrategy: useReferences ? "root" : "none",
2174
+ target: "jsonSchema7"
2175
+ // note: openai mode breaks various gemini conversions
2176
+ }),
2177
+ {
2178
+ validate: (value) => {
2179
+ const result = zodSchema2.safeParse(value);
2180
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2181
+ }
2182
+ }
2183
+ );
2184
+ }
2185
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
2186
+ function jsonSchema(jsonSchema2, {
2187
+ validate
2188
+ } = {}) {
2189
+ return {
2190
+ [schemaSymbol]: true,
2191
+ _type: void 0,
2192
+ // should never be used directly
2193
+ [validatorSymbol]: true,
2194
+ jsonSchema: jsonSchema2,
2195
+ validate
2196
+ };
2197
+ }
2198
+ function isSchema(value) {
2199
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2200
+ }
2201
+ function asSchema(schema) {
2202
+ return isSchema(schema) ? schema : zodSchema(schema);
2203
+ }
2204
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
2205
+ var VERSION = "1.9.0";
2206
+ var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
2207
+ function _makeCompatibilityCheck(ownVersion) {
2208
+ var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
2209
+ var rejectedVersions = /* @__PURE__ */ new Set();
2210
+ var myVersionMatch = ownVersion.match(re);
2211
+ if (!myVersionMatch) {
2212
+ return function() {
2213
+ return false;
2214
+ };
2215
+ }
2216
+ var ownVersionParsed = {
2217
+ major: +myVersionMatch[1],
2218
+ minor: +myVersionMatch[2],
2219
+ patch: +myVersionMatch[3],
2220
+ prerelease: myVersionMatch[4]
2221
+ };
2222
+ if (ownVersionParsed.prerelease != null) {
2223
+ return function isExactmatch(globalVersion) {
2224
+ return globalVersion === ownVersion;
2225
+ };
2226
+ }
2227
+ function _reject(v) {
2228
+ rejectedVersions.add(v);
2229
+ return false;
2230
+ }
2231
+ function _accept(v) {
2232
+ acceptedVersions.add(v);
2233
+ return true;
2234
+ }
2235
+ return function isCompatible2(globalVersion) {
2236
+ if (acceptedVersions.has(globalVersion)) {
2237
+ return true;
2238
+ }
2239
+ if (rejectedVersions.has(globalVersion)) {
2240
+ return false;
2241
+ }
2242
+ var globalVersionMatch = globalVersion.match(re);
2243
+ if (!globalVersionMatch) {
2244
+ return _reject(globalVersion);
2245
+ }
2246
+ var globalVersionParsed = {
2247
+ major: +globalVersionMatch[1],
2248
+ minor: +globalVersionMatch[2],
2249
+ patch: +globalVersionMatch[3],
2250
+ prerelease: globalVersionMatch[4]
2251
+ };
2252
+ if (globalVersionParsed.prerelease != null) {
2253
+ return _reject(globalVersion);
2254
+ }
2255
+ if (ownVersionParsed.major !== globalVersionParsed.major) {
2256
+ return _reject(globalVersion);
2257
+ }
2258
+ if (ownVersionParsed.major === 0) {
2259
+ if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
2260
+ return _accept(globalVersion);
2261
+ }
2262
+ return _reject(globalVersion);
2263
+ }
2264
+ if (ownVersionParsed.minor <= globalVersionParsed.minor) {
2265
+ return _accept(globalVersion);
2266
+ }
2267
+ return _reject(globalVersion);
2268
+ };
2269
+ }
2270
+ var isCompatible = _makeCompatibilityCheck(VERSION);
2271
+ var major = VERSION.split(".")[0];
2272
+ var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
2273
+ var _global = _globalThis;
2274
+ function registerGlobal(type, instance, diag, allowOverride) {
2275
+ var _a17;
2276
+ if (allowOverride === void 0) {
2277
+ allowOverride = false;
2278
+ }
2279
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a17 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a17 !== void 0 ? _a17 : {
2280
+ version: VERSION
2281
+ };
2282
+ if (!allowOverride && api[type]) {
2283
+ var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
2284
+ diag.error(err.stack || err.message);
2285
+ return false;
2286
+ }
2287
+ if (api.version !== VERSION) {
2288
+ var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
2289
+ diag.error(err.stack || err.message);
2290
+ return false;
2291
+ }
2292
+ api[type] = instance;
2293
+ diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
2294
+ return true;
2295
+ }
2296
+ function getGlobal(type) {
2297
+ var _a17, _b;
2298
+ var globalVersion = (_a17 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a17 === void 0 ? void 0 : _a17.version;
2299
+ if (!globalVersion || !isCompatible(globalVersion)) {
2300
+ return;
2301
+ }
2302
+ return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
2303
+ }
2304
+ function unregisterGlobal(type, diag) {
2305
+ diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
2306
+ var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
2307
+ if (api) {
2308
+ delete api[type];
2309
+ }
2310
+ }
2311
+ var __read = function(o, n) {
2312
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
2313
+ if (!m) return o;
2314
+ var i = m.call(o), r, ar = [], e;
2315
+ try {
2316
+ while (!(r = i.next()).done) ar.push(r.value);
2317
+ } catch (error) {
2318
+ e = { error };
2319
+ } finally {
2320
+ try {
2321
+ if (r && !r.done && (m = i["return"])) m.call(i);
2322
+ } finally {
2323
+ if (e) throw e.error;
2324
+ }
2325
+ }
2326
+ return ar;
2327
+ };
2328
+ var __spreadArray = function(to, from, pack) {
2329
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
2330
+ if (ar || !(i in from)) {
2331
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
2332
+ ar[i] = from[i];
2333
+ }
2334
+ }
2335
+ return to.concat(ar || Array.prototype.slice.call(from));
2336
+ };
2337
+ var DiagComponentLogger = (
2338
+ /** @class */
2339
+ (function() {
2340
+ function DiagComponentLogger2(props) {
2341
+ this._namespace = props.namespace || "DiagComponentLogger";
2342
+ }
2343
+ DiagComponentLogger2.prototype.debug = function() {
2344
+ var args = [];
2345
+ for (var _i = 0; _i < arguments.length; _i++) {
2346
+ args[_i] = arguments[_i];
2347
+ }
2348
+ return logProxy("debug", this._namespace, args);
2349
+ };
2350
+ DiagComponentLogger2.prototype.error = function() {
2351
+ var args = [];
2352
+ for (var _i = 0; _i < arguments.length; _i++) {
2353
+ args[_i] = arguments[_i];
2354
+ }
2355
+ return logProxy("error", this._namespace, args);
2356
+ };
2357
+ DiagComponentLogger2.prototype.info = function() {
2358
+ var args = [];
2359
+ for (var _i = 0; _i < arguments.length; _i++) {
2360
+ args[_i] = arguments[_i];
2361
+ }
2362
+ return logProxy("info", this._namespace, args);
2363
+ };
2364
+ DiagComponentLogger2.prototype.warn = function() {
2365
+ var args = [];
2366
+ for (var _i = 0; _i < arguments.length; _i++) {
2367
+ args[_i] = arguments[_i];
2368
+ }
2369
+ return logProxy("warn", this._namespace, args);
2370
+ };
2371
+ DiagComponentLogger2.prototype.verbose = function() {
2372
+ var args = [];
2373
+ for (var _i = 0; _i < arguments.length; _i++) {
2374
+ args[_i] = arguments[_i];
2375
+ }
2376
+ return logProxy("verbose", this._namespace, args);
2377
+ };
2378
+ return DiagComponentLogger2;
2379
+ })()
2380
+ );
2381
+ function logProxy(funcName, namespace, args) {
2382
+ var logger = getGlobal("diag");
2383
+ if (!logger) {
2384
+ return;
2385
+ }
2386
+ args.unshift(namespace);
2387
+ return logger[funcName].apply(logger, __spreadArray([], __read(args), false));
2388
+ }
2389
+ var DiagLogLevel;
2390
+ (function(DiagLogLevel2) {
2391
+ DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
2392
+ DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
2393
+ DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
2394
+ DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
2395
+ DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
2396
+ DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
2397
+ DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
2398
+ })(DiagLogLevel || (DiagLogLevel = {}));
2399
+ function createLogLevelDiagLogger(maxLevel, logger) {
2400
+ if (maxLevel < DiagLogLevel.NONE) {
2401
+ maxLevel = DiagLogLevel.NONE;
2402
+ } else if (maxLevel > DiagLogLevel.ALL) {
2403
+ maxLevel = DiagLogLevel.ALL;
2404
+ }
2405
+ logger = logger || {};
2406
+ function _filterFunc(funcName, theLevel) {
2407
+ var theFunc = logger[funcName];
2408
+ if (typeof theFunc === "function" && maxLevel >= theLevel) {
2409
+ return theFunc.bind(logger);
2410
+ }
2411
+ return function() {
2412
+ };
2413
+ }
2414
+ return {
2415
+ error: _filterFunc("error", DiagLogLevel.ERROR),
2416
+ warn: _filterFunc("warn", DiagLogLevel.WARN),
2417
+ info: _filterFunc("info", DiagLogLevel.INFO),
2418
+ debug: _filterFunc("debug", DiagLogLevel.DEBUG),
2419
+ verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
2420
+ };
2421
+ }
2422
+ var __read2 = function(o, n) {
2423
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
2424
+ if (!m) return o;
2425
+ var i = m.call(o), r, ar = [], e;
2426
+ try {
2427
+ while (!(r = i.next()).done) ar.push(r.value);
2428
+ } catch (error) {
2429
+ e = { error };
2430
+ } finally {
2431
+ try {
2432
+ if (r && !r.done && (m = i["return"])) m.call(i);
2433
+ } finally {
2434
+ if (e) throw e.error;
2435
+ }
2436
+ }
2437
+ return ar;
2438
+ };
2439
+ var __spreadArray2 = function(to, from, pack) {
2440
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
2441
+ if (ar || !(i in from)) {
2442
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
2443
+ ar[i] = from[i];
2444
+ }
2445
+ }
2446
+ return to.concat(ar || Array.prototype.slice.call(from));
2447
+ };
2448
+ var API_NAME = "diag";
2449
+ var DiagAPI = (
2450
+ /** @class */
2451
+ (function() {
2452
+ function DiagAPI2() {
2453
+ function _logProxy(funcName) {
2454
+ return function() {
2455
+ var args = [];
2456
+ for (var _i = 0; _i < arguments.length; _i++) {
2457
+ args[_i] = arguments[_i];
2458
+ }
2459
+ var logger = getGlobal("diag");
2460
+ if (!logger)
2461
+ return;
2462
+ return logger[funcName].apply(logger, __spreadArray2([], __read2(args), false));
2463
+ };
2464
+ }
2465
+ var self = this;
2466
+ var setLogger = function(logger, optionsOrLogLevel) {
2467
+ var _a17, _b, _c;
2468
+ if (optionsOrLogLevel === void 0) {
2469
+ optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
2470
+ }
2471
+ if (logger === self) {
2472
+ var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
2473
+ self.error((_a17 = err.stack) !== null && _a17 !== void 0 ? _a17 : err.message);
2474
+ return false;
2475
+ }
2476
+ if (typeof optionsOrLogLevel === "number") {
2477
+ optionsOrLogLevel = {
2478
+ logLevel: optionsOrLogLevel
2479
+ };
2480
+ }
2481
+ var oldLogger = getGlobal("diag");
2482
+ var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
2483
+ if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
2484
+ var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
2485
+ oldLogger.warn("Current logger will be overwritten from " + stack);
2486
+ newLogger.warn("Current logger will overwrite one already registered from " + stack);
2487
+ }
2488
+ return registerGlobal("diag", newLogger, self, true);
2489
+ };
2490
+ self.setLogger = setLogger;
2491
+ self.disable = function() {
2492
+ unregisterGlobal(API_NAME, self);
2493
+ };
2494
+ self.createComponentLogger = function(options) {
2495
+ return new DiagComponentLogger(options);
2496
+ };
2497
+ self.verbose = _logProxy("verbose");
2498
+ self.debug = _logProxy("debug");
2499
+ self.info = _logProxy("info");
2500
+ self.warn = _logProxy("warn");
2501
+ self.error = _logProxy("error");
2502
+ }
2503
+ DiagAPI2.instance = function() {
2504
+ if (!this._instance) {
2505
+ this._instance = new DiagAPI2();
2506
+ }
2507
+ return this._instance;
2508
+ };
2509
+ return DiagAPI2;
2510
+ })()
2511
+ );
2512
+ function createContextKey(description) {
2513
+ return Symbol.for(description);
2514
+ }
2515
+ var BaseContext = (
2516
+ /** @class */
2517
+ /* @__PURE__ */ (function() {
2518
+ function BaseContext2(parentContext) {
2519
+ var self = this;
2520
+ self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
2521
+ self.getValue = function(key) {
2522
+ return self._currentContext.get(key);
2523
+ };
2524
+ self.setValue = function(key, value) {
2525
+ var context = new BaseContext2(self._currentContext);
2526
+ context._currentContext.set(key, value);
2527
+ return context;
2528
+ };
2529
+ self.deleteValue = function(key) {
2530
+ var context = new BaseContext2(self._currentContext);
2531
+ context._currentContext.delete(key);
2532
+ return context;
2533
+ };
2534
+ }
2535
+ return BaseContext2;
2536
+ })()
2537
+ );
2538
+ var ROOT_CONTEXT = new BaseContext();
2539
+ var __read3 = function(o, n) {
2540
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
2541
+ if (!m) return o;
2542
+ var i = m.call(o), r, ar = [], e;
2543
+ try {
2544
+ while (!(r = i.next()).done) ar.push(r.value);
2545
+ } catch (error) {
2546
+ e = { error };
2547
+ } finally {
2548
+ try {
2549
+ if (r && !r.done && (m = i["return"])) m.call(i);
2550
+ } finally {
2551
+ if (e) throw e.error;
2552
+ }
2553
+ }
2554
+ return ar;
2555
+ };
2556
+ var __spreadArray3 = function(to, from, pack) {
2557
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
2558
+ if (ar || !(i in from)) {
2559
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
2560
+ ar[i] = from[i];
2561
+ }
2562
+ }
2563
+ return to.concat(ar || Array.prototype.slice.call(from));
2564
+ };
2565
+ var NoopContextManager = (
2566
+ /** @class */
2567
+ (function() {
2568
+ function NoopContextManager2() {
2569
+ }
2570
+ NoopContextManager2.prototype.active = function() {
2571
+ return ROOT_CONTEXT;
2572
+ };
2573
+ NoopContextManager2.prototype.with = function(_context, fn, thisArg) {
2574
+ var args = [];
2575
+ for (var _i = 3; _i < arguments.length; _i++) {
2576
+ args[_i - 3] = arguments[_i];
2577
+ }
2578
+ return fn.call.apply(fn, __spreadArray3([thisArg], __read3(args), false));
2579
+ };
2580
+ NoopContextManager2.prototype.bind = function(_context, target) {
2581
+ return target;
2582
+ };
2583
+ NoopContextManager2.prototype.enable = function() {
2584
+ return this;
2585
+ };
2586
+ NoopContextManager2.prototype.disable = function() {
2587
+ return this;
2588
+ };
2589
+ return NoopContextManager2;
2590
+ })()
2591
+ );
2592
+ var __read4 = function(o, n) {
2593
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
2594
+ if (!m) return o;
2595
+ var i = m.call(o), r, ar = [], e;
2596
+ try {
2597
+ while (!(r = i.next()).done) ar.push(r.value);
2598
+ } catch (error) {
2599
+ e = { error };
2600
+ } finally {
2601
+ try {
2602
+ if (r && !r.done && (m = i["return"])) m.call(i);
2603
+ } finally {
2604
+ if (e) throw e.error;
2605
+ }
2606
+ }
2607
+ return ar;
2608
+ };
2609
+ var __spreadArray4 = function(to, from, pack) {
2610
+ if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
2611
+ if (ar || !(i in from)) {
2612
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
2613
+ ar[i] = from[i];
2614
+ }
2615
+ }
2616
+ return to.concat(ar || Array.prototype.slice.call(from));
2617
+ };
2618
+ var API_NAME2 = "context";
2619
+ var NOOP_CONTEXT_MANAGER = new NoopContextManager();
2620
+ var ContextAPI = (
2621
+ /** @class */
2622
+ (function() {
2623
+ function ContextAPI2() {
2624
+ }
2625
+ ContextAPI2.getInstance = function() {
2626
+ if (!this._instance) {
2627
+ this._instance = new ContextAPI2();
2628
+ }
2629
+ return this._instance;
2630
+ };
2631
+ ContextAPI2.prototype.setGlobalContextManager = function(contextManager) {
2632
+ return registerGlobal(API_NAME2, contextManager, DiagAPI.instance());
2633
+ };
2634
+ ContextAPI2.prototype.active = function() {
2635
+ return this._getContextManager().active();
2636
+ };
2637
+ ContextAPI2.prototype.with = function(context, fn, thisArg) {
2638
+ var _a17;
2639
+ var args = [];
2640
+ for (var _i = 3; _i < arguments.length; _i++) {
2641
+ args[_i - 3] = arguments[_i];
2642
+ }
2643
+ return (_a17 = this._getContextManager()).with.apply(_a17, __spreadArray4([context, fn, thisArg], __read4(args), false));
2644
+ };
2645
+ ContextAPI2.prototype.bind = function(context, target) {
2646
+ return this._getContextManager().bind(context, target);
2647
+ };
2648
+ ContextAPI2.prototype._getContextManager = function() {
2649
+ return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER;
2650
+ };
2651
+ ContextAPI2.prototype.disable = function() {
2652
+ this._getContextManager().disable();
2653
+ unregisterGlobal(API_NAME2, DiagAPI.instance());
2654
+ };
2655
+ return ContextAPI2;
2656
+ })()
2657
+ );
2658
+ var TraceFlags;
2659
+ (function(TraceFlags2) {
2660
+ TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
2661
+ TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
2662
+ })(TraceFlags || (TraceFlags = {}));
2663
+ var INVALID_SPANID = "0000000000000000";
2664
+ var INVALID_TRACEID = "00000000000000000000000000000000";
2665
+ var INVALID_SPAN_CONTEXT = {
2666
+ traceId: INVALID_TRACEID,
2667
+ spanId: INVALID_SPANID,
2668
+ traceFlags: TraceFlags.NONE
2669
+ };
2670
+ var NonRecordingSpan = (
2671
+ /** @class */
2672
+ (function() {
2673
+ function NonRecordingSpan2(_spanContext) {
2674
+ if (_spanContext === void 0) {
2675
+ _spanContext = INVALID_SPAN_CONTEXT;
2676
+ }
2677
+ this._spanContext = _spanContext;
2678
+ }
2679
+ NonRecordingSpan2.prototype.spanContext = function() {
2680
+ return this._spanContext;
2681
+ };
2682
+ NonRecordingSpan2.prototype.setAttribute = function(_key, _value) {
2683
+ return this;
2684
+ };
2685
+ NonRecordingSpan2.prototype.setAttributes = function(_attributes) {
2686
+ return this;
2687
+ };
2688
+ NonRecordingSpan2.prototype.addEvent = function(_name, _attributes) {
2689
+ return this;
2690
+ };
2691
+ NonRecordingSpan2.prototype.addLink = function(_link) {
2692
+ return this;
2693
+ };
2694
+ NonRecordingSpan2.prototype.addLinks = function(_links) {
2695
+ return this;
2696
+ };
2697
+ NonRecordingSpan2.prototype.setStatus = function(_status) {
2698
+ return this;
2699
+ };
2700
+ NonRecordingSpan2.prototype.updateName = function(_name) {
2701
+ return this;
2702
+ };
2703
+ NonRecordingSpan2.prototype.end = function(_endTime) {
2704
+ };
2705
+ NonRecordingSpan2.prototype.isRecording = function() {
2706
+ return false;
2707
+ };
2708
+ NonRecordingSpan2.prototype.recordException = function(_exception, _time) {
2709
+ };
2710
+ return NonRecordingSpan2;
2711
+ })()
2712
+ );
2713
+ var SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
2714
+ function getSpan(context) {
2715
+ return context.getValue(SPAN_KEY) || void 0;
2716
+ }
2717
+ function getActiveSpan() {
2718
+ return getSpan(ContextAPI.getInstance().active());
2719
+ }
2720
+ function setSpan(context, span) {
2721
+ return context.setValue(SPAN_KEY, span);
2722
+ }
2723
+ function deleteSpan(context) {
2724
+ return context.deleteValue(SPAN_KEY);
2725
+ }
2726
+ function setSpanContext(context, spanContext) {
2727
+ return setSpan(context, new NonRecordingSpan(spanContext));
2728
+ }
2729
+ function getSpanContext(context) {
2730
+ var _a17;
2731
+ return (_a17 = getSpan(context)) === null || _a17 === void 0 ? void 0 : _a17.spanContext();
2732
+ }
2733
+ var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
2734
+ var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
2735
+ function isValidTraceId(traceId) {
2736
+ return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;
2737
+ }
2738
+ function isValidSpanId(spanId) {
2739
+ return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;
2740
+ }
2741
+ function isSpanContextValid(spanContext) {
2742
+ return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
2743
+ }
2744
+ function wrapSpanContext(spanContext) {
2745
+ return new NonRecordingSpan(spanContext);
2746
+ }
2747
+ var contextApi = ContextAPI.getInstance();
2748
+ var NoopTracer = (
2749
+ /** @class */
2750
+ (function() {
2751
+ function NoopTracer2() {
2752
+ }
2753
+ NoopTracer2.prototype.startSpan = function(name17, options, context) {
2754
+ if (context === void 0) {
2755
+ context = contextApi.active();
2756
+ }
2757
+ var root = Boolean(options === null || options === void 0 ? void 0 : options.root);
2758
+ if (root) {
2759
+ return new NonRecordingSpan();
2760
+ }
2761
+ var parentFromContext = context && getSpanContext(context);
2762
+ if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) {
2763
+ return new NonRecordingSpan(parentFromContext);
2764
+ } else {
2765
+ return new NonRecordingSpan();
2766
+ }
2767
+ };
2768
+ NoopTracer2.prototype.startActiveSpan = function(name17, arg2, arg3, arg4) {
2769
+ var opts;
2770
+ var ctx;
2771
+ var fn;
2772
+ if (arguments.length < 2) {
2773
+ return;
2774
+ } else if (arguments.length === 2) {
2775
+ fn = arg2;
2776
+ } else if (arguments.length === 3) {
2777
+ opts = arg2;
2778
+ fn = arg3;
2779
+ } else {
2780
+ opts = arg2;
2781
+ ctx = arg3;
2782
+ fn = arg4;
2783
+ }
2784
+ var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
2785
+ var span = this.startSpan(name17, opts, parentContext);
2786
+ var contextWithSpanSet = setSpan(parentContext, span);
2787
+ return contextApi.with(contextWithSpanSet, fn, void 0, span);
2788
+ };
2789
+ return NoopTracer2;
2790
+ })()
2791
+ );
2792
+ function isSpanContext(spanContext) {
2793
+ return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
2794
+ }
2795
+ var NOOP_TRACER = new NoopTracer();
2796
+ var ProxyTracer = (
2797
+ /** @class */
2798
+ (function() {
2799
+ function ProxyTracer2(_provider, name17, version, options) {
2800
+ this._provider = _provider;
2801
+ this.name = name17;
2802
+ this.version = version;
2803
+ this.options = options;
2804
+ }
2805
+ ProxyTracer2.prototype.startSpan = function(name17, options, context) {
2806
+ return this._getTracer().startSpan(name17, options, context);
2807
+ };
2808
+ ProxyTracer2.prototype.startActiveSpan = function(_name, _options, _context, _fn) {
2809
+ var tracer = this._getTracer();
2810
+ return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
2811
+ };
2812
+ ProxyTracer2.prototype._getTracer = function() {
2813
+ if (this._delegate) {
2814
+ return this._delegate;
2815
+ }
2816
+ var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
2817
+ if (!tracer) {
2818
+ return NOOP_TRACER;
2819
+ }
2820
+ this._delegate = tracer;
2821
+ return this._delegate;
2822
+ };
2823
+ return ProxyTracer2;
2824
+ })()
2825
+ );
2826
+ var NoopTracerProvider = (
2827
+ /** @class */
2828
+ (function() {
2829
+ function NoopTracerProvider2() {
2830
+ }
2831
+ NoopTracerProvider2.prototype.getTracer = function(_name, _version, _options) {
2832
+ return new NoopTracer();
2833
+ };
2834
+ return NoopTracerProvider2;
2835
+ })()
2836
+ );
2837
+ var NOOP_TRACER_PROVIDER = new NoopTracerProvider();
2838
+ var ProxyTracerProvider = (
2839
+ /** @class */
2840
+ (function() {
2841
+ function ProxyTracerProvider2() {
2842
+ }
2843
+ ProxyTracerProvider2.prototype.getTracer = function(name17, version, options) {
2844
+ var _a17;
2845
+ return (_a17 = this.getDelegateTracer(name17, version, options)) !== null && _a17 !== void 0 ? _a17 : new ProxyTracer(this, name17, version, options);
2846
+ };
2847
+ ProxyTracerProvider2.prototype.getDelegate = function() {
2848
+ var _a17;
2849
+ return (_a17 = this._delegate) !== null && _a17 !== void 0 ? _a17 : NOOP_TRACER_PROVIDER;
2850
+ };
2851
+ ProxyTracerProvider2.prototype.setDelegate = function(delegate) {
2852
+ this._delegate = delegate;
2853
+ };
2854
+ ProxyTracerProvider2.prototype.getDelegateTracer = function(name17, version, options) {
2855
+ var _a17;
2856
+ return (_a17 = this._delegate) === null || _a17 === void 0 ? void 0 : _a17.getTracer(name17, version, options);
2857
+ };
2858
+ return ProxyTracerProvider2;
2859
+ })()
2860
+ );
2861
+ var SpanStatusCode;
2862
+ (function(SpanStatusCode2) {
2863
+ SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
2864
+ SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
2865
+ SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
2866
+ })(SpanStatusCode || (SpanStatusCode = {}));
2867
+ var API_NAME3 = "trace";
2868
+ var TraceAPI = (
2869
+ /** @class */
2870
+ (function() {
2871
+ function TraceAPI2() {
2872
+ this._proxyTracerProvider = new ProxyTracerProvider();
2873
+ this.wrapSpanContext = wrapSpanContext;
2874
+ this.isSpanContextValid = isSpanContextValid;
2875
+ this.deleteSpan = deleteSpan;
2876
+ this.getSpan = getSpan;
2877
+ this.getActiveSpan = getActiveSpan;
2878
+ this.getSpanContext = getSpanContext;
2879
+ this.setSpan = setSpan;
2880
+ this.setSpanContext = setSpanContext;
2881
+ }
2882
+ TraceAPI2.getInstance = function() {
2883
+ if (!this._instance) {
2884
+ this._instance = new TraceAPI2();
2885
+ }
2886
+ return this._instance;
2887
+ };
2888
+ TraceAPI2.prototype.setGlobalTracerProvider = function(provider) {
2889
+ var success = registerGlobal(API_NAME3, this._proxyTracerProvider, DiagAPI.instance());
2890
+ if (success) {
2891
+ this._proxyTracerProvider.setDelegate(provider);
2892
+ }
2893
+ return success;
2894
+ };
2895
+ TraceAPI2.prototype.getTracerProvider = function() {
2896
+ return getGlobal(API_NAME3) || this._proxyTracerProvider;
2897
+ };
2898
+ TraceAPI2.prototype.getTracer = function(name17, version) {
2899
+ return this.getTracerProvider().getTracer(name17, version);
2900
+ };
2901
+ TraceAPI2.prototype.disable = function() {
2902
+ unregisterGlobal(API_NAME3, DiagAPI.instance());
2903
+ this._proxyTracerProvider = new ProxyTracerProvider();
2904
+ };
2905
+ return TraceAPI2;
2906
+ })()
2907
+ );
2908
+ TraceAPI.getInstance();
2909
+ var __defProp2 = Object.defineProperty;
2910
+ var __export = (target, all) => {
2911
+ for (var name17 in all)
2912
+ __defProp2(target, name17, { get: all[name17], enumerable: true });
2913
+ };
2914
+ function prepareResponseHeaders(headers, {
2915
+ contentType,
2916
+ dataStreamVersion
2917
+ }) {
2918
+ const responseHeaders = new Headers(headers != null ? headers : {});
2919
+ if (!responseHeaders.has("Content-Type")) {
2920
+ responseHeaders.set("Content-Type", contentType);
2921
+ }
2922
+ {
2923
+ responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
2924
+ }
2925
+ return responseHeaders;
2926
+ }
2927
+ var name42 = "AI_NoObjectGeneratedError";
2928
+ var marker42 = `vercel.ai.error.${name42}`;
2929
+ var symbol42 = Symbol.for(marker42);
2930
+ var _a42;
2931
+ var NoObjectGeneratedError = class extends AISDKError {
2932
+ constructor({
2933
+ message = "No object generated.",
2934
+ cause,
2935
+ text: text2,
2936
+ response,
2937
+ usage,
2938
+ finishReason
2939
+ }) {
2940
+ super({ name: name42, message, cause });
2941
+ this[_a42] = true;
2942
+ this.text = text2;
2943
+ this.response = response;
2944
+ this.usage = usage;
2945
+ this.finishReason = finishReason;
2946
+ }
2947
+ static isInstance(error) {
2948
+ return AISDKError.hasMarker(error, marker42);
2949
+ }
2950
+ };
2951
+ _a42 = symbol42;
2952
+ var dataContentSchema = zod.z.union([
2953
+ zod.z.string(),
2954
+ zod.z.instanceof(Uint8Array),
2955
+ zod.z.instanceof(ArrayBuffer),
2956
+ zod.z.custom(
2957
+ // Buffer might not be available in some environments such as CloudFlare:
2958
+ (value) => {
2959
+ var _a17, _b;
2960
+ return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
2961
+ },
2962
+ { message: "Must be a Buffer" }
2963
+ )
2964
+ ]);
2965
+ var jsonValueSchema = zod.z.lazy(
2966
+ () => zod.z.union([
2967
+ zod.z.null(),
2968
+ zod.z.string(),
2969
+ zod.z.number(),
2970
+ zod.z.boolean(),
2971
+ zod.z.record(zod.z.string(), jsonValueSchema),
2972
+ zod.z.array(jsonValueSchema)
2973
+ ])
2974
+ );
2975
+ var providerMetadataSchema = zod.z.record(
2976
+ zod.z.string(),
2977
+ zod.z.record(zod.z.string(), jsonValueSchema)
2978
+ );
2979
+ var toolResultContentSchema = zod.z.array(
2980
+ zod.z.union([
2981
+ zod.z.object({ type: zod.z.literal("text"), text: zod.z.string() }),
2982
+ zod.z.object({
2983
+ type: zod.z.literal("image"),
2984
+ data: zod.z.string(),
2985
+ mimeType: zod.z.string().optional()
2986
+ })
2987
+ ])
2988
+ );
2989
+ var textPartSchema = zod.z.object({
2990
+ type: zod.z.literal("text"),
2991
+ text: zod.z.string(),
2992
+ providerOptions: providerMetadataSchema.optional(),
2993
+ experimental_providerMetadata: providerMetadataSchema.optional()
2994
+ });
2995
+ var imagePartSchema = zod.z.object({
2996
+ type: zod.z.literal("image"),
2997
+ image: zod.z.union([dataContentSchema, zod.z.instanceof(URL)]),
2998
+ mimeType: zod.z.string().optional(),
2999
+ providerOptions: providerMetadataSchema.optional(),
3000
+ experimental_providerMetadata: providerMetadataSchema.optional()
3001
+ });
3002
+ var filePartSchema = zod.z.object({
3003
+ type: zod.z.literal("file"),
3004
+ data: zod.z.union([dataContentSchema, zod.z.instanceof(URL)]),
3005
+ filename: zod.z.string().optional(),
3006
+ mimeType: zod.z.string(),
3007
+ providerOptions: providerMetadataSchema.optional(),
3008
+ experimental_providerMetadata: providerMetadataSchema.optional()
3009
+ });
3010
+ var reasoningPartSchema = zod.z.object({
3011
+ type: zod.z.literal("reasoning"),
3012
+ text: zod.z.string(),
3013
+ providerOptions: providerMetadataSchema.optional(),
3014
+ experimental_providerMetadata: providerMetadataSchema.optional()
3015
+ });
3016
+ var redactedReasoningPartSchema = zod.z.object({
3017
+ type: zod.z.literal("redacted-reasoning"),
3018
+ data: zod.z.string(),
3019
+ providerOptions: providerMetadataSchema.optional(),
3020
+ experimental_providerMetadata: providerMetadataSchema.optional()
3021
+ });
3022
+ var toolCallPartSchema = zod.z.object({
3023
+ type: zod.z.literal("tool-call"),
3024
+ toolCallId: zod.z.string(),
3025
+ toolName: zod.z.string(),
3026
+ args: zod.z.unknown(),
3027
+ providerOptions: providerMetadataSchema.optional(),
3028
+ experimental_providerMetadata: providerMetadataSchema.optional()
3029
+ });
3030
+ var toolResultPartSchema = zod.z.object({
3031
+ type: zod.z.literal("tool-result"),
3032
+ toolCallId: zod.z.string(),
3033
+ toolName: zod.z.string(),
3034
+ result: zod.z.unknown(),
3035
+ content: toolResultContentSchema.optional(),
3036
+ isError: zod.z.boolean().optional(),
3037
+ providerOptions: providerMetadataSchema.optional(),
3038
+ experimental_providerMetadata: providerMetadataSchema.optional()
3039
+ });
3040
+ var coreSystemMessageSchema = zod.z.object({
3041
+ role: zod.z.literal("system"),
3042
+ content: zod.z.string(),
3043
+ providerOptions: providerMetadataSchema.optional(),
3044
+ experimental_providerMetadata: providerMetadataSchema.optional()
3045
+ });
3046
+ var coreUserMessageSchema = zod.z.object({
3047
+ role: zod.z.literal("user"),
3048
+ content: zod.z.union([
3049
+ zod.z.string(),
3050
+ zod.z.array(zod.z.union([textPartSchema, imagePartSchema, filePartSchema]))
3051
+ ]),
3052
+ providerOptions: providerMetadataSchema.optional(),
3053
+ experimental_providerMetadata: providerMetadataSchema.optional()
3054
+ });
3055
+ var coreAssistantMessageSchema = zod.z.object({
3056
+ role: zod.z.literal("assistant"),
3057
+ content: zod.z.union([
3058
+ zod.z.string(),
3059
+ zod.z.array(
3060
+ zod.z.union([
3061
+ textPartSchema,
3062
+ filePartSchema,
3063
+ reasoningPartSchema,
3064
+ redactedReasoningPartSchema,
3065
+ toolCallPartSchema
3066
+ ])
3067
+ )
3068
+ ]),
3069
+ providerOptions: providerMetadataSchema.optional(),
3070
+ experimental_providerMetadata: providerMetadataSchema.optional()
3071
+ });
3072
+ var coreToolMessageSchema = zod.z.object({
3073
+ role: zod.z.literal("tool"),
3074
+ content: zod.z.array(toolResultPartSchema),
3075
+ providerOptions: providerMetadataSchema.optional(),
3076
+ experimental_providerMetadata: providerMetadataSchema.optional()
3077
+ });
3078
+ zod.z.union([
3079
+ coreSystemMessageSchema,
3080
+ coreUserMessageSchema,
3081
+ coreAssistantMessageSchema,
3082
+ coreToolMessageSchema
3083
+ ]);
3084
+ var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
3085
+ var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
3086
+ var DEFAULT_GENERIC_SUFFIX = "You MUST answer with JSON.";
3087
+ function injectJsonInstruction({
3088
+ prompt,
3089
+ schema,
3090
+ schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0,
3091
+ schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX
3092
+ }) {
3093
+ return [
3094
+ prompt != null && prompt.length > 0 ? prompt : void 0,
3095
+ prompt != null && prompt.length > 0 ? "" : void 0,
3096
+ // add a newline if prompt is not null
3097
+ schemaPrefix,
3098
+ schema != null ? JSON.stringify(schema) : void 0,
3099
+ schemaSuffix
3100
+ ].filter((line) => line != null).join("\n");
3101
+ }
3102
+ createIdGenerator({ prefix: "aiobj", size: 24 });
3103
+ createIdGenerator({ prefix: "aiobj", size: 24 });
3104
+ createIdGenerator({
3105
+ prefix: "aitxt",
3106
+ size: 24
3107
+ });
3108
+ createIdGenerator({
3109
+ prefix: "msg",
3110
+ size: 24
3111
+ });
3112
+ var output_exports = {};
3113
+ __export(output_exports, {
3114
+ object: () => object,
3115
+ text: () => text
3116
+ });
3117
+ var text = () => ({
3118
+ type: "text",
3119
+ responseFormat: () => ({ type: "text" }),
3120
+ injectIntoSystemPrompt({ system }) {
3121
+ return system;
3122
+ },
3123
+ parsePartial({ text: text2 }) {
3124
+ return { partial: text2 };
3125
+ },
3126
+ parseOutput({ text: text2 }) {
3127
+ return text2;
3128
+ }
3129
+ });
3130
+ var object = ({
3131
+ schema: inputSchema
3132
+ }) => {
3133
+ const schema = asSchema(inputSchema);
3134
+ return {
3135
+ type: "object",
3136
+ responseFormat: ({ model }) => ({
3137
+ type: "json",
3138
+ schema: model.supportsStructuredOutputs ? schema.jsonSchema : void 0
3139
+ }),
3140
+ injectIntoSystemPrompt({ system, model }) {
3141
+ return model.supportsStructuredOutputs ? system : injectJsonInstruction({
3142
+ prompt: system,
3143
+ schema: schema.jsonSchema
3144
+ });
3145
+ },
3146
+ parsePartial({ text: text2 }) {
3147
+ const result = parsePartialJson(text2);
3148
+ switch (result.state) {
3149
+ case "failed-parse":
3150
+ case "undefined-input":
3151
+ return void 0;
3152
+ case "repaired-parse":
3153
+ case "successful-parse":
3154
+ return {
3155
+ // Note: currently no validation of partial results:
3156
+ partial: result.value
3157
+ };
3158
+ default: {
3159
+ const _exhaustiveCheck = result.state;
3160
+ throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
3161
+ }
3162
+ }
3163
+ },
3164
+ parseOutput({ text: text2 }, context) {
3165
+ const parseResult = safeParseJSON({ text: text2 });
3166
+ if (!parseResult.success) {
3167
+ throw new NoObjectGeneratedError({
3168
+ message: "No object generated: could not parse the response.",
3169
+ cause: parseResult.error,
3170
+ text: text2,
3171
+ response: context.response,
3172
+ usage: context.usage,
3173
+ finishReason: context.finishReason
3174
+ });
3175
+ }
3176
+ const validationResult = safeValidateTypes({
3177
+ value: parseResult.value,
3178
+ schema
3179
+ });
3180
+ if (!validationResult.success) {
3181
+ throw new NoObjectGeneratedError({
3182
+ message: "No object generated: response did not match schema.",
3183
+ cause: validationResult.error,
3184
+ text: text2,
3185
+ response: context.response,
3186
+ usage: context.usage,
3187
+ finishReason: context.finishReason
3188
+ });
3189
+ }
3190
+ return validationResult.value;
3191
+ }
3192
+ };
3193
+ };
3194
+ function mergeStreams(stream1, stream2) {
3195
+ const reader1 = stream1.getReader();
3196
+ const reader2 = stream2.getReader();
3197
+ let lastRead1 = void 0;
3198
+ let lastRead2 = void 0;
3199
+ let stream1Done = false;
3200
+ let stream2Done = false;
3201
+ async function readStream1(controller) {
3202
+ try {
3203
+ if (lastRead1 == null) {
3204
+ lastRead1 = reader1.read();
3205
+ }
3206
+ const result = await lastRead1;
3207
+ lastRead1 = void 0;
3208
+ if (!result.done) {
3209
+ controller.enqueue(result.value);
3210
+ } else {
3211
+ controller.close();
3212
+ }
3213
+ } catch (error) {
3214
+ controller.error(error);
3215
+ }
3216
+ }
3217
+ async function readStream2(controller) {
3218
+ try {
3219
+ if (lastRead2 == null) {
3220
+ lastRead2 = reader2.read();
3221
+ }
3222
+ const result = await lastRead2;
3223
+ lastRead2 = void 0;
3224
+ if (!result.done) {
3225
+ controller.enqueue(result.value);
3226
+ } else {
3227
+ controller.close();
3228
+ }
3229
+ } catch (error) {
3230
+ controller.error(error);
3231
+ }
3232
+ }
3233
+ return new ReadableStream({
3234
+ async pull(controller) {
3235
+ try {
3236
+ if (stream1Done) {
3237
+ await readStream2(controller);
3238
+ return;
3239
+ }
3240
+ if (stream2Done) {
3241
+ await readStream1(controller);
3242
+ return;
3243
+ }
3244
+ if (lastRead1 == null) {
3245
+ lastRead1 = reader1.read();
3246
+ }
3247
+ if (lastRead2 == null) {
3248
+ lastRead2 = reader2.read();
3249
+ }
3250
+ const { result, reader } = await Promise.race([
3251
+ lastRead1.then((result2) => ({ result: result2, reader: reader1 })),
3252
+ lastRead2.then((result2) => ({ result: result2, reader: reader2 }))
3253
+ ]);
3254
+ if (!result.done) {
3255
+ controller.enqueue(result.value);
3256
+ }
3257
+ if (reader === reader1) {
3258
+ lastRead1 = void 0;
3259
+ if (result.done) {
3260
+ await readStream2(controller);
3261
+ stream1Done = true;
3262
+ }
3263
+ } else {
3264
+ lastRead2 = void 0;
3265
+ if (result.done) {
3266
+ stream2Done = true;
3267
+ await readStream1(controller);
3268
+ }
3269
+ }
3270
+ } catch (error) {
3271
+ controller.error(error);
3272
+ }
3273
+ },
3274
+ cancel() {
3275
+ reader1.cancel();
3276
+ reader2.cancel();
3277
+ }
3278
+ });
3279
+ }
3280
+ createIdGenerator({
3281
+ prefix: "aitxt",
3282
+ size: 24
3283
+ });
3284
+ createIdGenerator({
3285
+ prefix: "msg",
3286
+ size: 24
3287
+ });
3288
+ var ClientOrServerImplementationSchema = zod.z.object({
3289
+ name: zod.z.string(),
3290
+ version: zod.z.string()
3291
+ }).passthrough();
3292
+ var BaseParamsSchema = zod.z.object({
3293
+ _meta: zod.z.optional(zod.z.object({}).passthrough())
3294
+ }).passthrough();
3295
+ var ResultSchema = BaseParamsSchema;
3296
+ var RequestSchema = zod.z.object({
3297
+ method: zod.z.string(),
3298
+ params: zod.z.optional(BaseParamsSchema)
3299
+ });
3300
+ var ServerCapabilitiesSchema = zod.z.object({
3301
+ experimental: zod.z.optional(zod.z.object({}).passthrough()),
3302
+ logging: zod.z.optional(zod.z.object({}).passthrough()),
3303
+ prompts: zod.z.optional(
3304
+ zod.z.object({
3305
+ listChanged: zod.z.optional(zod.z.boolean())
3306
+ }).passthrough()
3307
+ ),
3308
+ resources: zod.z.optional(
3309
+ zod.z.object({
3310
+ subscribe: zod.z.optional(zod.z.boolean()),
3311
+ listChanged: zod.z.optional(zod.z.boolean())
3312
+ }).passthrough()
3313
+ ),
3314
+ tools: zod.z.optional(
3315
+ zod.z.object({
3316
+ listChanged: zod.z.optional(zod.z.boolean())
3317
+ }).passthrough()
3318
+ )
3319
+ }).passthrough();
3320
+ ResultSchema.extend({
3321
+ protocolVersion: zod.z.string(),
3322
+ capabilities: ServerCapabilitiesSchema,
3323
+ serverInfo: ClientOrServerImplementationSchema,
3324
+ instructions: zod.z.optional(zod.z.string())
3325
+ });
3326
+ var PaginatedResultSchema = ResultSchema.extend({
3327
+ nextCursor: zod.z.optional(zod.z.string())
3328
+ });
3329
+ var ToolSchema = zod.z.object({
3330
+ name: zod.z.string(),
3331
+ description: zod.z.optional(zod.z.string()),
3332
+ inputSchema: zod.z.object({
3333
+ type: zod.z.literal("object"),
3334
+ properties: zod.z.optional(zod.z.object({}).passthrough())
3335
+ }).passthrough()
3336
+ }).passthrough();
3337
+ PaginatedResultSchema.extend({
3338
+ tools: zod.z.array(ToolSchema)
3339
+ });
3340
+ var TextContentSchema = zod.z.object({
3341
+ type: zod.z.literal("text"),
3342
+ text: zod.z.string()
3343
+ }).passthrough();
3344
+ var ImageContentSchema = zod.z.object({
3345
+ type: zod.z.literal("image"),
3346
+ data: zod.z.string().base64(),
3347
+ mimeType: zod.z.string()
3348
+ }).passthrough();
3349
+ var ResourceContentsSchema = zod.z.object({
3350
+ /**
3351
+ * The URI of this resource.
3352
+ */
3353
+ uri: zod.z.string(),
3354
+ /**
3355
+ * The MIME type of this resource, if known.
3356
+ */
3357
+ mimeType: zod.z.optional(zod.z.string())
3358
+ }).passthrough();
3359
+ var TextResourceContentsSchema = ResourceContentsSchema.extend({
3360
+ text: zod.z.string()
3361
+ });
3362
+ var BlobResourceContentsSchema = ResourceContentsSchema.extend({
3363
+ blob: zod.z.string().base64()
3364
+ });
3365
+ var EmbeddedResourceSchema = zod.z.object({
3366
+ type: zod.z.literal("resource"),
3367
+ resource: zod.z.union([TextResourceContentsSchema, BlobResourceContentsSchema])
3368
+ }).passthrough();
3369
+ ResultSchema.extend({
3370
+ content: zod.z.array(
3371
+ zod.z.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
3372
+ ),
3373
+ isError: zod.z.boolean().default(false).optional()
3374
+ }).or(
3375
+ ResultSchema.extend({
3376
+ toolResult: zod.z.unknown()
3377
+ })
3378
+ );
3379
+ var JSONRPC_VERSION = "2.0";
3380
+ var JSONRPCRequestSchema = zod.z.object({
3381
+ jsonrpc: zod.z.literal(JSONRPC_VERSION),
3382
+ id: zod.z.union([zod.z.string(), zod.z.number().int()])
3383
+ }).merge(RequestSchema).strict();
3384
+ var JSONRPCResponseSchema = zod.z.object({
3385
+ jsonrpc: zod.z.literal(JSONRPC_VERSION),
3386
+ id: zod.z.union([zod.z.string(), zod.z.number().int()]),
3387
+ result: ResultSchema
3388
+ }).strict();
3389
+ var JSONRPCErrorSchema = zod.z.object({
3390
+ jsonrpc: zod.z.literal(JSONRPC_VERSION),
3391
+ id: zod.z.union([zod.z.string(), zod.z.number().int()]),
3392
+ error: zod.z.object({
3393
+ code: zod.z.number().int(),
3394
+ message: zod.z.string(),
3395
+ data: zod.z.optional(zod.z.unknown())
3396
+ })
3397
+ }).strict();
3398
+ var JSONRPCNotificationSchema = zod.z.object({
3399
+ jsonrpc: zod.z.literal(JSONRPC_VERSION)
3400
+ }).merge(
3401
+ zod.z.object({
3402
+ method: zod.z.string(),
3403
+ params: zod.z.optional(BaseParamsSchema)
3404
+ })
3405
+ ).strict();
3406
+ zod.z.union([
3407
+ JSONRPCRequestSchema,
3408
+ JSONRPCNotificationSchema,
3409
+ JSONRPCResponseSchema,
3410
+ JSONRPCErrorSchema
3411
+ ]);
3412
+ var langchain_adapter_exports = {};
3413
+ __export(langchain_adapter_exports, {
3414
+ mergeIntoDataStream: () => mergeIntoDataStream,
3415
+ toDataStream: () => toDataStream,
3416
+ toDataStreamResponse: () => toDataStreamResponse
3417
+ });
3418
+ function createCallbacksTransformer(callbacks = {}) {
3419
+ const textEncoder = new TextEncoder();
3420
+ let aggregatedResponse = "";
3421
+ return new TransformStream({
3422
+ async start() {
3423
+ if (callbacks.onStart)
3424
+ await callbacks.onStart();
3425
+ },
3426
+ async transform(message, controller) {
3427
+ controller.enqueue(textEncoder.encode(message));
3428
+ aggregatedResponse += message;
3429
+ if (callbacks.onToken)
3430
+ await callbacks.onToken(message);
3431
+ if (callbacks.onText && typeof message === "string") {
3432
+ await callbacks.onText(message);
3433
+ }
3434
+ },
3435
+ async flush() {
3436
+ if (callbacks.onCompletion) {
3437
+ await callbacks.onCompletion(aggregatedResponse);
3438
+ }
3439
+ if (callbacks.onFinal) {
3440
+ await callbacks.onFinal(aggregatedResponse);
3441
+ }
3442
+ }
3443
+ });
3444
+ }
3445
+ function toDataStreamInternal(stream, callbacks) {
3446
+ return stream.pipeThrough(
3447
+ new TransformStream({
3448
+ transform: async (value, controller) => {
3449
+ var _a17;
3450
+ if (typeof value === "string") {
3451
+ controller.enqueue(value);
3452
+ return;
3453
+ }
3454
+ if ("event" in value) {
3455
+ if (value.event === "on_chat_model_stream") {
3456
+ forwardAIMessageChunk(
3457
+ (_a17 = value.data) == null ? void 0 : _a17.chunk,
3458
+ controller
3459
+ );
3460
+ }
3461
+ return;
3462
+ }
3463
+ forwardAIMessageChunk(value, controller);
3464
+ }
3465
+ })
3466
+ ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
3467
+ new TransformStream({
3468
+ transform: async (chunk, controller) => {
3469
+ controller.enqueue(formatDataStreamPart("text", chunk));
3470
+ }
3471
+ })
3472
+ );
3473
+ }
3474
+ function toDataStream(stream, callbacks) {
3475
+ return toDataStreamInternal(stream, callbacks).pipeThrough(
3476
+ new TextEncoderStream()
3477
+ );
3478
+ }
3479
+ function toDataStreamResponse(stream, options) {
3480
+ var _a17;
3481
+ const dataStream = toDataStreamInternal(
3482
+ stream,
3483
+ options == null ? void 0 : options.callbacks
3484
+ ).pipeThrough(new TextEncoderStream());
3485
+ const data = options == null ? void 0 : options.data;
3486
+ const init = options == null ? void 0 : options.init;
3487
+ const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
3488
+ return new Response(responseStream, {
3489
+ status: (_a17 = init == null ? void 0 : init.status) != null ? _a17 : 200,
3490
+ statusText: init == null ? void 0 : init.statusText,
3491
+ headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
3492
+ contentType: "text/plain; charset=utf-8",
3493
+ dataStreamVersion: "v1"
3494
+ })
3495
+ });
3496
+ }
3497
+ function mergeIntoDataStream(stream, options) {
3498
+ options.dataStream.merge(toDataStreamInternal(stream, options.callbacks));
3499
+ }
3500
+ function forwardAIMessageChunk(chunk, controller) {
3501
+ if (typeof chunk.content === "string") {
3502
+ controller.enqueue(chunk.content);
3503
+ } else {
3504
+ const content = chunk.content;
3505
+ for (const item of content) {
3506
+ if (item.type === "text") {
3507
+ controller.enqueue(item.text);
3508
+ }
3509
+ }
3510
+ }
3511
+ }
3512
+ var llamaindex_adapter_exports = {};
3513
+ __export(llamaindex_adapter_exports, {
3514
+ mergeIntoDataStream: () => mergeIntoDataStream2,
3515
+ toDataStream: () => toDataStream2,
3516
+ toDataStreamResponse: () => toDataStreamResponse2
3517
+ });
3518
+ function toDataStreamInternal2(stream, callbacks) {
3519
+ const trimStart = trimStartOfStream();
3520
+ return convertAsyncIteratorToReadableStream(stream[Symbol.asyncIterator]()).pipeThrough(
3521
+ new TransformStream({
3522
+ async transform(message, controller) {
3523
+ controller.enqueue(trimStart(message.delta));
3524
+ }
3525
+ })
3526
+ ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
3527
+ new TransformStream({
3528
+ transform: async (chunk, controller) => {
3529
+ controller.enqueue(formatDataStreamPart("text", chunk));
3530
+ }
3531
+ })
3532
+ );
3533
+ }
3534
+ function toDataStream2(stream, callbacks) {
3535
+ return toDataStreamInternal2(stream, callbacks).pipeThrough(
3536
+ new TextEncoderStream()
3537
+ );
3538
+ }
3539
+ function toDataStreamResponse2(stream, options = {}) {
3540
+ var _a17;
3541
+ const { init, data, callbacks } = options;
3542
+ const dataStream = toDataStreamInternal2(stream, callbacks).pipeThrough(
3543
+ new TextEncoderStream()
3544
+ );
3545
+ const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
3546
+ return new Response(responseStream, {
3547
+ status: (_a17 = init == null ? void 0 : init.status) != null ? _a17 : 200,
3548
+ statusText: init == null ? void 0 : init.statusText,
3549
+ headers: prepareResponseHeaders(init == null ? void 0 : init.headers, {
3550
+ contentType: "text/plain; charset=utf-8",
3551
+ dataStreamVersion: "v1"
3552
+ })
3553
+ });
3554
+ }
3555
+ function mergeIntoDataStream2(stream, options) {
3556
+ options.dataStream.merge(toDataStreamInternal2(stream, options.callbacks));
3557
+ }
3558
+ function trimStartOfStream() {
3559
+ let isStreamStart = true;
3560
+ return (text2) => {
3561
+ if (isStreamStart) {
3562
+ text2 = text2.trimStart();
3563
+ if (text2)
3564
+ isStreamStart = false;
3565
+ }
3566
+ return text2;
3567
+ };
3568
+ }
3569
+
3570
+ // src/utils.ts
3571
+ function convertZodSchemaToAISDKSchema(zodSchema2, target = "jsonSchema7") {
3572
+ const jsonSchemaToUse = chunk5WM4A32G_cjs.zodToJsonSchema(zodSchema2, target);
3573
+ return jsonSchema(jsonSchemaToUse, {
13
3574
  validate: (value) => {
14
- const result = zodSchema.safeParse(value);
3575
+ const result = zodSchema2.safeParse(value);
15
3576
  return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
16
3577
  }
17
3578
  });
@@ -43,21 +3604,21 @@ function applyCompatLayer({
43
3604
  compatLayers,
44
3605
  mode
45
3606
  }) {
46
- let zodSchema;
3607
+ let zodSchema2;
47
3608
  if (!isZodType(schema)) {
48
- zodSchema = convertSchemaToZod(schema);
3609
+ zodSchema2 = convertSchemaToZod(schema);
49
3610
  } else {
50
- zodSchema = schema;
3611
+ zodSchema2 = schema;
51
3612
  }
52
3613
  for (const compat of compatLayers) {
53
3614
  if (compat.shouldApply()) {
54
- return mode === "jsonSchema" ? compat.processToJSONSchema(zodSchema) : compat.processToAISDKSchema(zodSchema);
3615
+ return mode === "jsonSchema" ? compat.processToJSONSchema(zodSchema2) : compat.processToAISDKSchema(zodSchema2);
55
3616
  }
56
3617
  }
57
3618
  if (mode === "jsonSchema") {
58
- return chunk5WM4A32G_cjs.zodToJsonSchema(zodSchema, "jsonSchema7");
3619
+ return chunk5WM4A32G_cjs.zodToJsonSchema(zodSchema2, "jsonSchema7");
59
3620
  } else {
60
- return convertZodSchemaToAISDKSchema(zodSchema);
3621
+ return convertZodSchemaToAISDKSchema(zodSchema2);
61
3622
  }
62
3623
  }
63
3624
 
@@ -468,8 +4029,8 @@ var SchemaCompatLayer = class {
468
4029
  * @param zodSchema - The Zod object schema to process
469
4030
  * @returns An AI SDK Schema with provider-specific compatibility applied
470
4031
  */
471
- processToAISDKSchema(zodSchema) {
472
- const processedSchema = this.processZodType(zodSchema);
4032
+ processToAISDKSchema(zodSchema2) {
4033
+ const processedSchema = this.processZodType(zodSchema2);
473
4034
  return convertZodSchemaToAISDKSchema(processedSchema, this.getSchemaTarget());
474
4035
  }
475
4036
  /**
@@ -478,8 +4039,8 @@ var SchemaCompatLayer = class {
478
4039
  * @param zodSchema - The Zod object schema to process
479
4040
  * @returns A JSONSchema7 object with provider-specific compatibility applied
480
4041
  */
481
- processToJSONSchema(zodSchema) {
482
- return this.processToAISDKSchema(zodSchema).jsonSchema;
4042
+ processToJSONSchema(zodSchema2) {
4043
+ return this.processToAISDKSchema(zodSchema2).jsonSchema;
483
4044
  }
484
4045
  };
485
4046
  var ALL_STRING_CHECKS2 = [
@@ -906,8 +4467,8 @@ var SchemaCompatLayer2 = class {
906
4467
  * @param zodSchema - The Zod object schema to process
907
4468
  * @returns An AI SDK Schema with provider-specific compatibility applied
908
4469
  */
909
- processToAISDKSchema(zodSchema) {
910
- const processedSchema = this.processZodType(zodSchema);
4470
+ processToAISDKSchema(zodSchema2) {
4471
+ const processedSchema = this.processZodType(zodSchema2);
911
4472
  return convertZodSchemaToAISDKSchema(processedSchema, this.getSchemaTarget());
912
4473
  }
913
4474
  /**
@@ -916,8 +4477,8 @@ var SchemaCompatLayer2 = class {
916
4477
  * @param zodSchema - The Zod object schema to process
917
4478
  * @returns A JSONSchema7 object with provider-specific compatibility applied
918
4479
  */
919
- processToJSONSchema(zodSchema) {
920
- return this.processToAISDKSchema(zodSchema).jsonSchema;
4480
+ processToJSONSchema(zodSchema2) {
4481
+ return this.processToAISDKSchema(zodSchema2).jsonSchema;
921
4482
  }
922
4483
  };
923
4484
 
@@ -1104,8 +4665,8 @@ var SchemaCompatLayer3 = class {
1104
4665
  * @param zodSchema - The Zod object schema to process
1105
4666
  * @returns An AI SDK Schema with provider-specific compatibility applied
1106
4667
  */
1107
- processToAISDKSchema(zodSchema) {
1108
- const processedSchema = this.processZodType(zodSchema);
4668
+ processToAISDKSchema(zodSchema2) {
4669
+ const processedSchema = this.processZodType(zodSchema2);
1109
4670
  return convertZodSchemaToAISDKSchema(processedSchema, this.getSchemaTarget());
1110
4671
  }
1111
4672
  /**
@@ -1114,41 +4675,41 @@ var SchemaCompatLayer3 = class {
1114
4675
  * @param zodSchema - The Zod object schema to process
1115
4676
  * @returns A JSONSchema7 object with provider-specific compatibility applied
1116
4677
  */
1117
- processToJSONSchema(zodSchema) {
1118
- return this.processToAISDKSchema(zodSchema).jsonSchema;
4678
+ processToJSONSchema(zodSchema2) {
4679
+ return this.processToAISDKSchema(zodSchema2).jsonSchema;
1119
4680
  }
1120
4681
  };
1121
4682
 
1122
4683
  // src/zodTypes.ts
1123
- function isOptional2(z10) {
1124
- return (v) => v instanceof z10["ZodOptional"];
4684
+ function isOptional2(z11) {
4685
+ return (v) => v instanceof z11["ZodOptional"];
1125
4686
  }
1126
- function isObj2(z10) {
1127
- return (v) => v instanceof z10["ZodObject"];
4687
+ function isObj2(z11) {
4688
+ return (v) => v instanceof z11["ZodObject"];
1128
4689
  }
1129
- function isNull(z10) {
1130
- return (v) => v instanceof z10["ZodNull"];
4690
+ function isNull(z11) {
4691
+ return (v) => v instanceof z11["ZodNull"];
1131
4692
  }
1132
- function isArr2(z10) {
1133
- return (v) => v instanceof z10["ZodArray"];
4693
+ function isArr2(z11) {
4694
+ return (v) => v instanceof z11["ZodArray"];
1134
4695
  }
1135
- function isUnion2(z10) {
1136
- return (v) => v instanceof z10["ZodUnion"];
4696
+ function isUnion2(z11) {
4697
+ return (v) => v instanceof z11["ZodUnion"];
1137
4698
  }
1138
- function isString2(z10) {
1139
- return (v) => v instanceof z10["ZodString"];
4699
+ function isString2(z11) {
4700
+ return (v) => v instanceof z11["ZodString"];
1140
4701
  }
1141
- function isNumber2(z10) {
1142
- return (v) => v instanceof z10["ZodNumber"];
4702
+ function isNumber2(z11) {
4703
+ return (v) => v instanceof z11["ZodNumber"];
1143
4704
  }
1144
- function isDate(z10) {
1145
- return (v) => v instanceof z10["ZodDate"];
4705
+ function isDate(z11) {
4706
+ return (v) => v instanceof z11["ZodDate"];
1146
4707
  }
1147
- function isDefault(z10) {
1148
- return (v) => v instanceof z10["ZodDefault"];
4708
+ function isDefault(z11) {
4709
+ return (v) => v instanceof z11["ZodDefault"];
1149
4710
  }
1150
- function isNullable(z10) {
1151
- return (v) => v instanceof z10["ZodNullable"];
4711
+ function isNullable(z11) {
4712
+ return (v) => v instanceof z11["ZodNullable"];
1152
4713
  }
1153
4714
 
1154
4715
  // src/provider-compats/anthropic.ts
@@ -1346,7 +4907,7 @@ var OpenAIReasoningSchemaCompatLayer = class extends SchemaCompatLayer3 {
1346
4907
  return this.getModel().modelId.includes(`o3`) || this.getModel().modelId.includes(`o4`) || this.getModel().modelId.includes(`o1`);
1347
4908
  }
1348
4909
  shouldApply() {
1349
- if ((this.getModel().supportsStructuredOutputs || this.isReasoningModel()) && (this.getModel().provider.includes(`openai`) || this.getModel().modelId.includes(`openai`))) {
4910
+ if (this.isReasoningModel() && (this.getModel().provider.includes(`openai`) || this.getModel().modelId.includes(`openai`))) {
1350
4911
  return true;
1351
4912
  }
1352
4913
  return false;
@@ -1437,5 +4998,6 @@ exports.isObj = isObj;
1437
4998
  exports.isOptional = isOptional;
1438
4999
  exports.isString = isString;
1439
5000
  exports.isUnion = isUnion;
5001
+ exports.jsonSchema = jsonSchema;
1440
5002
  //# sourceMappingURL=index.cjs.map
1441
5003
  //# sourceMappingURL=index.cjs.map