@orpc/openapi 0.17.0 → 0.19.0

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