@papicandela/mcx-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.
package/dist/index.js ADDED
@@ -0,0 +1,4679 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, {
5
+ get: all[name],
6
+ enumerable: true,
7
+ configurable: true,
8
+ set: (newValue) => all[name] = () => newValue
9
+ });
10
+ };
11
+
12
+ // src/sandbox/bun-worker.ts
13
+ var DEFAULT_CONFIG = {
14
+ timeout: 5000,
15
+ memoryLimit: 128,
16
+ allowAsync: true,
17
+ globals: {}
18
+ };
19
+
20
+ class BunWorkerSandbox {
21
+ config;
22
+ constructor(config) {
23
+ this.config = { ...DEFAULT_CONFIG, ...config };
24
+ }
25
+ getConfig() {
26
+ return { ...this.config };
27
+ }
28
+ configure(config) {
29
+ this.config = { ...this.config, ...config };
30
+ }
31
+ async execute(code, context) {
32
+ const startTime = performance.now();
33
+ return new Promise((resolve) => {
34
+ const adapterMethods = {};
35
+ for (const [name, methods] of Object.entries(context.adapters)) {
36
+ adapterMethods[name] = Object.keys(methods);
37
+ }
38
+ const workerCode = this.buildWorkerCode();
39
+ const blob = new Blob([workerCode], { type: "application/javascript" });
40
+ const url = URL.createObjectURL(blob);
41
+ const worker = new Worker(url);
42
+ let resolved = false;
43
+ const cleanup = () => {
44
+ if (!resolved) {
45
+ resolved = true;
46
+ worker.terminate();
47
+ URL.revokeObjectURL(url);
48
+ }
49
+ };
50
+ const timeoutId = setTimeout(() => {
51
+ if (!resolved) {
52
+ cleanup();
53
+ resolve({
54
+ success: false,
55
+ error: { name: "TimeoutError", message: `Execution timed out after ${this.config.timeout}ms` },
56
+ logs: [],
57
+ executionTime: performance.now() - startTime
58
+ });
59
+ }
60
+ }, this.config.timeout);
61
+ worker.onmessage = async (event) => {
62
+ const { type, ...data } = event.data;
63
+ if (type === "ready") {
64
+ worker.postMessage({ type: "execute", data: { code } });
65
+ } else if (type === "adapter_call") {
66
+ const { adapter, method, args, id } = data;
67
+ try {
68
+ const adapterObj = context.adapters[adapter];
69
+ if (!adapterObj || !adapterObj[method]) {
70
+ throw new Error(`Adapter method not found: ${adapter}.${method}`);
71
+ }
72
+ const result = await adapterObj[method](...args);
73
+ worker.postMessage({ type: "adapter_result", data: { id, result } });
74
+ } catch (err) {
75
+ const error = err instanceof Error ? err.message : String(err);
76
+ worker.postMessage({ type: "adapter_result", data: { id, error } });
77
+ }
78
+ } else if (type === "result") {
79
+ clearTimeout(timeoutId);
80
+ cleanup();
81
+ resolve({
82
+ success: data.success,
83
+ value: data.value,
84
+ error: data.error,
85
+ logs: data.logs || [],
86
+ executionTime: performance.now() - startTime
87
+ });
88
+ }
89
+ };
90
+ worker.onerror = (error) => {
91
+ clearTimeout(timeoutId);
92
+ cleanup();
93
+ resolve({
94
+ success: false,
95
+ error: { name: "WorkerError", message: error.message || "Unknown worker error" },
96
+ logs: [],
97
+ executionTime: performance.now() - startTime
98
+ });
99
+ };
100
+ worker.postMessage({
101
+ type: "init",
102
+ data: {
103
+ variables: context.variables || {},
104
+ adapterMethods,
105
+ globals: this.config.globals
106
+ }
107
+ });
108
+ });
109
+ }
110
+ buildWorkerCode() {
111
+ return `
112
+ const logs = [];
113
+ const pendingCalls = new Map();
114
+ let callId = 0;
115
+
116
+ const console = {
117
+ log: (...args) => logs.push(args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')),
118
+ warn: (...args) => logs.push('[WARN] ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')),
119
+ error: (...args) => logs.push('[ERROR] ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')),
120
+ info: (...args) => logs.push('[INFO] ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')),
121
+ };
122
+ globalThis.console = console;
123
+
124
+ globalThis.pick = (arr, fields) => {
125
+ if (!Array.isArray(arr)) return arr;
126
+ return arr.map(item => {
127
+ const result = {};
128
+ for (const field of fields) {
129
+ const parts = field.split('.');
130
+ let value = item;
131
+ let key = parts[parts.length - 1];
132
+ for (const part of parts) value = value?.[part];
133
+ result[key] = value;
134
+ }
135
+ return result;
136
+ });
137
+ };
138
+
139
+ globalThis.table = (arr, maxRows = 10) => {
140
+ if (!Array.isArray(arr) || arr.length === 0) return '(empty)';
141
+ const items = arr.slice(0, maxRows);
142
+ const keys = Object.keys(items[0]);
143
+ const header = '| ' + keys.join(' | ') + ' |';
144
+ const sep = '|' + keys.map(() => '---').join('|') + '|';
145
+ const rows = items.map(item => '| ' + keys.map(k => String(item[k] ?? '')).join(' | ') + ' |');
146
+ let result = [header, sep, ...rows].join('\\n');
147
+ if (arr.length > maxRows) result += '\\n... +' + (arr.length - maxRows) + ' more rows';
148
+ return result;
149
+ };
150
+
151
+ globalThis.count = (arr, field) => {
152
+ if (!Array.isArray(arr)) return {};
153
+ return arr.reduce((acc, item) => {
154
+ const key = String(item[field] ?? 'unknown');
155
+ acc[key] = (acc[key] || 0) + 1;
156
+ return acc;
157
+ }, {});
158
+ };
159
+
160
+ globalThis.sum = (arr, field) => {
161
+ if (!Array.isArray(arr)) return 0;
162
+ return arr.reduce((acc, item) => acc + (Number(item[field]) || 0), 0);
163
+ };
164
+
165
+ globalThis.first = (arr, n = 5) => {
166
+ if (!Array.isArray(arr)) return arr;
167
+ return arr.slice(0, n);
168
+ };
169
+
170
+ self.onmessage = async (event) => {
171
+ const { type, data } = event.data;
172
+
173
+ if (type === 'init') {
174
+ const { variables, adapterMethods, globals } = data;
175
+
176
+ for (const [key, value] of Object.entries(variables || {})) {
177
+ globalThis[key] = value;
178
+ }
179
+
180
+ for (const [key, value] of Object.entries(globals || {})) {
181
+ globalThis[key] = value;
182
+ }
183
+
184
+ globalThis.adapters = {};
185
+ for (const [adapterName, methods] of Object.entries(adapterMethods)) {
186
+ const adapterObj = {};
187
+ for (const methodName of methods) {
188
+ adapterObj[methodName] = async (...args) => {
189
+ const id = ++callId;
190
+ return new Promise((resolve, reject) => {
191
+ pendingCalls.set(id, { resolve, reject });
192
+ self.postMessage({
193
+ type: 'adapter_call',
194
+ adapter: adapterName,
195
+ method: methodName,
196
+ args,
197
+ id
198
+ });
199
+ });
200
+ };
201
+ }
202
+ globalThis.adapters[adapterName] = adapterObj;
203
+ globalThis[adapterName] = adapterObj;
204
+ }
205
+
206
+ self.postMessage({ type: 'ready' });
207
+ }
208
+
209
+ else if (type === 'adapter_result') {
210
+ const { id, result, error } = data;
211
+ const pending = pendingCalls.get(id);
212
+ if (pending) {
213
+ pendingCalls.delete(id);
214
+ if (error) pending.reject(new Error(error));
215
+ else pending.resolve(result);
216
+ }
217
+ }
218
+
219
+ else if (type === 'execute') {
220
+ try {
221
+ // SECURITY: This runs in isolated Worker context
222
+ const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
223
+ const fn = new AsyncFunction(data.code);
224
+ const result = await fn();
225
+ self.postMessage({ type: 'result', success: true, value: result, logs });
226
+ } catch (err) {
227
+ self.postMessage({
228
+ type: 'result',
229
+ success: false,
230
+ error: { name: err.name, message: err.message, stack: err.stack },
231
+ logs
232
+ });
233
+ }
234
+ }
235
+ };
236
+ `;
237
+ }
238
+ dispose() {}
239
+ }
240
+ function createSandbox(config) {
241
+ return new BunWorkerSandbox(config);
242
+ }
243
+ // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/external.js
244
+ var exports_external = {};
245
+ __export(exports_external, {
246
+ void: () => voidType,
247
+ util: () => util,
248
+ unknown: () => unknownType,
249
+ union: () => unionType,
250
+ undefined: () => undefinedType,
251
+ tuple: () => tupleType,
252
+ transformer: () => effectsType,
253
+ symbol: () => symbolType,
254
+ string: () => stringType,
255
+ strictObject: () => strictObjectType,
256
+ setErrorMap: () => setErrorMap,
257
+ set: () => setType,
258
+ record: () => recordType,
259
+ quotelessJson: () => quotelessJson,
260
+ promise: () => promiseType,
261
+ preprocess: () => preprocessType,
262
+ pipeline: () => pipelineType,
263
+ ostring: () => ostring,
264
+ optional: () => optionalType,
265
+ onumber: () => onumber,
266
+ oboolean: () => oboolean,
267
+ objectUtil: () => objectUtil,
268
+ object: () => objectType,
269
+ number: () => numberType,
270
+ nullable: () => nullableType,
271
+ null: () => nullType,
272
+ never: () => neverType,
273
+ nativeEnum: () => nativeEnumType,
274
+ nan: () => nanType,
275
+ map: () => mapType,
276
+ makeIssue: () => makeIssue,
277
+ literal: () => literalType,
278
+ lazy: () => lazyType,
279
+ late: () => late,
280
+ isValid: () => isValid,
281
+ isDirty: () => isDirty,
282
+ isAsync: () => isAsync,
283
+ isAborted: () => isAborted,
284
+ intersection: () => intersectionType,
285
+ instanceof: () => instanceOfType,
286
+ getParsedType: () => getParsedType,
287
+ getErrorMap: () => getErrorMap,
288
+ function: () => functionType,
289
+ enum: () => enumType,
290
+ effect: () => effectsType,
291
+ discriminatedUnion: () => discriminatedUnionType,
292
+ defaultErrorMap: () => en_default,
293
+ datetimeRegex: () => datetimeRegex,
294
+ date: () => dateType,
295
+ custom: () => custom,
296
+ coerce: () => coerce,
297
+ boolean: () => booleanType,
298
+ bigint: () => bigIntType,
299
+ array: () => arrayType,
300
+ any: () => anyType,
301
+ addIssueToContext: () => addIssueToContext,
302
+ ZodVoid: () => ZodVoid,
303
+ ZodUnknown: () => ZodUnknown,
304
+ ZodUnion: () => ZodUnion,
305
+ ZodUndefined: () => ZodUndefined,
306
+ ZodType: () => ZodType,
307
+ ZodTuple: () => ZodTuple,
308
+ ZodTransformer: () => ZodEffects,
309
+ ZodSymbol: () => ZodSymbol,
310
+ ZodString: () => ZodString,
311
+ ZodSet: () => ZodSet,
312
+ ZodSchema: () => ZodType,
313
+ ZodRecord: () => ZodRecord,
314
+ ZodReadonly: () => ZodReadonly,
315
+ ZodPromise: () => ZodPromise,
316
+ ZodPipeline: () => ZodPipeline,
317
+ ZodParsedType: () => ZodParsedType,
318
+ ZodOptional: () => ZodOptional,
319
+ ZodObject: () => ZodObject,
320
+ ZodNumber: () => ZodNumber,
321
+ ZodNullable: () => ZodNullable,
322
+ ZodNull: () => ZodNull,
323
+ ZodNever: () => ZodNever,
324
+ ZodNativeEnum: () => ZodNativeEnum,
325
+ ZodNaN: () => ZodNaN,
326
+ ZodMap: () => ZodMap,
327
+ ZodLiteral: () => ZodLiteral,
328
+ ZodLazy: () => ZodLazy,
329
+ ZodIssueCode: () => ZodIssueCode,
330
+ ZodIntersection: () => ZodIntersection,
331
+ ZodFunction: () => ZodFunction,
332
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
333
+ ZodError: () => ZodError,
334
+ ZodEnum: () => ZodEnum,
335
+ ZodEffects: () => ZodEffects,
336
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
337
+ ZodDefault: () => ZodDefault,
338
+ ZodDate: () => ZodDate,
339
+ ZodCatch: () => ZodCatch,
340
+ ZodBranded: () => ZodBranded,
341
+ ZodBoolean: () => ZodBoolean,
342
+ ZodBigInt: () => ZodBigInt,
343
+ ZodArray: () => ZodArray,
344
+ ZodAny: () => ZodAny,
345
+ Schema: () => ZodType,
346
+ ParseStatus: () => ParseStatus,
347
+ OK: () => OK,
348
+ NEVER: () => NEVER,
349
+ INVALID: () => INVALID,
350
+ EMPTY_PATH: () => EMPTY_PATH,
351
+ DIRTY: () => DIRTY,
352
+ BRAND: () => BRAND
353
+ });
354
+
355
+ // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/util.js
356
+ var util;
357
+ (function(util2) {
358
+ util2.assertEqual = (_) => {};
359
+ function assertIs(_arg) {}
360
+ util2.assertIs = assertIs;
361
+ function assertNever(_x) {
362
+ throw new Error;
363
+ }
364
+ util2.assertNever = assertNever;
365
+ util2.arrayToEnum = (items) => {
366
+ const obj = {};
367
+ for (const item of items) {
368
+ obj[item] = item;
369
+ }
370
+ return obj;
371
+ };
372
+ util2.getValidEnumValues = (obj) => {
373
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
374
+ const filtered = {};
375
+ for (const k of validKeys) {
376
+ filtered[k] = obj[k];
377
+ }
378
+ return util2.objectValues(filtered);
379
+ };
380
+ util2.objectValues = (obj) => {
381
+ return util2.objectKeys(obj).map(function(e) {
382
+ return obj[e];
383
+ });
384
+ };
385
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
386
+ const keys = [];
387
+ for (const key in object) {
388
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
389
+ keys.push(key);
390
+ }
391
+ }
392
+ return keys;
393
+ };
394
+ util2.find = (arr, checker) => {
395
+ for (const item of arr) {
396
+ if (checker(item))
397
+ return item;
398
+ }
399
+ return;
400
+ };
401
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
402
+ function joinValues(array, separator = " | ") {
403
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
404
+ }
405
+ util2.joinValues = joinValues;
406
+ util2.jsonStringifyReplacer = (_, value) => {
407
+ if (typeof value === "bigint") {
408
+ return value.toString();
409
+ }
410
+ return value;
411
+ };
412
+ })(util || (util = {}));
413
+ var objectUtil;
414
+ (function(objectUtil2) {
415
+ objectUtil2.mergeShapes = (first, second) => {
416
+ return {
417
+ ...first,
418
+ ...second
419
+ };
420
+ };
421
+ })(objectUtil || (objectUtil = {}));
422
+ var ZodParsedType = util.arrayToEnum([
423
+ "string",
424
+ "nan",
425
+ "number",
426
+ "integer",
427
+ "float",
428
+ "boolean",
429
+ "date",
430
+ "bigint",
431
+ "symbol",
432
+ "function",
433
+ "undefined",
434
+ "null",
435
+ "array",
436
+ "object",
437
+ "unknown",
438
+ "promise",
439
+ "void",
440
+ "never",
441
+ "map",
442
+ "set"
443
+ ]);
444
+ var getParsedType = (data) => {
445
+ const t = typeof data;
446
+ switch (t) {
447
+ case "undefined":
448
+ return ZodParsedType.undefined;
449
+ case "string":
450
+ return ZodParsedType.string;
451
+ case "number":
452
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
453
+ case "boolean":
454
+ return ZodParsedType.boolean;
455
+ case "function":
456
+ return ZodParsedType.function;
457
+ case "bigint":
458
+ return ZodParsedType.bigint;
459
+ case "symbol":
460
+ return ZodParsedType.symbol;
461
+ case "object":
462
+ if (Array.isArray(data)) {
463
+ return ZodParsedType.array;
464
+ }
465
+ if (data === null) {
466
+ return ZodParsedType.null;
467
+ }
468
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
469
+ return ZodParsedType.promise;
470
+ }
471
+ if (typeof Map !== "undefined" && data instanceof Map) {
472
+ return ZodParsedType.map;
473
+ }
474
+ if (typeof Set !== "undefined" && data instanceof Set) {
475
+ return ZodParsedType.set;
476
+ }
477
+ if (typeof Date !== "undefined" && data instanceof Date) {
478
+ return ZodParsedType.date;
479
+ }
480
+ return ZodParsedType.object;
481
+ default:
482
+ return ZodParsedType.unknown;
483
+ }
484
+ };
485
+
486
+ // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/ZodError.js
487
+ var ZodIssueCode = util.arrayToEnum([
488
+ "invalid_type",
489
+ "invalid_literal",
490
+ "custom",
491
+ "invalid_union",
492
+ "invalid_union_discriminator",
493
+ "invalid_enum_value",
494
+ "unrecognized_keys",
495
+ "invalid_arguments",
496
+ "invalid_return_type",
497
+ "invalid_date",
498
+ "invalid_string",
499
+ "too_small",
500
+ "too_big",
501
+ "invalid_intersection_types",
502
+ "not_multiple_of",
503
+ "not_finite"
504
+ ]);
505
+ var quotelessJson = (obj) => {
506
+ const json = JSON.stringify(obj, null, 2);
507
+ return json.replace(/"([^"]+)":/g, "$1:");
508
+ };
509
+
510
+ class ZodError extends Error {
511
+ get errors() {
512
+ return this.issues;
513
+ }
514
+ constructor(issues) {
515
+ super();
516
+ this.issues = [];
517
+ this.addIssue = (sub) => {
518
+ this.issues = [...this.issues, sub];
519
+ };
520
+ this.addIssues = (subs = []) => {
521
+ this.issues = [...this.issues, ...subs];
522
+ };
523
+ const actualProto = new.target.prototype;
524
+ if (Object.setPrototypeOf) {
525
+ Object.setPrototypeOf(this, actualProto);
526
+ } else {
527
+ this.__proto__ = actualProto;
528
+ }
529
+ this.name = "ZodError";
530
+ this.issues = issues;
531
+ }
532
+ format(_mapper) {
533
+ const mapper = _mapper || function(issue) {
534
+ return issue.message;
535
+ };
536
+ const fieldErrors = { _errors: [] };
537
+ const processError = (error) => {
538
+ for (const issue of error.issues) {
539
+ if (issue.code === "invalid_union") {
540
+ issue.unionErrors.map(processError);
541
+ } else if (issue.code === "invalid_return_type") {
542
+ processError(issue.returnTypeError);
543
+ } else if (issue.code === "invalid_arguments") {
544
+ processError(issue.argumentsError);
545
+ } else if (issue.path.length === 0) {
546
+ fieldErrors._errors.push(mapper(issue));
547
+ } else {
548
+ let curr = fieldErrors;
549
+ let i = 0;
550
+ while (i < issue.path.length) {
551
+ const el = issue.path[i];
552
+ const terminal = i === issue.path.length - 1;
553
+ if (!terminal) {
554
+ curr[el] = curr[el] || { _errors: [] };
555
+ } else {
556
+ curr[el] = curr[el] || { _errors: [] };
557
+ curr[el]._errors.push(mapper(issue));
558
+ }
559
+ curr = curr[el];
560
+ i++;
561
+ }
562
+ }
563
+ }
564
+ };
565
+ processError(this);
566
+ return fieldErrors;
567
+ }
568
+ static assert(value) {
569
+ if (!(value instanceof ZodError)) {
570
+ throw new Error(`Not a ZodError: ${value}`);
571
+ }
572
+ }
573
+ toString() {
574
+ return this.message;
575
+ }
576
+ get message() {
577
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
578
+ }
579
+ get isEmpty() {
580
+ return this.issues.length === 0;
581
+ }
582
+ flatten(mapper = (issue) => issue.message) {
583
+ const fieldErrors = {};
584
+ const formErrors = [];
585
+ for (const sub of this.issues) {
586
+ if (sub.path.length > 0) {
587
+ const firstEl = sub.path[0];
588
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
589
+ fieldErrors[firstEl].push(mapper(sub));
590
+ } else {
591
+ formErrors.push(mapper(sub));
592
+ }
593
+ }
594
+ return { formErrors, fieldErrors };
595
+ }
596
+ get formErrors() {
597
+ return this.flatten();
598
+ }
599
+ }
600
+ ZodError.create = (issues) => {
601
+ const error = new ZodError(issues);
602
+ return error;
603
+ };
604
+
605
+ // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/locales/en.js
606
+ var errorMap = (issue, _ctx) => {
607
+ let message;
608
+ switch (issue.code) {
609
+ case ZodIssueCode.invalid_type:
610
+ if (issue.received === ZodParsedType.undefined) {
611
+ message = "Required";
612
+ } else {
613
+ message = `Expected ${issue.expected}, received ${issue.received}`;
614
+ }
615
+ break;
616
+ case ZodIssueCode.invalid_literal:
617
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
618
+ break;
619
+ case ZodIssueCode.unrecognized_keys:
620
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
621
+ break;
622
+ case ZodIssueCode.invalid_union:
623
+ message = `Invalid input`;
624
+ break;
625
+ case ZodIssueCode.invalid_union_discriminator:
626
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
627
+ break;
628
+ case ZodIssueCode.invalid_enum_value:
629
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
630
+ break;
631
+ case ZodIssueCode.invalid_arguments:
632
+ message = `Invalid function arguments`;
633
+ break;
634
+ case ZodIssueCode.invalid_return_type:
635
+ message = `Invalid function return type`;
636
+ break;
637
+ case ZodIssueCode.invalid_date:
638
+ message = `Invalid date`;
639
+ break;
640
+ case ZodIssueCode.invalid_string:
641
+ if (typeof issue.validation === "object") {
642
+ if ("includes" in issue.validation) {
643
+ message = `Invalid input: must include "${issue.validation.includes}"`;
644
+ if (typeof issue.validation.position === "number") {
645
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
646
+ }
647
+ } else if ("startsWith" in issue.validation) {
648
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
649
+ } else if ("endsWith" in issue.validation) {
650
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
651
+ } else {
652
+ util.assertNever(issue.validation);
653
+ }
654
+ } else if (issue.validation !== "regex") {
655
+ message = `Invalid ${issue.validation}`;
656
+ } else {
657
+ message = "Invalid";
658
+ }
659
+ break;
660
+ case ZodIssueCode.too_small:
661
+ if (issue.type === "array")
662
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
663
+ else if (issue.type === "string")
664
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
665
+ else if (issue.type === "number")
666
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
667
+ else if (issue.type === "bigint")
668
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
669
+ else if (issue.type === "date")
670
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
671
+ else
672
+ message = "Invalid input";
673
+ break;
674
+ case ZodIssueCode.too_big:
675
+ if (issue.type === "array")
676
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
677
+ else if (issue.type === "string")
678
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
679
+ else if (issue.type === "number")
680
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
681
+ else if (issue.type === "bigint")
682
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
683
+ else if (issue.type === "date")
684
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
685
+ else
686
+ message = "Invalid input";
687
+ break;
688
+ case ZodIssueCode.custom:
689
+ message = `Invalid input`;
690
+ break;
691
+ case ZodIssueCode.invalid_intersection_types:
692
+ message = `Intersection results could not be merged`;
693
+ break;
694
+ case ZodIssueCode.not_multiple_of:
695
+ message = `Number must be a multiple of ${issue.multipleOf}`;
696
+ break;
697
+ case ZodIssueCode.not_finite:
698
+ message = "Number must be finite";
699
+ break;
700
+ default:
701
+ message = _ctx.defaultError;
702
+ util.assertNever(issue);
703
+ }
704
+ return { message };
705
+ };
706
+ var en_default = errorMap;
707
+
708
+ // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/errors.js
709
+ var overrideErrorMap = en_default;
710
+ function setErrorMap(map) {
711
+ overrideErrorMap = map;
712
+ }
713
+ function getErrorMap() {
714
+ return overrideErrorMap;
715
+ }
716
+ // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
717
+ var makeIssue = (params) => {
718
+ const { data, path, errorMaps, issueData } = params;
719
+ const fullPath = [...path, ...issueData.path || []];
720
+ const fullIssue = {
721
+ ...issueData,
722
+ path: fullPath
723
+ };
724
+ if (issueData.message !== undefined) {
725
+ return {
726
+ ...issueData,
727
+ path: fullPath,
728
+ message: issueData.message
729
+ };
730
+ }
731
+ let errorMessage = "";
732
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
733
+ for (const map of maps) {
734
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
735
+ }
736
+ return {
737
+ ...issueData,
738
+ path: fullPath,
739
+ message: errorMessage
740
+ };
741
+ };
742
+ var EMPTY_PATH = [];
743
+ function addIssueToContext(ctx, issueData) {
744
+ const overrideMap = getErrorMap();
745
+ const issue = makeIssue({
746
+ issueData,
747
+ data: ctx.data,
748
+ path: ctx.path,
749
+ errorMaps: [
750
+ ctx.common.contextualErrorMap,
751
+ ctx.schemaErrorMap,
752
+ overrideMap,
753
+ overrideMap === en_default ? undefined : en_default
754
+ ].filter((x) => !!x)
755
+ });
756
+ ctx.common.issues.push(issue);
757
+ }
758
+
759
+ class ParseStatus {
760
+ constructor() {
761
+ this.value = "valid";
762
+ }
763
+ dirty() {
764
+ if (this.value === "valid")
765
+ this.value = "dirty";
766
+ }
767
+ abort() {
768
+ if (this.value !== "aborted")
769
+ this.value = "aborted";
770
+ }
771
+ static mergeArray(status, results) {
772
+ const arrayValue = [];
773
+ for (const s of results) {
774
+ if (s.status === "aborted")
775
+ return INVALID;
776
+ if (s.status === "dirty")
777
+ status.dirty();
778
+ arrayValue.push(s.value);
779
+ }
780
+ return { status: status.value, value: arrayValue };
781
+ }
782
+ static async mergeObjectAsync(status, pairs) {
783
+ const syncPairs = [];
784
+ for (const pair of pairs) {
785
+ const key = await pair.key;
786
+ const value = await pair.value;
787
+ syncPairs.push({
788
+ key,
789
+ value
790
+ });
791
+ }
792
+ return ParseStatus.mergeObjectSync(status, syncPairs);
793
+ }
794
+ static mergeObjectSync(status, pairs) {
795
+ const finalObject = {};
796
+ for (const pair of pairs) {
797
+ const { key, value } = pair;
798
+ if (key.status === "aborted")
799
+ return INVALID;
800
+ if (value.status === "aborted")
801
+ return INVALID;
802
+ if (key.status === "dirty")
803
+ status.dirty();
804
+ if (value.status === "dirty")
805
+ status.dirty();
806
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
807
+ finalObject[key.value] = value.value;
808
+ }
809
+ }
810
+ return { status: status.value, value: finalObject };
811
+ }
812
+ }
813
+ var INVALID = Object.freeze({
814
+ status: "aborted"
815
+ });
816
+ var DIRTY = (value) => ({ status: "dirty", value });
817
+ var OK = (value) => ({ status: "valid", value });
818
+ var isAborted = (x) => x.status === "aborted";
819
+ var isDirty = (x) => x.status === "dirty";
820
+ var isValid = (x) => x.status === "valid";
821
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
822
+ // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
823
+ var errorUtil;
824
+ (function(errorUtil2) {
825
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
826
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
827
+ })(errorUtil || (errorUtil = {}));
828
+
829
+ // ../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/types.js
830
+ class ParseInputLazyPath {
831
+ constructor(parent, value, path, key) {
832
+ this._cachedPath = [];
833
+ this.parent = parent;
834
+ this.data = value;
835
+ this._path = path;
836
+ this._key = key;
837
+ }
838
+ get path() {
839
+ if (!this._cachedPath.length) {
840
+ if (Array.isArray(this._key)) {
841
+ this._cachedPath.push(...this._path, ...this._key);
842
+ } else {
843
+ this._cachedPath.push(...this._path, this._key);
844
+ }
845
+ }
846
+ return this._cachedPath;
847
+ }
848
+ }
849
+ var handleResult = (ctx, result) => {
850
+ if (isValid(result)) {
851
+ return { success: true, data: result.value };
852
+ } else {
853
+ if (!ctx.common.issues.length) {
854
+ throw new Error("Validation failed but no issues detected.");
855
+ }
856
+ return {
857
+ success: false,
858
+ get error() {
859
+ if (this._error)
860
+ return this._error;
861
+ const error = new ZodError(ctx.common.issues);
862
+ this._error = error;
863
+ return this._error;
864
+ }
865
+ };
866
+ }
867
+ };
868
+ function processCreateParams(params) {
869
+ if (!params)
870
+ return {};
871
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
872
+ if (errorMap2 && (invalid_type_error || required_error)) {
873
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
874
+ }
875
+ if (errorMap2)
876
+ return { errorMap: errorMap2, description };
877
+ const customMap = (iss, ctx) => {
878
+ const { message } = params;
879
+ if (iss.code === "invalid_enum_value") {
880
+ return { message: message ?? ctx.defaultError };
881
+ }
882
+ if (typeof ctx.data === "undefined") {
883
+ return { message: message ?? required_error ?? ctx.defaultError };
884
+ }
885
+ if (iss.code !== "invalid_type")
886
+ return { message: ctx.defaultError };
887
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
888
+ };
889
+ return { errorMap: customMap, description };
890
+ }
891
+
892
+ class ZodType {
893
+ get description() {
894
+ return this._def.description;
895
+ }
896
+ _getType(input) {
897
+ return getParsedType(input.data);
898
+ }
899
+ _getOrReturnCtx(input, ctx) {
900
+ return ctx || {
901
+ common: input.parent.common,
902
+ data: input.data,
903
+ parsedType: getParsedType(input.data),
904
+ schemaErrorMap: this._def.errorMap,
905
+ path: input.path,
906
+ parent: input.parent
907
+ };
908
+ }
909
+ _processInputParams(input) {
910
+ return {
911
+ status: new ParseStatus,
912
+ ctx: {
913
+ common: input.parent.common,
914
+ data: input.data,
915
+ parsedType: getParsedType(input.data),
916
+ schemaErrorMap: this._def.errorMap,
917
+ path: input.path,
918
+ parent: input.parent
919
+ }
920
+ };
921
+ }
922
+ _parseSync(input) {
923
+ const result = this._parse(input);
924
+ if (isAsync(result)) {
925
+ throw new Error("Synchronous parse encountered promise.");
926
+ }
927
+ return result;
928
+ }
929
+ _parseAsync(input) {
930
+ const result = this._parse(input);
931
+ return Promise.resolve(result);
932
+ }
933
+ parse(data, params) {
934
+ const result = this.safeParse(data, params);
935
+ if (result.success)
936
+ return result.data;
937
+ throw result.error;
938
+ }
939
+ safeParse(data, params) {
940
+ const ctx = {
941
+ common: {
942
+ issues: [],
943
+ async: params?.async ?? false,
944
+ contextualErrorMap: params?.errorMap
945
+ },
946
+ path: params?.path || [],
947
+ schemaErrorMap: this._def.errorMap,
948
+ parent: null,
949
+ data,
950
+ parsedType: getParsedType(data)
951
+ };
952
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
953
+ return handleResult(ctx, result);
954
+ }
955
+ "~validate"(data) {
956
+ const ctx = {
957
+ common: {
958
+ issues: [],
959
+ async: !!this["~standard"].async
960
+ },
961
+ path: [],
962
+ schemaErrorMap: this._def.errorMap,
963
+ parent: null,
964
+ data,
965
+ parsedType: getParsedType(data)
966
+ };
967
+ if (!this["~standard"].async) {
968
+ try {
969
+ const result = this._parseSync({ data, path: [], parent: ctx });
970
+ return isValid(result) ? {
971
+ value: result.value
972
+ } : {
973
+ issues: ctx.common.issues
974
+ };
975
+ } catch (err) {
976
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
977
+ this["~standard"].async = true;
978
+ }
979
+ ctx.common = {
980
+ issues: [],
981
+ async: true
982
+ };
983
+ }
984
+ }
985
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
986
+ value: result.value
987
+ } : {
988
+ issues: ctx.common.issues
989
+ });
990
+ }
991
+ async parseAsync(data, params) {
992
+ const result = await this.safeParseAsync(data, params);
993
+ if (result.success)
994
+ return result.data;
995
+ throw result.error;
996
+ }
997
+ async safeParseAsync(data, params) {
998
+ const ctx = {
999
+ common: {
1000
+ issues: [],
1001
+ contextualErrorMap: params?.errorMap,
1002
+ async: true
1003
+ },
1004
+ path: params?.path || [],
1005
+ schemaErrorMap: this._def.errorMap,
1006
+ parent: null,
1007
+ data,
1008
+ parsedType: getParsedType(data)
1009
+ };
1010
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
1011
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1012
+ return handleResult(ctx, result);
1013
+ }
1014
+ refine(check, message) {
1015
+ const getIssueProperties = (val) => {
1016
+ if (typeof message === "string" || typeof message === "undefined") {
1017
+ return { message };
1018
+ } else if (typeof message === "function") {
1019
+ return message(val);
1020
+ } else {
1021
+ return message;
1022
+ }
1023
+ };
1024
+ return this._refinement((val, ctx) => {
1025
+ const result = check(val);
1026
+ const setError = () => ctx.addIssue({
1027
+ code: ZodIssueCode.custom,
1028
+ ...getIssueProperties(val)
1029
+ });
1030
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
1031
+ return result.then((data) => {
1032
+ if (!data) {
1033
+ setError();
1034
+ return false;
1035
+ } else {
1036
+ return true;
1037
+ }
1038
+ });
1039
+ }
1040
+ if (!result) {
1041
+ setError();
1042
+ return false;
1043
+ } else {
1044
+ return true;
1045
+ }
1046
+ });
1047
+ }
1048
+ refinement(check, refinementData) {
1049
+ return this._refinement((val, ctx) => {
1050
+ if (!check(val)) {
1051
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
1052
+ return false;
1053
+ } else {
1054
+ return true;
1055
+ }
1056
+ });
1057
+ }
1058
+ _refinement(refinement) {
1059
+ return new ZodEffects({
1060
+ schema: this,
1061
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1062
+ effect: { type: "refinement", refinement }
1063
+ });
1064
+ }
1065
+ superRefine(refinement) {
1066
+ return this._refinement(refinement);
1067
+ }
1068
+ constructor(def) {
1069
+ this.spa = this.safeParseAsync;
1070
+ this._def = def;
1071
+ this.parse = this.parse.bind(this);
1072
+ this.safeParse = this.safeParse.bind(this);
1073
+ this.parseAsync = this.parseAsync.bind(this);
1074
+ this.safeParseAsync = this.safeParseAsync.bind(this);
1075
+ this.spa = this.spa.bind(this);
1076
+ this.refine = this.refine.bind(this);
1077
+ this.refinement = this.refinement.bind(this);
1078
+ this.superRefine = this.superRefine.bind(this);
1079
+ this.optional = this.optional.bind(this);
1080
+ this.nullable = this.nullable.bind(this);
1081
+ this.nullish = this.nullish.bind(this);
1082
+ this.array = this.array.bind(this);
1083
+ this.promise = this.promise.bind(this);
1084
+ this.or = this.or.bind(this);
1085
+ this.and = this.and.bind(this);
1086
+ this.transform = this.transform.bind(this);
1087
+ this.brand = this.brand.bind(this);
1088
+ this.default = this.default.bind(this);
1089
+ this.catch = this.catch.bind(this);
1090
+ this.describe = this.describe.bind(this);
1091
+ this.pipe = this.pipe.bind(this);
1092
+ this.readonly = this.readonly.bind(this);
1093
+ this.isNullable = this.isNullable.bind(this);
1094
+ this.isOptional = this.isOptional.bind(this);
1095
+ this["~standard"] = {
1096
+ version: 1,
1097
+ vendor: "zod",
1098
+ validate: (data) => this["~validate"](data)
1099
+ };
1100
+ }
1101
+ optional() {
1102
+ return ZodOptional.create(this, this._def);
1103
+ }
1104
+ nullable() {
1105
+ return ZodNullable.create(this, this._def);
1106
+ }
1107
+ nullish() {
1108
+ return this.nullable().optional();
1109
+ }
1110
+ array() {
1111
+ return ZodArray.create(this);
1112
+ }
1113
+ promise() {
1114
+ return ZodPromise.create(this, this._def);
1115
+ }
1116
+ or(option) {
1117
+ return ZodUnion.create([this, option], this._def);
1118
+ }
1119
+ and(incoming) {
1120
+ return ZodIntersection.create(this, incoming, this._def);
1121
+ }
1122
+ transform(transform) {
1123
+ return new ZodEffects({
1124
+ ...processCreateParams(this._def),
1125
+ schema: this,
1126
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1127
+ effect: { type: "transform", transform }
1128
+ });
1129
+ }
1130
+ default(def) {
1131
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
1132
+ return new ZodDefault({
1133
+ ...processCreateParams(this._def),
1134
+ innerType: this,
1135
+ defaultValue: defaultValueFunc,
1136
+ typeName: ZodFirstPartyTypeKind.ZodDefault
1137
+ });
1138
+ }
1139
+ brand() {
1140
+ return new ZodBranded({
1141
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
1142
+ type: this,
1143
+ ...processCreateParams(this._def)
1144
+ });
1145
+ }
1146
+ catch(def) {
1147
+ const catchValueFunc = typeof def === "function" ? def : () => def;
1148
+ return new ZodCatch({
1149
+ ...processCreateParams(this._def),
1150
+ innerType: this,
1151
+ catchValue: catchValueFunc,
1152
+ typeName: ZodFirstPartyTypeKind.ZodCatch
1153
+ });
1154
+ }
1155
+ describe(description) {
1156
+ const This = this.constructor;
1157
+ return new This({
1158
+ ...this._def,
1159
+ description
1160
+ });
1161
+ }
1162
+ pipe(target) {
1163
+ return ZodPipeline.create(this, target);
1164
+ }
1165
+ readonly() {
1166
+ return ZodReadonly.create(this);
1167
+ }
1168
+ isOptional() {
1169
+ return this.safeParse(undefined).success;
1170
+ }
1171
+ isNullable() {
1172
+ return this.safeParse(null).success;
1173
+ }
1174
+ }
1175
+ var cuidRegex = /^c[^\s-]{8,}$/i;
1176
+ var cuid2Regex = /^[0-9a-z]+$/;
1177
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1178
+ var uuidRegex = /^[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}$/i;
1179
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
1180
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1181
+ var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
1182
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1183
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1184
+ var emojiRegex;
1185
+ var ipv4Regex = /^(?:(?: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])$/;
1186
+ var ipv4CidrRegex = /^(?:(?: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])$/;
1187
+ var ipv6Regex = /^(([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]))$/;
1188
+ var ipv6CidrRegex = /^(([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])$/;
1189
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1190
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1191
+ var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
1192
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
1193
+ function timeRegexSource(args) {
1194
+ let secondsRegexSource = `[0-5]\\d`;
1195
+ if (args.precision) {
1196
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
1197
+ } else if (args.precision == null) {
1198
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
1199
+ }
1200
+ const secondsQuantifier = args.precision ? "+" : "?";
1201
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
1202
+ }
1203
+ function timeRegex(args) {
1204
+ return new RegExp(`^${timeRegexSource(args)}$`);
1205
+ }
1206
+ function datetimeRegex(args) {
1207
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1208
+ const opts = [];
1209
+ opts.push(args.local ? `Z?` : `Z`);
1210
+ if (args.offset)
1211
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1212
+ regex = `${regex}(${opts.join("|")})`;
1213
+ return new RegExp(`^${regex}$`);
1214
+ }
1215
+ function isValidIP(ip, version) {
1216
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1217
+ return true;
1218
+ }
1219
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1220
+ return true;
1221
+ }
1222
+ return false;
1223
+ }
1224
+ function isValidJWT(jwt, alg) {
1225
+ if (!jwtRegex.test(jwt))
1226
+ return false;
1227
+ try {
1228
+ const [header] = jwt.split(".");
1229
+ if (!header)
1230
+ return false;
1231
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1232
+ const decoded = JSON.parse(atob(base64));
1233
+ if (typeof decoded !== "object" || decoded === null)
1234
+ return false;
1235
+ if ("typ" in decoded && decoded?.typ !== "JWT")
1236
+ return false;
1237
+ if (!decoded.alg)
1238
+ return false;
1239
+ if (alg && decoded.alg !== alg)
1240
+ return false;
1241
+ return true;
1242
+ } catch {
1243
+ return false;
1244
+ }
1245
+ }
1246
+ function isValidCidr(ip, version) {
1247
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1248
+ return true;
1249
+ }
1250
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1251
+ return true;
1252
+ }
1253
+ return false;
1254
+ }
1255
+
1256
+ class ZodString extends ZodType {
1257
+ _parse(input) {
1258
+ if (this._def.coerce) {
1259
+ input.data = String(input.data);
1260
+ }
1261
+ const parsedType = this._getType(input);
1262
+ if (parsedType !== ZodParsedType.string) {
1263
+ const ctx2 = this._getOrReturnCtx(input);
1264
+ addIssueToContext(ctx2, {
1265
+ code: ZodIssueCode.invalid_type,
1266
+ expected: ZodParsedType.string,
1267
+ received: ctx2.parsedType
1268
+ });
1269
+ return INVALID;
1270
+ }
1271
+ const status = new ParseStatus;
1272
+ let ctx = undefined;
1273
+ for (const check of this._def.checks) {
1274
+ if (check.kind === "min") {
1275
+ if (input.data.length < check.value) {
1276
+ ctx = this._getOrReturnCtx(input, ctx);
1277
+ addIssueToContext(ctx, {
1278
+ code: ZodIssueCode.too_small,
1279
+ minimum: check.value,
1280
+ type: "string",
1281
+ inclusive: true,
1282
+ exact: false,
1283
+ message: check.message
1284
+ });
1285
+ status.dirty();
1286
+ }
1287
+ } else if (check.kind === "max") {
1288
+ if (input.data.length > check.value) {
1289
+ ctx = this._getOrReturnCtx(input, ctx);
1290
+ addIssueToContext(ctx, {
1291
+ code: ZodIssueCode.too_big,
1292
+ maximum: check.value,
1293
+ type: "string",
1294
+ inclusive: true,
1295
+ exact: false,
1296
+ message: check.message
1297
+ });
1298
+ status.dirty();
1299
+ }
1300
+ } else if (check.kind === "length") {
1301
+ const tooBig = input.data.length > check.value;
1302
+ const tooSmall = input.data.length < check.value;
1303
+ if (tooBig || tooSmall) {
1304
+ ctx = this._getOrReturnCtx(input, ctx);
1305
+ if (tooBig) {
1306
+ addIssueToContext(ctx, {
1307
+ code: ZodIssueCode.too_big,
1308
+ maximum: check.value,
1309
+ type: "string",
1310
+ inclusive: true,
1311
+ exact: true,
1312
+ message: check.message
1313
+ });
1314
+ } else if (tooSmall) {
1315
+ addIssueToContext(ctx, {
1316
+ code: ZodIssueCode.too_small,
1317
+ minimum: check.value,
1318
+ type: "string",
1319
+ inclusive: true,
1320
+ exact: true,
1321
+ message: check.message
1322
+ });
1323
+ }
1324
+ status.dirty();
1325
+ }
1326
+ } else if (check.kind === "email") {
1327
+ if (!emailRegex.test(input.data)) {
1328
+ ctx = this._getOrReturnCtx(input, ctx);
1329
+ addIssueToContext(ctx, {
1330
+ validation: "email",
1331
+ code: ZodIssueCode.invalid_string,
1332
+ message: check.message
1333
+ });
1334
+ status.dirty();
1335
+ }
1336
+ } else if (check.kind === "emoji") {
1337
+ if (!emojiRegex) {
1338
+ emojiRegex = new RegExp(_emojiRegex, "u");
1339
+ }
1340
+ if (!emojiRegex.test(input.data)) {
1341
+ ctx = this._getOrReturnCtx(input, ctx);
1342
+ addIssueToContext(ctx, {
1343
+ validation: "emoji",
1344
+ code: ZodIssueCode.invalid_string,
1345
+ message: check.message
1346
+ });
1347
+ status.dirty();
1348
+ }
1349
+ } else if (check.kind === "uuid") {
1350
+ if (!uuidRegex.test(input.data)) {
1351
+ ctx = this._getOrReturnCtx(input, ctx);
1352
+ addIssueToContext(ctx, {
1353
+ validation: "uuid",
1354
+ code: ZodIssueCode.invalid_string,
1355
+ message: check.message
1356
+ });
1357
+ status.dirty();
1358
+ }
1359
+ } else if (check.kind === "nanoid") {
1360
+ if (!nanoidRegex.test(input.data)) {
1361
+ ctx = this._getOrReturnCtx(input, ctx);
1362
+ addIssueToContext(ctx, {
1363
+ validation: "nanoid",
1364
+ code: ZodIssueCode.invalid_string,
1365
+ message: check.message
1366
+ });
1367
+ status.dirty();
1368
+ }
1369
+ } else if (check.kind === "cuid") {
1370
+ if (!cuidRegex.test(input.data)) {
1371
+ ctx = this._getOrReturnCtx(input, ctx);
1372
+ addIssueToContext(ctx, {
1373
+ validation: "cuid",
1374
+ code: ZodIssueCode.invalid_string,
1375
+ message: check.message
1376
+ });
1377
+ status.dirty();
1378
+ }
1379
+ } else if (check.kind === "cuid2") {
1380
+ if (!cuid2Regex.test(input.data)) {
1381
+ ctx = this._getOrReturnCtx(input, ctx);
1382
+ addIssueToContext(ctx, {
1383
+ validation: "cuid2",
1384
+ code: ZodIssueCode.invalid_string,
1385
+ message: check.message
1386
+ });
1387
+ status.dirty();
1388
+ }
1389
+ } else if (check.kind === "ulid") {
1390
+ if (!ulidRegex.test(input.data)) {
1391
+ ctx = this._getOrReturnCtx(input, ctx);
1392
+ addIssueToContext(ctx, {
1393
+ validation: "ulid",
1394
+ code: ZodIssueCode.invalid_string,
1395
+ message: check.message
1396
+ });
1397
+ status.dirty();
1398
+ }
1399
+ } else if (check.kind === "url") {
1400
+ try {
1401
+ new URL(input.data);
1402
+ } catch {
1403
+ ctx = this._getOrReturnCtx(input, ctx);
1404
+ addIssueToContext(ctx, {
1405
+ validation: "url",
1406
+ code: ZodIssueCode.invalid_string,
1407
+ message: check.message
1408
+ });
1409
+ status.dirty();
1410
+ }
1411
+ } else if (check.kind === "regex") {
1412
+ check.regex.lastIndex = 0;
1413
+ const testResult = check.regex.test(input.data);
1414
+ if (!testResult) {
1415
+ ctx = this._getOrReturnCtx(input, ctx);
1416
+ addIssueToContext(ctx, {
1417
+ validation: "regex",
1418
+ code: ZodIssueCode.invalid_string,
1419
+ message: check.message
1420
+ });
1421
+ status.dirty();
1422
+ }
1423
+ } else if (check.kind === "trim") {
1424
+ input.data = input.data.trim();
1425
+ } else if (check.kind === "includes") {
1426
+ if (!input.data.includes(check.value, check.position)) {
1427
+ ctx = this._getOrReturnCtx(input, ctx);
1428
+ addIssueToContext(ctx, {
1429
+ code: ZodIssueCode.invalid_string,
1430
+ validation: { includes: check.value, position: check.position },
1431
+ message: check.message
1432
+ });
1433
+ status.dirty();
1434
+ }
1435
+ } else if (check.kind === "toLowerCase") {
1436
+ input.data = input.data.toLowerCase();
1437
+ } else if (check.kind === "toUpperCase") {
1438
+ input.data = input.data.toUpperCase();
1439
+ } else if (check.kind === "startsWith") {
1440
+ if (!input.data.startsWith(check.value)) {
1441
+ ctx = this._getOrReturnCtx(input, ctx);
1442
+ addIssueToContext(ctx, {
1443
+ code: ZodIssueCode.invalid_string,
1444
+ validation: { startsWith: check.value },
1445
+ message: check.message
1446
+ });
1447
+ status.dirty();
1448
+ }
1449
+ } else if (check.kind === "endsWith") {
1450
+ if (!input.data.endsWith(check.value)) {
1451
+ ctx = this._getOrReturnCtx(input, ctx);
1452
+ addIssueToContext(ctx, {
1453
+ code: ZodIssueCode.invalid_string,
1454
+ validation: { endsWith: check.value },
1455
+ message: check.message
1456
+ });
1457
+ status.dirty();
1458
+ }
1459
+ } else if (check.kind === "datetime") {
1460
+ const regex = datetimeRegex(check);
1461
+ if (!regex.test(input.data)) {
1462
+ ctx = this._getOrReturnCtx(input, ctx);
1463
+ addIssueToContext(ctx, {
1464
+ code: ZodIssueCode.invalid_string,
1465
+ validation: "datetime",
1466
+ message: check.message
1467
+ });
1468
+ status.dirty();
1469
+ }
1470
+ } else if (check.kind === "date") {
1471
+ const regex = dateRegex;
1472
+ if (!regex.test(input.data)) {
1473
+ ctx = this._getOrReturnCtx(input, ctx);
1474
+ addIssueToContext(ctx, {
1475
+ code: ZodIssueCode.invalid_string,
1476
+ validation: "date",
1477
+ message: check.message
1478
+ });
1479
+ status.dirty();
1480
+ }
1481
+ } else if (check.kind === "time") {
1482
+ const regex = timeRegex(check);
1483
+ if (!regex.test(input.data)) {
1484
+ ctx = this._getOrReturnCtx(input, ctx);
1485
+ addIssueToContext(ctx, {
1486
+ code: ZodIssueCode.invalid_string,
1487
+ validation: "time",
1488
+ message: check.message
1489
+ });
1490
+ status.dirty();
1491
+ }
1492
+ } else if (check.kind === "duration") {
1493
+ if (!durationRegex.test(input.data)) {
1494
+ ctx = this._getOrReturnCtx(input, ctx);
1495
+ addIssueToContext(ctx, {
1496
+ validation: "duration",
1497
+ code: ZodIssueCode.invalid_string,
1498
+ message: check.message
1499
+ });
1500
+ status.dirty();
1501
+ }
1502
+ } else if (check.kind === "ip") {
1503
+ if (!isValidIP(input.data, check.version)) {
1504
+ ctx = this._getOrReturnCtx(input, ctx);
1505
+ addIssueToContext(ctx, {
1506
+ validation: "ip",
1507
+ code: ZodIssueCode.invalid_string,
1508
+ message: check.message
1509
+ });
1510
+ status.dirty();
1511
+ }
1512
+ } else if (check.kind === "jwt") {
1513
+ if (!isValidJWT(input.data, check.alg)) {
1514
+ ctx = this._getOrReturnCtx(input, ctx);
1515
+ addIssueToContext(ctx, {
1516
+ validation: "jwt",
1517
+ code: ZodIssueCode.invalid_string,
1518
+ message: check.message
1519
+ });
1520
+ status.dirty();
1521
+ }
1522
+ } else if (check.kind === "cidr") {
1523
+ if (!isValidCidr(input.data, check.version)) {
1524
+ ctx = this._getOrReturnCtx(input, ctx);
1525
+ addIssueToContext(ctx, {
1526
+ validation: "cidr",
1527
+ code: ZodIssueCode.invalid_string,
1528
+ message: check.message
1529
+ });
1530
+ status.dirty();
1531
+ }
1532
+ } else if (check.kind === "base64") {
1533
+ if (!base64Regex.test(input.data)) {
1534
+ ctx = this._getOrReturnCtx(input, ctx);
1535
+ addIssueToContext(ctx, {
1536
+ validation: "base64",
1537
+ code: ZodIssueCode.invalid_string,
1538
+ message: check.message
1539
+ });
1540
+ status.dirty();
1541
+ }
1542
+ } else if (check.kind === "base64url") {
1543
+ if (!base64urlRegex.test(input.data)) {
1544
+ ctx = this._getOrReturnCtx(input, ctx);
1545
+ addIssueToContext(ctx, {
1546
+ validation: "base64url",
1547
+ code: ZodIssueCode.invalid_string,
1548
+ message: check.message
1549
+ });
1550
+ status.dirty();
1551
+ }
1552
+ } else {
1553
+ util.assertNever(check);
1554
+ }
1555
+ }
1556
+ return { status: status.value, value: input.data };
1557
+ }
1558
+ _regex(regex, validation, message) {
1559
+ return this.refinement((data) => regex.test(data), {
1560
+ validation,
1561
+ code: ZodIssueCode.invalid_string,
1562
+ ...errorUtil.errToObj(message)
1563
+ });
1564
+ }
1565
+ _addCheck(check) {
1566
+ return new ZodString({
1567
+ ...this._def,
1568
+ checks: [...this._def.checks, check]
1569
+ });
1570
+ }
1571
+ email(message) {
1572
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1573
+ }
1574
+ url(message) {
1575
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1576
+ }
1577
+ emoji(message) {
1578
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1579
+ }
1580
+ uuid(message) {
1581
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1582
+ }
1583
+ nanoid(message) {
1584
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1585
+ }
1586
+ cuid(message) {
1587
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1588
+ }
1589
+ cuid2(message) {
1590
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1591
+ }
1592
+ ulid(message) {
1593
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1594
+ }
1595
+ base64(message) {
1596
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1597
+ }
1598
+ base64url(message) {
1599
+ return this._addCheck({
1600
+ kind: "base64url",
1601
+ ...errorUtil.errToObj(message)
1602
+ });
1603
+ }
1604
+ jwt(options) {
1605
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1606
+ }
1607
+ ip(options) {
1608
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1609
+ }
1610
+ cidr(options) {
1611
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1612
+ }
1613
+ datetime(options) {
1614
+ if (typeof options === "string") {
1615
+ return this._addCheck({
1616
+ kind: "datetime",
1617
+ precision: null,
1618
+ offset: false,
1619
+ local: false,
1620
+ message: options
1621
+ });
1622
+ }
1623
+ return this._addCheck({
1624
+ kind: "datetime",
1625
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1626
+ offset: options?.offset ?? false,
1627
+ local: options?.local ?? false,
1628
+ ...errorUtil.errToObj(options?.message)
1629
+ });
1630
+ }
1631
+ date(message) {
1632
+ return this._addCheck({ kind: "date", message });
1633
+ }
1634
+ time(options) {
1635
+ if (typeof options === "string") {
1636
+ return this._addCheck({
1637
+ kind: "time",
1638
+ precision: null,
1639
+ message: options
1640
+ });
1641
+ }
1642
+ return this._addCheck({
1643
+ kind: "time",
1644
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1645
+ ...errorUtil.errToObj(options?.message)
1646
+ });
1647
+ }
1648
+ duration(message) {
1649
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1650
+ }
1651
+ regex(regex, message) {
1652
+ return this._addCheck({
1653
+ kind: "regex",
1654
+ regex,
1655
+ ...errorUtil.errToObj(message)
1656
+ });
1657
+ }
1658
+ includes(value, options) {
1659
+ return this._addCheck({
1660
+ kind: "includes",
1661
+ value,
1662
+ position: options?.position,
1663
+ ...errorUtil.errToObj(options?.message)
1664
+ });
1665
+ }
1666
+ startsWith(value, message) {
1667
+ return this._addCheck({
1668
+ kind: "startsWith",
1669
+ value,
1670
+ ...errorUtil.errToObj(message)
1671
+ });
1672
+ }
1673
+ endsWith(value, message) {
1674
+ return this._addCheck({
1675
+ kind: "endsWith",
1676
+ value,
1677
+ ...errorUtil.errToObj(message)
1678
+ });
1679
+ }
1680
+ min(minLength, message) {
1681
+ return this._addCheck({
1682
+ kind: "min",
1683
+ value: minLength,
1684
+ ...errorUtil.errToObj(message)
1685
+ });
1686
+ }
1687
+ max(maxLength, message) {
1688
+ return this._addCheck({
1689
+ kind: "max",
1690
+ value: maxLength,
1691
+ ...errorUtil.errToObj(message)
1692
+ });
1693
+ }
1694
+ length(len, message) {
1695
+ return this._addCheck({
1696
+ kind: "length",
1697
+ value: len,
1698
+ ...errorUtil.errToObj(message)
1699
+ });
1700
+ }
1701
+ nonempty(message) {
1702
+ return this.min(1, errorUtil.errToObj(message));
1703
+ }
1704
+ trim() {
1705
+ return new ZodString({
1706
+ ...this._def,
1707
+ checks: [...this._def.checks, { kind: "trim" }]
1708
+ });
1709
+ }
1710
+ toLowerCase() {
1711
+ return new ZodString({
1712
+ ...this._def,
1713
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
1714
+ });
1715
+ }
1716
+ toUpperCase() {
1717
+ return new ZodString({
1718
+ ...this._def,
1719
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
1720
+ });
1721
+ }
1722
+ get isDatetime() {
1723
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
1724
+ }
1725
+ get isDate() {
1726
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1727
+ }
1728
+ get isTime() {
1729
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1730
+ }
1731
+ get isDuration() {
1732
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1733
+ }
1734
+ get isEmail() {
1735
+ return !!this._def.checks.find((ch) => ch.kind === "email");
1736
+ }
1737
+ get isURL() {
1738
+ return !!this._def.checks.find((ch) => ch.kind === "url");
1739
+ }
1740
+ get isEmoji() {
1741
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
1742
+ }
1743
+ get isUUID() {
1744
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
1745
+ }
1746
+ get isNANOID() {
1747
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1748
+ }
1749
+ get isCUID() {
1750
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
1751
+ }
1752
+ get isCUID2() {
1753
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1754
+ }
1755
+ get isULID() {
1756
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
1757
+ }
1758
+ get isIP() {
1759
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
1760
+ }
1761
+ get isCIDR() {
1762
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
1763
+ }
1764
+ get isBase64() {
1765
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
1766
+ }
1767
+ get isBase64url() {
1768
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
1769
+ }
1770
+ get minLength() {
1771
+ let min = null;
1772
+ for (const ch of this._def.checks) {
1773
+ if (ch.kind === "min") {
1774
+ if (min === null || ch.value > min)
1775
+ min = ch.value;
1776
+ }
1777
+ }
1778
+ return min;
1779
+ }
1780
+ get maxLength() {
1781
+ let max = null;
1782
+ for (const ch of this._def.checks) {
1783
+ if (ch.kind === "max") {
1784
+ if (max === null || ch.value < max)
1785
+ max = ch.value;
1786
+ }
1787
+ }
1788
+ return max;
1789
+ }
1790
+ }
1791
+ ZodString.create = (params) => {
1792
+ return new ZodString({
1793
+ checks: [],
1794
+ typeName: ZodFirstPartyTypeKind.ZodString,
1795
+ coerce: params?.coerce ?? false,
1796
+ ...processCreateParams(params)
1797
+ });
1798
+ };
1799
+ function floatSafeRemainder(val, step) {
1800
+ const valDecCount = (val.toString().split(".")[1] || "").length;
1801
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
1802
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1803
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1804
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1805
+ return valInt % stepInt / 10 ** decCount;
1806
+ }
1807
+
1808
+ class ZodNumber extends ZodType {
1809
+ constructor() {
1810
+ super(...arguments);
1811
+ this.min = this.gte;
1812
+ this.max = this.lte;
1813
+ this.step = this.multipleOf;
1814
+ }
1815
+ _parse(input) {
1816
+ if (this._def.coerce) {
1817
+ input.data = Number(input.data);
1818
+ }
1819
+ const parsedType = this._getType(input);
1820
+ if (parsedType !== ZodParsedType.number) {
1821
+ const ctx2 = this._getOrReturnCtx(input);
1822
+ addIssueToContext(ctx2, {
1823
+ code: ZodIssueCode.invalid_type,
1824
+ expected: ZodParsedType.number,
1825
+ received: ctx2.parsedType
1826
+ });
1827
+ return INVALID;
1828
+ }
1829
+ let ctx = undefined;
1830
+ const status = new ParseStatus;
1831
+ for (const check of this._def.checks) {
1832
+ if (check.kind === "int") {
1833
+ if (!util.isInteger(input.data)) {
1834
+ ctx = this._getOrReturnCtx(input, ctx);
1835
+ addIssueToContext(ctx, {
1836
+ code: ZodIssueCode.invalid_type,
1837
+ expected: "integer",
1838
+ received: "float",
1839
+ message: check.message
1840
+ });
1841
+ status.dirty();
1842
+ }
1843
+ } else if (check.kind === "min") {
1844
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1845
+ if (tooSmall) {
1846
+ ctx = this._getOrReturnCtx(input, ctx);
1847
+ addIssueToContext(ctx, {
1848
+ code: ZodIssueCode.too_small,
1849
+ minimum: check.value,
1850
+ type: "number",
1851
+ inclusive: check.inclusive,
1852
+ exact: false,
1853
+ message: check.message
1854
+ });
1855
+ status.dirty();
1856
+ }
1857
+ } else if (check.kind === "max") {
1858
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1859
+ if (tooBig) {
1860
+ ctx = this._getOrReturnCtx(input, ctx);
1861
+ addIssueToContext(ctx, {
1862
+ code: ZodIssueCode.too_big,
1863
+ maximum: check.value,
1864
+ type: "number",
1865
+ inclusive: check.inclusive,
1866
+ exact: false,
1867
+ message: check.message
1868
+ });
1869
+ status.dirty();
1870
+ }
1871
+ } else if (check.kind === "multipleOf") {
1872
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
1873
+ ctx = this._getOrReturnCtx(input, ctx);
1874
+ addIssueToContext(ctx, {
1875
+ code: ZodIssueCode.not_multiple_of,
1876
+ multipleOf: check.value,
1877
+ message: check.message
1878
+ });
1879
+ status.dirty();
1880
+ }
1881
+ } else if (check.kind === "finite") {
1882
+ if (!Number.isFinite(input.data)) {
1883
+ ctx = this._getOrReturnCtx(input, ctx);
1884
+ addIssueToContext(ctx, {
1885
+ code: ZodIssueCode.not_finite,
1886
+ message: check.message
1887
+ });
1888
+ status.dirty();
1889
+ }
1890
+ } else {
1891
+ util.assertNever(check);
1892
+ }
1893
+ }
1894
+ return { status: status.value, value: input.data };
1895
+ }
1896
+ gte(value, message) {
1897
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1898
+ }
1899
+ gt(value, message) {
1900
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1901
+ }
1902
+ lte(value, message) {
1903
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1904
+ }
1905
+ lt(value, message) {
1906
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1907
+ }
1908
+ setLimit(kind, value, inclusive, message) {
1909
+ return new ZodNumber({
1910
+ ...this._def,
1911
+ checks: [
1912
+ ...this._def.checks,
1913
+ {
1914
+ kind,
1915
+ value,
1916
+ inclusive,
1917
+ message: errorUtil.toString(message)
1918
+ }
1919
+ ]
1920
+ });
1921
+ }
1922
+ _addCheck(check) {
1923
+ return new ZodNumber({
1924
+ ...this._def,
1925
+ checks: [...this._def.checks, check]
1926
+ });
1927
+ }
1928
+ int(message) {
1929
+ return this._addCheck({
1930
+ kind: "int",
1931
+ message: errorUtil.toString(message)
1932
+ });
1933
+ }
1934
+ positive(message) {
1935
+ return this._addCheck({
1936
+ kind: "min",
1937
+ value: 0,
1938
+ inclusive: false,
1939
+ message: errorUtil.toString(message)
1940
+ });
1941
+ }
1942
+ negative(message) {
1943
+ return this._addCheck({
1944
+ kind: "max",
1945
+ value: 0,
1946
+ inclusive: false,
1947
+ message: errorUtil.toString(message)
1948
+ });
1949
+ }
1950
+ nonpositive(message) {
1951
+ return this._addCheck({
1952
+ kind: "max",
1953
+ value: 0,
1954
+ inclusive: true,
1955
+ message: errorUtil.toString(message)
1956
+ });
1957
+ }
1958
+ nonnegative(message) {
1959
+ return this._addCheck({
1960
+ kind: "min",
1961
+ value: 0,
1962
+ inclusive: true,
1963
+ message: errorUtil.toString(message)
1964
+ });
1965
+ }
1966
+ multipleOf(value, message) {
1967
+ return this._addCheck({
1968
+ kind: "multipleOf",
1969
+ value,
1970
+ message: errorUtil.toString(message)
1971
+ });
1972
+ }
1973
+ finite(message) {
1974
+ return this._addCheck({
1975
+ kind: "finite",
1976
+ message: errorUtil.toString(message)
1977
+ });
1978
+ }
1979
+ safe(message) {
1980
+ return this._addCheck({
1981
+ kind: "min",
1982
+ inclusive: true,
1983
+ value: Number.MIN_SAFE_INTEGER,
1984
+ message: errorUtil.toString(message)
1985
+ })._addCheck({
1986
+ kind: "max",
1987
+ inclusive: true,
1988
+ value: Number.MAX_SAFE_INTEGER,
1989
+ message: errorUtil.toString(message)
1990
+ });
1991
+ }
1992
+ get minValue() {
1993
+ let min = null;
1994
+ for (const ch of this._def.checks) {
1995
+ if (ch.kind === "min") {
1996
+ if (min === null || ch.value > min)
1997
+ min = ch.value;
1998
+ }
1999
+ }
2000
+ return min;
2001
+ }
2002
+ get maxValue() {
2003
+ let max = null;
2004
+ for (const ch of this._def.checks) {
2005
+ if (ch.kind === "max") {
2006
+ if (max === null || ch.value < max)
2007
+ max = ch.value;
2008
+ }
2009
+ }
2010
+ return max;
2011
+ }
2012
+ get isInt() {
2013
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
2014
+ }
2015
+ get isFinite() {
2016
+ let max = null;
2017
+ let min = null;
2018
+ for (const ch of this._def.checks) {
2019
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
2020
+ return true;
2021
+ } else if (ch.kind === "min") {
2022
+ if (min === null || ch.value > min)
2023
+ min = ch.value;
2024
+ } else if (ch.kind === "max") {
2025
+ if (max === null || ch.value < max)
2026
+ max = ch.value;
2027
+ }
2028
+ }
2029
+ return Number.isFinite(min) && Number.isFinite(max);
2030
+ }
2031
+ }
2032
+ ZodNumber.create = (params) => {
2033
+ return new ZodNumber({
2034
+ checks: [],
2035
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
2036
+ coerce: params?.coerce || false,
2037
+ ...processCreateParams(params)
2038
+ });
2039
+ };
2040
+
2041
+ class ZodBigInt extends ZodType {
2042
+ constructor() {
2043
+ super(...arguments);
2044
+ this.min = this.gte;
2045
+ this.max = this.lte;
2046
+ }
2047
+ _parse(input) {
2048
+ if (this._def.coerce) {
2049
+ try {
2050
+ input.data = BigInt(input.data);
2051
+ } catch {
2052
+ return this._getInvalidInput(input);
2053
+ }
2054
+ }
2055
+ const parsedType = this._getType(input);
2056
+ if (parsedType !== ZodParsedType.bigint) {
2057
+ return this._getInvalidInput(input);
2058
+ }
2059
+ let ctx = undefined;
2060
+ const status = new ParseStatus;
2061
+ for (const check of this._def.checks) {
2062
+ if (check.kind === "min") {
2063
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2064
+ if (tooSmall) {
2065
+ ctx = this._getOrReturnCtx(input, ctx);
2066
+ addIssueToContext(ctx, {
2067
+ code: ZodIssueCode.too_small,
2068
+ type: "bigint",
2069
+ minimum: check.value,
2070
+ inclusive: check.inclusive,
2071
+ message: check.message
2072
+ });
2073
+ status.dirty();
2074
+ }
2075
+ } else if (check.kind === "max") {
2076
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2077
+ if (tooBig) {
2078
+ ctx = this._getOrReturnCtx(input, ctx);
2079
+ addIssueToContext(ctx, {
2080
+ code: ZodIssueCode.too_big,
2081
+ type: "bigint",
2082
+ maximum: check.value,
2083
+ inclusive: check.inclusive,
2084
+ message: check.message
2085
+ });
2086
+ status.dirty();
2087
+ }
2088
+ } else if (check.kind === "multipleOf") {
2089
+ if (input.data % check.value !== BigInt(0)) {
2090
+ ctx = this._getOrReturnCtx(input, ctx);
2091
+ addIssueToContext(ctx, {
2092
+ code: ZodIssueCode.not_multiple_of,
2093
+ multipleOf: check.value,
2094
+ message: check.message
2095
+ });
2096
+ status.dirty();
2097
+ }
2098
+ } else {
2099
+ util.assertNever(check);
2100
+ }
2101
+ }
2102
+ return { status: status.value, value: input.data };
2103
+ }
2104
+ _getInvalidInput(input) {
2105
+ const ctx = this._getOrReturnCtx(input);
2106
+ addIssueToContext(ctx, {
2107
+ code: ZodIssueCode.invalid_type,
2108
+ expected: ZodParsedType.bigint,
2109
+ received: ctx.parsedType
2110
+ });
2111
+ return INVALID;
2112
+ }
2113
+ gte(value, message) {
2114
+ return this.setLimit("min", value, true, errorUtil.toString(message));
2115
+ }
2116
+ gt(value, message) {
2117
+ return this.setLimit("min", value, false, errorUtil.toString(message));
2118
+ }
2119
+ lte(value, message) {
2120
+ return this.setLimit("max", value, true, errorUtil.toString(message));
2121
+ }
2122
+ lt(value, message) {
2123
+ return this.setLimit("max", value, false, errorUtil.toString(message));
2124
+ }
2125
+ setLimit(kind, value, inclusive, message) {
2126
+ return new ZodBigInt({
2127
+ ...this._def,
2128
+ checks: [
2129
+ ...this._def.checks,
2130
+ {
2131
+ kind,
2132
+ value,
2133
+ inclusive,
2134
+ message: errorUtil.toString(message)
2135
+ }
2136
+ ]
2137
+ });
2138
+ }
2139
+ _addCheck(check) {
2140
+ return new ZodBigInt({
2141
+ ...this._def,
2142
+ checks: [...this._def.checks, check]
2143
+ });
2144
+ }
2145
+ positive(message) {
2146
+ return this._addCheck({
2147
+ kind: "min",
2148
+ value: BigInt(0),
2149
+ inclusive: false,
2150
+ message: errorUtil.toString(message)
2151
+ });
2152
+ }
2153
+ negative(message) {
2154
+ return this._addCheck({
2155
+ kind: "max",
2156
+ value: BigInt(0),
2157
+ inclusive: false,
2158
+ message: errorUtil.toString(message)
2159
+ });
2160
+ }
2161
+ nonpositive(message) {
2162
+ return this._addCheck({
2163
+ kind: "max",
2164
+ value: BigInt(0),
2165
+ inclusive: true,
2166
+ message: errorUtil.toString(message)
2167
+ });
2168
+ }
2169
+ nonnegative(message) {
2170
+ return this._addCheck({
2171
+ kind: "min",
2172
+ value: BigInt(0),
2173
+ inclusive: true,
2174
+ message: errorUtil.toString(message)
2175
+ });
2176
+ }
2177
+ multipleOf(value, message) {
2178
+ return this._addCheck({
2179
+ kind: "multipleOf",
2180
+ value,
2181
+ message: errorUtil.toString(message)
2182
+ });
2183
+ }
2184
+ get minValue() {
2185
+ let min = null;
2186
+ for (const ch of this._def.checks) {
2187
+ if (ch.kind === "min") {
2188
+ if (min === null || ch.value > min)
2189
+ min = ch.value;
2190
+ }
2191
+ }
2192
+ return min;
2193
+ }
2194
+ get maxValue() {
2195
+ let max = null;
2196
+ for (const ch of this._def.checks) {
2197
+ if (ch.kind === "max") {
2198
+ if (max === null || ch.value < max)
2199
+ max = ch.value;
2200
+ }
2201
+ }
2202
+ return max;
2203
+ }
2204
+ }
2205
+ ZodBigInt.create = (params) => {
2206
+ return new ZodBigInt({
2207
+ checks: [],
2208
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
2209
+ coerce: params?.coerce ?? false,
2210
+ ...processCreateParams(params)
2211
+ });
2212
+ };
2213
+
2214
+ class ZodBoolean extends ZodType {
2215
+ _parse(input) {
2216
+ if (this._def.coerce) {
2217
+ input.data = Boolean(input.data);
2218
+ }
2219
+ const parsedType = this._getType(input);
2220
+ if (parsedType !== ZodParsedType.boolean) {
2221
+ const ctx = this._getOrReturnCtx(input);
2222
+ addIssueToContext(ctx, {
2223
+ code: ZodIssueCode.invalid_type,
2224
+ expected: ZodParsedType.boolean,
2225
+ received: ctx.parsedType
2226
+ });
2227
+ return INVALID;
2228
+ }
2229
+ return OK(input.data);
2230
+ }
2231
+ }
2232
+ ZodBoolean.create = (params) => {
2233
+ return new ZodBoolean({
2234
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
2235
+ coerce: params?.coerce || false,
2236
+ ...processCreateParams(params)
2237
+ });
2238
+ };
2239
+
2240
+ class ZodDate extends ZodType {
2241
+ _parse(input) {
2242
+ if (this._def.coerce) {
2243
+ input.data = new Date(input.data);
2244
+ }
2245
+ const parsedType = this._getType(input);
2246
+ if (parsedType !== ZodParsedType.date) {
2247
+ const ctx2 = this._getOrReturnCtx(input);
2248
+ addIssueToContext(ctx2, {
2249
+ code: ZodIssueCode.invalid_type,
2250
+ expected: ZodParsedType.date,
2251
+ received: ctx2.parsedType
2252
+ });
2253
+ return INVALID;
2254
+ }
2255
+ if (Number.isNaN(input.data.getTime())) {
2256
+ const ctx2 = this._getOrReturnCtx(input);
2257
+ addIssueToContext(ctx2, {
2258
+ code: ZodIssueCode.invalid_date
2259
+ });
2260
+ return INVALID;
2261
+ }
2262
+ const status = new ParseStatus;
2263
+ let ctx = undefined;
2264
+ for (const check of this._def.checks) {
2265
+ if (check.kind === "min") {
2266
+ if (input.data.getTime() < check.value) {
2267
+ ctx = this._getOrReturnCtx(input, ctx);
2268
+ addIssueToContext(ctx, {
2269
+ code: ZodIssueCode.too_small,
2270
+ message: check.message,
2271
+ inclusive: true,
2272
+ exact: false,
2273
+ minimum: check.value,
2274
+ type: "date"
2275
+ });
2276
+ status.dirty();
2277
+ }
2278
+ } else if (check.kind === "max") {
2279
+ if (input.data.getTime() > check.value) {
2280
+ ctx = this._getOrReturnCtx(input, ctx);
2281
+ addIssueToContext(ctx, {
2282
+ code: ZodIssueCode.too_big,
2283
+ message: check.message,
2284
+ inclusive: true,
2285
+ exact: false,
2286
+ maximum: check.value,
2287
+ type: "date"
2288
+ });
2289
+ status.dirty();
2290
+ }
2291
+ } else {
2292
+ util.assertNever(check);
2293
+ }
2294
+ }
2295
+ return {
2296
+ status: status.value,
2297
+ value: new Date(input.data.getTime())
2298
+ };
2299
+ }
2300
+ _addCheck(check) {
2301
+ return new ZodDate({
2302
+ ...this._def,
2303
+ checks: [...this._def.checks, check]
2304
+ });
2305
+ }
2306
+ min(minDate, message) {
2307
+ return this._addCheck({
2308
+ kind: "min",
2309
+ value: minDate.getTime(),
2310
+ message: errorUtil.toString(message)
2311
+ });
2312
+ }
2313
+ max(maxDate, message) {
2314
+ return this._addCheck({
2315
+ kind: "max",
2316
+ value: maxDate.getTime(),
2317
+ message: errorUtil.toString(message)
2318
+ });
2319
+ }
2320
+ get minDate() {
2321
+ let min = null;
2322
+ for (const ch of this._def.checks) {
2323
+ if (ch.kind === "min") {
2324
+ if (min === null || ch.value > min)
2325
+ min = ch.value;
2326
+ }
2327
+ }
2328
+ return min != null ? new Date(min) : null;
2329
+ }
2330
+ get maxDate() {
2331
+ let max = null;
2332
+ for (const ch of this._def.checks) {
2333
+ if (ch.kind === "max") {
2334
+ if (max === null || ch.value < max)
2335
+ max = ch.value;
2336
+ }
2337
+ }
2338
+ return max != null ? new Date(max) : null;
2339
+ }
2340
+ }
2341
+ ZodDate.create = (params) => {
2342
+ return new ZodDate({
2343
+ checks: [],
2344
+ coerce: params?.coerce || false,
2345
+ typeName: ZodFirstPartyTypeKind.ZodDate,
2346
+ ...processCreateParams(params)
2347
+ });
2348
+ };
2349
+
2350
+ class ZodSymbol extends ZodType {
2351
+ _parse(input) {
2352
+ const parsedType = this._getType(input);
2353
+ if (parsedType !== ZodParsedType.symbol) {
2354
+ const ctx = this._getOrReturnCtx(input);
2355
+ addIssueToContext(ctx, {
2356
+ code: ZodIssueCode.invalid_type,
2357
+ expected: ZodParsedType.symbol,
2358
+ received: ctx.parsedType
2359
+ });
2360
+ return INVALID;
2361
+ }
2362
+ return OK(input.data);
2363
+ }
2364
+ }
2365
+ ZodSymbol.create = (params) => {
2366
+ return new ZodSymbol({
2367
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
2368
+ ...processCreateParams(params)
2369
+ });
2370
+ };
2371
+
2372
+ class ZodUndefined extends ZodType {
2373
+ _parse(input) {
2374
+ const parsedType = this._getType(input);
2375
+ if (parsedType !== ZodParsedType.undefined) {
2376
+ const ctx = this._getOrReturnCtx(input);
2377
+ addIssueToContext(ctx, {
2378
+ code: ZodIssueCode.invalid_type,
2379
+ expected: ZodParsedType.undefined,
2380
+ received: ctx.parsedType
2381
+ });
2382
+ return INVALID;
2383
+ }
2384
+ return OK(input.data);
2385
+ }
2386
+ }
2387
+ ZodUndefined.create = (params) => {
2388
+ return new ZodUndefined({
2389
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2390
+ ...processCreateParams(params)
2391
+ });
2392
+ };
2393
+
2394
+ class ZodNull extends ZodType {
2395
+ _parse(input) {
2396
+ const parsedType = this._getType(input);
2397
+ if (parsedType !== ZodParsedType.null) {
2398
+ const ctx = this._getOrReturnCtx(input);
2399
+ addIssueToContext(ctx, {
2400
+ code: ZodIssueCode.invalid_type,
2401
+ expected: ZodParsedType.null,
2402
+ received: ctx.parsedType
2403
+ });
2404
+ return INVALID;
2405
+ }
2406
+ return OK(input.data);
2407
+ }
2408
+ }
2409
+ ZodNull.create = (params) => {
2410
+ return new ZodNull({
2411
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2412
+ ...processCreateParams(params)
2413
+ });
2414
+ };
2415
+
2416
+ class ZodAny extends ZodType {
2417
+ constructor() {
2418
+ super(...arguments);
2419
+ this._any = true;
2420
+ }
2421
+ _parse(input) {
2422
+ return OK(input.data);
2423
+ }
2424
+ }
2425
+ ZodAny.create = (params) => {
2426
+ return new ZodAny({
2427
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2428
+ ...processCreateParams(params)
2429
+ });
2430
+ };
2431
+
2432
+ class ZodUnknown extends ZodType {
2433
+ constructor() {
2434
+ super(...arguments);
2435
+ this._unknown = true;
2436
+ }
2437
+ _parse(input) {
2438
+ return OK(input.data);
2439
+ }
2440
+ }
2441
+ ZodUnknown.create = (params) => {
2442
+ return new ZodUnknown({
2443
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2444
+ ...processCreateParams(params)
2445
+ });
2446
+ };
2447
+
2448
+ class ZodNever extends ZodType {
2449
+ _parse(input) {
2450
+ const ctx = this._getOrReturnCtx(input);
2451
+ addIssueToContext(ctx, {
2452
+ code: ZodIssueCode.invalid_type,
2453
+ expected: ZodParsedType.never,
2454
+ received: ctx.parsedType
2455
+ });
2456
+ return INVALID;
2457
+ }
2458
+ }
2459
+ ZodNever.create = (params) => {
2460
+ return new ZodNever({
2461
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2462
+ ...processCreateParams(params)
2463
+ });
2464
+ };
2465
+
2466
+ class ZodVoid extends ZodType {
2467
+ _parse(input) {
2468
+ const parsedType = this._getType(input);
2469
+ if (parsedType !== ZodParsedType.undefined) {
2470
+ const ctx = this._getOrReturnCtx(input);
2471
+ addIssueToContext(ctx, {
2472
+ code: ZodIssueCode.invalid_type,
2473
+ expected: ZodParsedType.void,
2474
+ received: ctx.parsedType
2475
+ });
2476
+ return INVALID;
2477
+ }
2478
+ return OK(input.data);
2479
+ }
2480
+ }
2481
+ ZodVoid.create = (params) => {
2482
+ return new ZodVoid({
2483
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2484
+ ...processCreateParams(params)
2485
+ });
2486
+ };
2487
+
2488
+ class ZodArray extends ZodType {
2489
+ _parse(input) {
2490
+ const { ctx, status } = this._processInputParams(input);
2491
+ const def = this._def;
2492
+ if (ctx.parsedType !== ZodParsedType.array) {
2493
+ addIssueToContext(ctx, {
2494
+ code: ZodIssueCode.invalid_type,
2495
+ expected: ZodParsedType.array,
2496
+ received: ctx.parsedType
2497
+ });
2498
+ return INVALID;
2499
+ }
2500
+ if (def.exactLength !== null) {
2501
+ const tooBig = ctx.data.length > def.exactLength.value;
2502
+ const tooSmall = ctx.data.length < def.exactLength.value;
2503
+ if (tooBig || tooSmall) {
2504
+ addIssueToContext(ctx, {
2505
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2506
+ minimum: tooSmall ? def.exactLength.value : undefined,
2507
+ maximum: tooBig ? def.exactLength.value : undefined,
2508
+ type: "array",
2509
+ inclusive: true,
2510
+ exact: true,
2511
+ message: def.exactLength.message
2512
+ });
2513
+ status.dirty();
2514
+ }
2515
+ }
2516
+ if (def.minLength !== null) {
2517
+ if (ctx.data.length < def.minLength.value) {
2518
+ addIssueToContext(ctx, {
2519
+ code: ZodIssueCode.too_small,
2520
+ minimum: def.minLength.value,
2521
+ type: "array",
2522
+ inclusive: true,
2523
+ exact: false,
2524
+ message: def.minLength.message
2525
+ });
2526
+ status.dirty();
2527
+ }
2528
+ }
2529
+ if (def.maxLength !== null) {
2530
+ if (ctx.data.length > def.maxLength.value) {
2531
+ addIssueToContext(ctx, {
2532
+ code: ZodIssueCode.too_big,
2533
+ maximum: def.maxLength.value,
2534
+ type: "array",
2535
+ inclusive: true,
2536
+ exact: false,
2537
+ message: def.maxLength.message
2538
+ });
2539
+ status.dirty();
2540
+ }
2541
+ }
2542
+ if (ctx.common.async) {
2543
+ return Promise.all([...ctx.data].map((item, i) => {
2544
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2545
+ })).then((result2) => {
2546
+ return ParseStatus.mergeArray(status, result2);
2547
+ });
2548
+ }
2549
+ const result = [...ctx.data].map((item, i) => {
2550
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2551
+ });
2552
+ return ParseStatus.mergeArray(status, result);
2553
+ }
2554
+ get element() {
2555
+ return this._def.type;
2556
+ }
2557
+ min(minLength, message) {
2558
+ return new ZodArray({
2559
+ ...this._def,
2560
+ minLength: { value: minLength, message: errorUtil.toString(message) }
2561
+ });
2562
+ }
2563
+ max(maxLength, message) {
2564
+ return new ZodArray({
2565
+ ...this._def,
2566
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
2567
+ });
2568
+ }
2569
+ length(len, message) {
2570
+ return new ZodArray({
2571
+ ...this._def,
2572
+ exactLength: { value: len, message: errorUtil.toString(message) }
2573
+ });
2574
+ }
2575
+ nonempty(message) {
2576
+ return this.min(1, message);
2577
+ }
2578
+ }
2579
+ ZodArray.create = (schema, params) => {
2580
+ return new ZodArray({
2581
+ type: schema,
2582
+ minLength: null,
2583
+ maxLength: null,
2584
+ exactLength: null,
2585
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2586
+ ...processCreateParams(params)
2587
+ });
2588
+ };
2589
+ function deepPartialify(schema) {
2590
+ if (schema instanceof ZodObject) {
2591
+ const newShape = {};
2592
+ for (const key in schema.shape) {
2593
+ const fieldSchema = schema.shape[key];
2594
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2595
+ }
2596
+ return new ZodObject({
2597
+ ...schema._def,
2598
+ shape: () => newShape
2599
+ });
2600
+ } else if (schema instanceof ZodArray) {
2601
+ return new ZodArray({
2602
+ ...schema._def,
2603
+ type: deepPartialify(schema.element)
2604
+ });
2605
+ } else if (schema instanceof ZodOptional) {
2606
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
2607
+ } else if (schema instanceof ZodNullable) {
2608
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
2609
+ } else if (schema instanceof ZodTuple) {
2610
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2611
+ } else {
2612
+ return schema;
2613
+ }
2614
+ }
2615
+
2616
+ class ZodObject extends ZodType {
2617
+ constructor() {
2618
+ super(...arguments);
2619
+ this._cached = null;
2620
+ this.nonstrict = this.passthrough;
2621
+ this.augment = this.extend;
2622
+ }
2623
+ _getCached() {
2624
+ if (this._cached !== null)
2625
+ return this._cached;
2626
+ const shape = this._def.shape();
2627
+ const keys = util.objectKeys(shape);
2628
+ this._cached = { shape, keys };
2629
+ return this._cached;
2630
+ }
2631
+ _parse(input) {
2632
+ const parsedType = this._getType(input);
2633
+ if (parsedType !== ZodParsedType.object) {
2634
+ const ctx2 = this._getOrReturnCtx(input);
2635
+ addIssueToContext(ctx2, {
2636
+ code: ZodIssueCode.invalid_type,
2637
+ expected: ZodParsedType.object,
2638
+ received: ctx2.parsedType
2639
+ });
2640
+ return INVALID;
2641
+ }
2642
+ const { status, ctx } = this._processInputParams(input);
2643
+ const { shape, keys: shapeKeys } = this._getCached();
2644
+ const extraKeys = [];
2645
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2646
+ for (const key in ctx.data) {
2647
+ if (!shapeKeys.includes(key)) {
2648
+ extraKeys.push(key);
2649
+ }
2650
+ }
2651
+ }
2652
+ const pairs = [];
2653
+ for (const key of shapeKeys) {
2654
+ const keyValidator = shape[key];
2655
+ const value = ctx.data[key];
2656
+ pairs.push({
2657
+ key: { status: "valid", value: key },
2658
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2659
+ alwaysSet: key in ctx.data
2660
+ });
2661
+ }
2662
+ if (this._def.catchall instanceof ZodNever) {
2663
+ const unknownKeys = this._def.unknownKeys;
2664
+ if (unknownKeys === "passthrough") {
2665
+ for (const key of extraKeys) {
2666
+ pairs.push({
2667
+ key: { status: "valid", value: key },
2668
+ value: { status: "valid", value: ctx.data[key] }
2669
+ });
2670
+ }
2671
+ } else if (unknownKeys === "strict") {
2672
+ if (extraKeys.length > 0) {
2673
+ addIssueToContext(ctx, {
2674
+ code: ZodIssueCode.unrecognized_keys,
2675
+ keys: extraKeys
2676
+ });
2677
+ status.dirty();
2678
+ }
2679
+ } else if (unknownKeys === "strip") {} else {
2680
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2681
+ }
2682
+ } else {
2683
+ const catchall = this._def.catchall;
2684
+ for (const key of extraKeys) {
2685
+ const value = ctx.data[key];
2686
+ pairs.push({
2687
+ key: { status: "valid", value: key },
2688
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2689
+ alwaysSet: key in ctx.data
2690
+ });
2691
+ }
2692
+ }
2693
+ if (ctx.common.async) {
2694
+ return Promise.resolve().then(async () => {
2695
+ const syncPairs = [];
2696
+ for (const pair of pairs) {
2697
+ const key = await pair.key;
2698
+ const value = await pair.value;
2699
+ syncPairs.push({
2700
+ key,
2701
+ value,
2702
+ alwaysSet: pair.alwaysSet
2703
+ });
2704
+ }
2705
+ return syncPairs;
2706
+ }).then((syncPairs) => {
2707
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2708
+ });
2709
+ } else {
2710
+ return ParseStatus.mergeObjectSync(status, pairs);
2711
+ }
2712
+ }
2713
+ get shape() {
2714
+ return this._def.shape();
2715
+ }
2716
+ strict(message) {
2717
+ errorUtil.errToObj;
2718
+ return new ZodObject({
2719
+ ...this._def,
2720
+ unknownKeys: "strict",
2721
+ ...message !== undefined ? {
2722
+ errorMap: (issue, ctx) => {
2723
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2724
+ if (issue.code === "unrecognized_keys")
2725
+ return {
2726
+ message: errorUtil.errToObj(message).message ?? defaultError
2727
+ };
2728
+ return {
2729
+ message: defaultError
2730
+ };
2731
+ }
2732
+ } : {}
2733
+ });
2734
+ }
2735
+ strip() {
2736
+ return new ZodObject({
2737
+ ...this._def,
2738
+ unknownKeys: "strip"
2739
+ });
2740
+ }
2741
+ passthrough() {
2742
+ return new ZodObject({
2743
+ ...this._def,
2744
+ unknownKeys: "passthrough"
2745
+ });
2746
+ }
2747
+ extend(augmentation) {
2748
+ return new ZodObject({
2749
+ ...this._def,
2750
+ shape: () => ({
2751
+ ...this._def.shape(),
2752
+ ...augmentation
2753
+ })
2754
+ });
2755
+ }
2756
+ merge(merging) {
2757
+ const merged = new ZodObject({
2758
+ unknownKeys: merging._def.unknownKeys,
2759
+ catchall: merging._def.catchall,
2760
+ shape: () => ({
2761
+ ...this._def.shape(),
2762
+ ...merging._def.shape()
2763
+ }),
2764
+ typeName: ZodFirstPartyTypeKind.ZodObject
2765
+ });
2766
+ return merged;
2767
+ }
2768
+ setKey(key, schema) {
2769
+ return this.augment({ [key]: schema });
2770
+ }
2771
+ catchall(index) {
2772
+ return new ZodObject({
2773
+ ...this._def,
2774
+ catchall: index
2775
+ });
2776
+ }
2777
+ pick(mask) {
2778
+ const shape = {};
2779
+ for (const key of util.objectKeys(mask)) {
2780
+ if (mask[key] && this.shape[key]) {
2781
+ shape[key] = this.shape[key];
2782
+ }
2783
+ }
2784
+ return new ZodObject({
2785
+ ...this._def,
2786
+ shape: () => shape
2787
+ });
2788
+ }
2789
+ omit(mask) {
2790
+ const shape = {};
2791
+ for (const key of util.objectKeys(this.shape)) {
2792
+ if (!mask[key]) {
2793
+ shape[key] = this.shape[key];
2794
+ }
2795
+ }
2796
+ return new ZodObject({
2797
+ ...this._def,
2798
+ shape: () => shape
2799
+ });
2800
+ }
2801
+ deepPartial() {
2802
+ return deepPartialify(this);
2803
+ }
2804
+ partial(mask) {
2805
+ const newShape = {};
2806
+ for (const key of util.objectKeys(this.shape)) {
2807
+ const fieldSchema = this.shape[key];
2808
+ if (mask && !mask[key]) {
2809
+ newShape[key] = fieldSchema;
2810
+ } else {
2811
+ newShape[key] = fieldSchema.optional();
2812
+ }
2813
+ }
2814
+ return new ZodObject({
2815
+ ...this._def,
2816
+ shape: () => newShape
2817
+ });
2818
+ }
2819
+ required(mask) {
2820
+ const newShape = {};
2821
+ for (const key of util.objectKeys(this.shape)) {
2822
+ if (mask && !mask[key]) {
2823
+ newShape[key] = this.shape[key];
2824
+ } else {
2825
+ const fieldSchema = this.shape[key];
2826
+ let newField = fieldSchema;
2827
+ while (newField instanceof ZodOptional) {
2828
+ newField = newField._def.innerType;
2829
+ }
2830
+ newShape[key] = newField;
2831
+ }
2832
+ }
2833
+ return new ZodObject({
2834
+ ...this._def,
2835
+ shape: () => newShape
2836
+ });
2837
+ }
2838
+ keyof() {
2839
+ return createZodEnum(util.objectKeys(this.shape));
2840
+ }
2841
+ }
2842
+ ZodObject.create = (shape, params) => {
2843
+ return new ZodObject({
2844
+ shape: () => shape,
2845
+ unknownKeys: "strip",
2846
+ catchall: ZodNever.create(),
2847
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2848
+ ...processCreateParams(params)
2849
+ });
2850
+ };
2851
+ ZodObject.strictCreate = (shape, params) => {
2852
+ return new ZodObject({
2853
+ shape: () => shape,
2854
+ unknownKeys: "strict",
2855
+ catchall: ZodNever.create(),
2856
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2857
+ ...processCreateParams(params)
2858
+ });
2859
+ };
2860
+ ZodObject.lazycreate = (shape, params) => {
2861
+ return new ZodObject({
2862
+ shape,
2863
+ unknownKeys: "strip",
2864
+ catchall: ZodNever.create(),
2865
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2866
+ ...processCreateParams(params)
2867
+ });
2868
+ };
2869
+
2870
+ class ZodUnion extends ZodType {
2871
+ _parse(input) {
2872
+ const { ctx } = this._processInputParams(input);
2873
+ const options = this._def.options;
2874
+ function handleResults(results) {
2875
+ for (const result of results) {
2876
+ if (result.result.status === "valid") {
2877
+ return result.result;
2878
+ }
2879
+ }
2880
+ for (const result of results) {
2881
+ if (result.result.status === "dirty") {
2882
+ ctx.common.issues.push(...result.ctx.common.issues);
2883
+ return result.result;
2884
+ }
2885
+ }
2886
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2887
+ addIssueToContext(ctx, {
2888
+ code: ZodIssueCode.invalid_union,
2889
+ unionErrors
2890
+ });
2891
+ return INVALID;
2892
+ }
2893
+ if (ctx.common.async) {
2894
+ return Promise.all(options.map(async (option) => {
2895
+ const childCtx = {
2896
+ ...ctx,
2897
+ common: {
2898
+ ...ctx.common,
2899
+ issues: []
2900
+ },
2901
+ parent: null
2902
+ };
2903
+ return {
2904
+ result: await option._parseAsync({
2905
+ data: ctx.data,
2906
+ path: ctx.path,
2907
+ parent: childCtx
2908
+ }),
2909
+ ctx: childCtx
2910
+ };
2911
+ })).then(handleResults);
2912
+ } else {
2913
+ let dirty = undefined;
2914
+ const issues = [];
2915
+ for (const option of options) {
2916
+ const childCtx = {
2917
+ ...ctx,
2918
+ common: {
2919
+ ...ctx.common,
2920
+ issues: []
2921
+ },
2922
+ parent: null
2923
+ };
2924
+ const result = option._parseSync({
2925
+ data: ctx.data,
2926
+ path: ctx.path,
2927
+ parent: childCtx
2928
+ });
2929
+ if (result.status === "valid") {
2930
+ return result;
2931
+ } else if (result.status === "dirty" && !dirty) {
2932
+ dirty = { result, ctx: childCtx };
2933
+ }
2934
+ if (childCtx.common.issues.length) {
2935
+ issues.push(childCtx.common.issues);
2936
+ }
2937
+ }
2938
+ if (dirty) {
2939
+ ctx.common.issues.push(...dirty.ctx.common.issues);
2940
+ return dirty.result;
2941
+ }
2942
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
2943
+ addIssueToContext(ctx, {
2944
+ code: ZodIssueCode.invalid_union,
2945
+ unionErrors
2946
+ });
2947
+ return INVALID;
2948
+ }
2949
+ }
2950
+ get options() {
2951
+ return this._def.options;
2952
+ }
2953
+ }
2954
+ ZodUnion.create = (types, params) => {
2955
+ return new ZodUnion({
2956
+ options: types,
2957
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
2958
+ ...processCreateParams(params)
2959
+ });
2960
+ };
2961
+ var getDiscriminator = (type) => {
2962
+ if (type instanceof ZodLazy) {
2963
+ return getDiscriminator(type.schema);
2964
+ } else if (type instanceof ZodEffects) {
2965
+ return getDiscriminator(type.innerType());
2966
+ } else if (type instanceof ZodLiteral) {
2967
+ return [type.value];
2968
+ } else if (type instanceof ZodEnum) {
2969
+ return type.options;
2970
+ } else if (type instanceof ZodNativeEnum) {
2971
+ return util.objectValues(type.enum);
2972
+ } else if (type instanceof ZodDefault) {
2973
+ return getDiscriminator(type._def.innerType);
2974
+ } else if (type instanceof ZodUndefined) {
2975
+ return [undefined];
2976
+ } else if (type instanceof ZodNull) {
2977
+ return [null];
2978
+ } else if (type instanceof ZodOptional) {
2979
+ return [undefined, ...getDiscriminator(type.unwrap())];
2980
+ } else if (type instanceof ZodNullable) {
2981
+ return [null, ...getDiscriminator(type.unwrap())];
2982
+ } else if (type instanceof ZodBranded) {
2983
+ return getDiscriminator(type.unwrap());
2984
+ } else if (type instanceof ZodReadonly) {
2985
+ return getDiscriminator(type.unwrap());
2986
+ } else if (type instanceof ZodCatch) {
2987
+ return getDiscriminator(type._def.innerType);
2988
+ } else {
2989
+ return [];
2990
+ }
2991
+ };
2992
+
2993
+ class ZodDiscriminatedUnion extends ZodType {
2994
+ _parse(input) {
2995
+ const { ctx } = this._processInputParams(input);
2996
+ if (ctx.parsedType !== ZodParsedType.object) {
2997
+ addIssueToContext(ctx, {
2998
+ code: ZodIssueCode.invalid_type,
2999
+ expected: ZodParsedType.object,
3000
+ received: ctx.parsedType
3001
+ });
3002
+ return INVALID;
3003
+ }
3004
+ const discriminator = this.discriminator;
3005
+ const discriminatorValue = ctx.data[discriminator];
3006
+ const option = this.optionsMap.get(discriminatorValue);
3007
+ if (!option) {
3008
+ addIssueToContext(ctx, {
3009
+ code: ZodIssueCode.invalid_union_discriminator,
3010
+ options: Array.from(this.optionsMap.keys()),
3011
+ path: [discriminator]
3012
+ });
3013
+ return INVALID;
3014
+ }
3015
+ if (ctx.common.async) {
3016
+ return option._parseAsync({
3017
+ data: ctx.data,
3018
+ path: ctx.path,
3019
+ parent: ctx
3020
+ });
3021
+ } else {
3022
+ return option._parseSync({
3023
+ data: ctx.data,
3024
+ path: ctx.path,
3025
+ parent: ctx
3026
+ });
3027
+ }
3028
+ }
3029
+ get discriminator() {
3030
+ return this._def.discriminator;
3031
+ }
3032
+ get options() {
3033
+ return this._def.options;
3034
+ }
3035
+ get optionsMap() {
3036
+ return this._def.optionsMap;
3037
+ }
3038
+ static create(discriminator, options, params) {
3039
+ const optionsMap = new Map;
3040
+ for (const type of options) {
3041
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
3042
+ if (!discriminatorValues.length) {
3043
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
3044
+ }
3045
+ for (const value of discriminatorValues) {
3046
+ if (optionsMap.has(value)) {
3047
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
3048
+ }
3049
+ optionsMap.set(value, type);
3050
+ }
3051
+ }
3052
+ return new ZodDiscriminatedUnion({
3053
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
3054
+ discriminator,
3055
+ options,
3056
+ optionsMap,
3057
+ ...processCreateParams(params)
3058
+ });
3059
+ }
3060
+ }
3061
+ function mergeValues(a, b) {
3062
+ const aType = getParsedType(a);
3063
+ const bType = getParsedType(b);
3064
+ if (a === b) {
3065
+ return { valid: true, data: a };
3066
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
3067
+ const bKeys = util.objectKeys(b);
3068
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
3069
+ const newObj = { ...a, ...b };
3070
+ for (const key of sharedKeys) {
3071
+ const sharedValue = mergeValues(a[key], b[key]);
3072
+ if (!sharedValue.valid) {
3073
+ return { valid: false };
3074
+ }
3075
+ newObj[key] = sharedValue.data;
3076
+ }
3077
+ return { valid: true, data: newObj };
3078
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
3079
+ if (a.length !== b.length) {
3080
+ return { valid: false };
3081
+ }
3082
+ const newArray = [];
3083
+ for (let index = 0;index < a.length; index++) {
3084
+ const itemA = a[index];
3085
+ const itemB = b[index];
3086
+ const sharedValue = mergeValues(itemA, itemB);
3087
+ if (!sharedValue.valid) {
3088
+ return { valid: false };
3089
+ }
3090
+ newArray.push(sharedValue.data);
3091
+ }
3092
+ return { valid: true, data: newArray };
3093
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
3094
+ return { valid: true, data: a };
3095
+ } else {
3096
+ return { valid: false };
3097
+ }
3098
+ }
3099
+
3100
+ class ZodIntersection extends ZodType {
3101
+ _parse(input) {
3102
+ const { status, ctx } = this._processInputParams(input);
3103
+ const handleParsed = (parsedLeft, parsedRight) => {
3104
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
3105
+ return INVALID;
3106
+ }
3107
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
3108
+ if (!merged.valid) {
3109
+ addIssueToContext(ctx, {
3110
+ code: ZodIssueCode.invalid_intersection_types
3111
+ });
3112
+ return INVALID;
3113
+ }
3114
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
3115
+ status.dirty();
3116
+ }
3117
+ return { status: status.value, value: merged.data };
3118
+ };
3119
+ if (ctx.common.async) {
3120
+ return Promise.all([
3121
+ this._def.left._parseAsync({
3122
+ data: ctx.data,
3123
+ path: ctx.path,
3124
+ parent: ctx
3125
+ }),
3126
+ this._def.right._parseAsync({
3127
+ data: ctx.data,
3128
+ path: ctx.path,
3129
+ parent: ctx
3130
+ })
3131
+ ]).then(([left, right]) => handleParsed(left, right));
3132
+ } else {
3133
+ return handleParsed(this._def.left._parseSync({
3134
+ data: ctx.data,
3135
+ path: ctx.path,
3136
+ parent: ctx
3137
+ }), this._def.right._parseSync({
3138
+ data: ctx.data,
3139
+ path: ctx.path,
3140
+ parent: ctx
3141
+ }));
3142
+ }
3143
+ }
3144
+ }
3145
+ ZodIntersection.create = (left, right, params) => {
3146
+ return new ZodIntersection({
3147
+ left,
3148
+ right,
3149
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
3150
+ ...processCreateParams(params)
3151
+ });
3152
+ };
3153
+
3154
+ class ZodTuple extends ZodType {
3155
+ _parse(input) {
3156
+ const { status, ctx } = this._processInputParams(input);
3157
+ if (ctx.parsedType !== ZodParsedType.array) {
3158
+ addIssueToContext(ctx, {
3159
+ code: ZodIssueCode.invalid_type,
3160
+ expected: ZodParsedType.array,
3161
+ received: ctx.parsedType
3162
+ });
3163
+ return INVALID;
3164
+ }
3165
+ if (ctx.data.length < this._def.items.length) {
3166
+ addIssueToContext(ctx, {
3167
+ code: ZodIssueCode.too_small,
3168
+ minimum: this._def.items.length,
3169
+ inclusive: true,
3170
+ exact: false,
3171
+ type: "array"
3172
+ });
3173
+ return INVALID;
3174
+ }
3175
+ const rest = this._def.rest;
3176
+ if (!rest && ctx.data.length > this._def.items.length) {
3177
+ addIssueToContext(ctx, {
3178
+ code: ZodIssueCode.too_big,
3179
+ maximum: this._def.items.length,
3180
+ inclusive: true,
3181
+ exact: false,
3182
+ type: "array"
3183
+ });
3184
+ status.dirty();
3185
+ }
3186
+ const items = [...ctx.data].map((item, itemIndex) => {
3187
+ const schema = this._def.items[itemIndex] || this._def.rest;
3188
+ if (!schema)
3189
+ return null;
3190
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3191
+ }).filter((x) => !!x);
3192
+ if (ctx.common.async) {
3193
+ return Promise.all(items).then((results) => {
3194
+ return ParseStatus.mergeArray(status, results);
3195
+ });
3196
+ } else {
3197
+ return ParseStatus.mergeArray(status, items);
3198
+ }
3199
+ }
3200
+ get items() {
3201
+ return this._def.items;
3202
+ }
3203
+ rest(rest) {
3204
+ return new ZodTuple({
3205
+ ...this._def,
3206
+ rest
3207
+ });
3208
+ }
3209
+ }
3210
+ ZodTuple.create = (schemas, params) => {
3211
+ if (!Array.isArray(schemas)) {
3212
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3213
+ }
3214
+ return new ZodTuple({
3215
+ items: schemas,
3216
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
3217
+ rest: null,
3218
+ ...processCreateParams(params)
3219
+ });
3220
+ };
3221
+
3222
+ class ZodRecord extends ZodType {
3223
+ get keySchema() {
3224
+ return this._def.keyType;
3225
+ }
3226
+ get valueSchema() {
3227
+ return this._def.valueType;
3228
+ }
3229
+ _parse(input) {
3230
+ const { status, ctx } = this._processInputParams(input);
3231
+ if (ctx.parsedType !== ZodParsedType.object) {
3232
+ addIssueToContext(ctx, {
3233
+ code: ZodIssueCode.invalid_type,
3234
+ expected: ZodParsedType.object,
3235
+ received: ctx.parsedType
3236
+ });
3237
+ return INVALID;
3238
+ }
3239
+ const pairs = [];
3240
+ const keyType = this._def.keyType;
3241
+ const valueType = this._def.valueType;
3242
+ for (const key in ctx.data) {
3243
+ pairs.push({
3244
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3245
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3246
+ alwaysSet: key in ctx.data
3247
+ });
3248
+ }
3249
+ if (ctx.common.async) {
3250
+ return ParseStatus.mergeObjectAsync(status, pairs);
3251
+ } else {
3252
+ return ParseStatus.mergeObjectSync(status, pairs);
3253
+ }
3254
+ }
3255
+ get element() {
3256
+ return this._def.valueType;
3257
+ }
3258
+ static create(first, second, third) {
3259
+ if (second instanceof ZodType) {
3260
+ return new ZodRecord({
3261
+ keyType: first,
3262
+ valueType: second,
3263
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3264
+ ...processCreateParams(third)
3265
+ });
3266
+ }
3267
+ return new ZodRecord({
3268
+ keyType: ZodString.create(),
3269
+ valueType: first,
3270
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3271
+ ...processCreateParams(second)
3272
+ });
3273
+ }
3274
+ }
3275
+
3276
+ class ZodMap extends ZodType {
3277
+ get keySchema() {
3278
+ return this._def.keyType;
3279
+ }
3280
+ get valueSchema() {
3281
+ return this._def.valueType;
3282
+ }
3283
+ _parse(input) {
3284
+ const { status, ctx } = this._processInputParams(input);
3285
+ if (ctx.parsedType !== ZodParsedType.map) {
3286
+ addIssueToContext(ctx, {
3287
+ code: ZodIssueCode.invalid_type,
3288
+ expected: ZodParsedType.map,
3289
+ received: ctx.parsedType
3290
+ });
3291
+ return INVALID;
3292
+ }
3293
+ const keyType = this._def.keyType;
3294
+ const valueType = this._def.valueType;
3295
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3296
+ return {
3297
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3298
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3299
+ };
3300
+ });
3301
+ if (ctx.common.async) {
3302
+ const finalMap = new Map;
3303
+ return Promise.resolve().then(async () => {
3304
+ for (const pair of pairs) {
3305
+ const key = await pair.key;
3306
+ const value = await pair.value;
3307
+ if (key.status === "aborted" || value.status === "aborted") {
3308
+ return INVALID;
3309
+ }
3310
+ if (key.status === "dirty" || value.status === "dirty") {
3311
+ status.dirty();
3312
+ }
3313
+ finalMap.set(key.value, value.value);
3314
+ }
3315
+ return { status: status.value, value: finalMap };
3316
+ });
3317
+ } else {
3318
+ const finalMap = new Map;
3319
+ for (const pair of pairs) {
3320
+ const key = pair.key;
3321
+ const value = pair.value;
3322
+ if (key.status === "aborted" || value.status === "aborted") {
3323
+ return INVALID;
3324
+ }
3325
+ if (key.status === "dirty" || value.status === "dirty") {
3326
+ status.dirty();
3327
+ }
3328
+ finalMap.set(key.value, value.value);
3329
+ }
3330
+ return { status: status.value, value: finalMap };
3331
+ }
3332
+ }
3333
+ }
3334
+ ZodMap.create = (keyType, valueType, params) => {
3335
+ return new ZodMap({
3336
+ valueType,
3337
+ keyType,
3338
+ typeName: ZodFirstPartyTypeKind.ZodMap,
3339
+ ...processCreateParams(params)
3340
+ });
3341
+ };
3342
+
3343
+ class ZodSet extends ZodType {
3344
+ _parse(input) {
3345
+ const { status, ctx } = this._processInputParams(input);
3346
+ if (ctx.parsedType !== ZodParsedType.set) {
3347
+ addIssueToContext(ctx, {
3348
+ code: ZodIssueCode.invalid_type,
3349
+ expected: ZodParsedType.set,
3350
+ received: ctx.parsedType
3351
+ });
3352
+ return INVALID;
3353
+ }
3354
+ const def = this._def;
3355
+ if (def.minSize !== null) {
3356
+ if (ctx.data.size < def.minSize.value) {
3357
+ addIssueToContext(ctx, {
3358
+ code: ZodIssueCode.too_small,
3359
+ minimum: def.minSize.value,
3360
+ type: "set",
3361
+ inclusive: true,
3362
+ exact: false,
3363
+ message: def.minSize.message
3364
+ });
3365
+ status.dirty();
3366
+ }
3367
+ }
3368
+ if (def.maxSize !== null) {
3369
+ if (ctx.data.size > def.maxSize.value) {
3370
+ addIssueToContext(ctx, {
3371
+ code: ZodIssueCode.too_big,
3372
+ maximum: def.maxSize.value,
3373
+ type: "set",
3374
+ inclusive: true,
3375
+ exact: false,
3376
+ message: def.maxSize.message
3377
+ });
3378
+ status.dirty();
3379
+ }
3380
+ }
3381
+ const valueType = this._def.valueType;
3382
+ function finalizeSet(elements2) {
3383
+ const parsedSet = new Set;
3384
+ for (const element of elements2) {
3385
+ if (element.status === "aborted")
3386
+ return INVALID;
3387
+ if (element.status === "dirty")
3388
+ status.dirty();
3389
+ parsedSet.add(element.value);
3390
+ }
3391
+ return { status: status.value, value: parsedSet };
3392
+ }
3393
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3394
+ if (ctx.common.async) {
3395
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3396
+ } else {
3397
+ return finalizeSet(elements);
3398
+ }
3399
+ }
3400
+ min(minSize, message) {
3401
+ return new ZodSet({
3402
+ ...this._def,
3403
+ minSize: { value: minSize, message: errorUtil.toString(message) }
3404
+ });
3405
+ }
3406
+ max(maxSize, message) {
3407
+ return new ZodSet({
3408
+ ...this._def,
3409
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
3410
+ });
3411
+ }
3412
+ size(size, message) {
3413
+ return this.min(size, message).max(size, message);
3414
+ }
3415
+ nonempty(message) {
3416
+ return this.min(1, message);
3417
+ }
3418
+ }
3419
+ ZodSet.create = (valueType, params) => {
3420
+ return new ZodSet({
3421
+ valueType,
3422
+ minSize: null,
3423
+ maxSize: null,
3424
+ typeName: ZodFirstPartyTypeKind.ZodSet,
3425
+ ...processCreateParams(params)
3426
+ });
3427
+ };
3428
+
3429
+ class ZodFunction extends ZodType {
3430
+ constructor() {
3431
+ super(...arguments);
3432
+ this.validate = this.implement;
3433
+ }
3434
+ _parse(input) {
3435
+ const { ctx } = this._processInputParams(input);
3436
+ if (ctx.parsedType !== ZodParsedType.function) {
3437
+ addIssueToContext(ctx, {
3438
+ code: ZodIssueCode.invalid_type,
3439
+ expected: ZodParsedType.function,
3440
+ received: ctx.parsedType
3441
+ });
3442
+ return INVALID;
3443
+ }
3444
+ function makeArgsIssue(args, error) {
3445
+ return makeIssue({
3446
+ data: args,
3447
+ path: ctx.path,
3448
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3449
+ issueData: {
3450
+ code: ZodIssueCode.invalid_arguments,
3451
+ argumentsError: error
3452
+ }
3453
+ });
3454
+ }
3455
+ function makeReturnsIssue(returns, error) {
3456
+ return makeIssue({
3457
+ data: returns,
3458
+ path: ctx.path,
3459
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3460
+ issueData: {
3461
+ code: ZodIssueCode.invalid_return_type,
3462
+ returnTypeError: error
3463
+ }
3464
+ });
3465
+ }
3466
+ const params = { errorMap: ctx.common.contextualErrorMap };
3467
+ const fn = ctx.data;
3468
+ if (this._def.returns instanceof ZodPromise) {
3469
+ const me = this;
3470
+ return OK(async function(...args) {
3471
+ const error = new ZodError([]);
3472
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3473
+ error.addIssue(makeArgsIssue(args, e));
3474
+ throw error;
3475
+ });
3476
+ const result = await Reflect.apply(fn, this, parsedArgs);
3477
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3478
+ error.addIssue(makeReturnsIssue(result, e));
3479
+ throw error;
3480
+ });
3481
+ return parsedReturns;
3482
+ });
3483
+ } else {
3484
+ const me = this;
3485
+ return OK(function(...args) {
3486
+ const parsedArgs = me._def.args.safeParse(args, params);
3487
+ if (!parsedArgs.success) {
3488
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3489
+ }
3490
+ const result = Reflect.apply(fn, this, parsedArgs.data);
3491
+ const parsedReturns = me._def.returns.safeParse(result, params);
3492
+ if (!parsedReturns.success) {
3493
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3494
+ }
3495
+ return parsedReturns.data;
3496
+ });
3497
+ }
3498
+ }
3499
+ parameters() {
3500
+ return this._def.args;
3501
+ }
3502
+ returnType() {
3503
+ return this._def.returns;
3504
+ }
3505
+ args(...items) {
3506
+ return new ZodFunction({
3507
+ ...this._def,
3508
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
3509
+ });
3510
+ }
3511
+ returns(returnType) {
3512
+ return new ZodFunction({
3513
+ ...this._def,
3514
+ returns: returnType
3515
+ });
3516
+ }
3517
+ implement(func) {
3518
+ const validatedFunc = this.parse(func);
3519
+ return validatedFunc;
3520
+ }
3521
+ strictImplement(func) {
3522
+ const validatedFunc = this.parse(func);
3523
+ return validatedFunc;
3524
+ }
3525
+ static create(args, returns, params) {
3526
+ return new ZodFunction({
3527
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3528
+ returns: returns || ZodUnknown.create(),
3529
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
3530
+ ...processCreateParams(params)
3531
+ });
3532
+ }
3533
+ }
3534
+
3535
+ class ZodLazy extends ZodType {
3536
+ get schema() {
3537
+ return this._def.getter();
3538
+ }
3539
+ _parse(input) {
3540
+ const { ctx } = this._processInputParams(input);
3541
+ const lazySchema = this._def.getter();
3542
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3543
+ }
3544
+ }
3545
+ ZodLazy.create = (getter, params) => {
3546
+ return new ZodLazy({
3547
+ getter,
3548
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
3549
+ ...processCreateParams(params)
3550
+ });
3551
+ };
3552
+
3553
+ class ZodLiteral extends ZodType {
3554
+ _parse(input) {
3555
+ if (input.data !== this._def.value) {
3556
+ const ctx = this._getOrReturnCtx(input);
3557
+ addIssueToContext(ctx, {
3558
+ received: ctx.data,
3559
+ code: ZodIssueCode.invalid_literal,
3560
+ expected: this._def.value
3561
+ });
3562
+ return INVALID;
3563
+ }
3564
+ return { status: "valid", value: input.data };
3565
+ }
3566
+ get value() {
3567
+ return this._def.value;
3568
+ }
3569
+ }
3570
+ ZodLiteral.create = (value, params) => {
3571
+ return new ZodLiteral({
3572
+ value,
3573
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
3574
+ ...processCreateParams(params)
3575
+ });
3576
+ };
3577
+ function createZodEnum(values, params) {
3578
+ return new ZodEnum({
3579
+ values,
3580
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3581
+ ...processCreateParams(params)
3582
+ });
3583
+ }
3584
+
3585
+ class ZodEnum extends ZodType {
3586
+ _parse(input) {
3587
+ if (typeof input.data !== "string") {
3588
+ const ctx = this._getOrReturnCtx(input);
3589
+ const expectedValues = this._def.values;
3590
+ addIssueToContext(ctx, {
3591
+ expected: util.joinValues(expectedValues),
3592
+ received: ctx.parsedType,
3593
+ code: ZodIssueCode.invalid_type
3594
+ });
3595
+ return INVALID;
3596
+ }
3597
+ if (!this._cache) {
3598
+ this._cache = new Set(this._def.values);
3599
+ }
3600
+ if (!this._cache.has(input.data)) {
3601
+ const ctx = this._getOrReturnCtx(input);
3602
+ const expectedValues = this._def.values;
3603
+ addIssueToContext(ctx, {
3604
+ received: ctx.data,
3605
+ code: ZodIssueCode.invalid_enum_value,
3606
+ options: expectedValues
3607
+ });
3608
+ return INVALID;
3609
+ }
3610
+ return OK(input.data);
3611
+ }
3612
+ get options() {
3613
+ return this._def.values;
3614
+ }
3615
+ get enum() {
3616
+ const enumValues = {};
3617
+ for (const val of this._def.values) {
3618
+ enumValues[val] = val;
3619
+ }
3620
+ return enumValues;
3621
+ }
3622
+ get Values() {
3623
+ const enumValues = {};
3624
+ for (const val of this._def.values) {
3625
+ enumValues[val] = val;
3626
+ }
3627
+ return enumValues;
3628
+ }
3629
+ get Enum() {
3630
+ const enumValues = {};
3631
+ for (const val of this._def.values) {
3632
+ enumValues[val] = val;
3633
+ }
3634
+ return enumValues;
3635
+ }
3636
+ extract(values, newDef = this._def) {
3637
+ return ZodEnum.create(values, {
3638
+ ...this._def,
3639
+ ...newDef
3640
+ });
3641
+ }
3642
+ exclude(values, newDef = this._def) {
3643
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3644
+ ...this._def,
3645
+ ...newDef
3646
+ });
3647
+ }
3648
+ }
3649
+ ZodEnum.create = createZodEnum;
3650
+
3651
+ class ZodNativeEnum extends ZodType {
3652
+ _parse(input) {
3653
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
3654
+ const ctx = this._getOrReturnCtx(input);
3655
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3656
+ const expectedValues = util.objectValues(nativeEnumValues);
3657
+ addIssueToContext(ctx, {
3658
+ expected: util.joinValues(expectedValues),
3659
+ received: ctx.parsedType,
3660
+ code: ZodIssueCode.invalid_type
3661
+ });
3662
+ return INVALID;
3663
+ }
3664
+ if (!this._cache) {
3665
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
3666
+ }
3667
+ if (!this._cache.has(input.data)) {
3668
+ const expectedValues = util.objectValues(nativeEnumValues);
3669
+ addIssueToContext(ctx, {
3670
+ received: ctx.data,
3671
+ code: ZodIssueCode.invalid_enum_value,
3672
+ options: expectedValues
3673
+ });
3674
+ return INVALID;
3675
+ }
3676
+ return OK(input.data);
3677
+ }
3678
+ get enum() {
3679
+ return this._def.values;
3680
+ }
3681
+ }
3682
+ ZodNativeEnum.create = (values, params) => {
3683
+ return new ZodNativeEnum({
3684
+ values,
3685
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3686
+ ...processCreateParams(params)
3687
+ });
3688
+ };
3689
+
3690
+ class ZodPromise extends ZodType {
3691
+ unwrap() {
3692
+ return this._def.type;
3693
+ }
3694
+ _parse(input) {
3695
+ const { ctx } = this._processInputParams(input);
3696
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3697
+ addIssueToContext(ctx, {
3698
+ code: ZodIssueCode.invalid_type,
3699
+ expected: ZodParsedType.promise,
3700
+ received: ctx.parsedType
3701
+ });
3702
+ return INVALID;
3703
+ }
3704
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3705
+ return OK(promisified.then((data) => {
3706
+ return this._def.type.parseAsync(data, {
3707
+ path: ctx.path,
3708
+ errorMap: ctx.common.contextualErrorMap
3709
+ });
3710
+ }));
3711
+ }
3712
+ }
3713
+ ZodPromise.create = (schema, params) => {
3714
+ return new ZodPromise({
3715
+ type: schema,
3716
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
3717
+ ...processCreateParams(params)
3718
+ });
3719
+ };
3720
+
3721
+ class ZodEffects extends ZodType {
3722
+ innerType() {
3723
+ return this._def.schema;
3724
+ }
3725
+ sourceType() {
3726
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3727
+ }
3728
+ _parse(input) {
3729
+ const { status, ctx } = this._processInputParams(input);
3730
+ const effect = this._def.effect || null;
3731
+ const checkCtx = {
3732
+ addIssue: (arg) => {
3733
+ addIssueToContext(ctx, arg);
3734
+ if (arg.fatal) {
3735
+ status.abort();
3736
+ } else {
3737
+ status.dirty();
3738
+ }
3739
+ },
3740
+ get path() {
3741
+ return ctx.path;
3742
+ }
3743
+ };
3744
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3745
+ if (effect.type === "preprocess") {
3746
+ const processed = effect.transform(ctx.data, checkCtx);
3747
+ if (ctx.common.async) {
3748
+ return Promise.resolve(processed).then(async (processed2) => {
3749
+ if (status.value === "aborted")
3750
+ return INVALID;
3751
+ const result = await this._def.schema._parseAsync({
3752
+ data: processed2,
3753
+ path: ctx.path,
3754
+ parent: ctx
3755
+ });
3756
+ if (result.status === "aborted")
3757
+ return INVALID;
3758
+ if (result.status === "dirty")
3759
+ return DIRTY(result.value);
3760
+ if (status.value === "dirty")
3761
+ return DIRTY(result.value);
3762
+ return result;
3763
+ });
3764
+ } else {
3765
+ if (status.value === "aborted")
3766
+ return INVALID;
3767
+ const result = this._def.schema._parseSync({
3768
+ data: processed,
3769
+ path: ctx.path,
3770
+ parent: ctx
3771
+ });
3772
+ if (result.status === "aborted")
3773
+ return INVALID;
3774
+ if (result.status === "dirty")
3775
+ return DIRTY(result.value);
3776
+ if (status.value === "dirty")
3777
+ return DIRTY(result.value);
3778
+ return result;
3779
+ }
3780
+ }
3781
+ if (effect.type === "refinement") {
3782
+ const executeRefinement = (acc) => {
3783
+ const result = effect.refinement(acc, checkCtx);
3784
+ if (ctx.common.async) {
3785
+ return Promise.resolve(result);
3786
+ }
3787
+ if (result instanceof Promise) {
3788
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3789
+ }
3790
+ return acc;
3791
+ };
3792
+ if (ctx.common.async === false) {
3793
+ const inner = this._def.schema._parseSync({
3794
+ data: ctx.data,
3795
+ path: ctx.path,
3796
+ parent: ctx
3797
+ });
3798
+ if (inner.status === "aborted")
3799
+ return INVALID;
3800
+ if (inner.status === "dirty")
3801
+ status.dirty();
3802
+ executeRefinement(inner.value);
3803
+ return { status: status.value, value: inner.value };
3804
+ } else {
3805
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3806
+ if (inner.status === "aborted")
3807
+ return INVALID;
3808
+ if (inner.status === "dirty")
3809
+ status.dirty();
3810
+ return executeRefinement(inner.value).then(() => {
3811
+ return { status: status.value, value: inner.value };
3812
+ });
3813
+ });
3814
+ }
3815
+ }
3816
+ if (effect.type === "transform") {
3817
+ if (ctx.common.async === false) {
3818
+ const base = this._def.schema._parseSync({
3819
+ data: ctx.data,
3820
+ path: ctx.path,
3821
+ parent: ctx
3822
+ });
3823
+ if (!isValid(base))
3824
+ return INVALID;
3825
+ const result = effect.transform(base.value, checkCtx);
3826
+ if (result instanceof Promise) {
3827
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3828
+ }
3829
+ return { status: status.value, value: result };
3830
+ } else {
3831
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3832
+ if (!isValid(base))
3833
+ return INVALID;
3834
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3835
+ status: status.value,
3836
+ value: result
3837
+ }));
3838
+ });
3839
+ }
3840
+ }
3841
+ util.assertNever(effect);
3842
+ }
3843
+ }
3844
+ ZodEffects.create = (schema, effect, params) => {
3845
+ return new ZodEffects({
3846
+ schema,
3847
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3848
+ effect,
3849
+ ...processCreateParams(params)
3850
+ });
3851
+ };
3852
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3853
+ return new ZodEffects({
3854
+ schema,
3855
+ effect: { type: "preprocess", transform: preprocess },
3856
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3857
+ ...processCreateParams(params)
3858
+ });
3859
+ };
3860
+ class ZodOptional extends ZodType {
3861
+ _parse(input) {
3862
+ const parsedType = this._getType(input);
3863
+ if (parsedType === ZodParsedType.undefined) {
3864
+ return OK(undefined);
3865
+ }
3866
+ return this._def.innerType._parse(input);
3867
+ }
3868
+ unwrap() {
3869
+ return this._def.innerType;
3870
+ }
3871
+ }
3872
+ ZodOptional.create = (type, params) => {
3873
+ return new ZodOptional({
3874
+ innerType: type,
3875
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
3876
+ ...processCreateParams(params)
3877
+ });
3878
+ };
3879
+
3880
+ class ZodNullable extends ZodType {
3881
+ _parse(input) {
3882
+ const parsedType = this._getType(input);
3883
+ if (parsedType === ZodParsedType.null) {
3884
+ return OK(null);
3885
+ }
3886
+ return this._def.innerType._parse(input);
3887
+ }
3888
+ unwrap() {
3889
+ return this._def.innerType;
3890
+ }
3891
+ }
3892
+ ZodNullable.create = (type, params) => {
3893
+ return new ZodNullable({
3894
+ innerType: type,
3895
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
3896
+ ...processCreateParams(params)
3897
+ });
3898
+ };
3899
+
3900
+ class ZodDefault extends ZodType {
3901
+ _parse(input) {
3902
+ const { ctx } = this._processInputParams(input);
3903
+ let data = ctx.data;
3904
+ if (ctx.parsedType === ZodParsedType.undefined) {
3905
+ data = this._def.defaultValue();
3906
+ }
3907
+ return this._def.innerType._parse({
3908
+ data,
3909
+ path: ctx.path,
3910
+ parent: ctx
3911
+ });
3912
+ }
3913
+ removeDefault() {
3914
+ return this._def.innerType;
3915
+ }
3916
+ }
3917
+ ZodDefault.create = (type, params) => {
3918
+ return new ZodDefault({
3919
+ innerType: type,
3920
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
3921
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3922
+ ...processCreateParams(params)
3923
+ });
3924
+ };
3925
+
3926
+ class ZodCatch extends ZodType {
3927
+ _parse(input) {
3928
+ const { ctx } = this._processInputParams(input);
3929
+ const newCtx = {
3930
+ ...ctx,
3931
+ common: {
3932
+ ...ctx.common,
3933
+ issues: []
3934
+ }
3935
+ };
3936
+ const result = this._def.innerType._parse({
3937
+ data: newCtx.data,
3938
+ path: newCtx.path,
3939
+ parent: {
3940
+ ...newCtx
3941
+ }
3942
+ });
3943
+ if (isAsync(result)) {
3944
+ return result.then((result2) => {
3945
+ return {
3946
+ status: "valid",
3947
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
3948
+ get error() {
3949
+ return new ZodError(newCtx.common.issues);
3950
+ },
3951
+ input: newCtx.data
3952
+ })
3953
+ };
3954
+ });
3955
+ } else {
3956
+ return {
3957
+ status: "valid",
3958
+ value: result.status === "valid" ? result.value : this._def.catchValue({
3959
+ get error() {
3960
+ return new ZodError(newCtx.common.issues);
3961
+ },
3962
+ input: newCtx.data
3963
+ })
3964
+ };
3965
+ }
3966
+ }
3967
+ removeCatch() {
3968
+ return this._def.innerType;
3969
+ }
3970
+ }
3971
+ ZodCatch.create = (type, params) => {
3972
+ return new ZodCatch({
3973
+ innerType: type,
3974
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
3975
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3976
+ ...processCreateParams(params)
3977
+ });
3978
+ };
3979
+
3980
+ class ZodNaN extends ZodType {
3981
+ _parse(input) {
3982
+ const parsedType = this._getType(input);
3983
+ if (parsedType !== ZodParsedType.nan) {
3984
+ const ctx = this._getOrReturnCtx(input);
3985
+ addIssueToContext(ctx, {
3986
+ code: ZodIssueCode.invalid_type,
3987
+ expected: ZodParsedType.nan,
3988
+ received: ctx.parsedType
3989
+ });
3990
+ return INVALID;
3991
+ }
3992
+ return { status: "valid", value: input.data };
3993
+ }
3994
+ }
3995
+ ZodNaN.create = (params) => {
3996
+ return new ZodNaN({
3997
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
3998
+ ...processCreateParams(params)
3999
+ });
4000
+ };
4001
+ var BRAND = Symbol("zod_brand");
4002
+
4003
+ class ZodBranded extends ZodType {
4004
+ _parse(input) {
4005
+ const { ctx } = this._processInputParams(input);
4006
+ const data = ctx.data;
4007
+ return this._def.type._parse({
4008
+ data,
4009
+ path: ctx.path,
4010
+ parent: ctx
4011
+ });
4012
+ }
4013
+ unwrap() {
4014
+ return this._def.type;
4015
+ }
4016
+ }
4017
+
4018
+ class ZodPipeline extends ZodType {
4019
+ _parse(input) {
4020
+ const { status, ctx } = this._processInputParams(input);
4021
+ if (ctx.common.async) {
4022
+ const handleAsync = async () => {
4023
+ const inResult = await this._def.in._parseAsync({
4024
+ data: ctx.data,
4025
+ path: ctx.path,
4026
+ parent: ctx
4027
+ });
4028
+ if (inResult.status === "aborted")
4029
+ return INVALID;
4030
+ if (inResult.status === "dirty") {
4031
+ status.dirty();
4032
+ return DIRTY(inResult.value);
4033
+ } else {
4034
+ return this._def.out._parseAsync({
4035
+ data: inResult.value,
4036
+ path: ctx.path,
4037
+ parent: ctx
4038
+ });
4039
+ }
4040
+ };
4041
+ return handleAsync();
4042
+ } else {
4043
+ const inResult = this._def.in._parseSync({
4044
+ data: ctx.data,
4045
+ path: ctx.path,
4046
+ parent: ctx
4047
+ });
4048
+ if (inResult.status === "aborted")
4049
+ return INVALID;
4050
+ if (inResult.status === "dirty") {
4051
+ status.dirty();
4052
+ return {
4053
+ status: "dirty",
4054
+ value: inResult.value
4055
+ };
4056
+ } else {
4057
+ return this._def.out._parseSync({
4058
+ data: inResult.value,
4059
+ path: ctx.path,
4060
+ parent: ctx
4061
+ });
4062
+ }
4063
+ }
4064
+ }
4065
+ static create(a, b) {
4066
+ return new ZodPipeline({
4067
+ in: a,
4068
+ out: b,
4069
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
4070
+ });
4071
+ }
4072
+ }
4073
+
4074
+ class ZodReadonly extends ZodType {
4075
+ _parse(input) {
4076
+ const result = this._def.innerType._parse(input);
4077
+ const freeze = (data) => {
4078
+ if (isValid(data)) {
4079
+ data.value = Object.freeze(data.value);
4080
+ }
4081
+ return data;
4082
+ };
4083
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
4084
+ }
4085
+ unwrap() {
4086
+ return this._def.innerType;
4087
+ }
4088
+ }
4089
+ ZodReadonly.create = (type, params) => {
4090
+ return new ZodReadonly({
4091
+ innerType: type,
4092
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
4093
+ ...processCreateParams(params)
4094
+ });
4095
+ };
4096
+ function cleanParams(params, data) {
4097
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
4098
+ const p2 = typeof p === "string" ? { message: p } : p;
4099
+ return p2;
4100
+ }
4101
+ function custom(check, _params = {}, fatal) {
4102
+ if (check)
4103
+ return ZodAny.create().superRefine((data, ctx) => {
4104
+ const r = check(data);
4105
+ if (r instanceof Promise) {
4106
+ return r.then((r2) => {
4107
+ if (!r2) {
4108
+ const params = cleanParams(_params, data);
4109
+ const _fatal = params.fatal ?? fatal ?? true;
4110
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4111
+ }
4112
+ });
4113
+ }
4114
+ if (!r) {
4115
+ const params = cleanParams(_params, data);
4116
+ const _fatal = params.fatal ?? fatal ?? true;
4117
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4118
+ }
4119
+ return;
4120
+ });
4121
+ return ZodAny.create();
4122
+ }
4123
+ var late = {
4124
+ object: ZodObject.lazycreate
4125
+ };
4126
+ var ZodFirstPartyTypeKind;
4127
+ (function(ZodFirstPartyTypeKind2) {
4128
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
4129
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
4130
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
4131
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
4132
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
4133
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
4134
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
4135
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
4136
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
4137
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
4138
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
4139
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
4140
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
4141
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
4142
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
4143
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
4144
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
4145
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
4146
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
4147
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
4148
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
4149
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
4150
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
4151
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
4152
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
4153
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
4154
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
4155
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
4156
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
4157
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
4158
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
4159
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
4160
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
4161
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
4162
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
4163
+ ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
4164
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4165
+ var instanceOfType = (cls, params = {
4166
+ message: `Input not instance of ${cls.name}`
4167
+ }) => custom((data) => data instanceof cls, params);
4168
+ var stringType = ZodString.create;
4169
+ var numberType = ZodNumber.create;
4170
+ var nanType = ZodNaN.create;
4171
+ var bigIntType = ZodBigInt.create;
4172
+ var booleanType = ZodBoolean.create;
4173
+ var dateType = ZodDate.create;
4174
+ var symbolType = ZodSymbol.create;
4175
+ var undefinedType = ZodUndefined.create;
4176
+ var nullType = ZodNull.create;
4177
+ var anyType = ZodAny.create;
4178
+ var unknownType = ZodUnknown.create;
4179
+ var neverType = ZodNever.create;
4180
+ var voidType = ZodVoid.create;
4181
+ var arrayType = ZodArray.create;
4182
+ var objectType = ZodObject.create;
4183
+ var strictObjectType = ZodObject.strictCreate;
4184
+ var unionType = ZodUnion.create;
4185
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
4186
+ var intersectionType = ZodIntersection.create;
4187
+ var tupleType = ZodTuple.create;
4188
+ var recordType = ZodRecord.create;
4189
+ var mapType = ZodMap.create;
4190
+ var setType = ZodSet.create;
4191
+ var functionType = ZodFunction.create;
4192
+ var lazyType = ZodLazy.create;
4193
+ var literalType = ZodLiteral.create;
4194
+ var enumType = ZodEnum.create;
4195
+ var nativeEnumType = ZodNativeEnum.create;
4196
+ var promiseType = ZodPromise.create;
4197
+ var effectsType = ZodEffects.create;
4198
+ var optionalType = ZodOptional.create;
4199
+ var nullableType = ZodNullable.create;
4200
+ var preprocessType = ZodEffects.createWithPreprocess;
4201
+ var pipelineType = ZodPipeline.create;
4202
+ var ostring = () => stringType().optional();
4203
+ var onumber = () => numberType().optional();
4204
+ var oboolean = () => booleanType().optional();
4205
+ var coerce = {
4206
+ string: (arg) => ZodString.create({ ...arg, coerce: true }),
4207
+ number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
4208
+ boolean: (arg) => ZodBoolean.create({
4209
+ ...arg,
4210
+ coerce: true
4211
+ }),
4212
+ bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
4213
+ date: (arg) => ZodDate.create({ ...arg, coerce: true })
4214
+ };
4215
+ var NEVER = INVALID;
4216
+ // src/adapter.ts
4217
+ function createParameterValidator(params) {
4218
+ const shape = {};
4219
+ for (const param of params) {
4220
+ let schema;
4221
+ switch (param.type) {
4222
+ case "string":
4223
+ schema = exports_external.string();
4224
+ break;
4225
+ case "number":
4226
+ schema = exports_external.number();
4227
+ break;
4228
+ case "boolean":
4229
+ schema = exports_external.boolean();
4230
+ break;
4231
+ case "object":
4232
+ schema = exports_external.record(exports_external.unknown());
4233
+ break;
4234
+ case "array":
4235
+ schema = exports_external.array(exports_external.unknown());
4236
+ break;
4237
+ default:
4238
+ schema = exports_external.unknown();
4239
+ }
4240
+ if (param.default !== undefined) {
4241
+ schema = schema.default(param.default);
4242
+ }
4243
+ if (!param.required) {
4244
+ schema = schema.optional();
4245
+ }
4246
+ shape[param.name] = schema;
4247
+ }
4248
+ return exports_external.object(shape);
4249
+ }
4250
+ function createMethod(config) {
4251
+ const parameters = config.parameters ?? [];
4252
+ const validator = createParameterValidator(parameters);
4253
+ const execute = async (...args) => {
4254
+ const paramObj = {};
4255
+ parameters.forEach((param, index) => {
4256
+ if (index < args.length) {
4257
+ paramObj[param.name] = args[index];
4258
+ }
4259
+ });
4260
+ const validatedParams = validator.parse(paramObj);
4261
+ const validatedArgs = parameters.map((param) => validatedParams[param.name]);
4262
+ return config.handler(...validatedArgs);
4263
+ };
4264
+ return {
4265
+ name: config.name,
4266
+ description: config.description,
4267
+ parameters,
4268
+ execute
4269
+ };
4270
+ }
4271
+ function defineAdapter(config, adapterConfig) {
4272
+ let validatedConfig;
4273
+ if (config.configSchema && adapterConfig !== undefined) {
4274
+ validatedConfig = config.configSchema.parse(adapterConfig);
4275
+ } else {
4276
+ validatedConfig = adapterConfig;
4277
+ }
4278
+ const methods = new Map;
4279
+ for (const methodConfig of config.methods) {
4280
+ const method = createMethod(methodConfig);
4281
+ methods.set(method.name, method);
4282
+ }
4283
+ return {
4284
+ name: config.name,
4285
+ description: config.description,
4286
+ version: config.version ?? "1.0.0",
4287
+ methods,
4288
+ config: validatedConfig
4289
+ };
4290
+ }
4291
+ function createAdapterFactory(config) {
4292
+ return (adapterConfig) => defineAdapter(config, adapterConfig);
4293
+ }
4294
+ // src/skill.ts
4295
+ var DEFAULT_SANDBOX_CONFIG = {
4296
+ timeout: 5000,
4297
+ memoryLimit: 128,
4298
+ allowAsync: true,
4299
+ globals: {}
4300
+ };
4301
+ function defineSkill(config) {
4302
+ if (!config.name) {
4303
+ throw new Error("Skill name is required");
4304
+ }
4305
+ const hasCode = config.code && config.code.trim() !== "";
4306
+ const hasRun = typeof config.run === "function";
4307
+ if (!hasCode && !hasRun) {
4308
+ throw new Error("Skill must have either 'code' (string) or 'run' (function)");
4309
+ }
4310
+ return {
4311
+ name: config.name,
4312
+ description: config.description,
4313
+ version: config.version ?? "1.0.0",
4314
+ adapters: config.adapters ?? [],
4315
+ code: config.code,
4316
+ run: config.run,
4317
+ sandboxConfig: {
4318
+ ...DEFAULT_SANDBOX_CONFIG,
4319
+ ...config.sandbox
4320
+ }
4321
+ };
4322
+ }
4323
+ function defineSkills(configs) {
4324
+ return configs.map(defineSkill);
4325
+ }
4326
+ function skillBuilder(name) {
4327
+ return new SkillBuilder(name);
4328
+ }
4329
+
4330
+ class SkillBuilder {
4331
+ config;
4332
+ constructor(name) {
4333
+ this.config = {
4334
+ name,
4335
+ code: ""
4336
+ };
4337
+ }
4338
+ description(description) {
4339
+ this.config.description = description;
4340
+ return this;
4341
+ }
4342
+ version(version) {
4343
+ this.config.version = version;
4344
+ return this;
4345
+ }
4346
+ requires(...adapters) {
4347
+ this.config.adapters = adapters;
4348
+ return this;
4349
+ }
4350
+ timeout(ms) {
4351
+ this.config.sandbox = {
4352
+ ...this.config.sandbox,
4353
+ timeout: ms
4354
+ };
4355
+ return this;
4356
+ }
4357
+ memoryLimit(mb) {
4358
+ this.config.sandbox = {
4359
+ ...this.config.sandbox,
4360
+ memoryLimit: mb
4361
+ };
4362
+ return this;
4363
+ }
4364
+ code(code) {
4365
+ this.config.code = code;
4366
+ return this;
4367
+ }
4368
+ sandbox(config) {
4369
+ this.config.sandbox = {
4370
+ ...this.config.sandbox,
4371
+ ...config
4372
+ };
4373
+ return this;
4374
+ }
4375
+ build() {
4376
+ return defineSkill(this.config);
4377
+ }
4378
+ }
4379
+ // src/config.ts
4380
+ var DEFAULT_CONFIG2 = {
4381
+ sandbox: {
4382
+ timeout: 5000,
4383
+ memoryLimit: 128,
4384
+ allowAsync: true,
4385
+ globals: {}
4386
+ },
4387
+ adaptersDir: "./adapters",
4388
+ skillsDir: "./skills"
4389
+ };
4390
+ function defineConfig(config) {
4391
+ return {
4392
+ ...DEFAULT_CONFIG2,
4393
+ ...config,
4394
+ sandbox: {
4395
+ ...DEFAULT_CONFIG2.sandbox,
4396
+ ...config.sandbox
4397
+ }
4398
+ };
4399
+ }
4400
+ function configBuilder() {
4401
+ return new MCXConfigBuilder;
4402
+ }
4403
+
4404
+ class MCXConfigBuilder {
4405
+ config = {
4406
+ adapters: [],
4407
+ skills: []
4408
+ };
4409
+ adapter(adapter) {
4410
+ this.config.adapters = [...this.config.adapters ?? [], adapter];
4411
+ return this;
4412
+ }
4413
+ adapters(...adapters) {
4414
+ this.config.adapters = [...this.config.adapters ?? [], ...adapters];
4415
+ return this;
4416
+ }
4417
+ skill(skill) {
4418
+ this.config.skills = [...this.config.skills ?? [], skill];
4419
+ return this;
4420
+ }
4421
+ skills(...skills) {
4422
+ this.config.skills = [...this.config.skills ?? [], ...skills];
4423
+ return this;
4424
+ }
4425
+ sandbox(config) {
4426
+ this.config.sandbox = {
4427
+ ...this.config.sandbox,
4428
+ ...config
4429
+ };
4430
+ return this;
4431
+ }
4432
+ adaptersDir(path) {
4433
+ this.config.adaptersDir = path;
4434
+ return this;
4435
+ }
4436
+ skillsDir(path) {
4437
+ this.config.skillsDir = path;
4438
+ return this;
4439
+ }
4440
+ build() {
4441
+ return defineConfig(this.config);
4442
+ }
4443
+ }
4444
+ function mergeConfigs(...configs) {
4445
+ const merged = {
4446
+ adapters: [],
4447
+ skills: [],
4448
+ sandbox: { ...DEFAULT_CONFIG2.sandbox },
4449
+ adaptersDir: DEFAULT_CONFIG2.adaptersDir,
4450
+ skillsDir: DEFAULT_CONFIG2.skillsDir
4451
+ };
4452
+ for (const config of configs) {
4453
+ if (config.adapters) {
4454
+ merged.adapters = [...merged.adapters ?? [], ...config.adapters];
4455
+ }
4456
+ if (config.skills) {
4457
+ merged.skills = [...merged.skills ?? [], ...config.skills];
4458
+ }
4459
+ if (config.sandbox) {
4460
+ merged.sandbox = { ...merged.sandbox, ...config.sandbox };
4461
+ }
4462
+ if (config.adaptersDir) {
4463
+ merged.adaptersDir = config.adaptersDir;
4464
+ }
4465
+ if (config.skillsDir) {
4466
+ merged.skillsDir = config.skillsDir;
4467
+ }
4468
+ }
4469
+ return merged;
4470
+ }
4471
+ // src/executor.ts
4472
+ import { pathToFileURL } from "node:url";
4473
+ class MCXExecutor {
4474
+ adapters = new Map;
4475
+ skills = new Map;
4476
+ sandboxConfig;
4477
+ sandboxFactory;
4478
+ configPath;
4479
+ constructor(options = {}) {
4480
+ this.sandboxConfig = options.config?.sandbox ?? {
4481
+ timeout: 5000,
4482
+ memoryLimit: 128,
4483
+ allowAsync: true,
4484
+ globals: {}
4485
+ };
4486
+ this.sandboxFactory = options.sandboxFactory ?? createSandbox;
4487
+ this.configPath = options.configPath;
4488
+ if (options.config?.adapters) {
4489
+ for (const adapter of options.config.adapters) {
4490
+ this.registerAdapter(adapter);
4491
+ }
4492
+ }
4493
+ if (options.config?.skills) {
4494
+ for (const skill of options.config.skills) {
4495
+ this.registerSkill(skill);
4496
+ }
4497
+ }
4498
+ }
4499
+ async loadConfig(configPath) {
4500
+ const path = configPath ?? this.configPath ?? "./mcx.config.ts";
4501
+ try {
4502
+ const fileUrl = pathToFileURL(path).href;
4503
+ const module = await import(fileUrl);
4504
+ const config = module.default ?? module;
4505
+ if (config.sandbox) {
4506
+ this.sandboxConfig = {
4507
+ ...this.sandboxConfig,
4508
+ ...config.sandbox
4509
+ };
4510
+ }
4511
+ if (config.adapters) {
4512
+ for (const adapter of config.adapters) {
4513
+ this.registerAdapter(adapter);
4514
+ }
4515
+ }
4516
+ if (config.skills) {
4517
+ for (const skill of config.skills) {
4518
+ this.registerSkill(skill);
4519
+ }
4520
+ }
4521
+ } catch (error) {
4522
+ throw new Error(`Failed to load MCX config from ${path}: ${error instanceof Error ? error.message : String(error)}`);
4523
+ }
4524
+ }
4525
+ registerAdapter(adapter) {
4526
+ if (this.adapters.has(adapter.name)) {
4527
+ console.warn(`Adapter "${adapter.name}" is being overwritten`);
4528
+ }
4529
+ this.adapters.set(adapter.name, adapter);
4530
+ }
4531
+ unregisterAdapter(name) {
4532
+ return this.adapters.delete(name);
4533
+ }
4534
+ getAdapter(name) {
4535
+ return this.adapters.get(name);
4536
+ }
4537
+ getAdapterNames() {
4538
+ return Array.from(this.adapters.keys());
4539
+ }
4540
+ registerSkill(skill) {
4541
+ if (this.skills.has(skill.name)) {
4542
+ console.warn(`Skill "${skill.name}" is being overwritten`);
4543
+ }
4544
+ this.skills.set(skill.name, skill);
4545
+ }
4546
+ unregisterSkill(name) {
4547
+ return this.skills.delete(name);
4548
+ }
4549
+ getSkill(name) {
4550
+ return this.skills.get(name);
4551
+ }
4552
+ getSkillNames() {
4553
+ return Array.from(this.skills.keys());
4554
+ }
4555
+ async execute(code, options = {}) {
4556
+ const sandboxConfig = {
4557
+ ...this.sandboxConfig,
4558
+ ...options.sandbox
4559
+ };
4560
+ const sandbox = this.sandboxFactory(sandboxConfig);
4561
+ try {
4562
+ const context = this.buildExecutionContext(options.adapters, options.variables);
4563
+ return await sandbox.execute(code, context);
4564
+ } finally {
4565
+ sandbox.dispose();
4566
+ }
4567
+ }
4568
+ async runSkill(name, options = {}) {
4569
+ const skill = this.skills.get(name);
4570
+ if (!skill) {
4571
+ return {
4572
+ success: false,
4573
+ error: {
4574
+ name: "SkillNotFoundError",
4575
+ message: `Skill "${name}" not found`
4576
+ },
4577
+ logs: [],
4578
+ executionTime: 0
4579
+ };
4580
+ }
4581
+ const missingAdapters = skill.adapters.filter((adapterName) => !this.adapters.has(adapterName));
4582
+ if (missingAdapters.length > 0) {
4583
+ return {
4584
+ success: false,
4585
+ error: {
4586
+ name: "MissingAdaptersError",
4587
+ message: `Skill "${name}" requires missing adapters: ${missingAdapters.join(", ")}`
4588
+ },
4589
+ logs: [],
4590
+ executionTime: 0
4591
+ };
4592
+ }
4593
+ if (skill.run) {
4594
+ const startTime = performance.now();
4595
+ try {
4596
+ const context = this.buildExecutionContext(skill.adapters.length > 0 ? skill.adapters : undefined, options.variables);
4597
+ const result = await skill.run({
4598
+ ...context.adapters,
4599
+ ...context.variables
4600
+ });
4601
+ return {
4602
+ success: true,
4603
+ value: result,
4604
+ logs: [],
4605
+ executionTime: performance.now() - startTime
4606
+ };
4607
+ } catch (error) {
4608
+ const err = error instanceof Error ? error : new Error(String(error));
4609
+ return {
4610
+ success: false,
4611
+ error: {
4612
+ name: err.name,
4613
+ message: err.message,
4614
+ stack: err.stack
4615
+ },
4616
+ logs: [],
4617
+ executionTime: performance.now() - startTime
4618
+ };
4619
+ }
4620
+ }
4621
+ if (!skill.code) {
4622
+ return {
4623
+ success: false,
4624
+ error: {
4625
+ name: "InvalidSkillError",
4626
+ message: `Skill "${name}" has neither code nor run function`
4627
+ },
4628
+ logs: [],
4629
+ executionTime: 0
4630
+ };
4631
+ }
4632
+ return this.execute(skill.code, {
4633
+ sandbox: skill.sandboxConfig,
4634
+ adapters: skill.adapters.length > 0 ? skill.adapters : undefined,
4635
+ variables: options.variables
4636
+ });
4637
+ }
4638
+ configureSandbox(config) {
4639
+ this.sandboxConfig = {
4640
+ ...this.sandboxConfig,
4641
+ ...config
4642
+ };
4643
+ }
4644
+ buildExecutionContext(adapterNames, variables) {
4645
+ const adaptersToInclude = adapterNames ? adapterNames.filter((name) => this.adapters.has(name)) : Array.from(this.adapters.keys());
4646
+ const adapterMethods = {};
4647
+ for (const name of adaptersToInclude) {
4648
+ const adapter = this.adapters.get(name);
4649
+ if (!adapter)
4650
+ continue;
4651
+ adapterMethods[name] = {};
4652
+ for (const [methodName, method] of adapter.methods) {
4653
+ adapterMethods[name][methodName] = method.execute.bind(method);
4654
+ }
4655
+ }
4656
+ return {
4657
+ adapters: adapterMethods,
4658
+ variables
4659
+ };
4660
+ }
4661
+ }
4662
+ function createExecutor(options) {
4663
+ return new MCXExecutor(options);
4664
+ }
4665
+ export {
4666
+ exports_external as z,
4667
+ skillBuilder,
4668
+ mergeConfigs,
4669
+ defineSkills,
4670
+ defineSkill,
4671
+ defineConfig,
4672
+ defineAdapter,
4673
+ createSandbox,
4674
+ createExecutor,
4675
+ createAdapterFactory,
4676
+ configBuilder,
4677
+ MCXExecutor,
4678
+ BunWorkerSandbox
4679
+ };