@moneymq/better-auth 0.2.1

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