@statelyai/agent 0.0.7 → 0.1.0

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