@crosspost/sdk 0.1.9 → 0.1.10

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