@paykit-sdk/stripe 1.1.7 → 1.1.92

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