@deiondz/better-auth-razorpay 2.0.5 → 2.0.7

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