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