@hasna/calendar 0.1.0

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