@orpc/openapi 0.0.0-next.7b4c812 → 0.0.0-next.7ea4bbf

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