@mastra/ai-sdk 1.0.0-beta.7 → 1.0.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -0
- package/dist/_types/@ai-sdk_provider/dist/index.d.ts +1719 -0
- package/dist/chat-route.d.ts.map +1 -1
- package/dist/chunk-DES3K4SD.cjs +17 -0
- package/dist/chunk-DES3K4SD.cjs.map +1 -0
- package/dist/chunk-KYQEM4AK.js +294 -0
- package/dist/chunk-KYQEM4AK.js.map +1 -0
- package/dist/chunk-TD7TJ4N5.cjs +297 -0
- package/dist/chunk-TD7TJ4N5.cjs.map +1 -0
- package/dist/chunk-VUNV25KB.js +14 -0
- package/dist/chunk-VUNV25KB.js.map +1 -0
- package/dist/convert-messages.d.ts +83 -3
- package/dist/convert-messages.d.ts.map +1 -1
- package/dist/helpers.d.ts +8 -2
- package/dist/helpers.d.ts.map +1 -1
- package/dist/index.cjs +2971 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +2945 -20
- package/dist/index.js.map +1 -1
- package/dist/middleware.d.ts +1 -1
- package/dist/middleware.d.ts.map +1 -1
- package/dist/network-route.d.ts.map +1 -1
- package/dist/token-5ZTQBFQ6.cjs +63 -0
- package/dist/token-5ZTQBFQ6.cjs.map +1 -0
- package/dist/token-UOO4N54I.js +61 -0
- package/dist/token-UOO4N54I.js.map +1 -0
- package/dist/token-util-DUN56AZR.cjs +9 -0
- package/dist/token-util-DUN56AZR.cjs.map +1 -0
- package/dist/token-util-JCUK3SCT.js +7 -0
- package/dist/token-util-JCUK3SCT.js.map +1 -0
- package/dist/ui.cjs +0 -1
- package/dist/ui.cjs.map +1 -1
- package/dist/ui.js +0 -1
- package/dist/ui.js.map +1 -1
- package/package.json +5 -7
package/dist/index.js
CHANGED
|
@@ -1,11 +1,2911 @@
|
|
|
1
1
|
import { registerApiRoute } from '@mastra/core/server';
|
|
2
|
-
import
|
|
2
|
+
import * as z4 from 'zod/v4';
|
|
3
|
+
import { z } from 'zod/v4';
|
|
4
|
+
import { ZodFirstPartyTypeKind } from 'zod/v3';
|
|
3
5
|
import { convertFullStreamChunkToMastra, DefaultGeneratedFile, DefaultGeneratedFileWithType } from '@mastra/core/stream';
|
|
4
6
|
import { TripWire, MessageList } from '@mastra/core/agent';
|
|
5
7
|
import { RequestContext } from '@mastra/core/di';
|
|
6
8
|
import { WorkingMemory, MessageHistory, SemanticRecall } from '@mastra/core/processors';
|
|
7
9
|
|
|
8
|
-
//
|
|
10
|
+
// ../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/dist/index.mjs
|
|
11
|
+
var marker = "vercel.ai.error";
|
|
12
|
+
var symbol = Symbol.for(marker);
|
|
13
|
+
var _a;
|
|
14
|
+
var _AISDKError = class _AISDKError2 extends Error {
|
|
15
|
+
/**
|
|
16
|
+
* Creates an AI SDK Error.
|
|
17
|
+
*
|
|
18
|
+
* @param {Object} params - The parameters for creating the error.
|
|
19
|
+
* @param {string} params.name - The name of the error.
|
|
20
|
+
* @param {string} params.message - The error message.
|
|
21
|
+
* @param {unknown} [params.cause] - The underlying cause of the error.
|
|
22
|
+
*/
|
|
23
|
+
constructor({
|
|
24
|
+
name: name143,
|
|
25
|
+
message,
|
|
26
|
+
cause
|
|
27
|
+
}) {
|
|
28
|
+
super(message);
|
|
29
|
+
this[_a] = true;
|
|
30
|
+
this.name = name143;
|
|
31
|
+
this.cause = cause;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Checks if the given error is an AI SDK Error.
|
|
35
|
+
* @param {unknown} error - The error to check.
|
|
36
|
+
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
|
|
37
|
+
*/
|
|
38
|
+
static isInstance(error) {
|
|
39
|
+
return _AISDKError2.hasMarker(error, marker);
|
|
40
|
+
}
|
|
41
|
+
static hasMarker(error, marker153) {
|
|
42
|
+
const markerSymbol = Symbol.for(marker153);
|
|
43
|
+
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
_a = symbol;
|
|
47
|
+
var AISDKError = _AISDKError;
|
|
48
|
+
function getErrorMessage(error) {
|
|
49
|
+
if (error == null) {
|
|
50
|
+
return "unknown error";
|
|
51
|
+
}
|
|
52
|
+
if (typeof error === "string") {
|
|
53
|
+
return error;
|
|
54
|
+
}
|
|
55
|
+
if (error instanceof Error) {
|
|
56
|
+
return error.message;
|
|
57
|
+
}
|
|
58
|
+
return JSON.stringify(error);
|
|
59
|
+
}
|
|
60
|
+
var name3 = "AI_InvalidArgumentError";
|
|
61
|
+
var marker4 = `vercel.ai.error.${name3}`;
|
|
62
|
+
var symbol4 = Symbol.for(marker4);
|
|
63
|
+
var _a4;
|
|
64
|
+
var InvalidArgumentError = class extends AISDKError {
|
|
65
|
+
constructor({
|
|
66
|
+
message,
|
|
67
|
+
cause,
|
|
68
|
+
argument
|
|
69
|
+
}) {
|
|
70
|
+
super({ name: name3, message, cause });
|
|
71
|
+
this[_a4] = true;
|
|
72
|
+
this.argument = argument;
|
|
73
|
+
}
|
|
74
|
+
static isInstance(error) {
|
|
75
|
+
return AISDKError.hasMarker(error, marker4);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
_a4 = symbol4;
|
|
79
|
+
var name6 = "AI_JSONParseError";
|
|
80
|
+
var marker7 = `vercel.ai.error.${name6}`;
|
|
81
|
+
var symbol7 = Symbol.for(marker7);
|
|
82
|
+
var _a7;
|
|
83
|
+
var JSONParseError = class extends AISDKError {
|
|
84
|
+
constructor({ text: text2, cause }) {
|
|
85
|
+
super({
|
|
86
|
+
name: name6,
|
|
87
|
+
message: `JSON parsing failed: Text: ${text2}.
|
|
88
|
+
Error message: ${getErrorMessage(cause)}`,
|
|
89
|
+
cause
|
|
90
|
+
});
|
|
91
|
+
this[_a7] = true;
|
|
92
|
+
this.text = text2;
|
|
93
|
+
}
|
|
94
|
+
static isInstance(error) {
|
|
95
|
+
return AISDKError.hasMarker(error, marker7);
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
_a7 = symbol7;
|
|
99
|
+
var name12 = "AI_TypeValidationError";
|
|
100
|
+
var marker13 = `vercel.ai.error.${name12}`;
|
|
101
|
+
var symbol13 = Symbol.for(marker13);
|
|
102
|
+
var _a13;
|
|
103
|
+
var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
|
|
104
|
+
constructor({ value, cause }) {
|
|
105
|
+
super({
|
|
106
|
+
name: name12,
|
|
107
|
+
message: `Type validation failed: Value: ${JSON.stringify(value)}.
|
|
108
|
+
Error message: ${getErrorMessage(cause)}`,
|
|
109
|
+
cause
|
|
110
|
+
});
|
|
111
|
+
this[_a13] = true;
|
|
112
|
+
this.value = value;
|
|
113
|
+
}
|
|
114
|
+
static isInstance(error) {
|
|
115
|
+
return AISDKError.hasMarker(error, marker13);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Wraps an error into a TypeValidationError.
|
|
119
|
+
* If the cause is already a TypeValidationError with the same value, it returns the cause.
|
|
120
|
+
* Otherwise, it creates a new TypeValidationError.
|
|
121
|
+
*
|
|
122
|
+
* @param {Object} params - The parameters for wrapping the error.
|
|
123
|
+
* @param {unknown} params.value - The value that failed validation.
|
|
124
|
+
* @param {unknown} params.cause - The original error or cause of the validation failure.
|
|
125
|
+
* @returns {TypeValidationError} A TypeValidationError instance.
|
|
126
|
+
*/
|
|
127
|
+
static wrap({
|
|
128
|
+
value,
|
|
129
|
+
cause
|
|
130
|
+
}) {
|
|
131
|
+
return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
_a13 = symbol13;
|
|
135
|
+
var TypeValidationError = _TypeValidationError;
|
|
136
|
+
var createIdGenerator = ({
|
|
137
|
+
prefix,
|
|
138
|
+
size = 16,
|
|
139
|
+
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
|
140
|
+
separator = "-"
|
|
141
|
+
} = {}) => {
|
|
142
|
+
const generator = () => {
|
|
143
|
+
const alphabetLength = alphabet.length;
|
|
144
|
+
const chars = new Array(size);
|
|
145
|
+
for (let i = 0; i < size; i++) {
|
|
146
|
+
chars[i] = alphabet[Math.random() * alphabetLength | 0];
|
|
147
|
+
}
|
|
148
|
+
return chars.join("");
|
|
149
|
+
};
|
|
150
|
+
if (prefix == null) {
|
|
151
|
+
return generator;
|
|
152
|
+
}
|
|
153
|
+
if (alphabet.includes(separator)) {
|
|
154
|
+
throw new InvalidArgumentError({
|
|
155
|
+
argument: "separator",
|
|
156
|
+
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
return () => `${prefix}${separator}${generator()}`;
|
|
160
|
+
};
|
|
161
|
+
var generateId = createIdGenerator();
|
|
162
|
+
function getErrorMessage2(error) {
|
|
163
|
+
if (error == null) {
|
|
164
|
+
return "unknown error";
|
|
165
|
+
}
|
|
166
|
+
if (typeof error === "string") {
|
|
167
|
+
return error;
|
|
168
|
+
}
|
|
169
|
+
if (error instanceof Error) {
|
|
170
|
+
return error.message;
|
|
171
|
+
}
|
|
172
|
+
return JSON.stringify(error);
|
|
173
|
+
}
|
|
174
|
+
var suspectProtoRx = /"__proto__"\s*:/;
|
|
175
|
+
var suspectConstructorRx = /"constructor"\s*:/;
|
|
176
|
+
function _parse(text2) {
|
|
177
|
+
const obj = JSON.parse(text2);
|
|
178
|
+
if (obj === null || typeof obj !== "object") {
|
|
179
|
+
return obj;
|
|
180
|
+
}
|
|
181
|
+
if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) {
|
|
182
|
+
return obj;
|
|
183
|
+
}
|
|
184
|
+
return filter(obj);
|
|
185
|
+
}
|
|
186
|
+
function filter(obj) {
|
|
187
|
+
let next = [obj];
|
|
188
|
+
while (next.length) {
|
|
189
|
+
const nodes = next;
|
|
190
|
+
next = [];
|
|
191
|
+
for (const node of nodes) {
|
|
192
|
+
if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
|
|
193
|
+
throw new SyntaxError("Object contains forbidden prototype property");
|
|
194
|
+
}
|
|
195
|
+
if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
|
|
196
|
+
throw new SyntaxError("Object contains forbidden prototype property");
|
|
197
|
+
}
|
|
198
|
+
for (const key in node) {
|
|
199
|
+
const value = node[key];
|
|
200
|
+
if (value && typeof value === "object") {
|
|
201
|
+
next.push(value);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return obj;
|
|
207
|
+
}
|
|
208
|
+
function secureJsonParse(text2) {
|
|
209
|
+
const { stackTraceLimit } = Error;
|
|
210
|
+
Error.stackTraceLimit = 0;
|
|
211
|
+
try {
|
|
212
|
+
return _parse(text2);
|
|
213
|
+
} finally {
|
|
214
|
+
Error.stackTraceLimit = stackTraceLimit;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
var validatorSymbol = Symbol.for("vercel.ai.validator");
|
|
218
|
+
function validator(validate) {
|
|
219
|
+
return { [validatorSymbol]: true, validate };
|
|
220
|
+
}
|
|
221
|
+
function isValidator(value) {
|
|
222
|
+
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
|
|
223
|
+
}
|
|
224
|
+
function asValidator(value) {
|
|
225
|
+
return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
|
|
226
|
+
}
|
|
227
|
+
function standardSchemaValidator(standardSchema) {
|
|
228
|
+
return validator(async (value) => {
|
|
229
|
+
const result = await standardSchema["~standard"].validate(value);
|
|
230
|
+
return result.issues == null ? { success: true, value: result.value } : {
|
|
231
|
+
success: false,
|
|
232
|
+
error: new TypeValidationError({
|
|
233
|
+
value,
|
|
234
|
+
cause: result.issues
|
|
235
|
+
})
|
|
236
|
+
};
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
async function validateTypes({
|
|
240
|
+
value,
|
|
241
|
+
schema
|
|
242
|
+
}) {
|
|
243
|
+
const result = await safeValidateTypes({ value, schema });
|
|
244
|
+
if (!result.success) {
|
|
245
|
+
throw TypeValidationError.wrap({ value, cause: result.error });
|
|
246
|
+
}
|
|
247
|
+
return result.value;
|
|
248
|
+
}
|
|
249
|
+
async function safeValidateTypes({
|
|
250
|
+
value,
|
|
251
|
+
schema
|
|
252
|
+
}) {
|
|
253
|
+
const validator2 = asValidator(schema);
|
|
254
|
+
try {
|
|
255
|
+
if (validator2.validate == null) {
|
|
256
|
+
return { success: true, value, rawValue: value };
|
|
257
|
+
}
|
|
258
|
+
const result = await validator2.validate(value);
|
|
259
|
+
if (result.success) {
|
|
260
|
+
return { success: true, value: result.value, rawValue: value };
|
|
261
|
+
}
|
|
262
|
+
return {
|
|
263
|
+
success: false,
|
|
264
|
+
error: TypeValidationError.wrap({ value, cause: result.error }),
|
|
265
|
+
rawValue: value
|
|
266
|
+
};
|
|
267
|
+
} catch (error) {
|
|
268
|
+
return {
|
|
269
|
+
success: false,
|
|
270
|
+
error: TypeValidationError.wrap({ value, cause: error }),
|
|
271
|
+
rawValue: value
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
async function safeParseJSON({
|
|
276
|
+
text: text2,
|
|
277
|
+
schema
|
|
278
|
+
}) {
|
|
279
|
+
try {
|
|
280
|
+
const value = secureJsonParse(text2);
|
|
281
|
+
if (schema == null) {
|
|
282
|
+
return { success: true, value, rawValue: value };
|
|
283
|
+
}
|
|
284
|
+
return await safeValidateTypes({ value, schema });
|
|
285
|
+
} catch (error) {
|
|
286
|
+
return {
|
|
287
|
+
success: false,
|
|
288
|
+
error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text: text2, cause: error }),
|
|
289
|
+
rawValue: void 0
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
var getRelativePath = (pathA, pathB) => {
|
|
294
|
+
let i = 0;
|
|
295
|
+
for (; i < pathA.length && i < pathB.length; i++) {
|
|
296
|
+
if (pathA[i] !== pathB[i]) break;
|
|
297
|
+
}
|
|
298
|
+
return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
|
|
299
|
+
};
|
|
300
|
+
var ignoreOverride = Symbol(
|
|
301
|
+
"Let zodToJsonSchema decide on which parser to use"
|
|
302
|
+
);
|
|
303
|
+
var defaultOptions = {
|
|
304
|
+
name: void 0,
|
|
305
|
+
$refStrategy: "root",
|
|
306
|
+
basePath: ["#"],
|
|
307
|
+
effectStrategy: "input",
|
|
308
|
+
pipeStrategy: "all",
|
|
309
|
+
dateStrategy: "format:date-time",
|
|
310
|
+
mapStrategy: "entries",
|
|
311
|
+
removeAdditionalStrategy: "passthrough",
|
|
312
|
+
allowedAdditionalProperties: true,
|
|
313
|
+
rejectedAdditionalProperties: false,
|
|
314
|
+
definitionPath: "definitions",
|
|
315
|
+
strictUnions: false,
|
|
316
|
+
definitions: {},
|
|
317
|
+
errorMessages: false,
|
|
318
|
+
patternStrategy: "escape",
|
|
319
|
+
applyRegexFlags: false,
|
|
320
|
+
emailStrategy: "format:email",
|
|
321
|
+
base64Strategy: "contentEncoding:base64",
|
|
322
|
+
nameStrategy: "ref"
|
|
323
|
+
};
|
|
324
|
+
var getDefaultOptions = (options) => typeof options === "string" ? {
|
|
325
|
+
...defaultOptions,
|
|
326
|
+
name: options
|
|
327
|
+
} : {
|
|
328
|
+
...defaultOptions,
|
|
329
|
+
...options
|
|
330
|
+
};
|
|
331
|
+
function parseAnyDef() {
|
|
332
|
+
return {};
|
|
333
|
+
}
|
|
334
|
+
function parseArrayDef(def, refs) {
|
|
335
|
+
var _a17, _b, _c;
|
|
336
|
+
const res = {
|
|
337
|
+
type: "array"
|
|
338
|
+
};
|
|
339
|
+
if (((_a17 = def.type) == null ? void 0 : _a17._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
|
|
340
|
+
res.items = parseDef(def.type._def, {
|
|
341
|
+
...refs,
|
|
342
|
+
currentPath: [...refs.currentPath, "items"]
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
if (def.minLength) {
|
|
346
|
+
res.minItems = def.minLength.value;
|
|
347
|
+
}
|
|
348
|
+
if (def.maxLength) {
|
|
349
|
+
res.maxItems = def.maxLength.value;
|
|
350
|
+
}
|
|
351
|
+
if (def.exactLength) {
|
|
352
|
+
res.minItems = def.exactLength.value;
|
|
353
|
+
res.maxItems = def.exactLength.value;
|
|
354
|
+
}
|
|
355
|
+
return res;
|
|
356
|
+
}
|
|
357
|
+
function parseBigintDef(def) {
|
|
358
|
+
const res = {
|
|
359
|
+
type: "integer",
|
|
360
|
+
format: "int64"
|
|
361
|
+
};
|
|
362
|
+
if (!def.checks) return res;
|
|
363
|
+
for (const check of def.checks) {
|
|
364
|
+
switch (check.kind) {
|
|
365
|
+
case "min":
|
|
366
|
+
if (check.inclusive) {
|
|
367
|
+
res.minimum = check.value;
|
|
368
|
+
} else {
|
|
369
|
+
res.exclusiveMinimum = check.value;
|
|
370
|
+
}
|
|
371
|
+
break;
|
|
372
|
+
case "max":
|
|
373
|
+
if (check.inclusive) {
|
|
374
|
+
res.maximum = check.value;
|
|
375
|
+
} else {
|
|
376
|
+
res.exclusiveMaximum = check.value;
|
|
377
|
+
}
|
|
378
|
+
break;
|
|
379
|
+
case "multipleOf":
|
|
380
|
+
res.multipleOf = check.value;
|
|
381
|
+
break;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return res;
|
|
385
|
+
}
|
|
386
|
+
function parseBooleanDef() {
|
|
387
|
+
return { type: "boolean" };
|
|
388
|
+
}
|
|
389
|
+
function parseBrandedDef(_def, refs) {
|
|
390
|
+
return parseDef(_def.type._def, refs);
|
|
391
|
+
}
|
|
392
|
+
var parseCatchDef = (def, refs) => {
|
|
393
|
+
return parseDef(def.innerType._def, refs);
|
|
394
|
+
};
|
|
395
|
+
function parseDateDef(def, refs, overrideDateStrategy) {
|
|
396
|
+
const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
|
|
397
|
+
if (Array.isArray(strategy)) {
|
|
398
|
+
return {
|
|
399
|
+
anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
switch (strategy) {
|
|
403
|
+
case "string":
|
|
404
|
+
case "format:date-time":
|
|
405
|
+
return {
|
|
406
|
+
type: "string",
|
|
407
|
+
format: "date-time"
|
|
408
|
+
};
|
|
409
|
+
case "format:date":
|
|
410
|
+
return {
|
|
411
|
+
type: "string",
|
|
412
|
+
format: "date"
|
|
413
|
+
};
|
|
414
|
+
case "integer":
|
|
415
|
+
return integerDateParser(def);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
var integerDateParser = (def) => {
|
|
419
|
+
const res = {
|
|
420
|
+
type: "integer",
|
|
421
|
+
format: "unix-time"
|
|
422
|
+
};
|
|
423
|
+
for (const check of def.checks) {
|
|
424
|
+
switch (check.kind) {
|
|
425
|
+
case "min":
|
|
426
|
+
res.minimum = check.value;
|
|
427
|
+
break;
|
|
428
|
+
case "max":
|
|
429
|
+
res.maximum = check.value;
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
return res;
|
|
434
|
+
};
|
|
435
|
+
function parseDefaultDef(_def, refs) {
|
|
436
|
+
return {
|
|
437
|
+
...parseDef(_def.innerType._def, refs),
|
|
438
|
+
default: _def.defaultValue()
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
function parseEffectsDef(_def, refs) {
|
|
442
|
+
return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
|
|
443
|
+
}
|
|
444
|
+
function parseEnumDef(def) {
|
|
445
|
+
return {
|
|
446
|
+
type: "string",
|
|
447
|
+
enum: Array.from(def.values)
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
var isJsonSchema7AllOfType = (type) => {
|
|
451
|
+
if ("type" in type && type.type === "string") return false;
|
|
452
|
+
return "allOf" in type;
|
|
453
|
+
};
|
|
454
|
+
function parseIntersectionDef(def, refs) {
|
|
455
|
+
const allOf = [
|
|
456
|
+
parseDef(def.left._def, {
|
|
457
|
+
...refs,
|
|
458
|
+
currentPath: [...refs.currentPath, "allOf", "0"]
|
|
459
|
+
}),
|
|
460
|
+
parseDef(def.right._def, {
|
|
461
|
+
...refs,
|
|
462
|
+
currentPath: [...refs.currentPath, "allOf", "1"]
|
|
463
|
+
})
|
|
464
|
+
].filter((x) => !!x);
|
|
465
|
+
const mergedAllOf = [];
|
|
466
|
+
allOf.forEach((schema) => {
|
|
467
|
+
if (isJsonSchema7AllOfType(schema)) {
|
|
468
|
+
mergedAllOf.push(...schema.allOf);
|
|
469
|
+
} else {
|
|
470
|
+
let nestedSchema = schema;
|
|
471
|
+
if ("additionalProperties" in schema && schema.additionalProperties === false) {
|
|
472
|
+
const { additionalProperties, ...rest } = schema;
|
|
473
|
+
nestedSchema = rest;
|
|
474
|
+
}
|
|
475
|
+
mergedAllOf.push(nestedSchema);
|
|
476
|
+
}
|
|
477
|
+
});
|
|
478
|
+
return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
|
|
479
|
+
}
|
|
480
|
+
function parseLiteralDef(def) {
|
|
481
|
+
const parsedType = typeof def.value;
|
|
482
|
+
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
|
|
483
|
+
return {
|
|
484
|
+
type: Array.isArray(def.value) ? "array" : "object"
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
return {
|
|
488
|
+
type: parsedType === "bigint" ? "integer" : parsedType,
|
|
489
|
+
const: def.value
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
var emojiRegex = void 0;
|
|
493
|
+
var zodPatterns = {
|
|
494
|
+
/**
|
|
495
|
+
* `c` was changed to `[cC]` to replicate /i flag
|
|
496
|
+
*/
|
|
497
|
+
cuid: /^[cC][^\s-]{8,}$/,
|
|
498
|
+
cuid2: /^[0-9a-z]+$/,
|
|
499
|
+
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
|
|
500
|
+
/**
|
|
501
|
+
* `a-z` was added to replicate /i flag
|
|
502
|
+
*/
|
|
503
|
+
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
|
|
504
|
+
/**
|
|
505
|
+
* Constructed a valid Unicode RegExp
|
|
506
|
+
*
|
|
507
|
+
* Lazily instantiate since this type of regex isn't supported
|
|
508
|
+
* in all envs (e.g. React Native).
|
|
509
|
+
*
|
|
510
|
+
* See:
|
|
511
|
+
* https://github.com/colinhacks/zod/issues/2433
|
|
512
|
+
* Fix in Zod:
|
|
513
|
+
* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
|
|
514
|
+
*/
|
|
515
|
+
emoji: () => {
|
|
516
|
+
if (emojiRegex === void 0) {
|
|
517
|
+
emojiRegex = RegExp(
|
|
518
|
+
"^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
|
|
519
|
+
"u"
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
return emojiRegex;
|
|
523
|
+
},
|
|
524
|
+
/**
|
|
525
|
+
* Unused
|
|
526
|
+
*/
|
|
527
|
+
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}$/,
|
|
528
|
+
/**
|
|
529
|
+
* Unused
|
|
530
|
+
*/
|
|
531
|
+
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])$/,
|
|
532
|
+
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])$/,
|
|
533
|
+
/**
|
|
534
|
+
* Unused
|
|
535
|
+
*/
|
|
536
|
+
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})))$/,
|
|
537
|
+
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])$/,
|
|
538
|
+
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
|
|
539
|
+
base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
|
|
540
|
+
nanoid: /^[a-zA-Z0-9_-]{21}$/,
|
|
541
|
+
jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
|
|
542
|
+
};
|
|
543
|
+
function parseStringDef(def, refs) {
|
|
544
|
+
const res = {
|
|
545
|
+
type: "string"
|
|
546
|
+
};
|
|
547
|
+
if (def.checks) {
|
|
548
|
+
for (const check of def.checks) {
|
|
549
|
+
switch (check.kind) {
|
|
550
|
+
case "min":
|
|
551
|
+
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
|
|
552
|
+
break;
|
|
553
|
+
case "max":
|
|
554
|
+
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
|
|
555
|
+
break;
|
|
556
|
+
case "email":
|
|
557
|
+
switch (refs.emailStrategy) {
|
|
558
|
+
case "format:email":
|
|
559
|
+
addFormat(res, "email", check.message, refs);
|
|
560
|
+
break;
|
|
561
|
+
case "format:idn-email":
|
|
562
|
+
addFormat(res, "idn-email", check.message, refs);
|
|
563
|
+
break;
|
|
564
|
+
case "pattern:zod":
|
|
565
|
+
addPattern(res, zodPatterns.email, check.message, refs);
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
break;
|
|
569
|
+
case "url":
|
|
570
|
+
addFormat(res, "uri", check.message, refs);
|
|
571
|
+
break;
|
|
572
|
+
case "uuid":
|
|
573
|
+
addFormat(res, "uuid", check.message, refs);
|
|
574
|
+
break;
|
|
575
|
+
case "regex":
|
|
576
|
+
addPattern(res, check.regex, check.message, refs);
|
|
577
|
+
break;
|
|
578
|
+
case "cuid":
|
|
579
|
+
addPattern(res, zodPatterns.cuid, check.message, refs);
|
|
580
|
+
break;
|
|
581
|
+
case "cuid2":
|
|
582
|
+
addPattern(res, zodPatterns.cuid2, check.message, refs);
|
|
583
|
+
break;
|
|
584
|
+
case "startsWith":
|
|
585
|
+
addPattern(
|
|
586
|
+
res,
|
|
587
|
+
RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
|
|
588
|
+
check.message,
|
|
589
|
+
refs
|
|
590
|
+
);
|
|
591
|
+
break;
|
|
592
|
+
case "endsWith":
|
|
593
|
+
addPattern(
|
|
594
|
+
res,
|
|
595
|
+
RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
|
|
596
|
+
check.message,
|
|
597
|
+
refs
|
|
598
|
+
);
|
|
599
|
+
break;
|
|
600
|
+
case "datetime":
|
|
601
|
+
addFormat(res, "date-time", check.message, refs);
|
|
602
|
+
break;
|
|
603
|
+
case "date":
|
|
604
|
+
addFormat(res, "date", check.message, refs);
|
|
605
|
+
break;
|
|
606
|
+
case "time":
|
|
607
|
+
addFormat(res, "time", check.message, refs);
|
|
608
|
+
break;
|
|
609
|
+
case "duration":
|
|
610
|
+
addFormat(res, "duration", check.message, refs);
|
|
611
|
+
break;
|
|
612
|
+
case "length":
|
|
613
|
+
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
|
|
614
|
+
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
|
|
615
|
+
break;
|
|
616
|
+
case "includes": {
|
|
617
|
+
addPattern(
|
|
618
|
+
res,
|
|
619
|
+
RegExp(escapeLiteralCheckValue(check.value, refs)),
|
|
620
|
+
check.message,
|
|
621
|
+
refs
|
|
622
|
+
);
|
|
623
|
+
break;
|
|
624
|
+
}
|
|
625
|
+
case "ip": {
|
|
626
|
+
if (check.version !== "v6") {
|
|
627
|
+
addFormat(res, "ipv4", check.message, refs);
|
|
628
|
+
}
|
|
629
|
+
if (check.version !== "v4") {
|
|
630
|
+
addFormat(res, "ipv6", check.message, refs);
|
|
631
|
+
}
|
|
632
|
+
break;
|
|
633
|
+
}
|
|
634
|
+
case "base64url":
|
|
635
|
+
addPattern(res, zodPatterns.base64url, check.message, refs);
|
|
636
|
+
break;
|
|
637
|
+
case "jwt":
|
|
638
|
+
addPattern(res, zodPatterns.jwt, check.message, refs);
|
|
639
|
+
break;
|
|
640
|
+
case "cidr": {
|
|
641
|
+
if (check.version !== "v6") {
|
|
642
|
+
addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
|
|
643
|
+
}
|
|
644
|
+
if (check.version !== "v4") {
|
|
645
|
+
addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
|
|
646
|
+
}
|
|
647
|
+
break;
|
|
648
|
+
}
|
|
649
|
+
case "emoji":
|
|
650
|
+
addPattern(res, zodPatterns.emoji(), check.message, refs);
|
|
651
|
+
break;
|
|
652
|
+
case "ulid": {
|
|
653
|
+
addPattern(res, zodPatterns.ulid, check.message, refs);
|
|
654
|
+
break;
|
|
655
|
+
}
|
|
656
|
+
case "base64": {
|
|
657
|
+
switch (refs.base64Strategy) {
|
|
658
|
+
case "format:binary": {
|
|
659
|
+
addFormat(res, "binary", check.message, refs);
|
|
660
|
+
break;
|
|
661
|
+
}
|
|
662
|
+
case "contentEncoding:base64": {
|
|
663
|
+
res.contentEncoding = "base64";
|
|
664
|
+
break;
|
|
665
|
+
}
|
|
666
|
+
case "pattern:zod": {
|
|
667
|
+
addPattern(res, zodPatterns.base64, check.message, refs);
|
|
668
|
+
break;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
break;
|
|
672
|
+
}
|
|
673
|
+
case "nanoid": {
|
|
674
|
+
addPattern(res, zodPatterns.nanoid, check.message, refs);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
return res;
|
|
680
|
+
}
|
|
681
|
+
function escapeLiteralCheckValue(literal, refs) {
|
|
682
|
+
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
|
|
683
|
+
}
|
|
684
|
+
var ALPHA_NUMERIC = new Set(
|
|
685
|
+
"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
|
|
686
|
+
);
|
|
687
|
+
function escapeNonAlphaNumeric(source) {
|
|
688
|
+
let result = "";
|
|
689
|
+
for (let i = 0; i < source.length; i++) {
|
|
690
|
+
if (!ALPHA_NUMERIC.has(source[i])) {
|
|
691
|
+
result += "\\";
|
|
692
|
+
}
|
|
693
|
+
result += source[i];
|
|
694
|
+
}
|
|
695
|
+
return result;
|
|
696
|
+
}
|
|
697
|
+
function addFormat(schema, value, message, refs) {
|
|
698
|
+
var _a17;
|
|
699
|
+
if (schema.format || ((_a17 = schema.anyOf) == null ? void 0 : _a17.some((x) => x.format))) {
|
|
700
|
+
if (!schema.anyOf) {
|
|
701
|
+
schema.anyOf = [];
|
|
702
|
+
}
|
|
703
|
+
if (schema.format) {
|
|
704
|
+
schema.anyOf.push({
|
|
705
|
+
format: schema.format
|
|
706
|
+
});
|
|
707
|
+
delete schema.format;
|
|
708
|
+
}
|
|
709
|
+
schema.anyOf.push({
|
|
710
|
+
format: value,
|
|
711
|
+
...message && refs.errorMessages && { errorMessage: { format: message } }
|
|
712
|
+
});
|
|
713
|
+
} else {
|
|
714
|
+
schema.format = value;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
function addPattern(schema, regex, message, refs) {
|
|
718
|
+
var _a17;
|
|
719
|
+
if (schema.pattern || ((_a17 = schema.allOf) == null ? void 0 : _a17.some((x) => x.pattern))) {
|
|
720
|
+
if (!schema.allOf) {
|
|
721
|
+
schema.allOf = [];
|
|
722
|
+
}
|
|
723
|
+
if (schema.pattern) {
|
|
724
|
+
schema.allOf.push({
|
|
725
|
+
pattern: schema.pattern
|
|
726
|
+
});
|
|
727
|
+
delete schema.pattern;
|
|
728
|
+
}
|
|
729
|
+
schema.allOf.push({
|
|
730
|
+
pattern: stringifyRegExpWithFlags(regex, refs),
|
|
731
|
+
...message && refs.errorMessages && { errorMessage: { pattern: message } }
|
|
732
|
+
});
|
|
733
|
+
} else {
|
|
734
|
+
schema.pattern = stringifyRegExpWithFlags(regex, refs);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
function stringifyRegExpWithFlags(regex, refs) {
|
|
738
|
+
var _a17;
|
|
739
|
+
if (!refs.applyRegexFlags || !regex.flags) {
|
|
740
|
+
return regex.source;
|
|
741
|
+
}
|
|
742
|
+
const flags = {
|
|
743
|
+
i: regex.flags.includes("i"),
|
|
744
|
+
// Case-insensitive
|
|
745
|
+
m: regex.flags.includes("m"),
|
|
746
|
+
// `^` and `$` matches adjacent to newline characters
|
|
747
|
+
s: regex.flags.includes("s")
|
|
748
|
+
// `.` matches newlines
|
|
749
|
+
};
|
|
750
|
+
const source = flags.i ? regex.source.toLowerCase() : regex.source;
|
|
751
|
+
let pattern = "";
|
|
752
|
+
let isEscaped = false;
|
|
753
|
+
let inCharGroup = false;
|
|
754
|
+
let inCharRange = false;
|
|
755
|
+
for (let i = 0; i < source.length; i++) {
|
|
756
|
+
if (isEscaped) {
|
|
757
|
+
pattern += source[i];
|
|
758
|
+
isEscaped = false;
|
|
759
|
+
continue;
|
|
760
|
+
}
|
|
761
|
+
if (flags.i) {
|
|
762
|
+
if (inCharGroup) {
|
|
763
|
+
if (source[i].match(/[a-z]/)) {
|
|
764
|
+
if (inCharRange) {
|
|
765
|
+
pattern += source[i];
|
|
766
|
+
pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
|
|
767
|
+
inCharRange = false;
|
|
768
|
+
} else if (source[i + 1] === "-" && ((_a17 = source[i + 2]) == null ? void 0 : _a17.match(/[a-z]/))) {
|
|
769
|
+
pattern += source[i];
|
|
770
|
+
inCharRange = true;
|
|
771
|
+
} else {
|
|
772
|
+
pattern += `${source[i]}${source[i].toUpperCase()}`;
|
|
773
|
+
}
|
|
774
|
+
continue;
|
|
775
|
+
}
|
|
776
|
+
} else if (source[i].match(/[a-z]/)) {
|
|
777
|
+
pattern += `[${source[i]}${source[i].toUpperCase()}]`;
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
if (flags.m) {
|
|
782
|
+
if (source[i] === "^") {
|
|
783
|
+
pattern += `(^|(?<=[\r
|
|
784
|
+
]))`;
|
|
785
|
+
continue;
|
|
786
|
+
} else if (source[i] === "$") {
|
|
787
|
+
pattern += `($|(?=[\r
|
|
788
|
+
]))`;
|
|
789
|
+
continue;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
if (flags.s && source[i] === ".") {
|
|
793
|
+
pattern += inCharGroup ? `${source[i]}\r
|
|
794
|
+
` : `[${source[i]}\r
|
|
795
|
+
]`;
|
|
796
|
+
continue;
|
|
797
|
+
}
|
|
798
|
+
pattern += source[i];
|
|
799
|
+
if (source[i] === "\\") {
|
|
800
|
+
isEscaped = true;
|
|
801
|
+
} else if (inCharGroup && source[i] === "]") {
|
|
802
|
+
inCharGroup = false;
|
|
803
|
+
} else if (!inCharGroup && source[i] === "[") {
|
|
804
|
+
inCharGroup = true;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
return pattern;
|
|
808
|
+
}
|
|
809
|
+
function parseRecordDef(def, refs) {
|
|
810
|
+
var _a17, _b, _c, _d, _e, _f;
|
|
811
|
+
const schema = {
|
|
812
|
+
type: "object",
|
|
813
|
+
additionalProperties: (_a17 = parseDef(def.valueType._def, {
|
|
814
|
+
...refs,
|
|
815
|
+
currentPath: [...refs.currentPath, "additionalProperties"]
|
|
816
|
+
})) != null ? _a17 : refs.allowedAdditionalProperties
|
|
817
|
+
};
|
|
818
|
+
if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
|
|
819
|
+
const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
|
|
820
|
+
return {
|
|
821
|
+
...schema,
|
|
822
|
+
propertyNames: keyType
|
|
823
|
+
};
|
|
824
|
+
} else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) {
|
|
825
|
+
return {
|
|
826
|
+
...schema,
|
|
827
|
+
propertyNames: {
|
|
828
|
+
enum: def.keyType._def.values
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
} else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
|
|
832
|
+
const { type, ...keyType } = parseBrandedDef(
|
|
833
|
+
def.keyType._def,
|
|
834
|
+
refs
|
|
835
|
+
);
|
|
836
|
+
return {
|
|
837
|
+
...schema,
|
|
838
|
+
propertyNames: keyType
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
return schema;
|
|
842
|
+
}
|
|
843
|
+
function parseMapDef(def, refs) {
|
|
844
|
+
if (refs.mapStrategy === "record") {
|
|
845
|
+
return parseRecordDef(def, refs);
|
|
846
|
+
}
|
|
847
|
+
const keys = parseDef(def.keyType._def, {
|
|
848
|
+
...refs,
|
|
849
|
+
currentPath: [...refs.currentPath, "items", "items", "0"]
|
|
850
|
+
}) || parseAnyDef();
|
|
851
|
+
const values = parseDef(def.valueType._def, {
|
|
852
|
+
...refs,
|
|
853
|
+
currentPath: [...refs.currentPath, "items", "items", "1"]
|
|
854
|
+
}) || parseAnyDef();
|
|
855
|
+
return {
|
|
856
|
+
type: "array",
|
|
857
|
+
maxItems: 125,
|
|
858
|
+
items: {
|
|
859
|
+
type: "array",
|
|
860
|
+
items: [keys, values],
|
|
861
|
+
minItems: 2,
|
|
862
|
+
maxItems: 2
|
|
863
|
+
}
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
function parseNativeEnumDef(def) {
|
|
867
|
+
const object2 = def.values;
|
|
868
|
+
const actualKeys = Object.keys(def.values).filter((key) => {
|
|
869
|
+
return typeof object2[object2[key]] !== "number";
|
|
870
|
+
});
|
|
871
|
+
const actualValues = actualKeys.map((key) => object2[key]);
|
|
872
|
+
const parsedTypes = Array.from(
|
|
873
|
+
new Set(actualValues.map((values) => typeof values))
|
|
874
|
+
);
|
|
875
|
+
return {
|
|
876
|
+
type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
|
|
877
|
+
enum: actualValues
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
function parseNeverDef() {
|
|
881
|
+
return { not: parseAnyDef() };
|
|
882
|
+
}
|
|
883
|
+
function parseNullDef() {
|
|
884
|
+
return {
|
|
885
|
+
type: "null"
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
var primitiveMappings = {
|
|
889
|
+
ZodString: "string",
|
|
890
|
+
ZodNumber: "number",
|
|
891
|
+
ZodBigInt: "integer",
|
|
892
|
+
ZodBoolean: "boolean",
|
|
893
|
+
ZodNull: "null"
|
|
894
|
+
};
|
|
895
|
+
function parseUnionDef(def, refs) {
|
|
896
|
+
const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
|
|
897
|
+
if (options.every(
|
|
898
|
+
(x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
|
|
899
|
+
)) {
|
|
900
|
+
const types = options.reduce((types2, x) => {
|
|
901
|
+
const type = primitiveMappings[x._def.typeName];
|
|
902
|
+
return type && !types2.includes(type) ? [...types2, type] : types2;
|
|
903
|
+
}, []);
|
|
904
|
+
return {
|
|
905
|
+
type: types.length > 1 ? types : types[0]
|
|
906
|
+
};
|
|
907
|
+
} else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
|
|
908
|
+
const types = options.reduce(
|
|
909
|
+
(acc, x) => {
|
|
910
|
+
const type = typeof x._def.value;
|
|
911
|
+
switch (type) {
|
|
912
|
+
case "string":
|
|
913
|
+
case "number":
|
|
914
|
+
case "boolean":
|
|
915
|
+
return [...acc, type];
|
|
916
|
+
case "bigint":
|
|
917
|
+
return [...acc, "integer"];
|
|
918
|
+
case "object":
|
|
919
|
+
if (x._def.value === null) return [...acc, "null"];
|
|
920
|
+
case "symbol":
|
|
921
|
+
case "undefined":
|
|
922
|
+
case "function":
|
|
923
|
+
default:
|
|
924
|
+
return acc;
|
|
925
|
+
}
|
|
926
|
+
},
|
|
927
|
+
[]
|
|
928
|
+
);
|
|
929
|
+
if (types.length === options.length) {
|
|
930
|
+
const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
|
|
931
|
+
return {
|
|
932
|
+
type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
|
|
933
|
+
enum: options.reduce(
|
|
934
|
+
(acc, x) => {
|
|
935
|
+
return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
|
|
936
|
+
},
|
|
937
|
+
[]
|
|
938
|
+
)
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
} else if (options.every((x) => x._def.typeName === "ZodEnum")) {
|
|
942
|
+
return {
|
|
943
|
+
type: "string",
|
|
944
|
+
enum: options.reduce(
|
|
945
|
+
(acc, x) => [
|
|
946
|
+
...acc,
|
|
947
|
+
...x._def.values.filter((x2) => !acc.includes(x2))
|
|
948
|
+
],
|
|
949
|
+
[]
|
|
950
|
+
)
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
return asAnyOf(def, refs);
|
|
954
|
+
}
|
|
955
|
+
var asAnyOf = (def, refs) => {
|
|
956
|
+
const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
|
|
957
|
+
(x, i) => parseDef(x._def, {
|
|
958
|
+
...refs,
|
|
959
|
+
currentPath: [...refs.currentPath, "anyOf", `${i}`]
|
|
960
|
+
})
|
|
961
|
+
).filter(
|
|
962
|
+
(x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
|
|
963
|
+
);
|
|
964
|
+
return anyOf.length ? { anyOf } : void 0;
|
|
965
|
+
};
|
|
966
|
+
function parseNullableDef(def, refs) {
|
|
967
|
+
if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
|
|
968
|
+
def.innerType._def.typeName
|
|
969
|
+
) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
|
|
970
|
+
return {
|
|
971
|
+
type: [
|
|
972
|
+
primitiveMappings[def.innerType._def.typeName],
|
|
973
|
+
"null"
|
|
974
|
+
]
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
const base = parseDef(def.innerType._def, {
|
|
978
|
+
...refs,
|
|
979
|
+
currentPath: [...refs.currentPath, "anyOf", "0"]
|
|
980
|
+
});
|
|
981
|
+
return base && { anyOf: [base, { type: "null" }] };
|
|
982
|
+
}
|
|
983
|
+
function parseNumberDef(def) {
|
|
984
|
+
const res = {
|
|
985
|
+
type: "number"
|
|
986
|
+
};
|
|
987
|
+
if (!def.checks) return res;
|
|
988
|
+
for (const check of def.checks) {
|
|
989
|
+
switch (check.kind) {
|
|
990
|
+
case "int":
|
|
991
|
+
res.type = "integer";
|
|
992
|
+
break;
|
|
993
|
+
case "min":
|
|
994
|
+
if (check.inclusive) {
|
|
995
|
+
res.minimum = check.value;
|
|
996
|
+
} else {
|
|
997
|
+
res.exclusiveMinimum = check.value;
|
|
998
|
+
}
|
|
999
|
+
break;
|
|
1000
|
+
case "max":
|
|
1001
|
+
if (check.inclusive) {
|
|
1002
|
+
res.maximum = check.value;
|
|
1003
|
+
} else {
|
|
1004
|
+
res.exclusiveMaximum = check.value;
|
|
1005
|
+
}
|
|
1006
|
+
break;
|
|
1007
|
+
case "multipleOf":
|
|
1008
|
+
res.multipleOf = check.value;
|
|
1009
|
+
break;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
return res;
|
|
1013
|
+
}
|
|
1014
|
+
function parseObjectDef(def, refs) {
|
|
1015
|
+
const result = {
|
|
1016
|
+
type: "object",
|
|
1017
|
+
properties: {}
|
|
1018
|
+
};
|
|
1019
|
+
const required = [];
|
|
1020
|
+
const shape = def.shape();
|
|
1021
|
+
for (const propName in shape) {
|
|
1022
|
+
let propDef = shape[propName];
|
|
1023
|
+
if (propDef === void 0 || propDef._def === void 0) {
|
|
1024
|
+
continue;
|
|
1025
|
+
}
|
|
1026
|
+
const propOptional = safeIsOptional(propDef);
|
|
1027
|
+
const parsedDef = parseDef(propDef._def, {
|
|
1028
|
+
...refs,
|
|
1029
|
+
currentPath: [...refs.currentPath, "properties", propName],
|
|
1030
|
+
propertyPath: [...refs.currentPath, "properties", propName]
|
|
1031
|
+
});
|
|
1032
|
+
if (parsedDef === void 0) {
|
|
1033
|
+
continue;
|
|
1034
|
+
}
|
|
1035
|
+
result.properties[propName] = parsedDef;
|
|
1036
|
+
if (!propOptional) {
|
|
1037
|
+
required.push(propName);
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
if (required.length) {
|
|
1041
|
+
result.required = required;
|
|
1042
|
+
}
|
|
1043
|
+
const additionalProperties = decideAdditionalProperties(def, refs);
|
|
1044
|
+
if (additionalProperties !== void 0) {
|
|
1045
|
+
result.additionalProperties = additionalProperties;
|
|
1046
|
+
}
|
|
1047
|
+
return result;
|
|
1048
|
+
}
|
|
1049
|
+
function decideAdditionalProperties(def, refs) {
|
|
1050
|
+
if (def.catchall._def.typeName !== "ZodNever") {
|
|
1051
|
+
return parseDef(def.catchall._def, {
|
|
1052
|
+
...refs,
|
|
1053
|
+
currentPath: [...refs.currentPath, "additionalProperties"]
|
|
1054
|
+
});
|
|
1055
|
+
}
|
|
1056
|
+
switch (def.unknownKeys) {
|
|
1057
|
+
case "passthrough":
|
|
1058
|
+
return refs.allowedAdditionalProperties;
|
|
1059
|
+
case "strict":
|
|
1060
|
+
return refs.rejectedAdditionalProperties;
|
|
1061
|
+
case "strip":
|
|
1062
|
+
return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
function safeIsOptional(schema) {
|
|
1066
|
+
try {
|
|
1067
|
+
return schema.isOptional();
|
|
1068
|
+
} catch (e) {
|
|
1069
|
+
return true;
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
var parseOptionalDef = (def, refs) => {
|
|
1073
|
+
var _a17;
|
|
1074
|
+
if (refs.currentPath.toString() === ((_a17 = refs.propertyPath) == null ? void 0 : _a17.toString())) {
|
|
1075
|
+
return parseDef(def.innerType._def, refs);
|
|
1076
|
+
}
|
|
1077
|
+
const innerSchema = parseDef(def.innerType._def, {
|
|
1078
|
+
...refs,
|
|
1079
|
+
currentPath: [...refs.currentPath, "anyOf", "1"]
|
|
1080
|
+
});
|
|
1081
|
+
return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
|
|
1082
|
+
};
|
|
1083
|
+
var parsePipelineDef = (def, refs) => {
|
|
1084
|
+
if (refs.pipeStrategy === "input") {
|
|
1085
|
+
return parseDef(def.in._def, refs);
|
|
1086
|
+
} else if (refs.pipeStrategy === "output") {
|
|
1087
|
+
return parseDef(def.out._def, refs);
|
|
1088
|
+
}
|
|
1089
|
+
const a = parseDef(def.in._def, {
|
|
1090
|
+
...refs,
|
|
1091
|
+
currentPath: [...refs.currentPath, "allOf", "0"]
|
|
1092
|
+
});
|
|
1093
|
+
const b = parseDef(def.out._def, {
|
|
1094
|
+
...refs,
|
|
1095
|
+
currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
|
|
1096
|
+
});
|
|
1097
|
+
return {
|
|
1098
|
+
allOf: [a, b].filter((x) => x !== void 0)
|
|
1099
|
+
};
|
|
1100
|
+
};
|
|
1101
|
+
function parsePromiseDef(def, refs) {
|
|
1102
|
+
return parseDef(def.type._def, refs);
|
|
1103
|
+
}
|
|
1104
|
+
function parseSetDef(def, refs) {
|
|
1105
|
+
const items = parseDef(def.valueType._def, {
|
|
1106
|
+
...refs,
|
|
1107
|
+
currentPath: [...refs.currentPath, "items"]
|
|
1108
|
+
});
|
|
1109
|
+
const schema = {
|
|
1110
|
+
type: "array",
|
|
1111
|
+
uniqueItems: true,
|
|
1112
|
+
items
|
|
1113
|
+
};
|
|
1114
|
+
if (def.minSize) {
|
|
1115
|
+
schema.minItems = def.minSize.value;
|
|
1116
|
+
}
|
|
1117
|
+
if (def.maxSize) {
|
|
1118
|
+
schema.maxItems = def.maxSize.value;
|
|
1119
|
+
}
|
|
1120
|
+
return schema;
|
|
1121
|
+
}
|
|
1122
|
+
function parseTupleDef(def, refs) {
|
|
1123
|
+
if (def.rest) {
|
|
1124
|
+
return {
|
|
1125
|
+
type: "array",
|
|
1126
|
+
minItems: def.items.length,
|
|
1127
|
+
items: def.items.map(
|
|
1128
|
+
(x, i) => parseDef(x._def, {
|
|
1129
|
+
...refs,
|
|
1130
|
+
currentPath: [...refs.currentPath, "items", `${i}`]
|
|
1131
|
+
})
|
|
1132
|
+
).reduce(
|
|
1133
|
+
(acc, x) => x === void 0 ? acc : [...acc, x],
|
|
1134
|
+
[]
|
|
1135
|
+
),
|
|
1136
|
+
additionalItems: parseDef(def.rest._def, {
|
|
1137
|
+
...refs,
|
|
1138
|
+
currentPath: [...refs.currentPath, "additionalItems"]
|
|
1139
|
+
})
|
|
1140
|
+
};
|
|
1141
|
+
} else {
|
|
1142
|
+
return {
|
|
1143
|
+
type: "array",
|
|
1144
|
+
minItems: def.items.length,
|
|
1145
|
+
maxItems: def.items.length,
|
|
1146
|
+
items: def.items.map(
|
|
1147
|
+
(x, i) => parseDef(x._def, {
|
|
1148
|
+
...refs,
|
|
1149
|
+
currentPath: [...refs.currentPath, "items", `${i}`]
|
|
1150
|
+
})
|
|
1151
|
+
).reduce(
|
|
1152
|
+
(acc, x) => x === void 0 ? acc : [...acc, x],
|
|
1153
|
+
[]
|
|
1154
|
+
)
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
function parseUndefinedDef() {
|
|
1159
|
+
return {
|
|
1160
|
+
not: parseAnyDef()
|
|
1161
|
+
};
|
|
1162
|
+
}
|
|
1163
|
+
function parseUnknownDef() {
|
|
1164
|
+
return parseAnyDef();
|
|
1165
|
+
}
|
|
1166
|
+
var parseReadonlyDef = (def, refs) => {
|
|
1167
|
+
return parseDef(def.innerType._def, refs);
|
|
1168
|
+
};
|
|
1169
|
+
var selectParser = (def, typeName, refs) => {
|
|
1170
|
+
switch (typeName) {
|
|
1171
|
+
case ZodFirstPartyTypeKind.ZodString:
|
|
1172
|
+
return parseStringDef(def, refs);
|
|
1173
|
+
case ZodFirstPartyTypeKind.ZodNumber:
|
|
1174
|
+
return parseNumberDef(def);
|
|
1175
|
+
case ZodFirstPartyTypeKind.ZodObject:
|
|
1176
|
+
return parseObjectDef(def, refs);
|
|
1177
|
+
case ZodFirstPartyTypeKind.ZodBigInt:
|
|
1178
|
+
return parseBigintDef(def);
|
|
1179
|
+
case ZodFirstPartyTypeKind.ZodBoolean:
|
|
1180
|
+
return parseBooleanDef();
|
|
1181
|
+
case ZodFirstPartyTypeKind.ZodDate:
|
|
1182
|
+
return parseDateDef(def, refs);
|
|
1183
|
+
case ZodFirstPartyTypeKind.ZodUndefined:
|
|
1184
|
+
return parseUndefinedDef();
|
|
1185
|
+
case ZodFirstPartyTypeKind.ZodNull:
|
|
1186
|
+
return parseNullDef();
|
|
1187
|
+
case ZodFirstPartyTypeKind.ZodArray:
|
|
1188
|
+
return parseArrayDef(def, refs);
|
|
1189
|
+
case ZodFirstPartyTypeKind.ZodUnion:
|
|
1190
|
+
case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
|
|
1191
|
+
return parseUnionDef(def, refs);
|
|
1192
|
+
case ZodFirstPartyTypeKind.ZodIntersection:
|
|
1193
|
+
return parseIntersectionDef(def, refs);
|
|
1194
|
+
case ZodFirstPartyTypeKind.ZodTuple:
|
|
1195
|
+
return parseTupleDef(def, refs);
|
|
1196
|
+
case ZodFirstPartyTypeKind.ZodRecord:
|
|
1197
|
+
return parseRecordDef(def, refs);
|
|
1198
|
+
case ZodFirstPartyTypeKind.ZodLiteral:
|
|
1199
|
+
return parseLiteralDef(def);
|
|
1200
|
+
case ZodFirstPartyTypeKind.ZodEnum:
|
|
1201
|
+
return parseEnumDef(def);
|
|
1202
|
+
case ZodFirstPartyTypeKind.ZodNativeEnum:
|
|
1203
|
+
return parseNativeEnumDef(def);
|
|
1204
|
+
case ZodFirstPartyTypeKind.ZodNullable:
|
|
1205
|
+
return parseNullableDef(def, refs);
|
|
1206
|
+
case ZodFirstPartyTypeKind.ZodOptional:
|
|
1207
|
+
return parseOptionalDef(def, refs);
|
|
1208
|
+
case ZodFirstPartyTypeKind.ZodMap:
|
|
1209
|
+
return parseMapDef(def, refs);
|
|
1210
|
+
case ZodFirstPartyTypeKind.ZodSet:
|
|
1211
|
+
return parseSetDef(def, refs);
|
|
1212
|
+
case ZodFirstPartyTypeKind.ZodLazy:
|
|
1213
|
+
return () => def.getter()._def;
|
|
1214
|
+
case ZodFirstPartyTypeKind.ZodPromise:
|
|
1215
|
+
return parsePromiseDef(def, refs);
|
|
1216
|
+
case ZodFirstPartyTypeKind.ZodNaN:
|
|
1217
|
+
case ZodFirstPartyTypeKind.ZodNever:
|
|
1218
|
+
return parseNeverDef();
|
|
1219
|
+
case ZodFirstPartyTypeKind.ZodEffects:
|
|
1220
|
+
return parseEffectsDef(def, refs);
|
|
1221
|
+
case ZodFirstPartyTypeKind.ZodAny:
|
|
1222
|
+
return parseAnyDef();
|
|
1223
|
+
case ZodFirstPartyTypeKind.ZodUnknown:
|
|
1224
|
+
return parseUnknownDef();
|
|
1225
|
+
case ZodFirstPartyTypeKind.ZodDefault:
|
|
1226
|
+
return parseDefaultDef(def, refs);
|
|
1227
|
+
case ZodFirstPartyTypeKind.ZodBranded:
|
|
1228
|
+
return parseBrandedDef(def, refs);
|
|
1229
|
+
case ZodFirstPartyTypeKind.ZodReadonly:
|
|
1230
|
+
return parseReadonlyDef(def, refs);
|
|
1231
|
+
case ZodFirstPartyTypeKind.ZodCatch:
|
|
1232
|
+
return parseCatchDef(def, refs);
|
|
1233
|
+
case ZodFirstPartyTypeKind.ZodPipeline:
|
|
1234
|
+
return parsePipelineDef(def, refs);
|
|
1235
|
+
case ZodFirstPartyTypeKind.ZodFunction:
|
|
1236
|
+
case ZodFirstPartyTypeKind.ZodVoid:
|
|
1237
|
+
case ZodFirstPartyTypeKind.ZodSymbol:
|
|
1238
|
+
return void 0;
|
|
1239
|
+
default:
|
|
1240
|
+
return /* @__PURE__ */ ((_) => void 0)();
|
|
1241
|
+
}
|
|
1242
|
+
};
|
|
1243
|
+
function parseDef(def, refs, forceResolution = false) {
|
|
1244
|
+
var _a17;
|
|
1245
|
+
const seenItem = refs.seen.get(def);
|
|
1246
|
+
if (refs.override) {
|
|
1247
|
+
const overrideResult = (_a17 = refs.override) == null ? void 0 : _a17.call(
|
|
1248
|
+
refs,
|
|
1249
|
+
def,
|
|
1250
|
+
refs,
|
|
1251
|
+
seenItem,
|
|
1252
|
+
forceResolution
|
|
1253
|
+
);
|
|
1254
|
+
if (overrideResult !== ignoreOverride) {
|
|
1255
|
+
return overrideResult;
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
if (seenItem && !forceResolution) {
|
|
1259
|
+
const seenSchema = get$ref(seenItem, refs);
|
|
1260
|
+
if (seenSchema !== void 0) {
|
|
1261
|
+
return seenSchema;
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
|
|
1265
|
+
refs.seen.set(def, newItem);
|
|
1266
|
+
const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
|
|
1267
|
+
const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
|
|
1268
|
+
if (jsonSchema2) {
|
|
1269
|
+
addMeta(def, refs, jsonSchema2);
|
|
1270
|
+
}
|
|
1271
|
+
if (refs.postProcess) {
|
|
1272
|
+
const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
|
|
1273
|
+
newItem.jsonSchema = jsonSchema2;
|
|
1274
|
+
return postProcessResult;
|
|
1275
|
+
}
|
|
1276
|
+
newItem.jsonSchema = jsonSchema2;
|
|
1277
|
+
return jsonSchema2;
|
|
1278
|
+
}
|
|
1279
|
+
var get$ref = (item, refs) => {
|
|
1280
|
+
switch (refs.$refStrategy) {
|
|
1281
|
+
case "root":
|
|
1282
|
+
return { $ref: item.path.join("/") };
|
|
1283
|
+
case "relative":
|
|
1284
|
+
return { $ref: getRelativePath(refs.currentPath, item.path) };
|
|
1285
|
+
case "none":
|
|
1286
|
+
case "seen": {
|
|
1287
|
+
if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
|
|
1288
|
+
console.warn(
|
|
1289
|
+
`Recursive reference detected at ${refs.currentPath.join(
|
|
1290
|
+
"/"
|
|
1291
|
+
)}! Defaulting to any`
|
|
1292
|
+
);
|
|
1293
|
+
return parseAnyDef();
|
|
1294
|
+
}
|
|
1295
|
+
return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
};
|
|
1299
|
+
var addMeta = (def, refs, jsonSchema2) => {
|
|
1300
|
+
if (def.description) {
|
|
1301
|
+
jsonSchema2.description = def.description;
|
|
1302
|
+
}
|
|
1303
|
+
return jsonSchema2;
|
|
1304
|
+
};
|
|
1305
|
+
var getRefs = (options) => {
|
|
1306
|
+
const _options = getDefaultOptions(options);
|
|
1307
|
+
const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
|
|
1308
|
+
return {
|
|
1309
|
+
..._options,
|
|
1310
|
+
currentPath,
|
|
1311
|
+
propertyPath: void 0,
|
|
1312
|
+
seen: new Map(
|
|
1313
|
+
Object.entries(_options.definitions).map(([name17, def]) => [
|
|
1314
|
+
def._def,
|
|
1315
|
+
{
|
|
1316
|
+
def: def._def,
|
|
1317
|
+
path: [..._options.basePath, _options.definitionPath, name17],
|
|
1318
|
+
// Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
|
|
1319
|
+
jsonSchema: void 0
|
|
1320
|
+
}
|
|
1321
|
+
])
|
|
1322
|
+
)
|
|
1323
|
+
};
|
|
1324
|
+
};
|
|
1325
|
+
var zodToJsonSchema = (schema, options) => {
|
|
1326
|
+
var _a17;
|
|
1327
|
+
const refs = getRefs(options);
|
|
1328
|
+
let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
|
|
1329
|
+
(acc, [name23, schema2]) => {
|
|
1330
|
+
var _a23;
|
|
1331
|
+
return {
|
|
1332
|
+
...acc,
|
|
1333
|
+
[name23]: (_a23 = parseDef(
|
|
1334
|
+
schema2._def,
|
|
1335
|
+
{
|
|
1336
|
+
...refs,
|
|
1337
|
+
currentPath: [...refs.basePath, refs.definitionPath, name23]
|
|
1338
|
+
},
|
|
1339
|
+
true
|
|
1340
|
+
)) != null ? _a23 : parseAnyDef()
|
|
1341
|
+
};
|
|
1342
|
+
},
|
|
1343
|
+
{}
|
|
1344
|
+
) : void 0;
|
|
1345
|
+
const name17 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
|
|
1346
|
+
const main = (_a17 = parseDef(
|
|
1347
|
+
schema._def,
|
|
1348
|
+
name17 === void 0 ? refs : {
|
|
1349
|
+
...refs,
|
|
1350
|
+
currentPath: [...refs.basePath, refs.definitionPath, name17]
|
|
1351
|
+
},
|
|
1352
|
+
false
|
|
1353
|
+
)) != null ? _a17 : parseAnyDef();
|
|
1354
|
+
const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
|
|
1355
|
+
if (title !== void 0) {
|
|
1356
|
+
main.title = title;
|
|
1357
|
+
}
|
|
1358
|
+
const combined = name17 === void 0 ? definitions ? {
|
|
1359
|
+
...main,
|
|
1360
|
+
[refs.definitionPath]: definitions
|
|
1361
|
+
} : main : {
|
|
1362
|
+
$ref: [
|
|
1363
|
+
...refs.$refStrategy === "relative" ? [] : refs.basePath,
|
|
1364
|
+
refs.definitionPath,
|
|
1365
|
+
name17
|
|
1366
|
+
].join("/"),
|
|
1367
|
+
[refs.definitionPath]: {
|
|
1368
|
+
...definitions,
|
|
1369
|
+
[name17]: main
|
|
1370
|
+
}
|
|
1371
|
+
};
|
|
1372
|
+
combined.$schema = "http://json-schema.org/draft-07/schema#";
|
|
1373
|
+
return combined;
|
|
1374
|
+
};
|
|
1375
|
+
var zod_to_json_schema_default = zodToJsonSchema;
|
|
1376
|
+
function zod3Schema(zodSchema2, options) {
|
|
1377
|
+
var _a17;
|
|
1378
|
+
const useReferences = (_a17 = void 0 ) != null ? _a17 : false;
|
|
1379
|
+
return jsonSchema(
|
|
1380
|
+
// defer json schema creation to avoid unnecessary computation when only validation is needed
|
|
1381
|
+
() => zod_to_json_schema_default(zodSchema2, {
|
|
1382
|
+
$refStrategy: useReferences ? "root" : "none"
|
|
1383
|
+
}),
|
|
1384
|
+
{
|
|
1385
|
+
validate: async (value) => {
|
|
1386
|
+
const result = await zodSchema2.safeParseAsync(value);
|
|
1387
|
+
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
);
|
|
1391
|
+
}
|
|
1392
|
+
function zod4Schema(zodSchema2, options) {
|
|
1393
|
+
var _a17;
|
|
1394
|
+
const useReferences = (_a17 = void 0 ) != null ? _a17 : false;
|
|
1395
|
+
return jsonSchema(
|
|
1396
|
+
// defer json schema creation to avoid unnecessary computation when only validation is needed
|
|
1397
|
+
() => z4.toJSONSchema(zodSchema2, {
|
|
1398
|
+
target: "draft-7",
|
|
1399
|
+
io: "output",
|
|
1400
|
+
reused: useReferences ? "ref" : "inline"
|
|
1401
|
+
}),
|
|
1402
|
+
{
|
|
1403
|
+
validate: async (value) => {
|
|
1404
|
+
const result = await z4.safeParseAsync(zodSchema2, value);
|
|
1405
|
+
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
);
|
|
1409
|
+
}
|
|
1410
|
+
function isZod4Schema(zodSchema2) {
|
|
1411
|
+
return "_zod" in zodSchema2;
|
|
1412
|
+
}
|
|
1413
|
+
function zodSchema(zodSchema2, options) {
|
|
1414
|
+
if (isZod4Schema(zodSchema2)) {
|
|
1415
|
+
return zod4Schema(zodSchema2);
|
|
1416
|
+
} else {
|
|
1417
|
+
return zod3Schema(zodSchema2);
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
var schemaSymbol = Symbol.for("vercel.ai.schema");
|
|
1421
|
+
function jsonSchema(jsonSchema2, {
|
|
1422
|
+
validate
|
|
1423
|
+
} = {}) {
|
|
1424
|
+
return {
|
|
1425
|
+
[schemaSymbol]: true,
|
|
1426
|
+
_type: void 0,
|
|
1427
|
+
// should never be used directly
|
|
1428
|
+
[validatorSymbol]: true,
|
|
1429
|
+
get jsonSchema() {
|
|
1430
|
+
if (typeof jsonSchema2 === "function") {
|
|
1431
|
+
jsonSchema2 = jsonSchema2();
|
|
1432
|
+
}
|
|
1433
|
+
return jsonSchema2;
|
|
1434
|
+
},
|
|
1435
|
+
validate
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
function isSchema(value) {
|
|
1439
|
+
return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
|
|
1440
|
+
}
|
|
1441
|
+
function asSchema(schema) {
|
|
1442
|
+
return schema == null ? jsonSchema({
|
|
1443
|
+
properties: {},
|
|
1444
|
+
additionalProperties: false
|
|
1445
|
+
}) : isSchema(schema) ? schema : typeof schema === "function" ? schema() : zodSchema(schema);
|
|
1446
|
+
}
|
|
1447
|
+
var __defProp = Object.defineProperty;
|
|
1448
|
+
var __export = (target, all) => {
|
|
1449
|
+
for (var name17 in all)
|
|
1450
|
+
__defProp(target, name17, { get: all[name17], enumerable: true });
|
|
1451
|
+
};
|
|
1452
|
+
var name72 = "AI_NoObjectGeneratedError";
|
|
1453
|
+
var marker72 = `vercel.ai.error.${name72}`;
|
|
1454
|
+
var symbol72 = Symbol.for(marker72);
|
|
1455
|
+
var _a72;
|
|
1456
|
+
var NoObjectGeneratedError = class extends AISDKError {
|
|
1457
|
+
constructor({
|
|
1458
|
+
message = "No object generated.",
|
|
1459
|
+
cause,
|
|
1460
|
+
text: text2,
|
|
1461
|
+
response,
|
|
1462
|
+
usage,
|
|
1463
|
+
finishReason
|
|
1464
|
+
}) {
|
|
1465
|
+
super({ name: name72, message, cause });
|
|
1466
|
+
this[_a72] = true;
|
|
1467
|
+
this.text = text2;
|
|
1468
|
+
this.response = response;
|
|
1469
|
+
this.usage = usage;
|
|
1470
|
+
this.finishReason = finishReason;
|
|
1471
|
+
}
|
|
1472
|
+
static isInstance(error) {
|
|
1473
|
+
return AISDKError.hasMarker(error, marker72);
|
|
1474
|
+
}
|
|
1475
|
+
};
|
|
1476
|
+
_a72 = symbol72;
|
|
1477
|
+
var dataContentSchema = z.union([
|
|
1478
|
+
z.string(),
|
|
1479
|
+
z.instanceof(Uint8Array),
|
|
1480
|
+
z.instanceof(ArrayBuffer),
|
|
1481
|
+
z.custom(
|
|
1482
|
+
// Buffer might not be available in some environments such as CloudFlare:
|
|
1483
|
+
(value) => {
|
|
1484
|
+
var _a17, _b;
|
|
1485
|
+
return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
|
|
1486
|
+
},
|
|
1487
|
+
{ message: "Must be a Buffer" }
|
|
1488
|
+
)
|
|
1489
|
+
]);
|
|
1490
|
+
var jsonValueSchema = z.lazy(
|
|
1491
|
+
() => z.union([
|
|
1492
|
+
z.null(),
|
|
1493
|
+
z.string(),
|
|
1494
|
+
z.number(),
|
|
1495
|
+
z.boolean(),
|
|
1496
|
+
z.record(z.string(), jsonValueSchema),
|
|
1497
|
+
z.array(jsonValueSchema)
|
|
1498
|
+
])
|
|
1499
|
+
);
|
|
1500
|
+
var providerMetadataSchema = z.record(
|
|
1501
|
+
z.string(),
|
|
1502
|
+
z.record(z.string(), jsonValueSchema)
|
|
1503
|
+
);
|
|
1504
|
+
var textPartSchema = z.object({
|
|
1505
|
+
type: z.literal("text"),
|
|
1506
|
+
text: z.string(),
|
|
1507
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1508
|
+
});
|
|
1509
|
+
var imagePartSchema = z.object({
|
|
1510
|
+
type: z.literal("image"),
|
|
1511
|
+
image: z.union([dataContentSchema, z.instanceof(URL)]),
|
|
1512
|
+
mediaType: z.string().optional(),
|
|
1513
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1514
|
+
});
|
|
1515
|
+
var filePartSchema = z.object({
|
|
1516
|
+
type: z.literal("file"),
|
|
1517
|
+
data: z.union([dataContentSchema, z.instanceof(URL)]),
|
|
1518
|
+
filename: z.string().optional(),
|
|
1519
|
+
mediaType: z.string(),
|
|
1520
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1521
|
+
});
|
|
1522
|
+
var reasoningPartSchema = z.object({
|
|
1523
|
+
type: z.literal("reasoning"),
|
|
1524
|
+
text: z.string(),
|
|
1525
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1526
|
+
});
|
|
1527
|
+
var toolCallPartSchema = z.object({
|
|
1528
|
+
type: z.literal("tool-call"),
|
|
1529
|
+
toolCallId: z.string(),
|
|
1530
|
+
toolName: z.string(),
|
|
1531
|
+
input: z.unknown(),
|
|
1532
|
+
providerOptions: providerMetadataSchema.optional(),
|
|
1533
|
+
providerExecuted: z.boolean().optional()
|
|
1534
|
+
});
|
|
1535
|
+
var outputSchema = z.discriminatedUnion("type", [
|
|
1536
|
+
z.object({
|
|
1537
|
+
type: z.literal("text"),
|
|
1538
|
+
value: z.string()
|
|
1539
|
+
}),
|
|
1540
|
+
z.object({
|
|
1541
|
+
type: z.literal("json"),
|
|
1542
|
+
value: jsonValueSchema
|
|
1543
|
+
}),
|
|
1544
|
+
z.object({
|
|
1545
|
+
type: z.literal("error-text"),
|
|
1546
|
+
value: z.string()
|
|
1547
|
+
}),
|
|
1548
|
+
z.object({
|
|
1549
|
+
type: z.literal("error-json"),
|
|
1550
|
+
value: jsonValueSchema
|
|
1551
|
+
}),
|
|
1552
|
+
z.object({
|
|
1553
|
+
type: z.literal("content"),
|
|
1554
|
+
value: z.array(
|
|
1555
|
+
z.union([
|
|
1556
|
+
z.object({
|
|
1557
|
+
type: z.literal("text"),
|
|
1558
|
+
text: z.string()
|
|
1559
|
+
}),
|
|
1560
|
+
z.object({
|
|
1561
|
+
type: z.literal("media"),
|
|
1562
|
+
data: z.string(),
|
|
1563
|
+
mediaType: z.string()
|
|
1564
|
+
})
|
|
1565
|
+
])
|
|
1566
|
+
)
|
|
1567
|
+
})
|
|
1568
|
+
]);
|
|
1569
|
+
var toolResultPartSchema = z.object({
|
|
1570
|
+
type: z.literal("tool-result"),
|
|
1571
|
+
toolCallId: z.string(),
|
|
1572
|
+
toolName: z.string(),
|
|
1573
|
+
output: outputSchema,
|
|
1574
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1575
|
+
});
|
|
1576
|
+
var systemModelMessageSchema = z.object(
|
|
1577
|
+
{
|
|
1578
|
+
role: z.literal("system"),
|
|
1579
|
+
content: z.string(),
|
|
1580
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1581
|
+
}
|
|
1582
|
+
);
|
|
1583
|
+
var userModelMessageSchema = z.object({
|
|
1584
|
+
role: z.literal("user"),
|
|
1585
|
+
content: z.union([
|
|
1586
|
+
z.string(),
|
|
1587
|
+
z.array(z.union([textPartSchema, imagePartSchema, filePartSchema]))
|
|
1588
|
+
]),
|
|
1589
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1590
|
+
});
|
|
1591
|
+
var assistantModelMessageSchema = z.object({
|
|
1592
|
+
role: z.literal("assistant"),
|
|
1593
|
+
content: z.union([
|
|
1594
|
+
z.string(),
|
|
1595
|
+
z.array(
|
|
1596
|
+
z.union([
|
|
1597
|
+
textPartSchema,
|
|
1598
|
+
filePartSchema,
|
|
1599
|
+
reasoningPartSchema,
|
|
1600
|
+
toolCallPartSchema,
|
|
1601
|
+
toolResultPartSchema
|
|
1602
|
+
])
|
|
1603
|
+
)
|
|
1604
|
+
]),
|
|
1605
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1606
|
+
});
|
|
1607
|
+
var toolModelMessageSchema = z.object({
|
|
1608
|
+
role: z.literal("tool"),
|
|
1609
|
+
content: z.array(toolResultPartSchema),
|
|
1610
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1611
|
+
});
|
|
1612
|
+
z.union([
|
|
1613
|
+
systemModelMessageSchema,
|
|
1614
|
+
userModelMessageSchema,
|
|
1615
|
+
assistantModelMessageSchema,
|
|
1616
|
+
toolModelMessageSchema
|
|
1617
|
+
]);
|
|
1618
|
+
function asArray(value) {
|
|
1619
|
+
return value === void 0 ? [] : Array.isArray(value) ? value : [value];
|
|
1620
|
+
}
|
|
1621
|
+
createIdGenerator({
|
|
1622
|
+
prefix: "aitxt",
|
|
1623
|
+
size: 24
|
|
1624
|
+
});
|
|
1625
|
+
function prepareHeaders(headers, defaultHeaders) {
|
|
1626
|
+
const responseHeaders = new Headers(headers != null ? headers : {});
|
|
1627
|
+
for (const [key, value] of Object.entries(defaultHeaders)) {
|
|
1628
|
+
if (!responseHeaders.has(key)) {
|
|
1629
|
+
responseHeaders.set(key, value);
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
return responseHeaders;
|
|
1633
|
+
}
|
|
1634
|
+
var JsonToSseTransformStream = class extends TransformStream {
|
|
1635
|
+
constructor() {
|
|
1636
|
+
super({
|
|
1637
|
+
transform(part, controller) {
|
|
1638
|
+
controller.enqueue(`data: ${JSON.stringify(part)}
|
|
1639
|
+
|
|
1640
|
+
`);
|
|
1641
|
+
},
|
|
1642
|
+
flush(controller) {
|
|
1643
|
+
controller.enqueue("data: [DONE]\n\n");
|
|
1644
|
+
}
|
|
1645
|
+
});
|
|
1646
|
+
}
|
|
1647
|
+
};
|
|
1648
|
+
var UI_MESSAGE_STREAM_HEADERS = {
|
|
1649
|
+
"content-type": "text/event-stream",
|
|
1650
|
+
"cache-control": "no-cache",
|
|
1651
|
+
connection: "keep-alive",
|
|
1652
|
+
"x-vercel-ai-ui-message-stream": "v1",
|
|
1653
|
+
"x-accel-buffering": "no"
|
|
1654
|
+
// disable nginx buffering
|
|
1655
|
+
};
|
|
1656
|
+
function createUIMessageStreamResponse({
|
|
1657
|
+
status,
|
|
1658
|
+
statusText,
|
|
1659
|
+
headers,
|
|
1660
|
+
stream,
|
|
1661
|
+
consumeSseStream
|
|
1662
|
+
}) {
|
|
1663
|
+
let sseStream = stream.pipeThrough(new JsonToSseTransformStream());
|
|
1664
|
+
if (consumeSseStream) {
|
|
1665
|
+
const [stream1, stream2] = sseStream.tee();
|
|
1666
|
+
sseStream = stream1;
|
|
1667
|
+
consumeSseStream({ stream: stream2 });
|
|
1668
|
+
}
|
|
1669
|
+
return new Response(sseStream.pipeThrough(new TextEncoderStream()), {
|
|
1670
|
+
status,
|
|
1671
|
+
statusText,
|
|
1672
|
+
headers: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS)
|
|
1673
|
+
});
|
|
1674
|
+
}
|
|
1675
|
+
function isDataUIMessageChunk(chunk) {
|
|
1676
|
+
return chunk.type.startsWith("data-");
|
|
1677
|
+
}
|
|
1678
|
+
function mergeObjects(base, overrides) {
|
|
1679
|
+
if (base === void 0 && overrides === void 0) {
|
|
1680
|
+
return void 0;
|
|
1681
|
+
}
|
|
1682
|
+
if (base === void 0) {
|
|
1683
|
+
return overrides;
|
|
1684
|
+
}
|
|
1685
|
+
if (overrides === void 0) {
|
|
1686
|
+
return base;
|
|
1687
|
+
}
|
|
1688
|
+
const result = { ...base };
|
|
1689
|
+
for (const key in overrides) {
|
|
1690
|
+
if (Object.prototype.hasOwnProperty.call(overrides, key)) {
|
|
1691
|
+
const overridesValue = overrides[key];
|
|
1692
|
+
if (overridesValue === void 0)
|
|
1693
|
+
continue;
|
|
1694
|
+
const baseValue = key in base ? base[key] : void 0;
|
|
1695
|
+
const isSourceObject = overridesValue !== null && typeof overridesValue === "object" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);
|
|
1696
|
+
const isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === "object" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);
|
|
1697
|
+
if (isSourceObject && isTargetObject) {
|
|
1698
|
+
result[key] = mergeObjects(
|
|
1699
|
+
baseValue,
|
|
1700
|
+
overridesValue
|
|
1701
|
+
);
|
|
1702
|
+
} else {
|
|
1703
|
+
result[key] = overridesValue;
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
return result;
|
|
1708
|
+
}
|
|
1709
|
+
function fixJson(input) {
|
|
1710
|
+
const stack = ["ROOT"];
|
|
1711
|
+
let lastValidIndex = -1;
|
|
1712
|
+
let literalStart = null;
|
|
1713
|
+
function processValueStart(char, i, swapState) {
|
|
1714
|
+
{
|
|
1715
|
+
switch (char) {
|
|
1716
|
+
case '"': {
|
|
1717
|
+
lastValidIndex = i;
|
|
1718
|
+
stack.pop();
|
|
1719
|
+
stack.push(swapState);
|
|
1720
|
+
stack.push("INSIDE_STRING");
|
|
1721
|
+
break;
|
|
1722
|
+
}
|
|
1723
|
+
case "f":
|
|
1724
|
+
case "t":
|
|
1725
|
+
case "n": {
|
|
1726
|
+
lastValidIndex = i;
|
|
1727
|
+
literalStart = i;
|
|
1728
|
+
stack.pop();
|
|
1729
|
+
stack.push(swapState);
|
|
1730
|
+
stack.push("INSIDE_LITERAL");
|
|
1731
|
+
break;
|
|
1732
|
+
}
|
|
1733
|
+
case "-": {
|
|
1734
|
+
stack.pop();
|
|
1735
|
+
stack.push(swapState);
|
|
1736
|
+
stack.push("INSIDE_NUMBER");
|
|
1737
|
+
break;
|
|
1738
|
+
}
|
|
1739
|
+
case "0":
|
|
1740
|
+
case "1":
|
|
1741
|
+
case "2":
|
|
1742
|
+
case "3":
|
|
1743
|
+
case "4":
|
|
1744
|
+
case "5":
|
|
1745
|
+
case "6":
|
|
1746
|
+
case "7":
|
|
1747
|
+
case "8":
|
|
1748
|
+
case "9": {
|
|
1749
|
+
lastValidIndex = i;
|
|
1750
|
+
stack.pop();
|
|
1751
|
+
stack.push(swapState);
|
|
1752
|
+
stack.push("INSIDE_NUMBER");
|
|
1753
|
+
break;
|
|
1754
|
+
}
|
|
1755
|
+
case "{": {
|
|
1756
|
+
lastValidIndex = i;
|
|
1757
|
+
stack.pop();
|
|
1758
|
+
stack.push(swapState);
|
|
1759
|
+
stack.push("INSIDE_OBJECT_START");
|
|
1760
|
+
break;
|
|
1761
|
+
}
|
|
1762
|
+
case "[": {
|
|
1763
|
+
lastValidIndex = i;
|
|
1764
|
+
stack.pop();
|
|
1765
|
+
stack.push(swapState);
|
|
1766
|
+
stack.push("INSIDE_ARRAY_START");
|
|
1767
|
+
break;
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
function processAfterObjectValue(char, i) {
|
|
1773
|
+
switch (char) {
|
|
1774
|
+
case ",": {
|
|
1775
|
+
stack.pop();
|
|
1776
|
+
stack.push("INSIDE_OBJECT_AFTER_COMMA");
|
|
1777
|
+
break;
|
|
1778
|
+
}
|
|
1779
|
+
case "}": {
|
|
1780
|
+
lastValidIndex = i;
|
|
1781
|
+
stack.pop();
|
|
1782
|
+
break;
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
function processAfterArrayValue(char, i) {
|
|
1787
|
+
switch (char) {
|
|
1788
|
+
case ",": {
|
|
1789
|
+
stack.pop();
|
|
1790
|
+
stack.push("INSIDE_ARRAY_AFTER_COMMA");
|
|
1791
|
+
break;
|
|
1792
|
+
}
|
|
1793
|
+
case "]": {
|
|
1794
|
+
lastValidIndex = i;
|
|
1795
|
+
stack.pop();
|
|
1796
|
+
break;
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
for (let i = 0; i < input.length; i++) {
|
|
1801
|
+
const char = input[i];
|
|
1802
|
+
const currentState = stack[stack.length - 1];
|
|
1803
|
+
switch (currentState) {
|
|
1804
|
+
case "ROOT":
|
|
1805
|
+
processValueStart(char, i, "FINISH");
|
|
1806
|
+
break;
|
|
1807
|
+
case "INSIDE_OBJECT_START": {
|
|
1808
|
+
switch (char) {
|
|
1809
|
+
case '"': {
|
|
1810
|
+
stack.pop();
|
|
1811
|
+
stack.push("INSIDE_OBJECT_KEY");
|
|
1812
|
+
break;
|
|
1813
|
+
}
|
|
1814
|
+
case "}": {
|
|
1815
|
+
lastValidIndex = i;
|
|
1816
|
+
stack.pop();
|
|
1817
|
+
break;
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
break;
|
|
1821
|
+
}
|
|
1822
|
+
case "INSIDE_OBJECT_AFTER_COMMA": {
|
|
1823
|
+
switch (char) {
|
|
1824
|
+
case '"': {
|
|
1825
|
+
stack.pop();
|
|
1826
|
+
stack.push("INSIDE_OBJECT_KEY");
|
|
1827
|
+
break;
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
break;
|
|
1831
|
+
}
|
|
1832
|
+
case "INSIDE_OBJECT_KEY": {
|
|
1833
|
+
switch (char) {
|
|
1834
|
+
case '"': {
|
|
1835
|
+
stack.pop();
|
|
1836
|
+
stack.push("INSIDE_OBJECT_AFTER_KEY");
|
|
1837
|
+
break;
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
break;
|
|
1841
|
+
}
|
|
1842
|
+
case "INSIDE_OBJECT_AFTER_KEY": {
|
|
1843
|
+
switch (char) {
|
|
1844
|
+
case ":": {
|
|
1845
|
+
stack.pop();
|
|
1846
|
+
stack.push("INSIDE_OBJECT_BEFORE_VALUE");
|
|
1847
|
+
break;
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
break;
|
|
1851
|
+
}
|
|
1852
|
+
case "INSIDE_OBJECT_BEFORE_VALUE": {
|
|
1853
|
+
processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
|
|
1854
|
+
break;
|
|
1855
|
+
}
|
|
1856
|
+
case "INSIDE_OBJECT_AFTER_VALUE": {
|
|
1857
|
+
processAfterObjectValue(char, i);
|
|
1858
|
+
break;
|
|
1859
|
+
}
|
|
1860
|
+
case "INSIDE_STRING": {
|
|
1861
|
+
switch (char) {
|
|
1862
|
+
case '"': {
|
|
1863
|
+
stack.pop();
|
|
1864
|
+
lastValidIndex = i;
|
|
1865
|
+
break;
|
|
1866
|
+
}
|
|
1867
|
+
case "\\": {
|
|
1868
|
+
stack.push("INSIDE_STRING_ESCAPE");
|
|
1869
|
+
break;
|
|
1870
|
+
}
|
|
1871
|
+
default: {
|
|
1872
|
+
lastValidIndex = i;
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
break;
|
|
1876
|
+
}
|
|
1877
|
+
case "INSIDE_ARRAY_START": {
|
|
1878
|
+
switch (char) {
|
|
1879
|
+
case "]": {
|
|
1880
|
+
lastValidIndex = i;
|
|
1881
|
+
stack.pop();
|
|
1882
|
+
break;
|
|
1883
|
+
}
|
|
1884
|
+
default: {
|
|
1885
|
+
lastValidIndex = i;
|
|
1886
|
+
processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
|
|
1887
|
+
break;
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
break;
|
|
1891
|
+
}
|
|
1892
|
+
case "INSIDE_ARRAY_AFTER_VALUE": {
|
|
1893
|
+
switch (char) {
|
|
1894
|
+
case ",": {
|
|
1895
|
+
stack.pop();
|
|
1896
|
+
stack.push("INSIDE_ARRAY_AFTER_COMMA");
|
|
1897
|
+
break;
|
|
1898
|
+
}
|
|
1899
|
+
case "]": {
|
|
1900
|
+
lastValidIndex = i;
|
|
1901
|
+
stack.pop();
|
|
1902
|
+
break;
|
|
1903
|
+
}
|
|
1904
|
+
default: {
|
|
1905
|
+
lastValidIndex = i;
|
|
1906
|
+
break;
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
break;
|
|
1910
|
+
}
|
|
1911
|
+
case "INSIDE_ARRAY_AFTER_COMMA": {
|
|
1912
|
+
processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
|
|
1913
|
+
break;
|
|
1914
|
+
}
|
|
1915
|
+
case "INSIDE_STRING_ESCAPE": {
|
|
1916
|
+
stack.pop();
|
|
1917
|
+
lastValidIndex = i;
|
|
1918
|
+
break;
|
|
1919
|
+
}
|
|
1920
|
+
case "INSIDE_NUMBER": {
|
|
1921
|
+
switch (char) {
|
|
1922
|
+
case "0":
|
|
1923
|
+
case "1":
|
|
1924
|
+
case "2":
|
|
1925
|
+
case "3":
|
|
1926
|
+
case "4":
|
|
1927
|
+
case "5":
|
|
1928
|
+
case "6":
|
|
1929
|
+
case "7":
|
|
1930
|
+
case "8":
|
|
1931
|
+
case "9": {
|
|
1932
|
+
lastValidIndex = i;
|
|
1933
|
+
break;
|
|
1934
|
+
}
|
|
1935
|
+
case "e":
|
|
1936
|
+
case "E":
|
|
1937
|
+
case "-":
|
|
1938
|
+
case ".": {
|
|
1939
|
+
break;
|
|
1940
|
+
}
|
|
1941
|
+
case ",": {
|
|
1942
|
+
stack.pop();
|
|
1943
|
+
if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
|
|
1944
|
+
processAfterArrayValue(char, i);
|
|
1945
|
+
}
|
|
1946
|
+
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
|
|
1947
|
+
processAfterObjectValue(char, i);
|
|
1948
|
+
}
|
|
1949
|
+
break;
|
|
1950
|
+
}
|
|
1951
|
+
case "}": {
|
|
1952
|
+
stack.pop();
|
|
1953
|
+
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
|
|
1954
|
+
processAfterObjectValue(char, i);
|
|
1955
|
+
}
|
|
1956
|
+
break;
|
|
1957
|
+
}
|
|
1958
|
+
case "]": {
|
|
1959
|
+
stack.pop();
|
|
1960
|
+
if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
|
|
1961
|
+
processAfterArrayValue(char, i);
|
|
1962
|
+
}
|
|
1963
|
+
break;
|
|
1964
|
+
}
|
|
1965
|
+
default: {
|
|
1966
|
+
stack.pop();
|
|
1967
|
+
break;
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
break;
|
|
1971
|
+
}
|
|
1972
|
+
case "INSIDE_LITERAL": {
|
|
1973
|
+
const partialLiteral = input.substring(literalStart, i + 1);
|
|
1974
|
+
if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
|
|
1975
|
+
stack.pop();
|
|
1976
|
+
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
|
|
1977
|
+
processAfterObjectValue(char, i);
|
|
1978
|
+
} else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
|
|
1979
|
+
processAfterArrayValue(char, i);
|
|
1980
|
+
}
|
|
1981
|
+
} else {
|
|
1982
|
+
lastValidIndex = i;
|
|
1983
|
+
}
|
|
1984
|
+
break;
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
let result = input.slice(0, lastValidIndex + 1);
|
|
1989
|
+
for (let i = stack.length - 1; i >= 0; i--) {
|
|
1990
|
+
const state = stack[i];
|
|
1991
|
+
switch (state) {
|
|
1992
|
+
case "INSIDE_STRING": {
|
|
1993
|
+
result += '"';
|
|
1994
|
+
break;
|
|
1995
|
+
}
|
|
1996
|
+
case "INSIDE_OBJECT_KEY":
|
|
1997
|
+
case "INSIDE_OBJECT_AFTER_KEY":
|
|
1998
|
+
case "INSIDE_OBJECT_AFTER_COMMA":
|
|
1999
|
+
case "INSIDE_OBJECT_START":
|
|
2000
|
+
case "INSIDE_OBJECT_BEFORE_VALUE":
|
|
2001
|
+
case "INSIDE_OBJECT_AFTER_VALUE": {
|
|
2002
|
+
result += "}";
|
|
2003
|
+
break;
|
|
2004
|
+
}
|
|
2005
|
+
case "INSIDE_ARRAY_START":
|
|
2006
|
+
case "INSIDE_ARRAY_AFTER_COMMA":
|
|
2007
|
+
case "INSIDE_ARRAY_AFTER_VALUE": {
|
|
2008
|
+
result += "]";
|
|
2009
|
+
break;
|
|
2010
|
+
}
|
|
2011
|
+
case "INSIDE_LITERAL": {
|
|
2012
|
+
const partialLiteral = input.substring(literalStart, input.length);
|
|
2013
|
+
if ("true".startsWith(partialLiteral)) {
|
|
2014
|
+
result += "true".slice(partialLiteral.length);
|
|
2015
|
+
} else if ("false".startsWith(partialLiteral)) {
|
|
2016
|
+
result += "false".slice(partialLiteral.length);
|
|
2017
|
+
} else if ("null".startsWith(partialLiteral)) {
|
|
2018
|
+
result += "null".slice(partialLiteral.length);
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
return result;
|
|
2024
|
+
}
|
|
2025
|
+
async function parsePartialJson(jsonText) {
|
|
2026
|
+
if (jsonText === void 0) {
|
|
2027
|
+
return { value: void 0, state: "undefined-input" };
|
|
2028
|
+
}
|
|
2029
|
+
let result = await safeParseJSON({ text: jsonText });
|
|
2030
|
+
if (result.success) {
|
|
2031
|
+
return { value: result.value, state: "successful-parse" };
|
|
2032
|
+
}
|
|
2033
|
+
result = await safeParseJSON({ text: fixJson(jsonText) });
|
|
2034
|
+
if (result.success) {
|
|
2035
|
+
return { value: result.value, state: "repaired-parse" };
|
|
2036
|
+
}
|
|
2037
|
+
return { value: void 0, state: "failed-parse" };
|
|
2038
|
+
}
|
|
2039
|
+
function isToolUIPart(part) {
|
|
2040
|
+
return part.type.startsWith("tool-");
|
|
2041
|
+
}
|
|
2042
|
+
function getToolName(part) {
|
|
2043
|
+
return part.type.split("-").slice(1).join("-");
|
|
2044
|
+
}
|
|
2045
|
+
function createStreamingUIMessageState({
|
|
2046
|
+
lastMessage,
|
|
2047
|
+
messageId
|
|
2048
|
+
}) {
|
|
2049
|
+
return {
|
|
2050
|
+
message: (lastMessage == null ? void 0 : lastMessage.role) === "assistant" ? lastMessage : {
|
|
2051
|
+
id: messageId,
|
|
2052
|
+
metadata: void 0,
|
|
2053
|
+
role: "assistant",
|
|
2054
|
+
parts: []
|
|
2055
|
+
},
|
|
2056
|
+
activeTextParts: {},
|
|
2057
|
+
activeReasoningParts: {},
|
|
2058
|
+
partialToolCalls: {}
|
|
2059
|
+
};
|
|
2060
|
+
}
|
|
2061
|
+
function processUIMessageStream({
|
|
2062
|
+
stream,
|
|
2063
|
+
messageMetadataSchema,
|
|
2064
|
+
dataPartSchemas,
|
|
2065
|
+
runUpdateMessageJob,
|
|
2066
|
+
onError,
|
|
2067
|
+
onToolCall,
|
|
2068
|
+
onData
|
|
2069
|
+
}) {
|
|
2070
|
+
return stream.pipeThrough(
|
|
2071
|
+
new TransformStream({
|
|
2072
|
+
async transform(chunk, controller) {
|
|
2073
|
+
await runUpdateMessageJob(async ({ state, write }) => {
|
|
2074
|
+
var _a17, _b, _c, _d;
|
|
2075
|
+
function getToolInvocation(toolCallId) {
|
|
2076
|
+
const toolInvocations = state.message.parts.filter(isToolUIPart);
|
|
2077
|
+
const toolInvocation = toolInvocations.find(
|
|
2078
|
+
(invocation) => invocation.toolCallId === toolCallId
|
|
2079
|
+
);
|
|
2080
|
+
if (toolInvocation == null) {
|
|
2081
|
+
throw new Error(
|
|
2082
|
+
"tool-output-error must be preceded by a tool-input-available"
|
|
2083
|
+
);
|
|
2084
|
+
}
|
|
2085
|
+
return toolInvocation;
|
|
2086
|
+
}
|
|
2087
|
+
function getDynamicToolInvocation(toolCallId) {
|
|
2088
|
+
const toolInvocations = state.message.parts.filter(
|
|
2089
|
+
(part) => part.type === "dynamic-tool"
|
|
2090
|
+
);
|
|
2091
|
+
const toolInvocation = toolInvocations.find(
|
|
2092
|
+
(invocation) => invocation.toolCallId === toolCallId
|
|
2093
|
+
);
|
|
2094
|
+
if (toolInvocation == null) {
|
|
2095
|
+
throw new Error(
|
|
2096
|
+
"tool-output-error must be preceded by a tool-input-available"
|
|
2097
|
+
);
|
|
2098
|
+
}
|
|
2099
|
+
return toolInvocation;
|
|
2100
|
+
}
|
|
2101
|
+
function updateToolPart(options) {
|
|
2102
|
+
var _a18;
|
|
2103
|
+
const part = state.message.parts.find(
|
|
2104
|
+
(part2) => isToolUIPart(part2) && part2.toolCallId === options.toolCallId
|
|
2105
|
+
);
|
|
2106
|
+
const anyOptions = options;
|
|
2107
|
+
const anyPart = part;
|
|
2108
|
+
if (part != null) {
|
|
2109
|
+
part.state = options.state;
|
|
2110
|
+
anyPart.input = anyOptions.input;
|
|
2111
|
+
anyPart.output = anyOptions.output;
|
|
2112
|
+
anyPart.errorText = anyOptions.errorText;
|
|
2113
|
+
anyPart.rawInput = anyOptions.rawInput;
|
|
2114
|
+
anyPart.preliminary = anyOptions.preliminary;
|
|
2115
|
+
anyPart.providerExecuted = (_a18 = anyOptions.providerExecuted) != null ? _a18 : part.providerExecuted;
|
|
2116
|
+
if (anyOptions.providerMetadata != null && part.state === "input-available") {
|
|
2117
|
+
part.callProviderMetadata = anyOptions.providerMetadata;
|
|
2118
|
+
}
|
|
2119
|
+
} else {
|
|
2120
|
+
state.message.parts.push({
|
|
2121
|
+
type: `tool-${options.toolName}`,
|
|
2122
|
+
toolCallId: options.toolCallId,
|
|
2123
|
+
state: options.state,
|
|
2124
|
+
input: anyOptions.input,
|
|
2125
|
+
output: anyOptions.output,
|
|
2126
|
+
rawInput: anyOptions.rawInput,
|
|
2127
|
+
errorText: anyOptions.errorText,
|
|
2128
|
+
providerExecuted: anyOptions.providerExecuted,
|
|
2129
|
+
preliminary: anyOptions.preliminary,
|
|
2130
|
+
...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
|
|
2131
|
+
});
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
function updateDynamicToolPart(options) {
|
|
2135
|
+
var _a18;
|
|
2136
|
+
const part = state.message.parts.find(
|
|
2137
|
+
(part2) => part2.type === "dynamic-tool" && part2.toolCallId === options.toolCallId
|
|
2138
|
+
);
|
|
2139
|
+
const anyOptions = options;
|
|
2140
|
+
const anyPart = part;
|
|
2141
|
+
if (part != null) {
|
|
2142
|
+
part.state = options.state;
|
|
2143
|
+
anyPart.toolName = options.toolName;
|
|
2144
|
+
anyPart.input = anyOptions.input;
|
|
2145
|
+
anyPart.output = anyOptions.output;
|
|
2146
|
+
anyPart.errorText = anyOptions.errorText;
|
|
2147
|
+
anyPart.rawInput = (_a18 = anyOptions.rawInput) != null ? _a18 : anyPart.rawInput;
|
|
2148
|
+
anyPart.preliminary = anyOptions.preliminary;
|
|
2149
|
+
if (anyOptions.providerMetadata != null && part.state === "input-available") {
|
|
2150
|
+
part.callProviderMetadata = anyOptions.providerMetadata;
|
|
2151
|
+
}
|
|
2152
|
+
} else {
|
|
2153
|
+
state.message.parts.push({
|
|
2154
|
+
type: "dynamic-tool",
|
|
2155
|
+
toolName: options.toolName,
|
|
2156
|
+
toolCallId: options.toolCallId,
|
|
2157
|
+
state: options.state,
|
|
2158
|
+
input: anyOptions.input,
|
|
2159
|
+
output: anyOptions.output,
|
|
2160
|
+
errorText: anyOptions.errorText,
|
|
2161
|
+
preliminary: anyOptions.preliminary,
|
|
2162
|
+
...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
|
|
2163
|
+
});
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
async function updateMessageMetadata(metadata) {
|
|
2167
|
+
if (metadata != null) {
|
|
2168
|
+
const mergedMetadata = state.message.metadata != null ? mergeObjects(state.message.metadata, metadata) : metadata;
|
|
2169
|
+
if (messageMetadataSchema != null) {
|
|
2170
|
+
await validateTypes({
|
|
2171
|
+
value: mergedMetadata,
|
|
2172
|
+
schema: messageMetadataSchema
|
|
2173
|
+
});
|
|
2174
|
+
}
|
|
2175
|
+
state.message.metadata = mergedMetadata;
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
switch (chunk.type) {
|
|
2179
|
+
case "text-start": {
|
|
2180
|
+
const textPart = {
|
|
2181
|
+
type: "text",
|
|
2182
|
+
text: "",
|
|
2183
|
+
providerMetadata: chunk.providerMetadata,
|
|
2184
|
+
state: "streaming"
|
|
2185
|
+
};
|
|
2186
|
+
state.activeTextParts[chunk.id] = textPart;
|
|
2187
|
+
state.message.parts.push(textPart);
|
|
2188
|
+
write();
|
|
2189
|
+
break;
|
|
2190
|
+
}
|
|
2191
|
+
case "text-delta": {
|
|
2192
|
+
const textPart = state.activeTextParts[chunk.id];
|
|
2193
|
+
textPart.text += chunk.delta;
|
|
2194
|
+
textPart.providerMetadata = (_a17 = chunk.providerMetadata) != null ? _a17 : textPart.providerMetadata;
|
|
2195
|
+
write();
|
|
2196
|
+
break;
|
|
2197
|
+
}
|
|
2198
|
+
case "text-end": {
|
|
2199
|
+
const textPart = state.activeTextParts[chunk.id];
|
|
2200
|
+
textPart.state = "done";
|
|
2201
|
+
textPart.providerMetadata = (_b = chunk.providerMetadata) != null ? _b : textPart.providerMetadata;
|
|
2202
|
+
delete state.activeTextParts[chunk.id];
|
|
2203
|
+
write();
|
|
2204
|
+
break;
|
|
2205
|
+
}
|
|
2206
|
+
case "reasoning-start": {
|
|
2207
|
+
const reasoningPart = {
|
|
2208
|
+
type: "reasoning",
|
|
2209
|
+
text: "",
|
|
2210
|
+
providerMetadata: chunk.providerMetadata,
|
|
2211
|
+
state: "streaming"
|
|
2212
|
+
};
|
|
2213
|
+
state.activeReasoningParts[chunk.id] = reasoningPart;
|
|
2214
|
+
state.message.parts.push(reasoningPart);
|
|
2215
|
+
write();
|
|
2216
|
+
break;
|
|
2217
|
+
}
|
|
2218
|
+
case "reasoning-delta": {
|
|
2219
|
+
const reasoningPart = state.activeReasoningParts[chunk.id];
|
|
2220
|
+
reasoningPart.text += chunk.delta;
|
|
2221
|
+
reasoningPart.providerMetadata = (_c = chunk.providerMetadata) != null ? _c : reasoningPart.providerMetadata;
|
|
2222
|
+
write();
|
|
2223
|
+
break;
|
|
2224
|
+
}
|
|
2225
|
+
case "reasoning-end": {
|
|
2226
|
+
const reasoningPart = state.activeReasoningParts[chunk.id];
|
|
2227
|
+
reasoningPart.providerMetadata = (_d = chunk.providerMetadata) != null ? _d : reasoningPart.providerMetadata;
|
|
2228
|
+
reasoningPart.state = "done";
|
|
2229
|
+
delete state.activeReasoningParts[chunk.id];
|
|
2230
|
+
write();
|
|
2231
|
+
break;
|
|
2232
|
+
}
|
|
2233
|
+
case "file": {
|
|
2234
|
+
state.message.parts.push({
|
|
2235
|
+
type: "file",
|
|
2236
|
+
mediaType: chunk.mediaType,
|
|
2237
|
+
url: chunk.url
|
|
2238
|
+
});
|
|
2239
|
+
write();
|
|
2240
|
+
break;
|
|
2241
|
+
}
|
|
2242
|
+
case "source-url": {
|
|
2243
|
+
state.message.parts.push({
|
|
2244
|
+
type: "source-url",
|
|
2245
|
+
sourceId: chunk.sourceId,
|
|
2246
|
+
url: chunk.url,
|
|
2247
|
+
title: chunk.title,
|
|
2248
|
+
providerMetadata: chunk.providerMetadata
|
|
2249
|
+
});
|
|
2250
|
+
write();
|
|
2251
|
+
break;
|
|
2252
|
+
}
|
|
2253
|
+
case "source-document": {
|
|
2254
|
+
state.message.parts.push({
|
|
2255
|
+
type: "source-document",
|
|
2256
|
+
sourceId: chunk.sourceId,
|
|
2257
|
+
mediaType: chunk.mediaType,
|
|
2258
|
+
title: chunk.title,
|
|
2259
|
+
filename: chunk.filename,
|
|
2260
|
+
providerMetadata: chunk.providerMetadata
|
|
2261
|
+
});
|
|
2262
|
+
write();
|
|
2263
|
+
break;
|
|
2264
|
+
}
|
|
2265
|
+
case "tool-input-start": {
|
|
2266
|
+
const toolInvocations = state.message.parts.filter(isToolUIPart);
|
|
2267
|
+
state.partialToolCalls[chunk.toolCallId] = {
|
|
2268
|
+
text: "",
|
|
2269
|
+
toolName: chunk.toolName,
|
|
2270
|
+
index: toolInvocations.length,
|
|
2271
|
+
dynamic: chunk.dynamic
|
|
2272
|
+
};
|
|
2273
|
+
if (chunk.dynamic) {
|
|
2274
|
+
updateDynamicToolPart({
|
|
2275
|
+
toolCallId: chunk.toolCallId,
|
|
2276
|
+
toolName: chunk.toolName,
|
|
2277
|
+
state: "input-streaming",
|
|
2278
|
+
input: void 0
|
|
2279
|
+
});
|
|
2280
|
+
} else {
|
|
2281
|
+
updateToolPart({
|
|
2282
|
+
toolCallId: chunk.toolCallId,
|
|
2283
|
+
toolName: chunk.toolName,
|
|
2284
|
+
state: "input-streaming",
|
|
2285
|
+
input: void 0,
|
|
2286
|
+
providerExecuted: chunk.providerExecuted
|
|
2287
|
+
});
|
|
2288
|
+
}
|
|
2289
|
+
write();
|
|
2290
|
+
break;
|
|
2291
|
+
}
|
|
2292
|
+
case "tool-input-delta": {
|
|
2293
|
+
const partialToolCall = state.partialToolCalls[chunk.toolCallId];
|
|
2294
|
+
partialToolCall.text += chunk.inputTextDelta;
|
|
2295
|
+
const { value: partialArgs } = await parsePartialJson(
|
|
2296
|
+
partialToolCall.text
|
|
2297
|
+
);
|
|
2298
|
+
if (partialToolCall.dynamic) {
|
|
2299
|
+
updateDynamicToolPart({
|
|
2300
|
+
toolCallId: chunk.toolCallId,
|
|
2301
|
+
toolName: partialToolCall.toolName,
|
|
2302
|
+
state: "input-streaming",
|
|
2303
|
+
input: partialArgs
|
|
2304
|
+
});
|
|
2305
|
+
} else {
|
|
2306
|
+
updateToolPart({
|
|
2307
|
+
toolCallId: chunk.toolCallId,
|
|
2308
|
+
toolName: partialToolCall.toolName,
|
|
2309
|
+
state: "input-streaming",
|
|
2310
|
+
input: partialArgs
|
|
2311
|
+
});
|
|
2312
|
+
}
|
|
2313
|
+
write();
|
|
2314
|
+
break;
|
|
2315
|
+
}
|
|
2316
|
+
case "tool-input-available": {
|
|
2317
|
+
if (chunk.dynamic) {
|
|
2318
|
+
updateDynamicToolPart({
|
|
2319
|
+
toolCallId: chunk.toolCallId,
|
|
2320
|
+
toolName: chunk.toolName,
|
|
2321
|
+
state: "input-available",
|
|
2322
|
+
input: chunk.input,
|
|
2323
|
+
providerMetadata: chunk.providerMetadata
|
|
2324
|
+
});
|
|
2325
|
+
} else {
|
|
2326
|
+
updateToolPart({
|
|
2327
|
+
toolCallId: chunk.toolCallId,
|
|
2328
|
+
toolName: chunk.toolName,
|
|
2329
|
+
state: "input-available",
|
|
2330
|
+
input: chunk.input,
|
|
2331
|
+
providerExecuted: chunk.providerExecuted,
|
|
2332
|
+
providerMetadata: chunk.providerMetadata
|
|
2333
|
+
});
|
|
2334
|
+
}
|
|
2335
|
+
write();
|
|
2336
|
+
if (onToolCall && !chunk.providerExecuted) {
|
|
2337
|
+
await onToolCall({
|
|
2338
|
+
toolCall: chunk
|
|
2339
|
+
});
|
|
2340
|
+
}
|
|
2341
|
+
break;
|
|
2342
|
+
}
|
|
2343
|
+
case "tool-input-error": {
|
|
2344
|
+
if (chunk.dynamic) {
|
|
2345
|
+
updateDynamicToolPart({
|
|
2346
|
+
toolCallId: chunk.toolCallId,
|
|
2347
|
+
toolName: chunk.toolName,
|
|
2348
|
+
state: "output-error",
|
|
2349
|
+
input: chunk.input,
|
|
2350
|
+
errorText: chunk.errorText,
|
|
2351
|
+
providerMetadata: chunk.providerMetadata
|
|
2352
|
+
});
|
|
2353
|
+
} else {
|
|
2354
|
+
updateToolPart({
|
|
2355
|
+
toolCallId: chunk.toolCallId,
|
|
2356
|
+
toolName: chunk.toolName,
|
|
2357
|
+
state: "output-error",
|
|
2358
|
+
input: void 0,
|
|
2359
|
+
rawInput: chunk.input,
|
|
2360
|
+
errorText: chunk.errorText,
|
|
2361
|
+
providerExecuted: chunk.providerExecuted,
|
|
2362
|
+
providerMetadata: chunk.providerMetadata
|
|
2363
|
+
});
|
|
2364
|
+
}
|
|
2365
|
+
write();
|
|
2366
|
+
break;
|
|
2367
|
+
}
|
|
2368
|
+
case "tool-output-available": {
|
|
2369
|
+
if (chunk.dynamic) {
|
|
2370
|
+
const toolInvocation = getDynamicToolInvocation(
|
|
2371
|
+
chunk.toolCallId
|
|
2372
|
+
);
|
|
2373
|
+
updateDynamicToolPart({
|
|
2374
|
+
toolCallId: chunk.toolCallId,
|
|
2375
|
+
toolName: toolInvocation.toolName,
|
|
2376
|
+
state: "output-available",
|
|
2377
|
+
input: toolInvocation.input,
|
|
2378
|
+
output: chunk.output,
|
|
2379
|
+
preliminary: chunk.preliminary
|
|
2380
|
+
});
|
|
2381
|
+
} else {
|
|
2382
|
+
const toolInvocation = getToolInvocation(chunk.toolCallId);
|
|
2383
|
+
updateToolPart({
|
|
2384
|
+
toolCallId: chunk.toolCallId,
|
|
2385
|
+
toolName: getToolName(toolInvocation),
|
|
2386
|
+
state: "output-available",
|
|
2387
|
+
input: toolInvocation.input,
|
|
2388
|
+
output: chunk.output,
|
|
2389
|
+
providerExecuted: chunk.providerExecuted,
|
|
2390
|
+
preliminary: chunk.preliminary
|
|
2391
|
+
});
|
|
2392
|
+
}
|
|
2393
|
+
write();
|
|
2394
|
+
break;
|
|
2395
|
+
}
|
|
2396
|
+
case "tool-output-error": {
|
|
2397
|
+
if (chunk.dynamic) {
|
|
2398
|
+
const toolInvocation = getDynamicToolInvocation(
|
|
2399
|
+
chunk.toolCallId
|
|
2400
|
+
);
|
|
2401
|
+
updateDynamicToolPart({
|
|
2402
|
+
toolCallId: chunk.toolCallId,
|
|
2403
|
+
toolName: toolInvocation.toolName,
|
|
2404
|
+
state: "output-error",
|
|
2405
|
+
input: toolInvocation.input,
|
|
2406
|
+
errorText: chunk.errorText
|
|
2407
|
+
});
|
|
2408
|
+
} else {
|
|
2409
|
+
const toolInvocation = getToolInvocation(chunk.toolCallId);
|
|
2410
|
+
updateToolPart({
|
|
2411
|
+
toolCallId: chunk.toolCallId,
|
|
2412
|
+
toolName: getToolName(toolInvocation),
|
|
2413
|
+
state: "output-error",
|
|
2414
|
+
input: toolInvocation.input,
|
|
2415
|
+
rawInput: toolInvocation.rawInput,
|
|
2416
|
+
errorText: chunk.errorText
|
|
2417
|
+
});
|
|
2418
|
+
}
|
|
2419
|
+
write();
|
|
2420
|
+
break;
|
|
2421
|
+
}
|
|
2422
|
+
case "start-step": {
|
|
2423
|
+
state.message.parts.push({ type: "step-start" });
|
|
2424
|
+
break;
|
|
2425
|
+
}
|
|
2426
|
+
case "finish-step": {
|
|
2427
|
+
state.activeTextParts = {};
|
|
2428
|
+
state.activeReasoningParts = {};
|
|
2429
|
+
break;
|
|
2430
|
+
}
|
|
2431
|
+
case "start": {
|
|
2432
|
+
if (chunk.messageId != null) {
|
|
2433
|
+
state.message.id = chunk.messageId;
|
|
2434
|
+
}
|
|
2435
|
+
await updateMessageMetadata(chunk.messageMetadata);
|
|
2436
|
+
if (chunk.messageId != null || chunk.messageMetadata != null) {
|
|
2437
|
+
write();
|
|
2438
|
+
}
|
|
2439
|
+
break;
|
|
2440
|
+
}
|
|
2441
|
+
case "finish": {
|
|
2442
|
+
await updateMessageMetadata(chunk.messageMetadata);
|
|
2443
|
+
if (chunk.messageMetadata != null) {
|
|
2444
|
+
write();
|
|
2445
|
+
}
|
|
2446
|
+
break;
|
|
2447
|
+
}
|
|
2448
|
+
case "message-metadata": {
|
|
2449
|
+
await updateMessageMetadata(chunk.messageMetadata);
|
|
2450
|
+
if (chunk.messageMetadata != null) {
|
|
2451
|
+
write();
|
|
2452
|
+
}
|
|
2453
|
+
break;
|
|
2454
|
+
}
|
|
2455
|
+
case "error": {
|
|
2456
|
+
onError == null ? void 0 : onError(new Error(chunk.errorText));
|
|
2457
|
+
break;
|
|
2458
|
+
}
|
|
2459
|
+
default: {
|
|
2460
|
+
if (isDataUIMessageChunk(chunk)) {
|
|
2461
|
+
if ((dataPartSchemas == null ? void 0 : dataPartSchemas[chunk.type]) != null) {
|
|
2462
|
+
await validateTypes({
|
|
2463
|
+
value: chunk.data,
|
|
2464
|
+
schema: dataPartSchemas[chunk.type]
|
|
2465
|
+
});
|
|
2466
|
+
}
|
|
2467
|
+
const dataChunk = chunk;
|
|
2468
|
+
if (dataChunk.transient) {
|
|
2469
|
+
onData == null ? void 0 : onData(dataChunk);
|
|
2470
|
+
break;
|
|
2471
|
+
}
|
|
2472
|
+
const existingUIPart = dataChunk.id != null ? state.message.parts.find(
|
|
2473
|
+
(chunkArg) => dataChunk.type === chunkArg.type && dataChunk.id === chunkArg.id
|
|
2474
|
+
) : void 0;
|
|
2475
|
+
if (existingUIPart != null) {
|
|
2476
|
+
existingUIPart.data = dataChunk.data;
|
|
2477
|
+
} else {
|
|
2478
|
+
state.message.parts.push(dataChunk);
|
|
2479
|
+
}
|
|
2480
|
+
onData == null ? void 0 : onData(dataChunk);
|
|
2481
|
+
write();
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
}
|
|
2485
|
+
controller.enqueue(chunk);
|
|
2486
|
+
});
|
|
2487
|
+
}
|
|
2488
|
+
})
|
|
2489
|
+
);
|
|
2490
|
+
}
|
|
2491
|
+
function handleUIMessageStreamFinish({
|
|
2492
|
+
messageId,
|
|
2493
|
+
originalMessages = [],
|
|
2494
|
+
onFinish,
|
|
2495
|
+
onError,
|
|
2496
|
+
stream
|
|
2497
|
+
}) {
|
|
2498
|
+
let lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];
|
|
2499
|
+
if ((lastMessage == null ? void 0 : lastMessage.role) !== "assistant") {
|
|
2500
|
+
lastMessage = void 0;
|
|
2501
|
+
} else {
|
|
2502
|
+
messageId = lastMessage.id;
|
|
2503
|
+
}
|
|
2504
|
+
let isAborted = false;
|
|
2505
|
+
const idInjectedStream = stream.pipeThrough(
|
|
2506
|
+
new TransformStream({
|
|
2507
|
+
transform(chunk, controller) {
|
|
2508
|
+
if (chunk.type === "start") {
|
|
2509
|
+
const startChunk = chunk;
|
|
2510
|
+
if (startChunk.messageId == null && messageId != null) {
|
|
2511
|
+
startChunk.messageId = messageId;
|
|
2512
|
+
}
|
|
2513
|
+
}
|
|
2514
|
+
if (chunk.type === "abort") {
|
|
2515
|
+
isAborted = true;
|
|
2516
|
+
}
|
|
2517
|
+
controller.enqueue(chunk);
|
|
2518
|
+
}
|
|
2519
|
+
})
|
|
2520
|
+
);
|
|
2521
|
+
if (onFinish == null) {
|
|
2522
|
+
return idInjectedStream;
|
|
2523
|
+
}
|
|
2524
|
+
const state = createStreamingUIMessageState({
|
|
2525
|
+
lastMessage: lastMessage ? structuredClone(lastMessage) : void 0,
|
|
2526
|
+
messageId: messageId != null ? messageId : ""
|
|
2527
|
+
// will be overridden by the stream
|
|
2528
|
+
});
|
|
2529
|
+
const runUpdateMessageJob = async (job) => {
|
|
2530
|
+
await job({ state, write: () => {
|
|
2531
|
+
} });
|
|
2532
|
+
};
|
|
2533
|
+
let finishCalled = false;
|
|
2534
|
+
const callOnFinish = async () => {
|
|
2535
|
+
if (finishCalled || !onFinish) {
|
|
2536
|
+
return;
|
|
2537
|
+
}
|
|
2538
|
+
finishCalled = true;
|
|
2539
|
+
const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);
|
|
2540
|
+
await onFinish({
|
|
2541
|
+
isAborted,
|
|
2542
|
+
isContinuation,
|
|
2543
|
+
responseMessage: state.message,
|
|
2544
|
+
messages: [
|
|
2545
|
+
...isContinuation ? originalMessages.slice(0, -1) : originalMessages,
|
|
2546
|
+
state.message
|
|
2547
|
+
]
|
|
2548
|
+
});
|
|
2549
|
+
};
|
|
2550
|
+
return processUIMessageStream({
|
|
2551
|
+
stream: idInjectedStream,
|
|
2552
|
+
runUpdateMessageJob,
|
|
2553
|
+
onError
|
|
2554
|
+
}).pipeThrough(
|
|
2555
|
+
new TransformStream({
|
|
2556
|
+
transform(chunk, controller) {
|
|
2557
|
+
controller.enqueue(chunk);
|
|
2558
|
+
},
|
|
2559
|
+
// @ts-expect-error cancel is still new and missing from types https://developer.mozilla.org/en-US/docs/Web/API/TransformStream#browser_compatibility
|
|
2560
|
+
async cancel() {
|
|
2561
|
+
await callOnFinish();
|
|
2562
|
+
},
|
|
2563
|
+
async flush() {
|
|
2564
|
+
await callOnFinish();
|
|
2565
|
+
}
|
|
2566
|
+
})
|
|
2567
|
+
);
|
|
2568
|
+
}
|
|
2569
|
+
createIdGenerator({
|
|
2570
|
+
prefix: "aitxt",
|
|
2571
|
+
size: 24
|
|
2572
|
+
});
|
|
2573
|
+
createIdGenerator({ prefix: "aiobj", size: 24 });
|
|
2574
|
+
createIdGenerator({ prefix: "aiobj", size: 24 });
|
|
2575
|
+
var output_exports = {};
|
|
2576
|
+
__export(output_exports, {
|
|
2577
|
+
object: () => object,
|
|
2578
|
+
text: () => text
|
|
2579
|
+
});
|
|
2580
|
+
var text = () => ({
|
|
2581
|
+
type: "text",
|
|
2582
|
+
responseFormat: { type: "text" },
|
|
2583
|
+
async parsePartial({ text: text2 }) {
|
|
2584
|
+
return { partial: text2 };
|
|
2585
|
+
},
|
|
2586
|
+
async parseOutput({ text: text2 }) {
|
|
2587
|
+
return text2;
|
|
2588
|
+
}
|
|
2589
|
+
});
|
|
2590
|
+
var object = ({
|
|
2591
|
+
schema: inputSchema
|
|
2592
|
+
}) => {
|
|
2593
|
+
const schema = asSchema(inputSchema);
|
|
2594
|
+
return {
|
|
2595
|
+
type: "object",
|
|
2596
|
+
responseFormat: {
|
|
2597
|
+
type: "json",
|
|
2598
|
+
schema: schema.jsonSchema
|
|
2599
|
+
},
|
|
2600
|
+
async parsePartial({ text: text2 }) {
|
|
2601
|
+
const result = await parsePartialJson(text2);
|
|
2602
|
+
switch (result.state) {
|
|
2603
|
+
case "failed-parse":
|
|
2604
|
+
case "undefined-input":
|
|
2605
|
+
return void 0;
|
|
2606
|
+
case "repaired-parse":
|
|
2607
|
+
case "successful-parse":
|
|
2608
|
+
return {
|
|
2609
|
+
// Note: currently no validation of partial results:
|
|
2610
|
+
partial: result.value
|
|
2611
|
+
};
|
|
2612
|
+
default: {
|
|
2613
|
+
const _exhaustiveCheck = result.state;
|
|
2614
|
+
throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
|
|
2615
|
+
}
|
|
2616
|
+
}
|
|
2617
|
+
},
|
|
2618
|
+
async parseOutput({ text: text2 }, context) {
|
|
2619
|
+
const parseResult = await safeParseJSON({ text: text2 });
|
|
2620
|
+
if (!parseResult.success) {
|
|
2621
|
+
throw new NoObjectGeneratedError({
|
|
2622
|
+
message: "No object generated: could not parse the response.",
|
|
2623
|
+
cause: parseResult.error,
|
|
2624
|
+
text: text2,
|
|
2625
|
+
response: context.response,
|
|
2626
|
+
usage: context.usage,
|
|
2627
|
+
finishReason: context.finishReason
|
|
2628
|
+
});
|
|
2629
|
+
}
|
|
2630
|
+
const validationResult = await safeValidateTypes({
|
|
2631
|
+
value: parseResult.value,
|
|
2632
|
+
schema
|
|
2633
|
+
});
|
|
2634
|
+
if (!validationResult.success) {
|
|
2635
|
+
throw new NoObjectGeneratedError({
|
|
2636
|
+
message: "No object generated: response did not match schema.",
|
|
2637
|
+
cause: validationResult.error,
|
|
2638
|
+
text: text2,
|
|
2639
|
+
response: context.response,
|
|
2640
|
+
usage: context.usage,
|
|
2641
|
+
finishReason: context.finishReason
|
|
2642
|
+
});
|
|
2643
|
+
}
|
|
2644
|
+
return validationResult.value;
|
|
2645
|
+
}
|
|
2646
|
+
};
|
|
2647
|
+
};
|
|
2648
|
+
var wrapLanguageModel = ({
|
|
2649
|
+
model,
|
|
2650
|
+
middleware: middlewareArg,
|
|
2651
|
+
modelId,
|
|
2652
|
+
providerId
|
|
2653
|
+
}) => {
|
|
2654
|
+
return asArray(middlewareArg).reverse().reduce((wrappedModel, middleware) => {
|
|
2655
|
+
return doWrap({ model: wrappedModel, middleware, modelId, providerId });
|
|
2656
|
+
}, model);
|
|
2657
|
+
};
|
|
2658
|
+
var doWrap = ({
|
|
2659
|
+
model,
|
|
2660
|
+
middleware: {
|
|
2661
|
+
transformParams,
|
|
2662
|
+
wrapGenerate,
|
|
2663
|
+
wrapStream,
|
|
2664
|
+
overrideProvider,
|
|
2665
|
+
overrideModelId,
|
|
2666
|
+
overrideSupportedUrls
|
|
2667
|
+
},
|
|
2668
|
+
modelId,
|
|
2669
|
+
providerId
|
|
2670
|
+
}) => {
|
|
2671
|
+
var _a17, _b, _c;
|
|
2672
|
+
async function doTransform({
|
|
2673
|
+
params,
|
|
2674
|
+
type
|
|
2675
|
+
}) {
|
|
2676
|
+
return transformParams ? await transformParams({ params, type, model }) : params;
|
|
2677
|
+
}
|
|
2678
|
+
return {
|
|
2679
|
+
specificationVersion: "v2",
|
|
2680
|
+
provider: (_a17 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a17 : model.provider,
|
|
2681
|
+
modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,
|
|
2682
|
+
supportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,
|
|
2683
|
+
async doGenerate(params) {
|
|
2684
|
+
const transformedParams = await doTransform({ params, type: "generate" });
|
|
2685
|
+
const doGenerate = async () => model.doGenerate(transformedParams);
|
|
2686
|
+
const doStream = async () => model.doStream(transformedParams);
|
|
2687
|
+
return wrapGenerate ? wrapGenerate({
|
|
2688
|
+
doGenerate,
|
|
2689
|
+
doStream,
|
|
2690
|
+
params: transformedParams,
|
|
2691
|
+
model
|
|
2692
|
+
}) : doGenerate();
|
|
2693
|
+
},
|
|
2694
|
+
async doStream(params) {
|
|
2695
|
+
const transformedParams = await doTransform({ params, type: "stream" });
|
|
2696
|
+
const doGenerate = async () => model.doGenerate(transformedParams);
|
|
2697
|
+
const doStream = async () => model.doStream(transformedParams);
|
|
2698
|
+
return wrapStream ? wrapStream({ doGenerate, doStream, params: transformedParams, model }) : doStream();
|
|
2699
|
+
}
|
|
2700
|
+
};
|
|
2701
|
+
};
|
|
2702
|
+
var ClientOrServerImplementationSchema = z.looseObject({
|
|
2703
|
+
name: z.string(),
|
|
2704
|
+
version: z.string()
|
|
2705
|
+
});
|
|
2706
|
+
var BaseParamsSchema = z.looseObject({
|
|
2707
|
+
_meta: z.optional(z.object({}).loose())
|
|
2708
|
+
});
|
|
2709
|
+
var ResultSchema = BaseParamsSchema;
|
|
2710
|
+
var RequestSchema = z.object({
|
|
2711
|
+
method: z.string(),
|
|
2712
|
+
params: z.optional(BaseParamsSchema)
|
|
2713
|
+
});
|
|
2714
|
+
var ServerCapabilitiesSchema = z.looseObject({
|
|
2715
|
+
experimental: z.optional(z.object({}).loose()),
|
|
2716
|
+
logging: z.optional(z.object({}).loose()),
|
|
2717
|
+
prompts: z.optional(
|
|
2718
|
+
z.looseObject({
|
|
2719
|
+
listChanged: z.optional(z.boolean())
|
|
2720
|
+
})
|
|
2721
|
+
),
|
|
2722
|
+
resources: z.optional(
|
|
2723
|
+
z.looseObject({
|
|
2724
|
+
subscribe: z.optional(z.boolean()),
|
|
2725
|
+
listChanged: z.optional(z.boolean())
|
|
2726
|
+
})
|
|
2727
|
+
),
|
|
2728
|
+
tools: z.optional(
|
|
2729
|
+
z.looseObject({
|
|
2730
|
+
listChanged: z.optional(z.boolean())
|
|
2731
|
+
})
|
|
2732
|
+
)
|
|
2733
|
+
});
|
|
2734
|
+
ResultSchema.extend({
|
|
2735
|
+
protocolVersion: z.string(),
|
|
2736
|
+
capabilities: ServerCapabilitiesSchema,
|
|
2737
|
+
serverInfo: ClientOrServerImplementationSchema,
|
|
2738
|
+
instructions: z.optional(z.string())
|
|
2739
|
+
});
|
|
2740
|
+
var PaginatedResultSchema = ResultSchema.extend({
|
|
2741
|
+
nextCursor: z.optional(z.string())
|
|
2742
|
+
});
|
|
2743
|
+
var ToolSchema = z.object({
|
|
2744
|
+
name: z.string(),
|
|
2745
|
+
description: z.optional(z.string()),
|
|
2746
|
+
inputSchema: z.object({
|
|
2747
|
+
type: z.literal("object"),
|
|
2748
|
+
properties: z.optional(z.object({}).loose())
|
|
2749
|
+
}).loose()
|
|
2750
|
+
}).loose();
|
|
2751
|
+
PaginatedResultSchema.extend({
|
|
2752
|
+
tools: z.array(ToolSchema)
|
|
2753
|
+
});
|
|
2754
|
+
var TextContentSchema = z.object({
|
|
2755
|
+
type: z.literal("text"),
|
|
2756
|
+
text: z.string()
|
|
2757
|
+
}).loose();
|
|
2758
|
+
var ImageContentSchema = z.object({
|
|
2759
|
+
type: z.literal("image"),
|
|
2760
|
+
data: z.base64(),
|
|
2761
|
+
mimeType: z.string()
|
|
2762
|
+
}).loose();
|
|
2763
|
+
var ResourceContentsSchema = z.object({
|
|
2764
|
+
/**
|
|
2765
|
+
* The URI of this resource.
|
|
2766
|
+
*/
|
|
2767
|
+
uri: z.string(),
|
|
2768
|
+
/**
|
|
2769
|
+
* The MIME type of this resource, if known.
|
|
2770
|
+
*/
|
|
2771
|
+
mimeType: z.optional(z.string())
|
|
2772
|
+
}).loose();
|
|
2773
|
+
var TextResourceContentsSchema = ResourceContentsSchema.extend({
|
|
2774
|
+
text: z.string()
|
|
2775
|
+
});
|
|
2776
|
+
var BlobResourceContentsSchema = ResourceContentsSchema.extend({
|
|
2777
|
+
blob: z.base64()
|
|
2778
|
+
});
|
|
2779
|
+
var EmbeddedResourceSchema = z.object({
|
|
2780
|
+
type: z.literal("resource"),
|
|
2781
|
+
resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema])
|
|
2782
|
+
}).loose();
|
|
2783
|
+
ResultSchema.extend({
|
|
2784
|
+
content: z.array(
|
|
2785
|
+
z.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
|
|
2786
|
+
),
|
|
2787
|
+
isError: z.boolean().default(false).optional()
|
|
2788
|
+
}).or(
|
|
2789
|
+
ResultSchema.extend({
|
|
2790
|
+
toolResult: z.unknown()
|
|
2791
|
+
})
|
|
2792
|
+
);
|
|
2793
|
+
var JSONRPC_VERSION = "2.0";
|
|
2794
|
+
var JSONRPCRequestSchema = z.object({
|
|
2795
|
+
jsonrpc: z.literal(JSONRPC_VERSION),
|
|
2796
|
+
id: z.union([z.string(), z.number().int()])
|
|
2797
|
+
}).merge(RequestSchema).strict();
|
|
2798
|
+
var JSONRPCResponseSchema = z.object({
|
|
2799
|
+
jsonrpc: z.literal(JSONRPC_VERSION),
|
|
2800
|
+
id: z.union([z.string(), z.number().int()]),
|
|
2801
|
+
result: ResultSchema
|
|
2802
|
+
}).strict();
|
|
2803
|
+
var JSONRPCErrorSchema = z.object({
|
|
2804
|
+
jsonrpc: z.literal(JSONRPC_VERSION),
|
|
2805
|
+
id: z.union([z.string(), z.number().int()]),
|
|
2806
|
+
error: z.object({
|
|
2807
|
+
code: z.number().int(),
|
|
2808
|
+
message: z.string(),
|
|
2809
|
+
data: z.optional(z.unknown())
|
|
2810
|
+
})
|
|
2811
|
+
}).strict();
|
|
2812
|
+
var JSONRPCNotificationSchema = z.object({
|
|
2813
|
+
jsonrpc: z.literal(JSONRPC_VERSION)
|
|
2814
|
+
}).merge(
|
|
2815
|
+
z.object({
|
|
2816
|
+
method: z.string(),
|
|
2817
|
+
params: z.optional(BaseParamsSchema)
|
|
2818
|
+
})
|
|
2819
|
+
).strict();
|
|
2820
|
+
z.union([
|
|
2821
|
+
JSONRPCRequestSchema,
|
|
2822
|
+
JSONRPCNotificationSchema,
|
|
2823
|
+
JSONRPCResponseSchema,
|
|
2824
|
+
JSONRPCErrorSchema
|
|
2825
|
+
]);
|
|
2826
|
+
function createUIMessageStream({
|
|
2827
|
+
execute,
|
|
2828
|
+
onError = getErrorMessage2,
|
|
2829
|
+
originalMessages,
|
|
2830
|
+
onFinish,
|
|
2831
|
+
generateId: generateId3 = generateId
|
|
2832
|
+
}) {
|
|
2833
|
+
let controller;
|
|
2834
|
+
const ongoingStreamPromises = [];
|
|
2835
|
+
const stream = new ReadableStream({
|
|
2836
|
+
start(controllerArg) {
|
|
2837
|
+
controller = controllerArg;
|
|
2838
|
+
}
|
|
2839
|
+
});
|
|
2840
|
+
function safeEnqueue(data) {
|
|
2841
|
+
try {
|
|
2842
|
+
controller.enqueue(data);
|
|
2843
|
+
} catch (error) {
|
|
2844
|
+
}
|
|
2845
|
+
}
|
|
2846
|
+
try {
|
|
2847
|
+
const result = execute({
|
|
2848
|
+
writer: {
|
|
2849
|
+
write(part) {
|
|
2850
|
+
safeEnqueue(part);
|
|
2851
|
+
},
|
|
2852
|
+
merge(streamArg) {
|
|
2853
|
+
ongoingStreamPromises.push(
|
|
2854
|
+
(async () => {
|
|
2855
|
+
const reader = streamArg.getReader();
|
|
2856
|
+
while (true) {
|
|
2857
|
+
const { done, value } = await reader.read();
|
|
2858
|
+
if (done)
|
|
2859
|
+
break;
|
|
2860
|
+
safeEnqueue(value);
|
|
2861
|
+
}
|
|
2862
|
+
})().catch((error) => {
|
|
2863
|
+
safeEnqueue({
|
|
2864
|
+
type: "error",
|
|
2865
|
+
errorText: onError(error)
|
|
2866
|
+
});
|
|
2867
|
+
})
|
|
2868
|
+
);
|
|
2869
|
+
},
|
|
2870
|
+
onError
|
|
2871
|
+
}
|
|
2872
|
+
});
|
|
2873
|
+
if (result) {
|
|
2874
|
+
ongoingStreamPromises.push(
|
|
2875
|
+
result.catch((error) => {
|
|
2876
|
+
safeEnqueue({
|
|
2877
|
+
type: "error",
|
|
2878
|
+
errorText: onError(error)
|
|
2879
|
+
});
|
|
2880
|
+
})
|
|
2881
|
+
);
|
|
2882
|
+
}
|
|
2883
|
+
} catch (error) {
|
|
2884
|
+
safeEnqueue({
|
|
2885
|
+
type: "error",
|
|
2886
|
+
errorText: onError(error)
|
|
2887
|
+
});
|
|
2888
|
+
}
|
|
2889
|
+
const waitForStreams = new Promise(async (resolve2) => {
|
|
2890
|
+
while (ongoingStreamPromises.length > 0) {
|
|
2891
|
+
await ongoingStreamPromises.shift();
|
|
2892
|
+
}
|
|
2893
|
+
resolve2();
|
|
2894
|
+
});
|
|
2895
|
+
waitForStreams.finally(() => {
|
|
2896
|
+
try {
|
|
2897
|
+
controller.close();
|
|
2898
|
+
} catch (error) {
|
|
2899
|
+
}
|
|
2900
|
+
});
|
|
2901
|
+
return handleUIMessageStreamFinish({
|
|
2902
|
+
stream,
|
|
2903
|
+
messageId: generateId3(),
|
|
2904
|
+
originalMessages,
|
|
2905
|
+
onFinish,
|
|
2906
|
+
onError
|
|
2907
|
+
});
|
|
2908
|
+
}
|
|
9
2909
|
|
|
10
2910
|
// src/utils.ts
|
|
11
2911
|
var isDataChunkType = (chunk) => {
|
|
@@ -62,6 +2962,12 @@ var isWorkflowExecutionDataChunkType = (chunk) => {
|
|
|
62
2962
|
};
|
|
63
2963
|
|
|
64
2964
|
// src/helpers.ts
|
|
2965
|
+
function toAISDKFinishReason(reason) {
|
|
2966
|
+
if (reason === "tripwire" || reason === "retry") {
|
|
2967
|
+
return "other";
|
|
2968
|
+
}
|
|
2969
|
+
return reason;
|
|
2970
|
+
}
|
|
65
2971
|
function convertMastraChunkToAISDKv5({
|
|
66
2972
|
chunk,
|
|
67
2973
|
mode = "stream"
|
|
@@ -69,7 +2975,9 @@ function convertMastraChunkToAISDKv5({
|
|
|
69
2975
|
switch (chunk.type) {
|
|
70
2976
|
case "start":
|
|
71
2977
|
return {
|
|
72
|
-
type: "start"
|
|
2978
|
+
type: "start",
|
|
2979
|
+
// Preserve messageId from the payload so it can be sent to useChat
|
|
2980
|
+
...chunk.payload?.messageId ? { messageId: chunk.payload.messageId } : {}
|
|
73
2981
|
};
|
|
74
2982
|
case "step-start":
|
|
75
2983
|
const { messageId: _messageId, ...rest } = chunk.payload;
|
|
@@ -86,7 +2994,7 @@ function convertMastraChunkToAISDKv5({
|
|
|
86
2994
|
case "finish": {
|
|
87
2995
|
return {
|
|
88
2996
|
type: "finish",
|
|
89
|
-
finishReason: chunk.payload.stepResult.reason,
|
|
2997
|
+
finishReason: toAISDKFinishReason(chunk.payload.stepResult.reason),
|
|
90
2998
|
totalUsage: chunk.payload.output.usage
|
|
91
2999
|
};
|
|
92
3000
|
}
|
|
@@ -225,7 +3133,7 @@ function convertMastraChunkToAISDKv5({
|
|
|
225
3133
|
...rest2
|
|
226
3134
|
},
|
|
227
3135
|
usage: chunk.payload.output.usage,
|
|
228
|
-
finishReason: chunk.payload.stepResult.reason,
|
|
3136
|
+
finishReason: toAISDKFinishReason(chunk.payload.stepResult.reason),
|
|
229
3137
|
providerMetadata
|
|
230
3138
|
};
|
|
231
3139
|
}
|
|
@@ -286,7 +3194,10 @@ function convertMastraChunkToAISDKv5({
|
|
|
286
3194
|
return {
|
|
287
3195
|
type: "data-tripwire",
|
|
288
3196
|
data: {
|
|
289
|
-
|
|
3197
|
+
reason: chunk.payload.reason,
|
|
3198
|
+
retry: chunk.payload.retry,
|
|
3199
|
+
metadata: chunk.payload.metadata,
|
|
3200
|
+
processorId: chunk.payload.processorId
|
|
290
3201
|
}
|
|
291
3202
|
};
|
|
292
3203
|
default:
|
|
@@ -479,10 +3390,11 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
479
3390
|
}
|
|
480
3391
|
case "start": {
|
|
481
3392
|
if (sendStart) {
|
|
3393
|
+
const messageId = ("messageId" in part ? part.messageId : void 0) || responseMessageId;
|
|
482
3394
|
return {
|
|
483
3395
|
type: "start",
|
|
484
3396
|
...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {},
|
|
485
|
-
...
|
|
3397
|
+
...messageId != null ? { messageId } : {}
|
|
486
3398
|
};
|
|
487
3399
|
}
|
|
488
3400
|
return;
|
|
@@ -1260,7 +4172,7 @@ async function handleChatStream({
|
|
|
1260
4172
|
mastra,
|
|
1261
4173
|
agentId,
|
|
1262
4174
|
params,
|
|
1263
|
-
defaultOptions,
|
|
4175
|
+
defaultOptions: defaultOptions2,
|
|
1264
4176
|
sendStart = true,
|
|
1265
4177
|
sendFinish = true,
|
|
1266
4178
|
sendReasoning = false,
|
|
@@ -1278,10 +4190,10 @@ async function handleChatStream({
|
|
|
1278
4190
|
throw new Error("Messages must be an array of UIMessage objects");
|
|
1279
4191
|
}
|
|
1280
4192
|
const mergedOptions = {
|
|
1281
|
-
...
|
|
4193
|
+
...defaultOptions2,
|
|
1282
4194
|
...rest,
|
|
1283
4195
|
...runId && { runId },
|
|
1284
|
-
requestContext: requestContext ||
|
|
4196
|
+
requestContext: requestContext || defaultOptions2?.requestContext
|
|
1285
4197
|
};
|
|
1286
4198
|
const result = resumeData ? await agentObj.resumeStream(resumeData, mergedOptions) : await agentObj.stream(messages, mergedOptions);
|
|
1287
4199
|
let lastMessageId;
|
|
@@ -1310,7 +4222,7 @@ async function handleChatStream({
|
|
|
1310
4222
|
function chatRoute({
|
|
1311
4223
|
path = "/chat/:agentId",
|
|
1312
4224
|
agent,
|
|
1313
|
-
defaultOptions,
|
|
4225
|
+
defaultOptions: defaultOptions2,
|
|
1314
4226
|
sendStart = true,
|
|
1315
4227
|
sendFinish = true,
|
|
1316
4228
|
sendReasoning = false,
|
|
@@ -1434,8 +4346,11 @@ function chatRoute({
|
|
|
1434
4346
|
`Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
|
|
1435
4347
|
);
|
|
1436
4348
|
}
|
|
1437
|
-
|
|
1438
|
-
|
|
4349
|
+
const routeRequestContext = contextRequestContext || defaultOptions2?.requestContext;
|
|
4350
|
+
if (routeRequestContext && params.requestContext) {
|
|
4351
|
+
mastra.getLogger()?.warn(
|
|
4352
|
+
`"requestContext" from the request body will be ignored because "requestContext" is already set in the route options.`
|
|
4353
|
+
);
|
|
1439
4354
|
}
|
|
1440
4355
|
if (!agentToUse) {
|
|
1441
4356
|
throw new Error("Agent ID is required");
|
|
@@ -1447,7 +4362,7 @@ function chatRoute({
|
|
|
1447
4362
|
...params,
|
|
1448
4363
|
requestContext: contextRequestContext || params.requestContext
|
|
1449
4364
|
},
|
|
1450
|
-
defaultOptions,
|
|
4365
|
+
defaultOptions: defaultOptions2,
|
|
1451
4366
|
sendStart,
|
|
1452
4367
|
sendFinish,
|
|
1453
4368
|
sendReasoning,
|
|
@@ -1572,7 +4487,7 @@ async function handleNetworkStream({
|
|
|
1572
4487
|
mastra,
|
|
1573
4488
|
agentId,
|
|
1574
4489
|
params,
|
|
1575
|
-
defaultOptions
|
|
4490
|
+
defaultOptions: defaultOptions2
|
|
1576
4491
|
}) {
|
|
1577
4492
|
const { messages, ...rest } = params;
|
|
1578
4493
|
const agentObj = mastra.getAgentById(agentId);
|
|
@@ -1580,7 +4495,7 @@ async function handleNetworkStream({
|
|
|
1580
4495
|
throw new Error(`Agent ${agentId} not found`);
|
|
1581
4496
|
}
|
|
1582
4497
|
const result = await agentObj.network(messages, {
|
|
1583
|
-
...
|
|
4498
|
+
...defaultOptions2,
|
|
1584
4499
|
...rest
|
|
1585
4500
|
});
|
|
1586
4501
|
return createUIMessageStream({
|
|
@@ -1594,7 +4509,7 @@ async function handleNetworkStream({
|
|
|
1594
4509
|
function networkRoute({
|
|
1595
4510
|
path = "/network/:agentId",
|
|
1596
4511
|
agent,
|
|
1597
|
-
defaultOptions
|
|
4512
|
+
defaultOptions: defaultOptions2
|
|
1598
4513
|
}) {
|
|
1599
4514
|
if (!agent && !path.includes("/:agentId")) {
|
|
1600
4515
|
throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
|
|
@@ -1653,6 +4568,7 @@ function networkRoute({
|
|
|
1653
4568
|
handler: async (c) => {
|
|
1654
4569
|
const params = await c.req.json();
|
|
1655
4570
|
const mastra = c.get("mastra");
|
|
4571
|
+
const contextRequestContext = c.get("requestContext");
|
|
1656
4572
|
let agentToUse = agent;
|
|
1657
4573
|
if (!agent) {
|
|
1658
4574
|
const agentId = c.req.param("agentId");
|
|
@@ -1663,14 +4579,23 @@ function networkRoute({
|
|
|
1663
4579
|
`Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
|
|
1664
4580
|
);
|
|
1665
4581
|
}
|
|
4582
|
+
const routeRequestContext = contextRequestContext || defaultOptions2?.requestContext;
|
|
4583
|
+
if (routeRequestContext && params.requestContext) {
|
|
4584
|
+
mastra.getLogger()?.warn(
|
|
4585
|
+
`"requestContext" from the request body will be ignored because "requestContext" is already set in the route options.`
|
|
4586
|
+
);
|
|
4587
|
+
}
|
|
1666
4588
|
if (!agentToUse) {
|
|
1667
4589
|
throw new Error("Agent ID is required");
|
|
1668
4590
|
}
|
|
1669
4591
|
const uiMessageStream = await handleNetworkStream({
|
|
1670
4592
|
mastra,
|
|
1671
4593
|
agentId: agentToUse,
|
|
1672
|
-
params
|
|
1673
|
-
|
|
4594
|
+
params: {
|
|
4595
|
+
...params,
|
|
4596
|
+
requestContext: routeRequestContext || params.requestContext
|
|
4597
|
+
},
|
|
4598
|
+
defaultOptions: defaultOptions2
|
|
1674
4599
|
});
|
|
1675
4600
|
return createUIMessageStreamResponse({ stream: uiMessageStream });
|
|
1676
4601
|
}
|
|
@@ -2106,7 +5031,7 @@ function convertMastraChunkToAISDKStreamPart(chunk) {
|
|
|
2106
5031
|
const usage = chunk.payload.output?.usage;
|
|
2107
5032
|
return {
|
|
2108
5033
|
type: "finish",
|
|
2109
|
-
finishReason: chunk.payload.stepResult?.reason || "stop",
|
|
5034
|
+
finishReason: toAISDKFinishReason(chunk.payload.stepResult?.reason || "stop"),
|
|
2110
5035
|
usage: usage ? {
|
|
2111
5036
|
inputTokens: usage.inputTokens || 0,
|
|
2112
5037
|
outputTokens: usage.outputTokens || 0,
|