@hasna/accounts 0.1.5 → 0.1.7

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