@agentchatme/agent-core 0.0.1

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