@paykit-sdk/paypal 1.0.6 → 1.0.7

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