@snap-agent/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2227 @@
1
+ // node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/dist/index.mjs
2
+ var marker = "vercel.ai.error";
3
+ var symbol = Symbol.for(marker);
4
+ var _a;
5
+ var _AISDKError = class _AISDKError2 extends Error {
6
+ /**
7
+ * Creates an AI SDK Error.
8
+ *
9
+ * @param {Object} params - The parameters for creating the error.
10
+ * @param {string} params.name - The name of the error.
11
+ * @param {string} params.message - The error message.
12
+ * @param {unknown} [params.cause] - The underlying cause of the error.
13
+ */
14
+ constructor({
15
+ name: name14,
16
+ message,
17
+ cause
18
+ }) {
19
+ super(message);
20
+ this[_a] = true;
21
+ this.name = name14;
22
+ this.cause = cause;
23
+ }
24
+ /**
25
+ * Checks if the given error is an AI SDK Error.
26
+ * @param {unknown} error - The error to check.
27
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
28
+ */
29
+ static isInstance(error) {
30
+ return _AISDKError2.hasMarker(error, marker);
31
+ }
32
+ static hasMarker(error, marker15) {
33
+ const markerSymbol = Symbol.for(marker15);
34
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
35
+ }
36
+ };
37
+ _a = symbol;
38
+ var AISDKError = _AISDKError;
39
+ var name = "AI_APICallError";
40
+ var marker2 = `vercel.ai.error.${name}`;
41
+ var symbol2 = Symbol.for(marker2);
42
+ var _a2;
43
+ var APICallError = class extends AISDKError {
44
+ constructor({
45
+ message,
46
+ url,
47
+ requestBodyValues,
48
+ statusCode,
49
+ responseHeaders,
50
+ responseBody,
51
+ cause,
52
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
53
+ statusCode === 409 || // conflict
54
+ statusCode === 429 || // too many requests
55
+ statusCode >= 500),
56
+ // server error
57
+ data
58
+ }) {
59
+ super({ name, message, cause });
60
+ this[_a2] = true;
61
+ this.url = url;
62
+ this.requestBodyValues = requestBodyValues;
63
+ this.statusCode = statusCode;
64
+ this.responseHeaders = responseHeaders;
65
+ this.responseBody = responseBody;
66
+ this.isRetryable = isRetryable;
67
+ this.data = data;
68
+ }
69
+ static isInstance(error) {
70
+ return AISDKError.hasMarker(error, marker2);
71
+ }
72
+ };
73
+ _a2 = symbol2;
74
+ var name2 = "AI_EmptyResponseBodyError";
75
+ var marker3 = `vercel.ai.error.${name2}`;
76
+ var symbol3 = Symbol.for(marker3);
77
+ var _a3;
78
+ var EmptyResponseBodyError = class extends AISDKError {
79
+ // used in isInstance
80
+ constructor({ message = "Empty response body" } = {}) {
81
+ super({ name: name2, message });
82
+ this[_a3] = true;
83
+ }
84
+ static isInstance(error) {
85
+ return AISDKError.hasMarker(error, marker3);
86
+ }
87
+ };
88
+ _a3 = symbol3;
89
+ function getErrorMessage(error) {
90
+ if (error == null) {
91
+ return "unknown error";
92
+ }
93
+ if (typeof error === "string") {
94
+ return error;
95
+ }
96
+ if (error instanceof Error) {
97
+ return error.message;
98
+ }
99
+ return JSON.stringify(error);
100
+ }
101
+ var name3 = "AI_InvalidArgumentError";
102
+ var marker4 = `vercel.ai.error.${name3}`;
103
+ var symbol4 = Symbol.for(marker4);
104
+ var _a4;
105
+ var InvalidArgumentError = class extends AISDKError {
106
+ constructor({
107
+ message,
108
+ cause,
109
+ argument
110
+ }) {
111
+ super({ name: name3, message, cause });
112
+ this[_a4] = true;
113
+ this.argument = argument;
114
+ }
115
+ static isInstance(error) {
116
+ return AISDKError.hasMarker(error, marker4);
117
+ }
118
+ };
119
+ _a4 = symbol4;
120
+ var name4 = "AI_InvalidPromptError";
121
+ var marker5 = `vercel.ai.error.${name4}`;
122
+ var symbol5 = Symbol.for(marker5);
123
+ var _a5;
124
+ _a5 = symbol5;
125
+ var name5 = "AI_InvalidResponseDataError";
126
+ var marker6 = `vercel.ai.error.${name5}`;
127
+ var symbol6 = Symbol.for(marker6);
128
+ var _a6;
129
+ _a6 = symbol6;
130
+ var name6 = "AI_JSONParseError";
131
+ var marker7 = `vercel.ai.error.${name6}`;
132
+ var symbol7 = Symbol.for(marker7);
133
+ var _a7;
134
+ var JSONParseError = class extends AISDKError {
135
+ constructor({ text, cause }) {
136
+ super({
137
+ name: name6,
138
+ message: `JSON parsing failed: Text: ${text}.
139
+ Error message: ${getErrorMessage(cause)}`,
140
+ cause
141
+ });
142
+ this[_a7] = true;
143
+ this.text = text;
144
+ }
145
+ static isInstance(error) {
146
+ return AISDKError.hasMarker(error, marker7);
147
+ }
148
+ };
149
+ _a7 = symbol7;
150
+ var name7 = "AI_LoadAPIKeyError";
151
+ var marker8 = `vercel.ai.error.${name7}`;
152
+ var symbol8 = Symbol.for(marker8);
153
+ var _a8;
154
+ var LoadAPIKeyError = class extends AISDKError {
155
+ // used in isInstance
156
+ constructor({ message }) {
157
+ super({ name: name7, message });
158
+ this[_a8] = true;
159
+ }
160
+ static isInstance(error) {
161
+ return AISDKError.hasMarker(error, marker8);
162
+ }
163
+ };
164
+ _a8 = symbol8;
165
+ var name8 = "AI_LoadSettingError";
166
+ var marker9 = `vercel.ai.error.${name8}`;
167
+ var symbol9 = Symbol.for(marker9);
168
+ var _a9;
169
+ _a9 = symbol9;
170
+ var name9 = "AI_NoContentGeneratedError";
171
+ var marker10 = `vercel.ai.error.${name9}`;
172
+ var symbol10 = Symbol.for(marker10);
173
+ var _a10;
174
+ _a10 = symbol10;
175
+ var name10 = "AI_NoSuchModelError";
176
+ var marker11 = `vercel.ai.error.${name10}`;
177
+ var symbol11 = Symbol.for(marker11);
178
+ var _a11;
179
+ var NoSuchModelError = class extends AISDKError {
180
+ constructor({
181
+ errorName = name10,
182
+ modelId,
183
+ modelType,
184
+ message = `No such ${modelType}: ${modelId}`
185
+ }) {
186
+ super({ name: errorName, message });
187
+ this[_a11] = true;
188
+ this.modelId = modelId;
189
+ this.modelType = modelType;
190
+ }
191
+ static isInstance(error) {
192
+ return AISDKError.hasMarker(error, marker11);
193
+ }
194
+ };
195
+ _a11 = symbol11;
196
+ var name11 = "AI_TooManyEmbeddingValuesForCallError";
197
+ var marker12 = `vercel.ai.error.${name11}`;
198
+ var symbol12 = Symbol.for(marker12);
199
+ var _a12;
200
+ var TooManyEmbeddingValuesForCallError = class extends AISDKError {
201
+ constructor(options) {
202
+ super({
203
+ name: name11,
204
+ message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`
205
+ });
206
+ this[_a12] = true;
207
+ this.provider = options.provider;
208
+ this.modelId = options.modelId;
209
+ this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
210
+ this.values = options.values;
211
+ }
212
+ static isInstance(error) {
213
+ return AISDKError.hasMarker(error, marker12);
214
+ }
215
+ };
216
+ _a12 = symbol12;
217
+ var name12 = "AI_TypeValidationError";
218
+ var marker13 = `vercel.ai.error.${name12}`;
219
+ var symbol13 = Symbol.for(marker13);
220
+ var _a13;
221
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
222
+ constructor({ value, cause }) {
223
+ super({
224
+ name: name12,
225
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
226
+ Error message: ${getErrorMessage(cause)}`,
227
+ cause
228
+ });
229
+ this[_a13] = true;
230
+ this.value = value;
231
+ }
232
+ static isInstance(error) {
233
+ return AISDKError.hasMarker(error, marker13);
234
+ }
235
+ /**
236
+ * Wraps an error into a TypeValidationError.
237
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
238
+ * Otherwise, it creates a new TypeValidationError.
239
+ *
240
+ * @param {Object} params - The parameters for wrapping the error.
241
+ * @param {unknown} params.value - The value that failed validation.
242
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
243
+ * @returns {TypeValidationError} A TypeValidationError instance.
244
+ */
245
+ static wrap({
246
+ value,
247
+ cause
248
+ }) {
249
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
250
+ }
251
+ };
252
+ _a13 = symbol13;
253
+ var TypeValidationError = _TypeValidationError;
254
+ var name13 = "AI_UnsupportedFunctionalityError";
255
+ var marker14 = `vercel.ai.error.${name13}`;
256
+ var symbol14 = Symbol.for(marker14);
257
+ var _a14;
258
+ var UnsupportedFunctionalityError = class extends AISDKError {
259
+ constructor({
260
+ functionality,
261
+ message = `'${functionality}' functionality not supported.`
262
+ }) {
263
+ super({ name: name13, message });
264
+ this[_a14] = true;
265
+ this.functionality = functionality;
266
+ }
267
+ static isInstance(error) {
268
+ return AISDKError.hasMarker(error, marker14);
269
+ }
270
+ };
271
+ _a14 = symbol14;
272
+
273
+ // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js
274
+ var ParseError = class extends Error {
275
+ constructor(message, options) {
276
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
277
+ }
278
+ };
279
+ function noop(_arg) {
280
+ }
281
+ function createParser(callbacks) {
282
+ if (typeof callbacks == "function")
283
+ throw new TypeError(
284
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
285
+ );
286
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
287
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
288
+ function feed(newChunk) {
289
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
290
+ for (const line of complete)
291
+ parseLine(line);
292
+ incompleteLine = incomplete, isFirstChunk = false;
293
+ }
294
+ function parseLine(line) {
295
+ if (line === "") {
296
+ dispatchEvent();
297
+ return;
298
+ }
299
+ if (line.startsWith(":")) {
300
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
301
+ return;
302
+ }
303
+ const fieldSeparatorIndex = line.indexOf(":");
304
+ if (fieldSeparatorIndex !== -1) {
305
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
306
+ processField(field, value, line);
307
+ return;
308
+ }
309
+ processField(line, "", line);
310
+ }
311
+ function processField(field, value, line) {
312
+ switch (field) {
313
+ case "event":
314
+ eventType = value;
315
+ break;
316
+ case "data":
317
+ data = `${data}${value}
318
+ `;
319
+ break;
320
+ case "id":
321
+ id = value.includes("\0") ? void 0 : value;
322
+ break;
323
+ case "retry":
324
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
325
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
326
+ type: "invalid-retry",
327
+ value,
328
+ line
329
+ })
330
+ );
331
+ break;
332
+ default:
333
+ onError(
334
+ new ParseError(
335
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
336
+ { type: "unknown-field", field, value, line }
337
+ )
338
+ );
339
+ break;
340
+ }
341
+ }
342
+ function dispatchEvent() {
343
+ data.length > 0 && onEvent({
344
+ id,
345
+ event: eventType || void 0,
346
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
347
+ // then remove the last character from the data buffer.
348
+ data: data.endsWith(`
349
+ `) ? data.slice(0, -1) : data
350
+ }), id = void 0, data = "", eventType = "";
351
+ }
352
+ function reset(options = {}) {
353
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
354
+ }
355
+ return { feed, reset };
356
+ }
357
+ function splitLines(chunk) {
358
+ const lines = [];
359
+ let incompleteLine = "", searchIndex = 0;
360
+ for (; searchIndex < chunk.length; ) {
361
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
362
+ `, searchIndex);
363
+ let lineEnd = -1;
364
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
365
+ incompleteLine = chunk.slice(searchIndex);
366
+ break;
367
+ } else {
368
+ const line = chunk.slice(searchIndex, lineEnd);
369
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
370
+ ` && searchIndex++;
371
+ }
372
+ }
373
+ return [lines, incompleteLine];
374
+ }
375
+
376
+ // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js
377
+ var EventSourceParserStream = class extends TransformStream {
378
+ constructor({ onError, onRetry, onComment } = {}) {
379
+ let parser;
380
+ super({
381
+ start(controller) {
382
+ parser = createParser({
383
+ onEvent: (event) => {
384
+ controller.enqueue(event);
385
+ },
386
+ onError(error) {
387
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
388
+ },
389
+ onRetry,
390
+ onComment
391
+ });
392
+ },
393
+ transform(chunk) {
394
+ parser.feed(chunk);
395
+ }
396
+ });
397
+ }
398
+ };
399
+
400
+ // node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
401
+ import * as z4 from "zod/v4";
402
+ import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
403
+ import { ZodFirstPartyTypeKind } from "zod/v3";
404
+ import {
405
+ ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2
406
+ } from "zod/v3";
407
+ function combineHeaders(...headers) {
408
+ return headers.reduce(
409
+ (combinedHeaders, currentHeaders) => ({
410
+ ...combinedHeaders,
411
+ ...currentHeaders != null ? currentHeaders : {}
412
+ }),
413
+ {}
414
+ );
415
+ }
416
+ function extractResponseHeaders(response) {
417
+ return Object.fromEntries([...response.headers]);
418
+ }
419
+ var createIdGenerator = ({
420
+ prefix,
421
+ size = 16,
422
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
423
+ separator = "-"
424
+ } = {}) => {
425
+ const generator = () => {
426
+ const alphabetLength = alphabet.length;
427
+ const chars = new Array(size);
428
+ for (let i = 0; i < size; i++) {
429
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
430
+ }
431
+ return chars.join("");
432
+ };
433
+ if (prefix == null) {
434
+ return generator;
435
+ }
436
+ if (alphabet.includes(separator)) {
437
+ throw new InvalidArgumentError({
438
+ argument: "separator",
439
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
440
+ });
441
+ }
442
+ return () => `${prefix}${separator}${generator()}`;
443
+ };
444
+ var generateId = createIdGenerator();
445
+ function isAbortError(error) {
446
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
447
+ error.name === "TimeoutError");
448
+ }
449
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
450
+ function handleFetchError({
451
+ error,
452
+ url,
453
+ requestBodyValues
454
+ }) {
455
+ if (isAbortError(error)) {
456
+ return error;
457
+ }
458
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
459
+ const cause = error.cause;
460
+ if (cause != null) {
461
+ return new APICallError({
462
+ message: `Cannot connect to API: ${cause.message}`,
463
+ cause,
464
+ url,
465
+ requestBodyValues,
466
+ isRetryable: true
467
+ // retry when network error
468
+ });
469
+ }
470
+ }
471
+ return error;
472
+ }
473
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
474
+ var _a15, _b, _c;
475
+ if (globalThisAny.window) {
476
+ return `runtime/browser`;
477
+ }
478
+ if ((_a15 = globalThisAny.navigator) == null ? void 0 : _a15.userAgent) {
479
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
480
+ }
481
+ if ((_c = (_b = globalThisAny.process) == null ? void 0 : _b.versions) == null ? void 0 : _c.node) {
482
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
483
+ }
484
+ if (globalThisAny.EdgeRuntime) {
485
+ return `runtime/vercel-edge`;
486
+ }
487
+ return "runtime/unknown";
488
+ }
489
+ function normalizeHeaders(headers) {
490
+ if (headers == null) {
491
+ return {};
492
+ }
493
+ const normalized = {};
494
+ if (headers instanceof Headers) {
495
+ headers.forEach((value, key) => {
496
+ normalized[key.toLowerCase()] = value;
497
+ });
498
+ } else {
499
+ if (!Array.isArray(headers)) {
500
+ headers = Object.entries(headers);
501
+ }
502
+ for (const [key, value] of headers) {
503
+ if (value != null) {
504
+ normalized[key.toLowerCase()] = value;
505
+ }
506
+ }
507
+ }
508
+ return normalized;
509
+ }
510
+ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
511
+ const normalizedHeaders = new Headers(normalizeHeaders(headers));
512
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
513
+ normalizedHeaders.set(
514
+ "user-agent",
515
+ [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
516
+ );
517
+ return Object.fromEntries(normalizedHeaders.entries());
518
+ }
519
+ var VERSION = true ? "3.0.19" : "0.0.0-test";
520
+ function loadApiKey({
521
+ apiKey,
522
+ environmentVariableName,
523
+ apiKeyParameterName = "apiKey",
524
+ description
525
+ }) {
526
+ if (typeof apiKey === "string") {
527
+ return apiKey;
528
+ }
529
+ if (apiKey != null) {
530
+ throw new LoadAPIKeyError({
531
+ message: `${description} API key must be a string.`
532
+ });
533
+ }
534
+ if (typeof process === "undefined") {
535
+ throw new LoadAPIKeyError({
536
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
537
+ });
538
+ }
539
+ apiKey = process.env[environmentVariableName];
540
+ if (apiKey == null) {
541
+ throw new LoadAPIKeyError({
542
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
543
+ });
544
+ }
545
+ if (typeof apiKey !== "string") {
546
+ throw new LoadAPIKeyError({
547
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
548
+ });
549
+ }
550
+ return apiKey;
551
+ }
552
+ function loadOptionalSetting({
553
+ settingValue,
554
+ environmentVariableName
555
+ }) {
556
+ if (typeof settingValue === "string") {
557
+ return settingValue;
558
+ }
559
+ if (settingValue != null || typeof process === "undefined") {
560
+ return void 0;
561
+ }
562
+ settingValue = process.env[environmentVariableName];
563
+ if (settingValue == null || typeof settingValue !== "string") {
564
+ return void 0;
565
+ }
566
+ return settingValue;
567
+ }
568
+ var suspectProtoRx = /"__proto__"\s*:/;
569
+ var suspectConstructorRx = /"constructor"\s*:/;
570
+ function _parse(text) {
571
+ const obj = JSON.parse(text);
572
+ if (obj === null || typeof obj !== "object") {
573
+ return obj;
574
+ }
575
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
576
+ return obj;
577
+ }
578
+ return filter(obj);
579
+ }
580
+ function filter(obj) {
581
+ let next = [obj];
582
+ while (next.length) {
583
+ const nodes = next;
584
+ next = [];
585
+ for (const node of nodes) {
586
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
587
+ throw new SyntaxError("Object contains forbidden prototype property");
588
+ }
589
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
590
+ throw new SyntaxError("Object contains forbidden prototype property");
591
+ }
592
+ for (const key in node) {
593
+ const value = node[key];
594
+ if (value && typeof value === "object") {
595
+ next.push(value);
596
+ }
597
+ }
598
+ }
599
+ }
600
+ return obj;
601
+ }
602
+ function secureJsonParse(text) {
603
+ const { stackTraceLimit } = Error;
604
+ try {
605
+ Error.stackTraceLimit = 0;
606
+ } catch (e) {
607
+ return _parse(text);
608
+ }
609
+ try {
610
+ return _parse(text);
611
+ } finally {
612
+ Error.stackTraceLimit = stackTraceLimit;
613
+ }
614
+ }
615
+ var validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
616
+ function validator(validate) {
617
+ return { [validatorSymbol]: true, validate };
618
+ }
619
+ function isValidator(value) {
620
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
621
+ }
622
+ function asValidator(value) {
623
+ return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
624
+ }
625
+ function standardSchemaValidator(standardSchema) {
626
+ return validator(async (value) => {
627
+ const result = await standardSchema["~standard"].validate(value);
628
+ return result.issues == null ? { success: true, value: result.value } : {
629
+ success: false,
630
+ error: new TypeValidationError({
631
+ value,
632
+ cause: result.issues
633
+ })
634
+ };
635
+ });
636
+ }
637
+ async function validateTypes({
638
+ value,
639
+ schema
640
+ }) {
641
+ const result = await safeValidateTypes({ value, schema });
642
+ if (!result.success) {
643
+ throw TypeValidationError.wrap({ value, cause: result.error });
644
+ }
645
+ return result.value;
646
+ }
647
+ async function safeValidateTypes({
648
+ value,
649
+ schema
650
+ }) {
651
+ const validator2 = asValidator(schema);
652
+ try {
653
+ if (validator2.validate == null) {
654
+ return { success: true, value, rawValue: value };
655
+ }
656
+ const result = await validator2.validate(value);
657
+ if (result.success) {
658
+ return { success: true, value: result.value, rawValue: value };
659
+ }
660
+ return {
661
+ success: false,
662
+ error: TypeValidationError.wrap({ value, cause: result.error }),
663
+ rawValue: value
664
+ };
665
+ } catch (error) {
666
+ return {
667
+ success: false,
668
+ error: TypeValidationError.wrap({ value, cause: error }),
669
+ rawValue: value
670
+ };
671
+ }
672
+ }
673
+ async function parseJSON({
674
+ text,
675
+ schema
676
+ }) {
677
+ try {
678
+ const value = secureJsonParse(text);
679
+ if (schema == null) {
680
+ return value;
681
+ }
682
+ return validateTypes({ value, schema });
683
+ } catch (error) {
684
+ if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
685
+ throw error;
686
+ }
687
+ throw new JSONParseError({ text, cause: error });
688
+ }
689
+ }
690
+ async function safeParseJSON({
691
+ text,
692
+ schema
693
+ }) {
694
+ try {
695
+ const value = secureJsonParse(text);
696
+ if (schema == null) {
697
+ return { success: true, value, rawValue: value };
698
+ }
699
+ return await safeValidateTypes({ value, schema });
700
+ } catch (error) {
701
+ return {
702
+ success: false,
703
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
704
+ rawValue: void 0
705
+ };
706
+ }
707
+ }
708
+ function parseJsonEventStream({
709
+ stream,
710
+ schema
711
+ }) {
712
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
713
+ new TransformStream({
714
+ async transform({ data }, controller) {
715
+ if (data === "[DONE]") {
716
+ return;
717
+ }
718
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
719
+ }
720
+ })
721
+ );
722
+ }
723
+ async function parseProviderOptions({
724
+ provider,
725
+ providerOptions,
726
+ schema
727
+ }) {
728
+ if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
729
+ return void 0;
730
+ }
731
+ const parsedProviderOptions = await safeValidateTypes({
732
+ value: providerOptions[provider],
733
+ schema
734
+ });
735
+ if (!parsedProviderOptions.success) {
736
+ throw new InvalidArgumentError({
737
+ argument: "providerOptions",
738
+ message: `invalid ${provider} provider options`,
739
+ cause: parsedProviderOptions.error
740
+ });
741
+ }
742
+ return parsedProviderOptions.value;
743
+ }
744
+ var getOriginalFetch2 = () => globalThis.fetch;
745
+ var postJsonToApi = async ({
746
+ url,
747
+ headers,
748
+ body,
749
+ failedResponseHandler,
750
+ successfulResponseHandler,
751
+ abortSignal,
752
+ fetch
753
+ }) => postToApi({
754
+ url,
755
+ headers: {
756
+ "Content-Type": "application/json",
757
+ ...headers
758
+ },
759
+ body: {
760
+ content: JSON.stringify(body),
761
+ values: body
762
+ },
763
+ failedResponseHandler,
764
+ successfulResponseHandler,
765
+ abortSignal,
766
+ fetch
767
+ });
768
+ var postToApi = async ({
769
+ url,
770
+ headers = {},
771
+ body,
772
+ successfulResponseHandler,
773
+ failedResponseHandler,
774
+ abortSignal,
775
+ fetch = getOriginalFetch2()
776
+ }) => {
777
+ try {
778
+ const response = await fetch(url, {
779
+ method: "POST",
780
+ headers: withUserAgentSuffix(
781
+ headers,
782
+ `ai-sdk/provider-utils/${VERSION}`,
783
+ getRuntimeEnvironmentUserAgent()
784
+ ),
785
+ body: body.content,
786
+ signal: abortSignal
787
+ });
788
+ const responseHeaders = extractResponseHeaders(response);
789
+ if (!response.ok) {
790
+ let errorInformation;
791
+ try {
792
+ errorInformation = await failedResponseHandler({
793
+ response,
794
+ url,
795
+ requestBodyValues: body.values
796
+ });
797
+ } catch (error) {
798
+ if (isAbortError(error) || APICallError.isInstance(error)) {
799
+ throw error;
800
+ }
801
+ throw new APICallError({
802
+ message: "Failed to process error response",
803
+ cause: error,
804
+ statusCode: response.status,
805
+ url,
806
+ responseHeaders,
807
+ requestBodyValues: body.values
808
+ });
809
+ }
810
+ throw errorInformation.value;
811
+ }
812
+ try {
813
+ return await successfulResponseHandler({
814
+ response,
815
+ url,
816
+ requestBodyValues: body.values
817
+ });
818
+ } catch (error) {
819
+ if (error instanceof Error) {
820
+ if (isAbortError(error) || APICallError.isInstance(error)) {
821
+ throw error;
822
+ }
823
+ }
824
+ throw new APICallError({
825
+ message: "Failed to process successful response",
826
+ cause: error,
827
+ statusCode: response.status,
828
+ url,
829
+ responseHeaders,
830
+ requestBodyValues: body.values
831
+ });
832
+ }
833
+ } catch (error) {
834
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
835
+ }
836
+ };
837
+ function tool(tool2) {
838
+ return tool2;
839
+ }
840
+ function createProviderDefinedToolFactory({
841
+ id,
842
+ name: name14,
843
+ inputSchema
844
+ }) {
845
+ return ({
846
+ execute,
847
+ outputSchema,
848
+ toModelOutput,
849
+ onInputStart,
850
+ onInputDelta,
851
+ onInputAvailable,
852
+ ...args
853
+ }) => tool({
854
+ type: "provider-defined",
855
+ id,
856
+ name: name14,
857
+ args,
858
+ inputSchema,
859
+ outputSchema,
860
+ execute,
861
+ toModelOutput,
862
+ onInputStart,
863
+ onInputDelta,
864
+ onInputAvailable
865
+ });
866
+ }
867
+ function createProviderDefinedToolFactoryWithOutputSchema({
868
+ id,
869
+ name: name14,
870
+ inputSchema,
871
+ outputSchema
872
+ }) {
873
+ return ({
874
+ execute,
875
+ toModelOutput,
876
+ onInputStart,
877
+ onInputDelta,
878
+ onInputAvailable,
879
+ ...args
880
+ }) => tool({
881
+ type: "provider-defined",
882
+ id,
883
+ name: name14,
884
+ args,
885
+ inputSchema,
886
+ outputSchema,
887
+ execute,
888
+ toModelOutput,
889
+ onInputStart,
890
+ onInputDelta,
891
+ onInputAvailable
892
+ });
893
+ }
894
+ async function resolve(value) {
895
+ if (typeof value === "function") {
896
+ value = value();
897
+ }
898
+ return Promise.resolve(value);
899
+ }
900
+ var createJsonErrorResponseHandler = ({
901
+ errorSchema,
902
+ errorToMessage,
903
+ isRetryable
904
+ }) => async ({ response, url, requestBodyValues }) => {
905
+ const responseBody = await response.text();
906
+ const responseHeaders = extractResponseHeaders(response);
907
+ if (responseBody.trim() === "") {
908
+ return {
909
+ responseHeaders,
910
+ value: new APICallError({
911
+ message: response.statusText,
912
+ url,
913
+ requestBodyValues,
914
+ statusCode: response.status,
915
+ responseHeaders,
916
+ responseBody,
917
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
918
+ })
919
+ };
920
+ }
921
+ try {
922
+ const parsedError = await parseJSON({
923
+ text: responseBody,
924
+ schema: errorSchema
925
+ });
926
+ return {
927
+ responseHeaders,
928
+ value: new APICallError({
929
+ message: errorToMessage(parsedError),
930
+ url,
931
+ requestBodyValues,
932
+ statusCode: response.status,
933
+ responseHeaders,
934
+ responseBody,
935
+ data: parsedError,
936
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
937
+ })
938
+ };
939
+ } catch (parseError) {
940
+ return {
941
+ responseHeaders,
942
+ value: new APICallError({
943
+ message: response.statusText,
944
+ url,
945
+ requestBodyValues,
946
+ statusCode: response.status,
947
+ responseHeaders,
948
+ responseBody,
949
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
950
+ })
951
+ };
952
+ }
953
+ };
954
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
955
+ const responseHeaders = extractResponseHeaders(response);
956
+ if (response.body == null) {
957
+ throw new EmptyResponseBodyError({});
958
+ }
959
+ return {
960
+ responseHeaders,
961
+ value: parseJsonEventStream({
962
+ stream: response.body,
963
+ schema: chunkSchema
964
+ })
965
+ };
966
+ };
967
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
968
+ const responseBody = await response.text();
969
+ const parsedResult = await safeParseJSON({
970
+ text: responseBody,
971
+ schema: responseSchema
972
+ });
973
+ const responseHeaders = extractResponseHeaders(response);
974
+ if (!parsedResult.success) {
975
+ throw new APICallError({
976
+ message: "Invalid JSON response",
977
+ cause: parsedResult.error,
978
+ statusCode: response.status,
979
+ responseHeaders,
980
+ responseBody,
981
+ url,
982
+ requestBodyValues
983
+ });
984
+ }
985
+ return {
986
+ responseHeaders,
987
+ value: parsedResult.value,
988
+ rawValue: parsedResult.rawValue
989
+ };
990
+ };
991
+ function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
992
+ if (jsonSchema2.type === "object") {
993
+ jsonSchema2.additionalProperties = false;
994
+ const properties = jsonSchema2.properties;
995
+ if (properties != null) {
996
+ for (const property in properties) {
997
+ properties[property] = addAdditionalPropertiesToJsonSchema(
998
+ properties[property]
999
+ );
1000
+ }
1001
+ }
1002
+ }
1003
+ if (jsonSchema2.type === "array" && jsonSchema2.items != null) {
1004
+ if (Array.isArray(jsonSchema2.items)) {
1005
+ jsonSchema2.items = jsonSchema2.items.map(
1006
+ (item) => addAdditionalPropertiesToJsonSchema(item)
1007
+ );
1008
+ } else {
1009
+ jsonSchema2.items = addAdditionalPropertiesToJsonSchema(
1010
+ jsonSchema2.items
1011
+ );
1012
+ }
1013
+ }
1014
+ return jsonSchema2;
1015
+ }
1016
+ var getRelativePath = (pathA, pathB) => {
1017
+ let i = 0;
1018
+ for (; i < pathA.length && i < pathB.length; i++) {
1019
+ if (pathA[i] !== pathB[i]) break;
1020
+ }
1021
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1022
+ };
1023
+ var ignoreOverride = /* @__PURE__ */ Symbol(
1024
+ "Let zodToJsonSchema decide on which parser to use"
1025
+ );
1026
+ var defaultOptions = {
1027
+ name: void 0,
1028
+ $refStrategy: "root",
1029
+ basePath: ["#"],
1030
+ effectStrategy: "input",
1031
+ pipeStrategy: "all",
1032
+ dateStrategy: "format:date-time",
1033
+ mapStrategy: "entries",
1034
+ removeAdditionalStrategy: "passthrough",
1035
+ allowedAdditionalProperties: true,
1036
+ rejectedAdditionalProperties: false,
1037
+ definitionPath: "definitions",
1038
+ strictUnions: false,
1039
+ definitions: {},
1040
+ errorMessages: false,
1041
+ patternStrategy: "escape",
1042
+ applyRegexFlags: false,
1043
+ emailStrategy: "format:email",
1044
+ base64Strategy: "contentEncoding:base64",
1045
+ nameStrategy: "ref"
1046
+ };
1047
+ var getDefaultOptions = (options) => typeof options === "string" ? {
1048
+ ...defaultOptions,
1049
+ name: options
1050
+ } : {
1051
+ ...defaultOptions,
1052
+ ...options
1053
+ };
1054
+ function parseAnyDef() {
1055
+ return {};
1056
+ }
1057
+ function parseArrayDef(def, refs) {
1058
+ var _a15, _b, _c;
1059
+ const res = {
1060
+ type: "array"
1061
+ };
1062
+ if (((_a15 = def.type) == null ? void 0 : _a15._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
1063
+ res.items = parseDef(def.type._def, {
1064
+ ...refs,
1065
+ currentPath: [...refs.currentPath, "items"]
1066
+ });
1067
+ }
1068
+ if (def.minLength) {
1069
+ res.minItems = def.minLength.value;
1070
+ }
1071
+ if (def.maxLength) {
1072
+ res.maxItems = def.maxLength.value;
1073
+ }
1074
+ if (def.exactLength) {
1075
+ res.minItems = def.exactLength.value;
1076
+ res.maxItems = def.exactLength.value;
1077
+ }
1078
+ return res;
1079
+ }
1080
+ function parseBigintDef(def) {
1081
+ const res = {
1082
+ type: "integer",
1083
+ format: "int64"
1084
+ };
1085
+ if (!def.checks) return res;
1086
+ for (const check of def.checks) {
1087
+ switch (check.kind) {
1088
+ case "min":
1089
+ if (check.inclusive) {
1090
+ res.minimum = check.value;
1091
+ } else {
1092
+ res.exclusiveMinimum = check.value;
1093
+ }
1094
+ break;
1095
+ case "max":
1096
+ if (check.inclusive) {
1097
+ res.maximum = check.value;
1098
+ } else {
1099
+ res.exclusiveMaximum = check.value;
1100
+ }
1101
+ break;
1102
+ case "multipleOf":
1103
+ res.multipleOf = check.value;
1104
+ break;
1105
+ }
1106
+ }
1107
+ return res;
1108
+ }
1109
+ function parseBooleanDef() {
1110
+ return { type: "boolean" };
1111
+ }
1112
+ function parseBrandedDef(_def, refs) {
1113
+ return parseDef(_def.type._def, refs);
1114
+ }
1115
+ var parseCatchDef = (def, refs) => {
1116
+ return parseDef(def.innerType._def, refs);
1117
+ };
1118
+ function parseDateDef(def, refs, overrideDateStrategy) {
1119
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
1120
+ if (Array.isArray(strategy)) {
1121
+ return {
1122
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
1123
+ };
1124
+ }
1125
+ switch (strategy) {
1126
+ case "string":
1127
+ case "format:date-time":
1128
+ return {
1129
+ type: "string",
1130
+ format: "date-time"
1131
+ };
1132
+ case "format:date":
1133
+ return {
1134
+ type: "string",
1135
+ format: "date"
1136
+ };
1137
+ case "integer":
1138
+ return integerDateParser(def);
1139
+ }
1140
+ }
1141
+ var integerDateParser = (def) => {
1142
+ const res = {
1143
+ type: "integer",
1144
+ format: "unix-time"
1145
+ };
1146
+ for (const check of def.checks) {
1147
+ switch (check.kind) {
1148
+ case "min":
1149
+ res.minimum = check.value;
1150
+ break;
1151
+ case "max":
1152
+ res.maximum = check.value;
1153
+ break;
1154
+ }
1155
+ }
1156
+ return res;
1157
+ };
1158
+ function parseDefaultDef(_def, refs) {
1159
+ return {
1160
+ ...parseDef(_def.innerType._def, refs),
1161
+ default: _def.defaultValue()
1162
+ };
1163
+ }
1164
+ function parseEffectsDef(_def, refs) {
1165
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
1166
+ }
1167
+ function parseEnumDef(def) {
1168
+ return {
1169
+ type: "string",
1170
+ enum: Array.from(def.values)
1171
+ };
1172
+ }
1173
+ var isJsonSchema7AllOfType = (type) => {
1174
+ if ("type" in type && type.type === "string") return false;
1175
+ return "allOf" in type;
1176
+ };
1177
+ function parseIntersectionDef(def, refs) {
1178
+ const allOf = [
1179
+ parseDef(def.left._def, {
1180
+ ...refs,
1181
+ currentPath: [...refs.currentPath, "allOf", "0"]
1182
+ }),
1183
+ parseDef(def.right._def, {
1184
+ ...refs,
1185
+ currentPath: [...refs.currentPath, "allOf", "1"]
1186
+ })
1187
+ ].filter((x) => !!x);
1188
+ const mergedAllOf = [];
1189
+ allOf.forEach((schema) => {
1190
+ if (isJsonSchema7AllOfType(schema)) {
1191
+ mergedAllOf.push(...schema.allOf);
1192
+ } else {
1193
+ let nestedSchema = schema;
1194
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
1195
+ const { additionalProperties, ...rest } = schema;
1196
+ nestedSchema = rest;
1197
+ }
1198
+ mergedAllOf.push(nestedSchema);
1199
+ }
1200
+ });
1201
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
1202
+ }
1203
+ function parseLiteralDef(def) {
1204
+ const parsedType = typeof def.value;
1205
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
1206
+ return {
1207
+ type: Array.isArray(def.value) ? "array" : "object"
1208
+ };
1209
+ }
1210
+ return {
1211
+ type: parsedType === "bigint" ? "integer" : parsedType,
1212
+ const: def.value
1213
+ };
1214
+ }
1215
+ var emojiRegex = void 0;
1216
+ var zodPatterns = {
1217
+ /**
1218
+ * `c` was changed to `[cC]` to replicate /i flag
1219
+ */
1220
+ cuid: /^[cC][^\s-]{8,}$/,
1221
+ cuid2: /^[0-9a-z]+$/,
1222
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
1223
+ /**
1224
+ * `a-z` was added to replicate /i flag
1225
+ */
1226
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1227
+ /**
1228
+ * Constructed a valid Unicode RegExp
1229
+ *
1230
+ * Lazily instantiate since this type of regex isn't supported
1231
+ * in all envs (e.g. React Native).
1232
+ *
1233
+ * See:
1234
+ * https://github.com/colinhacks/zod/issues/2433
1235
+ * Fix in Zod:
1236
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
1237
+ */
1238
+ emoji: () => {
1239
+ if (emojiRegex === void 0) {
1240
+ emojiRegex = RegExp(
1241
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
1242
+ "u"
1243
+ );
1244
+ }
1245
+ return emojiRegex;
1246
+ },
1247
+ /**
1248
+ * Unused
1249
+ */
1250
+ 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}$/,
1251
+ /**
1252
+ * Unused
1253
+ */
1254
+ 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])$/,
1255
+ 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])$/,
1256
+ /**
1257
+ * Unused
1258
+ */
1259
+ 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})))$/,
1260
+ 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])$/,
1261
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1262
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1263
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
1264
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1265
+ };
1266
+ function parseStringDef(def, refs) {
1267
+ const res = {
1268
+ type: "string"
1269
+ };
1270
+ if (def.checks) {
1271
+ for (const check of def.checks) {
1272
+ switch (check.kind) {
1273
+ case "min":
1274
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1275
+ break;
1276
+ case "max":
1277
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1278
+ break;
1279
+ case "email":
1280
+ switch (refs.emailStrategy) {
1281
+ case "format:email":
1282
+ addFormat(res, "email", check.message, refs);
1283
+ break;
1284
+ case "format:idn-email":
1285
+ addFormat(res, "idn-email", check.message, refs);
1286
+ break;
1287
+ case "pattern:zod":
1288
+ addPattern(res, zodPatterns.email, check.message, refs);
1289
+ break;
1290
+ }
1291
+ break;
1292
+ case "url":
1293
+ addFormat(res, "uri", check.message, refs);
1294
+ break;
1295
+ case "uuid":
1296
+ addFormat(res, "uuid", check.message, refs);
1297
+ break;
1298
+ case "regex":
1299
+ addPattern(res, check.regex, check.message, refs);
1300
+ break;
1301
+ case "cuid":
1302
+ addPattern(res, zodPatterns.cuid, check.message, refs);
1303
+ break;
1304
+ case "cuid2":
1305
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
1306
+ break;
1307
+ case "startsWith":
1308
+ addPattern(
1309
+ res,
1310
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
1311
+ check.message,
1312
+ refs
1313
+ );
1314
+ break;
1315
+ case "endsWith":
1316
+ addPattern(
1317
+ res,
1318
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
1319
+ check.message,
1320
+ refs
1321
+ );
1322
+ break;
1323
+ case "datetime":
1324
+ addFormat(res, "date-time", check.message, refs);
1325
+ break;
1326
+ case "date":
1327
+ addFormat(res, "date", check.message, refs);
1328
+ break;
1329
+ case "time":
1330
+ addFormat(res, "time", check.message, refs);
1331
+ break;
1332
+ case "duration":
1333
+ addFormat(res, "duration", check.message, refs);
1334
+ break;
1335
+ case "length":
1336
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1337
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1338
+ break;
1339
+ case "includes": {
1340
+ addPattern(
1341
+ res,
1342
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
1343
+ check.message,
1344
+ refs
1345
+ );
1346
+ break;
1347
+ }
1348
+ case "ip": {
1349
+ if (check.version !== "v6") {
1350
+ addFormat(res, "ipv4", check.message, refs);
1351
+ }
1352
+ if (check.version !== "v4") {
1353
+ addFormat(res, "ipv6", check.message, refs);
1354
+ }
1355
+ break;
1356
+ }
1357
+ case "base64url":
1358
+ addPattern(res, zodPatterns.base64url, check.message, refs);
1359
+ break;
1360
+ case "jwt":
1361
+ addPattern(res, zodPatterns.jwt, check.message, refs);
1362
+ break;
1363
+ case "cidr": {
1364
+ if (check.version !== "v6") {
1365
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1366
+ }
1367
+ if (check.version !== "v4") {
1368
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1369
+ }
1370
+ break;
1371
+ }
1372
+ case "emoji":
1373
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
1374
+ break;
1375
+ case "ulid": {
1376
+ addPattern(res, zodPatterns.ulid, check.message, refs);
1377
+ break;
1378
+ }
1379
+ case "base64": {
1380
+ switch (refs.base64Strategy) {
1381
+ case "format:binary": {
1382
+ addFormat(res, "binary", check.message, refs);
1383
+ break;
1384
+ }
1385
+ case "contentEncoding:base64": {
1386
+ res.contentEncoding = "base64";
1387
+ break;
1388
+ }
1389
+ case "pattern:zod": {
1390
+ addPattern(res, zodPatterns.base64, check.message, refs);
1391
+ break;
1392
+ }
1393
+ }
1394
+ break;
1395
+ }
1396
+ case "nanoid": {
1397
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
1398
+ }
1399
+ case "toLowerCase":
1400
+ case "toUpperCase":
1401
+ case "trim":
1402
+ break;
1403
+ default:
1404
+ /* @__PURE__ */ ((_) => {
1405
+ })(check);
1406
+ }
1407
+ }
1408
+ }
1409
+ return res;
1410
+ }
1411
+ function escapeLiteralCheckValue(literal, refs) {
1412
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1413
+ }
1414
+ var ALPHA_NUMERIC = new Set(
1415
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1416
+ );
1417
+ function escapeNonAlphaNumeric(source) {
1418
+ let result = "";
1419
+ for (let i = 0; i < source.length; i++) {
1420
+ if (!ALPHA_NUMERIC.has(source[i])) {
1421
+ result += "\\";
1422
+ }
1423
+ result += source[i];
1424
+ }
1425
+ return result;
1426
+ }
1427
+ function addFormat(schema, value, message, refs) {
1428
+ var _a15;
1429
+ if (schema.format || ((_a15 = schema.anyOf) == null ? void 0 : _a15.some((x) => x.format))) {
1430
+ if (!schema.anyOf) {
1431
+ schema.anyOf = [];
1432
+ }
1433
+ if (schema.format) {
1434
+ schema.anyOf.push({
1435
+ format: schema.format
1436
+ });
1437
+ delete schema.format;
1438
+ }
1439
+ schema.anyOf.push({
1440
+ format: value,
1441
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
1442
+ });
1443
+ } else {
1444
+ schema.format = value;
1445
+ }
1446
+ }
1447
+ function addPattern(schema, regex, message, refs) {
1448
+ var _a15;
1449
+ if (schema.pattern || ((_a15 = schema.allOf) == null ? void 0 : _a15.some((x) => x.pattern))) {
1450
+ if (!schema.allOf) {
1451
+ schema.allOf = [];
1452
+ }
1453
+ if (schema.pattern) {
1454
+ schema.allOf.push({
1455
+ pattern: schema.pattern
1456
+ });
1457
+ delete schema.pattern;
1458
+ }
1459
+ schema.allOf.push({
1460
+ pattern: stringifyRegExpWithFlags(regex, refs),
1461
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
1462
+ });
1463
+ } else {
1464
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
1465
+ }
1466
+ }
1467
+ function stringifyRegExpWithFlags(regex, refs) {
1468
+ var _a15;
1469
+ if (!refs.applyRegexFlags || !regex.flags) {
1470
+ return regex.source;
1471
+ }
1472
+ const flags = {
1473
+ i: regex.flags.includes("i"),
1474
+ // Case-insensitive
1475
+ m: regex.flags.includes("m"),
1476
+ // `^` and `$` matches adjacent to newline characters
1477
+ s: regex.flags.includes("s")
1478
+ // `.` matches newlines
1479
+ };
1480
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1481
+ let pattern = "";
1482
+ let isEscaped = false;
1483
+ let inCharGroup = false;
1484
+ let inCharRange = false;
1485
+ for (let i = 0; i < source.length; i++) {
1486
+ if (isEscaped) {
1487
+ pattern += source[i];
1488
+ isEscaped = false;
1489
+ continue;
1490
+ }
1491
+ if (flags.i) {
1492
+ if (inCharGroup) {
1493
+ if (source[i].match(/[a-z]/)) {
1494
+ if (inCharRange) {
1495
+ pattern += source[i];
1496
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1497
+ inCharRange = false;
1498
+ } else if (source[i + 1] === "-" && ((_a15 = source[i + 2]) == null ? void 0 : _a15.match(/[a-z]/))) {
1499
+ pattern += source[i];
1500
+ inCharRange = true;
1501
+ } else {
1502
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1503
+ }
1504
+ continue;
1505
+ }
1506
+ } else if (source[i].match(/[a-z]/)) {
1507
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1508
+ continue;
1509
+ }
1510
+ }
1511
+ if (flags.m) {
1512
+ if (source[i] === "^") {
1513
+ pattern += `(^|(?<=[\r
1514
+ ]))`;
1515
+ continue;
1516
+ } else if (source[i] === "$") {
1517
+ pattern += `($|(?=[\r
1518
+ ]))`;
1519
+ continue;
1520
+ }
1521
+ }
1522
+ if (flags.s && source[i] === ".") {
1523
+ pattern += inCharGroup ? `${source[i]}\r
1524
+ ` : `[${source[i]}\r
1525
+ ]`;
1526
+ continue;
1527
+ }
1528
+ pattern += source[i];
1529
+ if (source[i] === "\\") {
1530
+ isEscaped = true;
1531
+ } else if (inCharGroup && source[i] === "]") {
1532
+ inCharGroup = false;
1533
+ } else if (!inCharGroup && source[i] === "[") {
1534
+ inCharGroup = true;
1535
+ }
1536
+ }
1537
+ try {
1538
+ new RegExp(pattern);
1539
+ } catch (e) {
1540
+ console.warn(
1541
+ `Could not convert regex pattern at ${refs.currentPath.join(
1542
+ "/"
1543
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1544
+ );
1545
+ return regex.source;
1546
+ }
1547
+ return pattern;
1548
+ }
1549
+ function parseRecordDef(def, refs) {
1550
+ var _a15, _b, _c, _d, _e, _f;
1551
+ const schema = {
1552
+ type: "object",
1553
+ additionalProperties: (_a15 = parseDef(def.valueType._def, {
1554
+ ...refs,
1555
+ currentPath: [...refs.currentPath, "additionalProperties"]
1556
+ })) != null ? _a15 : refs.allowedAdditionalProperties
1557
+ };
1558
+ if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1559
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1560
+ return {
1561
+ ...schema,
1562
+ propertyNames: keyType
1563
+ };
1564
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1565
+ return {
1566
+ ...schema,
1567
+ propertyNames: {
1568
+ enum: def.keyType._def.values
1569
+ }
1570
+ };
1571
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1572
+ const { type, ...keyType } = parseBrandedDef(
1573
+ def.keyType._def,
1574
+ refs
1575
+ );
1576
+ return {
1577
+ ...schema,
1578
+ propertyNames: keyType
1579
+ };
1580
+ }
1581
+ return schema;
1582
+ }
1583
+ function parseMapDef(def, refs) {
1584
+ if (refs.mapStrategy === "record") {
1585
+ return parseRecordDef(def, refs);
1586
+ }
1587
+ const keys = parseDef(def.keyType._def, {
1588
+ ...refs,
1589
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1590
+ }) || parseAnyDef();
1591
+ const values = parseDef(def.valueType._def, {
1592
+ ...refs,
1593
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1594
+ }) || parseAnyDef();
1595
+ return {
1596
+ type: "array",
1597
+ maxItems: 125,
1598
+ items: {
1599
+ type: "array",
1600
+ items: [keys, values],
1601
+ minItems: 2,
1602
+ maxItems: 2
1603
+ }
1604
+ };
1605
+ }
1606
+ function parseNativeEnumDef(def) {
1607
+ const object = def.values;
1608
+ const actualKeys = Object.keys(def.values).filter((key) => {
1609
+ return typeof object[object[key]] !== "number";
1610
+ });
1611
+ const actualValues = actualKeys.map((key) => object[key]);
1612
+ const parsedTypes = Array.from(
1613
+ new Set(actualValues.map((values) => typeof values))
1614
+ );
1615
+ return {
1616
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1617
+ enum: actualValues
1618
+ };
1619
+ }
1620
+ function parseNeverDef() {
1621
+ return { not: parseAnyDef() };
1622
+ }
1623
+ function parseNullDef() {
1624
+ return {
1625
+ type: "null"
1626
+ };
1627
+ }
1628
+ var primitiveMappings = {
1629
+ ZodString: "string",
1630
+ ZodNumber: "number",
1631
+ ZodBigInt: "integer",
1632
+ ZodBoolean: "boolean",
1633
+ ZodNull: "null"
1634
+ };
1635
+ function parseUnionDef(def, refs) {
1636
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1637
+ if (options.every(
1638
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1639
+ )) {
1640
+ const types = options.reduce((types2, x) => {
1641
+ const type = primitiveMappings[x._def.typeName];
1642
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1643
+ }, []);
1644
+ return {
1645
+ type: types.length > 1 ? types : types[0]
1646
+ };
1647
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1648
+ const types = options.reduce(
1649
+ (acc, x) => {
1650
+ const type = typeof x._def.value;
1651
+ switch (type) {
1652
+ case "string":
1653
+ case "number":
1654
+ case "boolean":
1655
+ return [...acc, type];
1656
+ case "bigint":
1657
+ return [...acc, "integer"];
1658
+ case "object":
1659
+ if (x._def.value === null) return [...acc, "null"];
1660
+ case "symbol":
1661
+ case "undefined":
1662
+ case "function":
1663
+ default:
1664
+ return acc;
1665
+ }
1666
+ },
1667
+ []
1668
+ );
1669
+ if (types.length === options.length) {
1670
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1671
+ return {
1672
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1673
+ enum: options.reduce(
1674
+ (acc, x) => {
1675
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1676
+ },
1677
+ []
1678
+ )
1679
+ };
1680
+ }
1681
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1682
+ return {
1683
+ type: "string",
1684
+ enum: options.reduce(
1685
+ (acc, x) => [
1686
+ ...acc,
1687
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1688
+ ],
1689
+ []
1690
+ )
1691
+ };
1692
+ }
1693
+ return asAnyOf(def, refs);
1694
+ }
1695
+ var asAnyOf = (def, refs) => {
1696
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1697
+ (x, i) => parseDef(x._def, {
1698
+ ...refs,
1699
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1700
+ })
1701
+ ).filter(
1702
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1703
+ );
1704
+ return anyOf.length ? { anyOf } : void 0;
1705
+ };
1706
+ function parseNullableDef(def, refs) {
1707
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1708
+ def.innerType._def.typeName
1709
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1710
+ return {
1711
+ type: [
1712
+ primitiveMappings[def.innerType._def.typeName],
1713
+ "null"
1714
+ ]
1715
+ };
1716
+ }
1717
+ const base = parseDef(def.innerType._def, {
1718
+ ...refs,
1719
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1720
+ });
1721
+ return base && { anyOf: [base, { type: "null" }] };
1722
+ }
1723
+ function parseNumberDef(def) {
1724
+ const res = {
1725
+ type: "number"
1726
+ };
1727
+ if (!def.checks) return res;
1728
+ for (const check of def.checks) {
1729
+ switch (check.kind) {
1730
+ case "int":
1731
+ res.type = "integer";
1732
+ break;
1733
+ case "min":
1734
+ if (check.inclusive) {
1735
+ res.minimum = check.value;
1736
+ } else {
1737
+ res.exclusiveMinimum = check.value;
1738
+ }
1739
+ break;
1740
+ case "max":
1741
+ if (check.inclusive) {
1742
+ res.maximum = check.value;
1743
+ } else {
1744
+ res.exclusiveMaximum = check.value;
1745
+ }
1746
+ break;
1747
+ case "multipleOf":
1748
+ res.multipleOf = check.value;
1749
+ break;
1750
+ }
1751
+ }
1752
+ return res;
1753
+ }
1754
+ function parseObjectDef(def, refs) {
1755
+ const result = {
1756
+ type: "object",
1757
+ properties: {}
1758
+ };
1759
+ const required = [];
1760
+ const shape = def.shape();
1761
+ for (const propName in shape) {
1762
+ let propDef = shape[propName];
1763
+ if (propDef === void 0 || propDef._def === void 0) {
1764
+ continue;
1765
+ }
1766
+ const propOptional = safeIsOptional(propDef);
1767
+ const parsedDef = parseDef(propDef._def, {
1768
+ ...refs,
1769
+ currentPath: [...refs.currentPath, "properties", propName],
1770
+ propertyPath: [...refs.currentPath, "properties", propName]
1771
+ });
1772
+ if (parsedDef === void 0) {
1773
+ continue;
1774
+ }
1775
+ result.properties[propName] = parsedDef;
1776
+ if (!propOptional) {
1777
+ required.push(propName);
1778
+ }
1779
+ }
1780
+ if (required.length) {
1781
+ result.required = required;
1782
+ }
1783
+ const additionalProperties = decideAdditionalProperties(def, refs);
1784
+ if (additionalProperties !== void 0) {
1785
+ result.additionalProperties = additionalProperties;
1786
+ }
1787
+ return result;
1788
+ }
1789
+ function decideAdditionalProperties(def, refs) {
1790
+ if (def.catchall._def.typeName !== "ZodNever") {
1791
+ return parseDef(def.catchall._def, {
1792
+ ...refs,
1793
+ currentPath: [...refs.currentPath, "additionalProperties"]
1794
+ });
1795
+ }
1796
+ switch (def.unknownKeys) {
1797
+ case "passthrough":
1798
+ return refs.allowedAdditionalProperties;
1799
+ case "strict":
1800
+ return refs.rejectedAdditionalProperties;
1801
+ case "strip":
1802
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1803
+ }
1804
+ }
1805
+ function safeIsOptional(schema) {
1806
+ try {
1807
+ return schema.isOptional();
1808
+ } catch (e) {
1809
+ return true;
1810
+ }
1811
+ }
1812
+ var parseOptionalDef = (def, refs) => {
1813
+ var _a15;
1814
+ if (refs.currentPath.toString() === ((_a15 = refs.propertyPath) == null ? void 0 : _a15.toString())) {
1815
+ return parseDef(def.innerType._def, refs);
1816
+ }
1817
+ const innerSchema = parseDef(def.innerType._def, {
1818
+ ...refs,
1819
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1820
+ });
1821
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1822
+ };
1823
+ var parsePipelineDef = (def, refs) => {
1824
+ if (refs.pipeStrategy === "input") {
1825
+ return parseDef(def.in._def, refs);
1826
+ } else if (refs.pipeStrategy === "output") {
1827
+ return parseDef(def.out._def, refs);
1828
+ }
1829
+ const a = parseDef(def.in._def, {
1830
+ ...refs,
1831
+ currentPath: [...refs.currentPath, "allOf", "0"]
1832
+ });
1833
+ const b = parseDef(def.out._def, {
1834
+ ...refs,
1835
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1836
+ });
1837
+ return {
1838
+ allOf: [a, b].filter((x) => x !== void 0)
1839
+ };
1840
+ };
1841
+ function parsePromiseDef(def, refs) {
1842
+ return parseDef(def.type._def, refs);
1843
+ }
1844
+ function parseSetDef(def, refs) {
1845
+ const items = parseDef(def.valueType._def, {
1846
+ ...refs,
1847
+ currentPath: [...refs.currentPath, "items"]
1848
+ });
1849
+ const schema = {
1850
+ type: "array",
1851
+ uniqueItems: true,
1852
+ items
1853
+ };
1854
+ if (def.minSize) {
1855
+ schema.minItems = def.minSize.value;
1856
+ }
1857
+ if (def.maxSize) {
1858
+ schema.maxItems = def.maxSize.value;
1859
+ }
1860
+ return schema;
1861
+ }
1862
+ function parseTupleDef(def, refs) {
1863
+ if (def.rest) {
1864
+ return {
1865
+ type: "array",
1866
+ minItems: def.items.length,
1867
+ items: def.items.map(
1868
+ (x, i) => parseDef(x._def, {
1869
+ ...refs,
1870
+ currentPath: [...refs.currentPath, "items", `${i}`]
1871
+ })
1872
+ ).reduce(
1873
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1874
+ []
1875
+ ),
1876
+ additionalItems: parseDef(def.rest._def, {
1877
+ ...refs,
1878
+ currentPath: [...refs.currentPath, "additionalItems"]
1879
+ })
1880
+ };
1881
+ } else {
1882
+ return {
1883
+ type: "array",
1884
+ minItems: def.items.length,
1885
+ maxItems: def.items.length,
1886
+ items: def.items.map(
1887
+ (x, i) => parseDef(x._def, {
1888
+ ...refs,
1889
+ currentPath: [...refs.currentPath, "items", `${i}`]
1890
+ })
1891
+ ).reduce(
1892
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1893
+ []
1894
+ )
1895
+ };
1896
+ }
1897
+ }
1898
+ function parseUndefinedDef() {
1899
+ return {
1900
+ not: parseAnyDef()
1901
+ };
1902
+ }
1903
+ function parseUnknownDef() {
1904
+ return parseAnyDef();
1905
+ }
1906
+ var parseReadonlyDef = (def, refs) => {
1907
+ return parseDef(def.innerType._def, refs);
1908
+ };
1909
+ var selectParser = (def, typeName, refs) => {
1910
+ switch (typeName) {
1911
+ case ZodFirstPartyTypeKind3.ZodString:
1912
+ return parseStringDef(def, refs);
1913
+ case ZodFirstPartyTypeKind3.ZodNumber:
1914
+ return parseNumberDef(def);
1915
+ case ZodFirstPartyTypeKind3.ZodObject:
1916
+ return parseObjectDef(def, refs);
1917
+ case ZodFirstPartyTypeKind3.ZodBigInt:
1918
+ return parseBigintDef(def);
1919
+ case ZodFirstPartyTypeKind3.ZodBoolean:
1920
+ return parseBooleanDef();
1921
+ case ZodFirstPartyTypeKind3.ZodDate:
1922
+ return parseDateDef(def, refs);
1923
+ case ZodFirstPartyTypeKind3.ZodUndefined:
1924
+ return parseUndefinedDef();
1925
+ case ZodFirstPartyTypeKind3.ZodNull:
1926
+ return parseNullDef();
1927
+ case ZodFirstPartyTypeKind3.ZodArray:
1928
+ return parseArrayDef(def, refs);
1929
+ case ZodFirstPartyTypeKind3.ZodUnion:
1930
+ case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1931
+ return parseUnionDef(def, refs);
1932
+ case ZodFirstPartyTypeKind3.ZodIntersection:
1933
+ return parseIntersectionDef(def, refs);
1934
+ case ZodFirstPartyTypeKind3.ZodTuple:
1935
+ return parseTupleDef(def, refs);
1936
+ case ZodFirstPartyTypeKind3.ZodRecord:
1937
+ return parseRecordDef(def, refs);
1938
+ case ZodFirstPartyTypeKind3.ZodLiteral:
1939
+ return parseLiteralDef(def);
1940
+ case ZodFirstPartyTypeKind3.ZodEnum:
1941
+ return parseEnumDef(def);
1942
+ case ZodFirstPartyTypeKind3.ZodNativeEnum:
1943
+ return parseNativeEnumDef(def);
1944
+ case ZodFirstPartyTypeKind3.ZodNullable:
1945
+ return parseNullableDef(def, refs);
1946
+ case ZodFirstPartyTypeKind3.ZodOptional:
1947
+ return parseOptionalDef(def, refs);
1948
+ case ZodFirstPartyTypeKind3.ZodMap:
1949
+ return parseMapDef(def, refs);
1950
+ case ZodFirstPartyTypeKind3.ZodSet:
1951
+ return parseSetDef(def, refs);
1952
+ case ZodFirstPartyTypeKind3.ZodLazy:
1953
+ return () => def.getter()._def;
1954
+ case ZodFirstPartyTypeKind3.ZodPromise:
1955
+ return parsePromiseDef(def, refs);
1956
+ case ZodFirstPartyTypeKind3.ZodNaN:
1957
+ case ZodFirstPartyTypeKind3.ZodNever:
1958
+ return parseNeverDef();
1959
+ case ZodFirstPartyTypeKind3.ZodEffects:
1960
+ return parseEffectsDef(def, refs);
1961
+ case ZodFirstPartyTypeKind3.ZodAny:
1962
+ return parseAnyDef();
1963
+ case ZodFirstPartyTypeKind3.ZodUnknown:
1964
+ return parseUnknownDef();
1965
+ case ZodFirstPartyTypeKind3.ZodDefault:
1966
+ return parseDefaultDef(def, refs);
1967
+ case ZodFirstPartyTypeKind3.ZodBranded:
1968
+ return parseBrandedDef(def, refs);
1969
+ case ZodFirstPartyTypeKind3.ZodReadonly:
1970
+ return parseReadonlyDef(def, refs);
1971
+ case ZodFirstPartyTypeKind3.ZodCatch:
1972
+ return parseCatchDef(def, refs);
1973
+ case ZodFirstPartyTypeKind3.ZodPipeline:
1974
+ return parsePipelineDef(def, refs);
1975
+ case ZodFirstPartyTypeKind3.ZodFunction:
1976
+ case ZodFirstPartyTypeKind3.ZodVoid:
1977
+ case ZodFirstPartyTypeKind3.ZodSymbol:
1978
+ return void 0;
1979
+ default:
1980
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
1981
+ }
1982
+ };
1983
+ function parseDef(def, refs, forceResolution = false) {
1984
+ var _a15;
1985
+ const seenItem = refs.seen.get(def);
1986
+ if (refs.override) {
1987
+ const overrideResult = (_a15 = refs.override) == null ? void 0 : _a15.call(
1988
+ refs,
1989
+ def,
1990
+ refs,
1991
+ seenItem,
1992
+ forceResolution
1993
+ );
1994
+ if (overrideResult !== ignoreOverride) {
1995
+ return overrideResult;
1996
+ }
1997
+ }
1998
+ if (seenItem && !forceResolution) {
1999
+ const seenSchema = get$ref(seenItem, refs);
2000
+ if (seenSchema !== void 0) {
2001
+ return seenSchema;
2002
+ }
2003
+ }
2004
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
2005
+ refs.seen.set(def, newItem);
2006
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
2007
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
2008
+ if (jsonSchema2) {
2009
+ addMeta(def, refs, jsonSchema2);
2010
+ }
2011
+ if (refs.postProcess) {
2012
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
2013
+ newItem.jsonSchema = jsonSchema2;
2014
+ return postProcessResult;
2015
+ }
2016
+ newItem.jsonSchema = jsonSchema2;
2017
+ return jsonSchema2;
2018
+ }
2019
+ var get$ref = (item, refs) => {
2020
+ switch (refs.$refStrategy) {
2021
+ case "root":
2022
+ return { $ref: item.path.join("/") };
2023
+ case "relative":
2024
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
2025
+ case "none":
2026
+ case "seen": {
2027
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
2028
+ console.warn(
2029
+ `Recursive reference detected at ${refs.currentPath.join(
2030
+ "/"
2031
+ )}! Defaulting to any`
2032
+ );
2033
+ return parseAnyDef();
2034
+ }
2035
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
2036
+ }
2037
+ }
2038
+ };
2039
+ var addMeta = (def, refs, jsonSchema2) => {
2040
+ if (def.description) {
2041
+ jsonSchema2.description = def.description;
2042
+ }
2043
+ return jsonSchema2;
2044
+ };
2045
+ var getRefs = (options) => {
2046
+ const _options = getDefaultOptions(options);
2047
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
2048
+ return {
2049
+ ..._options,
2050
+ currentPath,
2051
+ propertyPath: void 0,
2052
+ seen: new Map(
2053
+ Object.entries(_options.definitions).map(([name14, def]) => [
2054
+ def._def,
2055
+ {
2056
+ def: def._def,
2057
+ path: [..._options.basePath, _options.definitionPath, name14],
2058
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
2059
+ jsonSchema: void 0
2060
+ }
2061
+ ])
2062
+ )
2063
+ };
2064
+ };
2065
+ var zodToJsonSchema = (schema, options) => {
2066
+ var _a15;
2067
+ const refs = getRefs(options);
2068
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
2069
+ (acc, [name22, schema2]) => {
2070
+ var _a22;
2071
+ return {
2072
+ ...acc,
2073
+ [name22]: (_a22 = parseDef(
2074
+ schema2._def,
2075
+ {
2076
+ ...refs,
2077
+ currentPath: [...refs.basePath, refs.definitionPath, name22]
2078
+ },
2079
+ true
2080
+ )) != null ? _a22 : parseAnyDef()
2081
+ };
2082
+ },
2083
+ {}
2084
+ ) : void 0;
2085
+ const name14 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
2086
+ const main = (_a15 = parseDef(
2087
+ schema._def,
2088
+ name14 === void 0 ? refs : {
2089
+ ...refs,
2090
+ currentPath: [...refs.basePath, refs.definitionPath, name14]
2091
+ },
2092
+ false
2093
+ )) != null ? _a15 : parseAnyDef();
2094
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
2095
+ if (title !== void 0) {
2096
+ main.title = title;
2097
+ }
2098
+ const combined = name14 === void 0 ? definitions ? {
2099
+ ...main,
2100
+ [refs.definitionPath]: definitions
2101
+ } : main : {
2102
+ $ref: [
2103
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
2104
+ refs.definitionPath,
2105
+ name14
2106
+ ].join("/"),
2107
+ [refs.definitionPath]: {
2108
+ ...definitions,
2109
+ [name14]: main
2110
+ }
2111
+ };
2112
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
2113
+ return combined;
2114
+ };
2115
+ var zod_to_json_schema_default = zodToJsonSchema;
2116
+ function zod3Schema(zodSchema2, options) {
2117
+ var _a15;
2118
+ const useReferences = (_a15 = options == null ? void 0 : options.useReferences) != null ? _a15 : false;
2119
+ return jsonSchema(
2120
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
2121
+ () => zod_to_json_schema_default(zodSchema2, {
2122
+ $refStrategy: useReferences ? "root" : "none"
2123
+ }),
2124
+ {
2125
+ validate: async (value) => {
2126
+ const result = await zodSchema2.safeParseAsync(value);
2127
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2128
+ }
2129
+ }
2130
+ );
2131
+ }
2132
+ function zod4Schema(zodSchema2, options) {
2133
+ var _a15;
2134
+ const useReferences = (_a15 = options == null ? void 0 : options.useReferences) != null ? _a15 : false;
2135
+ return jsonSchema(
2136
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
2137
+ () => addAdditionalPropertiesToJsonSchema(
2138
+ z4.toJSONSchema(zodSchema2, {
2139
+ target: "draft-7",
2140
+ io: "input",
2141
+ reused: useReferences ? "ref" : "inline"
2142
+ })
2143
+ ),
2144
+ {
2145
+ validate: async (value) => {
2146
+ const result = await z4.safeParseAsync(zodSchema2, value);
2147
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2148
+ }
2149
+ }
2150
+ );
2151
+ }
2152
+ function isZod4Schema(zodSchema2) {
2153
+ return "_zod" in zodSchema2;
2154
+ }
2155
+ function zodSchema(zodSchema2, options) {
2156
+ if (isZod4Schema(zodSchema2)) {
2157
+ return zod4Schema(zodSchema2, options);
2158
+ } else {
2159
+ return zod3Schema(zodSchema2, options);
2160
+ }
2161
+ }
2162
+ var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
2163
+ function lazySchema(createSchema) {
2164
+ let schema;
2165
+ return () => {
2166
+ if (schema == null) {
2167
+ schema = createSchema();
2168
+ }
2169
+ return schema;
2170
+ };
2171
+ }
2172
+ function jsonSchema(jsonSchema2, {
2173
+ validate
2174
+ } = {}) {
2175
+ return {
2176
+ [schemaSymbol]: true,
2177
+ _type: void 0,
2178
+ // should never be used directly
2179
+ [validatorSymbol]: true,
2180
+ get jsonSchema() {
2181
+ if (typeof jsonSchema2 === "function") {
2182
+ jsonSchema2 = jsonSchema2();
2183
+ }
2184
+ return jsonSchema2;
2185
+ },
2186
+ validate
2187
+ };
2188
+ }
2189
+ var { btoa, atob } = globalThis;
2190
+ function convertUint8ArrayToBase64(array) {
2191
+ let latin1string = "";
2192
+ for (let i = 0; i < array.length; i++) {
2193
+ latin1string += String.fromCodePoint(array[i]);
2194
+ }
2195
+ return btoa(latin1string);
2196
+ }
2197
+ function convertToBase64(value) {
2198
+ return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;
2199
+ }
2200
+ function withoutTrailingSlash(url) {
2201
+ return url == null ? void 0 : url.replace(/\/$/, "");
2202
+ }
2203
+
2204
+ export {
2205
+ APICallError,
2206
+ NoSuchModelError,
2207
+ TooManyEmbeddingValuesForCallError,
2208
+ UnsupportedFunctionalityError,
2209
+ combineHeaders,
2210
+ generateId,
2211
+ withUserAgentSuffix,
2212
+ loadApiKey,
2213
+ loadOptionalSetting,
2214
+ validateTypes,
2215
+ parseProviderOptions,
2216
+ postJsonToApi,
2217
+ createProviderDefinedToolFactory,
2218
+ createProviderDefinedToolFactoryWithOutputSchema,
2219
+ resolve,
2220
+ createJsonErrorResponseHandler,
2221
+ createEventSourceResponseHandler,
2222
+ createJsonResponseHandler,
2223
+ zodSchema,
2224
+ lazySchema,
2225
+ convertToBase64,
2226
+ withoutTrailingSlash
2227
+ };