freestyle-sandboxes 0.0.77 → 0.0.79

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