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