@paykit-sdk/stripe 1.1.7 → 1.1.9

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