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