freestyle-sandboxes 0.0.97 → 0.1.0

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