@hasna/accounts 0.1.2

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