@scalar/nextjs-api-reference 0.7.0 → 0.7.2

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