@meetsmore-oss/use-ai-plugin-workflows 1.2.1

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