@orpc/openapi 0.0.0-next.ef3ba82 → 0.0.0-next.f99e554

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