@paykit-sdk/polar 1.1.99 → 1.1.100

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