zod-openapi 2.19.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,2118 +1,5 @@
1
+ import { getDefaultComponents, createPaths, createComponents } from "./components.chunk.mjs";
1
2
  import { extendZodWithOpenApi } from "./extendZod.chunk.mjs";
2
- const isZodType = (zodType, typeName) => {
3
- var _a;
4
- return ((_a = zodType == null ? void 0 : zodType._def) == null ? void 0 : _a.typeName) === typeName;
5
- };
6
- const isAnyZodType = (zodType) => {
7
- var _a;
8
- return Boolean(
9
- (_a = zodType == null ? void 0 : zodType._def) == null ? void 0 : _a.typeName
10
- );
11
- };
12
- const enhanceWithMetadata = (schema, metadata) => {
13
- if (schema.type === "ref") {
14
- if (Object.values(metadata).every((val) => val === void 0)) {
15
- return schema;
16
- }
17
- return {
18
- type: "schema",
19
- schema: {
20
- allOf: [schema.schema, metadata]
21
- },
22
- effects: schema.effects
23
- };
24
- }
25
- return {
26
- type: "schema",
27
- schema: {
28
- ...schema.schema,
29
- ...metadata
30
- },
31
- effects: schema.effects
32
- };
33
- };
34
- const createArraySchema = (zodArray, state) => {
35
- var _a, _b, _c, _d;
36
- const zodType = zodArray._def.type;
37
- const minItems = ((_a = zodArray._def.exactLength) == null ? void 0 : _a.value) ?? ((_b = zodArray._def.minLength) == null ? void 0 : _b.value);
38
- const maxItems = ((_c = zodArray._def.exactLength) == null ? void 0 : _c.value) ?? ((_d = zodArray._def.maxLength) == null ? void 0 : _d.value);
39
- const items = createSchemaObject(zodType, state, ["array items"]);
40
- return {
41
- type: "schema",
42
- schema: {
43
- type: "array",
44
- items: items.schema,
45
- ...minItems !== void 0 && { minItems },
46
- ...maxItems !== void 0 && { maxItems }
47
- },
48
- effects: items.effects
49
- };
50
- };
51
- const createBooleanSchema = (_zodBoolean) => ({
52
- type: "schema",
53
- schema: {
54
- type: "boolean"
55
- }
56
- });
57
- const createBrandedSchema = (zodBranded, state) => createSchemaObject(zodBranded._def.type, state, ["brand"]);
58
- const createCatchSchema = (zodCatch, state) => createSchemaObject(zodCatch._def.innerType, state, ["catch"]);
59
- const createDateSchema = (_zodDate) => ({
60
- type: "schema",
61
- schema: {
62
- type: "string"
63
- }
64
- });
65
- const createDefaultSchema = (zodDefault, state) => {
66
- const schemaObject = createSchemaObject(zodDefault._def.innerType, state, [
67
- "default"
68
- ]);
69
- return enhanceWithMetadata(schemaObject, {
70
- default: zodDefault._def.defaultValue()
71
- });
72
- };
73
- const openApiVersions = [
74
- "3.0.0",
75
- "3.0.1",
76
- "3.0.2",
77
- "3.0.3",
78
- "3.1.0"
79
- ];
80
- const satisfiesVersion = (test, against) => openApiVersions.indexOf(test) >= openApiVersions.indexOf(against);
81
- const createNativeEnumSchema = (zodEnum, state) => {
82
- const enumValues = getValidEnumValues(zodEnum._def.values);
83
- const { numbers, strings } = sortStringsAndNumbers(enumValues);
84
- if (strings.length && numbers.length) {
85
- if (satisfiesVersion(state.components.openapi, "3.1.0"))
86
- return {
87
- type: "schema",
88
- schema: {
89
- type: ["string", "number"],
90
- enum: [...strings, ...numbers]
91
- }
92
- };
93
- return {
94
- type: "schema",
95
- schema: {
96
- oneOf: [
97
- { type: "string", enum: strings },
98
- { type: "number", enum: numbers }
99
- ]
100
- }
101
- };
102
- }
103
- if (strings.length) {
104
- return {
105
- type: "schema",
106
- schema: {
107
- type: "string",
108
- enum: strings
109
- }
110
- };
111
- }
112
- return {
113
- type: "schema",
114
- schema: {
115
- type: "number",
116
- enum: numbers
117
- }
118
- };
119
- };
120
- const getValidEnumValues = (enumValues) => {
121
- const keys = Object.keys(enumValues).filter(
122
- (key) => typeof enumValues[enumValues[key]] !== "number"
123
- );
124
- return keys.map((key) => enumValues[key]);
125
- };
126
- const sortStringsAndNumbers = (values) => ({
127
- strings: values.filter((value) => typeof value === "string"),
128
- numbers: values.filter((value) => typeof value === "number")
129
- });
130
- const createTransformSchema = (zodTransform, state) => {
131
- var _a, _b, _c;
132
- if (((_a = zodTransform._def.openapi) == null ? void 0 : _a.effectType) === "output") {
133
- return {
134
- type: "schema",
135
- schema: createManualOutputTransformSchema(zodTransform, state)
136
- };
137
- }
138
- if (((_b = zodTransform._def.openapi) == null ? void 0 : _b.effectType) === "input" || ((_c = zodTransform._def.openapi) == null ? void 0 : _c.effectType) === "same") {
139
- return createSchemaObject(zodTransform._def.schema, state, [
140
- "transform input"
141
- ]);
142
- }
143
- if (state.type === "output") {
144
- return {
145
- type: "schema",
146
- schema: createManualOutputTransformSchema(zodTransform, state)
147
- };
148
- }
149
- const schema = createSchemaObject(zodTransform._def.schema, state, [
150
- "transform input"
151
- ]);
152
- return {
153
- ...schema,
154
- effects: flattenEffects([
155
- [
156
- {
157
- type: "schema",
158
- creationType: "input",
159
- zodType: zodTransform,
160
- path: [...state.path]
161
- }
162
- ],
163
- schema.effects
164
- ])
165
- };
166
- };
167
- const createManualOutputTransformSchema = (zodTransform, state) => {
168
- var _a;
169
- if (!((_a = zodTransform._def.openapi) == null ? void 0 : _a.type)) {
170
- const zodType = zodTransform.constructor.name;
171
- const schemaName = `${zodType} - ${zodTransform._def.effect.type}`;
172
- throw new Error(
173
- `Failed to determine a type for ${schemaName} at ${state.path.join(
174
- " > "
175
- )}. Please change the 'effectType' to 'input', wrap it in a ZodPipeline or assign it a manual 'type'.`
176
- );
177
- }
178
- return {
179
- type: zodTransform._def.openapi.type
180
- };
181
- };
182
- const getZodTypeName = (zodType) => {
183
- if (isZodType(zodType, "ZodEffects")) {
184
- return `${zodType._def.typeName} - ${zodType._def.effect.type}`;
185
- }
186
- return zodType._def.typeName;
187
- };
188
- const throwTransformError = (effect) => {
189
- const typeName = getZodTypeName(effect.zodType);
190
- const input = effect.creationType;
191
- const opposite = input === "input" ? "output" : "input";
192
- throw new Error(
193
- `The ${typeName} at ${effect.path.join(
194
- " > "
195
- )} is used within a registered compoment schema${effect.component ? ` (${effect.component.ref})` : ""} and contains an ${input} transformation${effect.component ? ` (${getZodTypeName(
196
- effect.component.zodType
197
- )}) defined at ${effect.component.path.join(" > ")}` : ""} which is also used in an ${opposite} schema.
198
-
199
- This may cause the schema to render incorrectly and is most likely a mistake. You can resolve this by:
200
-
201
- 1. Setting an \`effectType\` on one of the transformations to \`same\` (Not applicable for ZodDefault), \`input\` or \`output\` eg. \`.openapi({type: 'same'})\`
202
- 2. Wrapping the transformation in a ZodPipeline
203
- 3. Assigning a manual type to the transformation eg. \`.openapi({type: 'string'})\`
204
- 4. Removing the transformation
205
- 5. Deregister the component containing the transformation`
206
- );
207
- };
208
- const resolveSingleEffect = (effect, state) => {
209
- if (effect.type === "schema") {
210
- return {
211
- creationType: effect.creationType,
212
- path: effect.path,
213
- zodType: effect.zodType
214
- };
215
- }
216
- if (effect.type === "component") {
217
- if (state.visited.has(effect.zodType)) {
218
- return;
219
- }
220
- const component = state.components.schemas.get(effect.zodType);
221
- if ((component == null ? void 0 : component.type) !== "complete") {
222
- throw new Error("Something went wrong, component schema is not complete");
223
- }
224
- if (component.resolvedEffect) {
225
- return {
226
- creationType: component.resolvedEffect.creationType,
227
- path: effect.path,
228
- zodType: effect.zodType,
229
- component: {
230
- ref: component.ref,
231
- zodType: component.resolvedEffect.zodType,
232
- path: component.resolvedEffect.path
233
- }
234
- };
235
- }
236
- if (!component.effects) {
237
- return void 0;
238
- }
239
- state.visited.add(effect.zodType);
240
- const resolved = resolveEffect(component.effects, state);
241
- state.visited.delete(effect.zodType);
242
- if (!resolved) {
243
- return void 0;
244
- }
245
- component.resolvedEffect = resolved;
246
- return resolved;
247
- }
248
- return void 0;
249
- };
250
- const resolveEffect = (effects, state) => {
251
- const { input, output } = effects.reduce(
252
- (acc, effect) => {
253
- const resolvedSchemaEffect = resolveSingleEffect(effect, state);
254
- if ((resolvedSchemaEffect == null ? void 0 : resolvedSchemaEffect.creationType) === "input") {
255
- acc.input.push(resolvedSchemaEffect);
256
- }
257
- if ((resolvedSchemaEffect == null ? void 0 : resolvedSchemaEffect.creationType) === "output") {
258
- acc.output.push(resolvedSchemaEffect);
259
- }
260
- if (resolvedSchemaEffect && acc.input.length > 1 && acc.output.length > 1) {
261
- throwTransformError(resolvedSchemaEffect);
262
- }
263
- return acc;
264
- },
265
- { input: [], output: [] }
266
- );
267
- if (input.length > 0) {
268
- return input[0];
269
- }
270
- if (output.length > 0) {
271
- return output[0];
272
- }
273
- return void 0;
274
- };
275
- const verifyEffects = (effects, state) => {
276
- const resolved = resolveEffect(effects, state);
277
- if ((resolved == null ? void 0 : resolved.creationType) && resolved.creationType !== state.type) {
278
- throwTransformError(resolved);
279
- }
280
- };
281
- const flattenEffects = (effects) => {
282
- const allEffects = effects.reduce((acc, effect) => {
283
- if (effect) {
284
- return acc.concat(effect);
285
- }
286
- return acc;
287
- }, []);
288
- return allEffects.length ? allEffects : void 0;
289
- };
290
- const createDiscriminatedUnionSchema = (zodDiscriminatedUnion, state) => {
291
- const options = zodDiscriminatedUnion.options;
292
- const schemas = options.map(
293
- (option, index) => createSchemaObject(option, state, [`discriminated union option ${index}`])
294
- );
295
- const schemaObjects = schemas.map((schema) => schema.schema);
296
- const discriminator = mapDiscriminator(
297
- schemaObjects,
298
- options,
299
- zodDiscriminatedUnion.discriminator,
300
- state
301
- );
302
- return {
303
- type: "schema",
304
- schema: {
305
- oneOf: schemaObjects,
306
- ...discriminator && { discriminator }
307
- },
308
- effects: flattenEffects(schemas.map((schema) => schema.effects))
309
- };
310
- };
311
- const unwrapLiterals = (zodType, state) => {
312
- if (isZodType(zodType, "ZodLiteral")) {
313
- if (typeof zodType._def.value !== "string") {
314
- return void 0;
315
- }
316
- return [zodType._def.value];
317
- }
318
- if (isZodType(zodType, "ZodNativeEnum")) {
319
- const schema = createNativeEnumSchema(zodType, state);
320
- if (schema.type === "schema" && schema.schema.type === "string") {
321
- return schema.schema.enum;
322
- }
323
- }
324
- if (isZodType(zodType, "ZodEnum")) {
325
- return zodType._def.values;
326
- }
327
- if (isZodType(zodType, "ZodBranded")) {
328
- return unwrapLiterals(zodType._def.type, state);
329
- }
330
- if (isZodType(zodType, "ZodReadonly")) {
331
- return unwrapLiterals(zodType._def.innerType, state);
332
- }
333
- if (isZodType(zodType, "ZodCatch")) {
334
- return unwrapLiterals(zodType._def.innerType, state);
335
- }
336
- return void 0;
337
- };
338
- const mapDiscriminator = (schemas, zodObjects, discriminator, state) => {
339
- if (typeof discriminator !== "string") {
340
- return void 0;
341
- }
342
- const mapping = {};
343
- for (const [index, zodObject] of zodObjects.entries()) {
344
- const schema = schemas[index];
345
- const componentSchemaRef = "$ref" in schema ? schema == null ? void 0 : schema.$ref : void 0;
346
- if (!componentSchemaRef) {
347
- return void 0;
348
- }
349
- const value = zodObject.shape[discriminator];
350
- const literals = unwrapLiterals(value, state);
351
- if (!literals) {
352
- return void 0;
353
- }
354
- for (const enumValue of literals) {
355
- mapping[enumValue] = componentSchemaRef;
356
- }
357
- }
358
- return {
359
- propertyName: discriminator,
360
- mapping
361
- };
362
- };
363
- const createEnumSchema = (zodEnum) => ({
364
- type: "schema",
365
- schema: {
366
- type: "string",
367
- enum: zodEnum._def.values
368
- }
369
- });
370
- const createIntersectionSchema = (zodIntersection, state) => {
371
- const left = createSchemaObject(zodIntersection._def.left, state, [
372
- "intersection left"
373
- ]);
374
- const right = createSchemaObject(zodIntersection._def.right, state, [
375
- "intersection right"
376
- ]);
377
- return {
378
- type: "schema",
379
- schema: {
380
- allOf: [left.schema, right.schema]
381
- },
382
- effects: flattenEffects([left.effects, right.effects])
383
- };
384
- };
385
- const createLazySchema = (zodLazy, state) => {
386
- const innerSchema = zodLazy._def.getter();
387
- return createSchemaObject(innerSchema, state, ["lazy schema"]);
388
- };
389
- const createNullSchema = () => ({
390
- type: "schema",
391
- schema: {
392
- type: "null"
393
- }
394
- });
395
- const createLiteralSchema = (zodLiteral, state) => {
396
- if (zodLiteral.value === null) {
397
- return createNullSchema();
398
- }
399
- if (satisfiesVersion(state.components.openapi, "3.1.0")) {
400
- return {
401
- type: "schema",
402
- schema: {
403
- type: typeof zodLiteral.value,
404
- const: zodLiteral.value
405
- }
406
- };
407
- }
408
- return {
409
- type: "schema",
410
- schema: {
411
- type: typeof zodLiteral.value,
412
- enum: [zodLiteral.value]
413
- }
414
- };
415
- };
416
- const createManualTypeSchema = (zodSchema, state) => {
417
- var _a;
418
- if (!((_a = zodSchema._def.openapi) == null ? void 0 : _a.type)) {
419
- const schemaName = zodSchema.constructor.name;
420
- throw new Error(
421
- `Unknown schema ${schemaName} at ${state.path.join(
422
- " > "
423
- )}. Please assign it a manual 'type'.`
424
- );
425
- }
426
- return {
427
- type: "schema",
428
- schema: {
429
- type: zodSchema._def.openapi.type
430
- }
431
- };
432
- };
433
- const createNullableSchema = (zodNullable, state) => {
434
- const schemaObject = createSchemaObject(zodNullable.unwrap(), state, [
435
- "nullable"
436
- ]);
437
- if (satisfiesVersion(state.components.openapi, "3.1.0")) {
438
- if (schemaObject.type === "ref" || schemaObject.schema.allOf) {
439
- return {
440
- type: "schema",
441
- schema: {
442
- oneOf: mapNullOf([schemaObject.schema], state.components.openapi)
443
- },
444
- effects: schemaObject.effects
445
- };
446
- }
447
- if (schemaObject.schema.oneOf) {
448
- const { oneOf, ...schema3 } = schemaObject.schema;
449
- return {
450
- type: "schema",
451
- schema: {
452
- oneOf: mapNullOf(oneOf, state.components.openapi),
453
- ...schema3
454
- },
455
- effects: schemaObject.effects
456
- };
457
- }
458
- if (schemaObject.schema.anyOf) {
459
- const { anyOf, ...schema3 } = schemaObject.schema;
460
- return {
461
- type: "schema",
462
- schema: {
463
- anyOf: mapNullOf(anyOf, state.components.openapi),
464
- ...schema3
465
- },
466
- effects: schemaObject.effects
467
- };
468
- }
469
- const { type: type2, ...schema2 } = schemaObject.schema;
470
- return {
471
- type: "schema",
472
- schema: {
473
- type: mapNullType(type2),
474
- ...schema2
475
- },
476
- effects: schemaObject.effects
477
- };
478
- }
479
- if (schemaObject.type === "ref") {
480
- return {
481
- type: "schema",
482
- schema: {
483
- allOf: [schemaObject.schema],
484
- nullable: true
485
- },
486
- effects: schemaObject.effects
487
- };
488
- }
489
- const { type, ...schema } = schemaObject.schema;
490
- return {
491
- type: "schema",
492
- schema: {
493
- ...type && { type },
494
- nullable: true,
495
- ...schema,
496
- // https://github.com/OAI/OpenAPI-Specification/blob/main/proposals/2019-10-31-Clarify-Nullable.md#if-a-schema-specifies-nullable-true-and-enum-1-2-3-does-that-schema-allow-null-values-see-1900
497
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
498
- ...schema.enum && { enum: [...schema.enum, null] }
499
- },
500
- effects: schemaObject.effects
501
- };
502
- };
503
- const mapNullType = (type) => {
504
- if (!type) {
505
- return "null";
506
- }
507
- if (Array.isArray(type)) {
508
- return [...type, "null"];
509
- }
510
- return [type, "null"];
511
- };
512
- const mapNullOf = (ofSchema, openapi) => {
513
- if (satisfiesVersion(openapi, "3.1.0")) {
514
- return [...ofSchema, { type: "null" }];
515
- }
516
- return [...ofSchema, { nullable: true }];
517
- };
518
- const createNumberSchema = (zodNumber, state) => {
519
- const zodNumberChecks = getZodNumberChecks(zodNumber);
520
- const minimum = mapMinimum(zodNumberChecks, state.components.openapi);
521
- const maximum = mapMaximum(zodNumberChecks, state.components.openapi);
522
- return {
523
- type: "schema",
524
- schema: {
525
- type: mapNumberType(zodNumberChecks),
526
- ...minimum && minimum,
527
- // Union types are not easy to tame
528
- ...maximum && maximum
529
- }
530
- };
531
- };
532
- const mapMaximum = (zodNumberCheck, openapi) => {
533
- if (!zodNumberCheck.max) {
534
- return void 0;
535
- }
536
- const maximum = zodNumberCheck.max.value;
537
- if (zodNumberCheck.max.inclusive) {
538
- return { ...maximum !== void 0 && { maximum } };
539
- }
540
- if (satisfiesVersion(openapi, "3.1.0")) {
541
- return { exclusiveMaximum: maximum };
542
- }
543
- return { maximum, exclusiveMaximum: true };
544
- };
545
- const mapMinimum = (zodNumberCheck, openapi) => {
546
- if (!zodNumberCheck.min) {
547
- return void 0;
548
- }
549
- const minimum = zodNumberCheck.min.value;
550
- if (zodNumberCheck.min.inclusive) {
551
- return { ...minimum !== void 0 && { minimum } };
552
- }
553
- if (satisfiesVersion(openapi, "3.1.0")) {
554
- return { exclusiveMinimum: minimum };
555
- }
556
- return { minimum, exclusiveMinimum: true };
557
- };
558
- const getZodNumberChecks = (zodNumber) => zodNumber._def.checks.reduce((acc, check) => {
559
- acc[check.kind] = check;
560
- return acc;
561
- }, {});
562
- const mapNumberType = (zodNumberChecks) => zodNumberChecks.int ? "integer" : "number";
563
- const createOptionalSchema = (zodOptional, state) => createSchemaObject(zodOptional.unwrap(), state, ["optional"]);
564
- const isOptionalSchema = (zodSchema, state) => {
565
- var _a, _b, _c;
566
- if (isZodType(zodSchema, "ZodOptional") || isZodType(zodSchema, "ZodNever") || isZodType(zodSchema, "ZodUndefined") || isZodType(zodSchema, "ZodLiteral") && zodSchema._def.value === void 0) {
567
- return { optional: true };
568
- }
569
- if (isZodType(zodSchema, "ZodDefault")) {
570
- if (((_a = zodSchema._def.openapi) == null ? void 0 : _a.effectType) === "input") {
571
- return { optional: true };
572
- }
573
- if (((_b = zodSchema._def.openapi) == null ? void 0 : _b.effectType) === "output") {
574
- return { optional: false };
575
- }
576
- return {
577
- optional: state.type === "input",
578
- effects: [
579
- {
580
- type: "schema",
581
- creationType: state.type,
582
- zodType: zodSchema,
583
- path: [...state.path]
584
- }
585
- ]
586
- };
587
- }
588
- if (isZodType(zodSchema, "ZodNullable") || isZodType(zodSchema, "ZodCatch")) {
589
- return isOptionalSchema(zodSchema._def.innerType, state);
590
- }
591
- if (isZodType(zodSchema, "ZodEffects")) {
592
- return isOptionalSchema(zodSchema._def.schema, state);
593
- }
594
- if (isZodType(zodSchema, "ZodUnion") || isZodType(zodSchema, "ZodDiscriminatedUnion")) {
595
- const results = zodSchema._def.options.map(
596
- (schema) => isOptionalSchema(schema, state)
597
- );
598
- return results.reduce(
599
- (acc, result) => ({
600
- optional: acc.optional || result.optional,
601
- effects: flattenEffects([acc.effects, result.effects])
602
- }),
603
- { optional: false }
604
- );
605
- }
606
- if (isZodType(zodSchema, "ZodIntersection")) {
607
- const results = [zodSchema._def.left, zodSchema._def.right].map(
608
- (schema) => isOptionalSchema(schema, state)
609
- );
610
- return results.reduce(
611
- (acc, result) => ({
612
- optional: acc.optional || result.optional,
613
- effects: flattenEffects([acc.effects, result.effects])
614
- }),
615
- { optional: false }
616
- );
617
- }
618
- if (isZodType(zodSchema, "ZodPipeline")) {
619
- const type = ((_c = zodSchema._def.openapi) == null ? void 0 : _c.effectType) ?? state.type;
620
- if (type === "input") {
621
- return isOptionalSchema(zodSchema._def.in, state);
622
- }
623
- if (type === "output") {
624
- return isOptionalSchema(zodSchema._def.out, state);
625
- }
626
- }
627
- if (isZodType(zodSchema, "ZodLazy")) {
628
- return isOptionalSchema(zodSchema._def.getter(), state);
629
- }
630
- return { optional: zodSchema.isOptional() };
631
- };
632
- const createObjectSchema = (zodObject, state) => {
633
- var _a;
634
- const extendedSchema = createExtendedSchema(
635
- zodObject,
636
- (_a = zodObject._def.extendMetadata) == null ? void 0 : _a.extends,
637
- state
638
- );
639
- if (extendedSchema) {
640
- return extendedSchema;
641
- }
642
- return createObjectSchemaFromShape(
643
- zodObject.shape,
644
- {
645
- unknownKeys: zodObject._def.unknownKeys,
646
- catchAll: zodObject._def.catchall
647
- },
648
- state
649
- );
650
- };
651
- const createExtendedSchema = (zodObject, baseZodObject, state) => {
652
- var _a;
653
- if (!baseZodObject) {
654
- return void 0;
655
- }
656
- const component = state.components.schemas.get(baseZodObject);
657
- if (component ?? ((_a = baseZodObject._def.openapi) == null ? void 0 : _a.ref)) {
658
- createSchemaObject(baseZodObject, state, ["extended schema"]);
659
- }
660
- const completeComponent = state.components.schemas.get(baseZodObject);
661
- if (!completeComponent) {
662
- return void 0;
663
- }
664
- const diffOpts = createDiffOpts(
665
- {
666
- unknownKeys: baseZodObject._def.unknownKeys,
667
- catchAll: baseZodObject._def.catchall
668
- },
669
- {
670
- unknownKeys: zodObject._def.unknownKeys,
671
- catchAll: zodObject._def.catchall
672
- }
673
- );
674
- if (!diffOpts) {
675
- return void 0;
676
- }
677
- const diffShape = createShapeDiff(
678
- baseZodObject._def.shape(),
679
- zodObject._def.shape()
680
- );
681
- if (!diffShape) {
682
- return void 0;
683
- }
684
- const extendedSchema = createObjectSchemaFromShape(
685
- diffShape,
686
- diffOpts,
687
- state
688
- );
689
- return {
690
- type: "schema",
691
- schema: {
692
- allOf: [{ $ref: createComponentSchemaRef(completeComponent.ref) }],
693
- ...extendedSchema.schema
694
- },
695
- effects: flattenEffects([
696
- completeComponent.type === "complete" ? completeComponent.effects : [],
697
- completeComponent.type === "in-progress" ? [
698
- {
699
- type: "component",
700
- zodType: zodObject,
701
- path: [...state.path]
702
- }
703
- ] : [],
704
- extendedSchema.effects
705
- ])
706
- };
707
- };
708
- const createDiffOpts = (baseOpts, extendedOpts) => {
709
- if (baseOpts.unknownKeys === "strict" || !isZodType(baseOpts.catchAll, "ZodNever")) {
710
- return void 0;
711
- }
712
- return {
713
- catchAll: extendedOpts.catchAll,
714
- unknownKeys: extendedOpts.unknownKeys
715
- };
716
- };
717
- const createShapeDiff = (baseObj, extendedObj) => {
718
- const acc = {};
719
- for (const [key, val] of Object.entries(extendedObj)) {
720
- const baseValue = baseObj[key];
721
- if (val === baseValue) {
722
- continue;
723
- }
724
- if (baseValue === void 0) {
725
- acc[key] = extendedObj[key];
726
- continue;
727
- }
728
- return null;
729
- }
730
- return acc;
731
- };
732
- const createObjectSchemaFromShape = (shape, { unknownKeys, catchAll }, state) => {
733
- const properties = mapProperties(shape, state);
734
- const required = mapRequired(shape, state);
735
- const additionalProperties = !isZodType(catchAll, "ZodNever") ? createSchemaObject(catchAll, state, ["additional properties"]) : void 0;
736
- return {
737
- type: "schema",
738
- schema: {
739
- type: "object",
740
- ...properties && { properties: properties.properties },
741
- ...(required == null ? void 0 : required.required.length) && { required: required.required },
742
- ...unknownKeys === "strict" && { additionalProperties: false },
743
- ...additionalProperties && {
744
- additionalProperties: additionalProperties.schema
745
- }
746
- },
747
- effects: flattenEffects([
748
- ...(properties == null ? void 0 : properties.effects) ?? [],
749
- additionalProperties == null ? void 0 : additionalProperties.effects,
750
- required == null ? void 0 : required.effects
751
- ])
752
- };
753
- };
754
- const mapRequired = (shape, state) => {
755
- const { required, effects: allEffects } = Object.entries(shape).reduce(
756
- (acc, [key, zodSchema]) => {
757
- state.path.push(`property: ${key}`);
758
- const { optional, effects } = isOptionalSchema(zodSchema, state);
759
- state.path.pop();
760
- if (!optional) {
761
- acc.required.push(key);
762
- }
763
- if (effects) {
764
- acc.effects.push(effects);
765
- }
766
- return acc;
767
- },
768
- {
769
- required: [],
770
- effects: []
771
- }
772
- );
773
- return { required, effects: flattenEffects(allEffects) };
774
- };
775
- const mapProperties = (shape, state) => {
776
- const shapeEntries = Object.entries(shape);
777
- if (!shapeEntries.length) {
778
- return void 0;
779
- }
780
- return shapeEntries.reduce(
781
- (acc, [key, zodSchema]) => {
782
- if (isZodType(zodSchema, "ZodNever") || isZodType(zodSchema, "ZodUndefined")) {
783
- return acc;
784
- }
785
- const property = createSchemaObject(zodSchema, state, [
786
- `property: ${key}`
787
- ]);
788
- acc.properties[key] = property.schema;
789
- acc.effects.push(property.effects);
790
- return acc;
791
- },
792
- {
793
- properties: {},
794
- effects: []
795
- }
796
- );
797
- };
798
- const createPipelineSchema = (zodPipeline, state) => {
799
- var _a, _b, _c;
800
- if (((_a = zodPipeline._def.openapi) == null ? void 0 : _a.effectType) === "input" || ((_b = zodPipeline._def.openapi) == null ? void 0 : _b.effectType) === "same") {
801
- return createSchemaObject(zodPipeline._def.in, state, ["pipeline input"]);
802
- }
803
- if (((_c = zodPipeline._def.openapi) == null ? void 0 : _c.effectType) === "output") {
804
- return createSchemaObject(zodPipeline._def.out, state, ["pipeline output"]);
805
- }
806
- if (state.type === "input") {
807
- const schema2 = createSchemaObject(zodPipeline._def.in, state, [
808
- "pipeline input"
809
- ]);
810
- return {
811
- ...schema2,
812
- effects: flattenEffects([
813
- [
814
- {
815
- type: "schema",
816
- creationType: "input",
817
- path: [...state.path],
818
- zodType: zodPipeline
819
- }
820
- ],
821
- schema2.effects
822
- ])
823
- };
824
- }
825
- const schema = createSchemaObject(zodPipeline._def.out, state, [
826
- "pipeline output"
827
- ]);
828
- return {
829
- ...schema,
830
- effects: flattenEffects([
831
- [
832
- {
833
- type: "schema",
834
- creationType: "output",
835
- path: [...state.path],
836
- zodType: zodPipeline
837
- }
838
- ],
839
- schema.effects
840
- ])
841
- };
842
- };
843
- const createPreprocessSchema = (zodPreprocess, state) => createSchemaObject(zodPreprocess._def.schema, state, ["preprocess schema"]);
844
- const createReadonlySchema = (zodReadonly, state) => (
845
- // Readonly doesn't change OpenAPI schema
846
- createSchemaObject(zodReadonly._def.innerType, state, ["readonly"])
847
- );
848
- const createRecordSchema = (zodRecord, state) => {
849
- const additionalProperties = createSchemaObject(
850
- zodRecord.valueSchema,
851
- state,
852
- ["record value"]
853
- );
854
- const keySchema = createSchemaObject(zodRecord.keySchema, state, [
855
- "record key"
856
- ]);
857
- const maybeComponent = state.components.schemas.get(zodRecord.keySchema);
858
- const isComplete = maybeComponent && maybeComponent.type === "complete";
859
- const maybeSchema = isComplete && maybeComponent.schemaObject;
860
- const maybeEffects = isComplete && maybeComponent.effects || void 0;
861
- const renderedKeySchema = maybeSchema || keySchema.schema;
862
- if ("enum" in renderedKeySchema && renderedKeySchema.enum) {
863
- return {
864
- type: "schema",
865
- schema: {
866
- type: "object",
867
- properties: renderedKeySchema.enum.reduce((acc, key) => {
868
- acc[key] = additionalProperties.schema;
869
- return acc;
870
- }, {}),
871
- additionalProperties: false
872
- },
873
- effects: flattenEffects([
874
- keySchema.effects,
875
- additionalProperties.effects,
876
- maybeEffects
877
- ])
878
- };
879
- }
880
- if (satisfiesVersion(state.components.openapi, "3.1.0") && "type" in renderedKeySchema && renderedKeySchema.type === "string" && Object.keys(renderedKeySchema).length > 1) {
881
- return {
882
- type: "schema",
883
- schema: {
884
- type: "object",
885
- propertyNames: keySchema.schema,
886
- additionalProperties: additionalProperties.schema
887
- },
888
- effects: flattenEffects([
889
- keySchema.effects,
890
- additionalProperties.effects
891
- ])
892
- };
893
- }
894
- return {
895
- type: "schema",
896
- schema: {
897
- type: "object",
898
- additionalProperties: additionalProperties.schema
899
- },
900
- effects: additionalProperties.effects
901
- };
902
- };
903
- const createRefineSchema = (zodRefine, state) => createSchemaObject(zodRefine._def.schema, state, ["refine schema"]);
904
- const createSetSchema = (zodSet, state) => {
905
- var _a, _b;
906
- const schema = zodSet._def.valueType;
907
- const minItems = (_a = zodSet._def.minSize) == null ? void 0 : _a.value;
908
- const maxItems = (_b = zodSet._def.maxSize) == null ? void 0 : _b.value;
909
- const itemSchema = createSchemaObject(schema, state, ["set items"]);
910
- return {
911
- type: "schema",
912
- schema: {
913
- type: "array",
914
- items: itemSchema.schema,
915
- uniqueItems: true,
916
- ...minItems !== void 0 && { minItems },
917
- ...maxItems !== void 0 && { maxItems }
918
- },
919
- effects: itemSchema.effects
920
- };
921
- };
922
- const createStringSchema = (zodString, state) => {
923
- var _a, _b, _c, _d, _e, _f, _g, _h;
924
- const zodStringChecks = getZodStringChecks(zodString);
925
- const format = mapStringFormat(zodStringChecks);
926
- const patterns = mapPatterns(zodStringChecks);
927
- const minLength = ((_b = (_a = zodStringChecks.length) == null ? void 0 : _a[0]) == null ? void 0 : _b.value) ?? ((_d = (_c = zodStringChecks.min) == null ? void 0 : _c[0]) == null ? void 0 : _d.value);
928
- const maxLength = ((_f = (_e = zodStringChecks.length) == null ? void 0 : _e[0]) == null ? void 0 : _f.value) ?? ((_h = (_g = zodStringChecks.max) == null ? void 0 : _g[0]) == null ? void 0 : _h.value);
929
- const contentEncoding = satisfiesVersion(state.components.openapi, "3.1.0") ? mapContentEncoding(zodStringChecks) : void 0;
930
- if (patterns.length <= 1) {
931
- return {
932
- type: "schema",
933
- schema: {
934
- type: "string",
935
- ...format && { format },
936
- ...patterns[0] && { pattern: patterns[0] },
937
- ...minLength !== void 0 && { minLength },
938
- ...maxLength !== void 0 && { maxLength },
939
- ...contentEncoding && { contentEncoding }
940
- }
941
- };
942
- }
943
- return {
944
- type: "schema",
945
- schema: {
946
- allOf: [
947
- {
948
- type: "string",
949
- ...format && { format },
950
- ...patterns[0] && { pattern: patterns[0] },
951
- ...minLength !== void 0 && { minLength },
952
- ...maxLength !== void 0 && { maxLength },
953
- ...contentEncoding && { contentEncoding }
954
- },
955
- ...patterns.slice(1).map(
956
- (pattern) => ({
957
- type: "string",
958
- pattern
959
- })
960
- )
961
- ]
962
- }
963
- };
964
- };
965
- const getZodStringChecks = (zodString) => zodString._def.checks.reduce(
966
- (acc, check) => {
967
- const mapping = acc[check.kind];
968
- if (mapping) {
969
- mapping.push(check);
970
- return acc;
971
- }
972
- acc[check.kind] = [check];
973
- return acc;
974
- },
975
- {}
976
- );
977
- const mapPatterns = (zodStringChecks) => {
978
- const startsWith = mapStartsWith(zodStringChecks);
979
- const endsWith = mapEndsWith(zodStringChecks);
980
- const regex = mapRegex(zodStringChecks);
981
- const includes = mapIncludes(zodStringChecks);
982
- const patterns = [
983
- ...regex ?? [],
984
- ...startsWith ? [startsWith] : [],
985
- ...endsWith ? [endsWith] : [],
986
- ...includes ?? []
987
- ];
988
- return patterns;
989
- };
990
- const mapStartsWith = (zodStringChecks) => {
991
- var _a, _b;
992
- if ((_b = (_a = zodStringChecks.startsWith) == null ? void 0 : _a[0]) == null ? void 0 : _b.value) {
993
- return `^${zodStringChecks.startsWith[0].value}`;
994
- }
995
- return void 0;
996
- };
997
- const mapEndsWith = (zodStringChecks) => {
998
- var _a, _b;
999
- if ((_b = (_a = zodStringChecks.endsWith) == null ? void 0 : _a[0]) == null ? void 0 : _b.value) {
1000
- return `${zodStringChecks.endsWith[0].value}$`;
1001
- }
1002
- return void 0;
1003
- };
1004
- const mapRegex = (zodStringChecks) => {
1005
- var _a;
1006
- return (_a = zodStringChecks.regex) == null ? void 0 : _a.map((regexCheck) => regexCheck.regex.source);
1007
- };
1008
- const mapIncludes = (zodStringChecks) => {
1009
- var _a;
1010
- return (_a = zodStringChecks.includes) == null ? void 0 : _a.map((includeCheck) => {
1011
- if (includeCheck.position === 0) {
1012
- return `^${includeCheck.value}`;
1013
- }
1014
- if (includeCheck.position) {
1015
- return `^.{${includeCheck.position}}${includeCheck.value}`;
1016
- }
1017
- return includeCheck.value;
1018
- });
1019
- };
1020
- const mapStringFormat = (zodStringChecks) => {
1021
- if (zodStringChecks.uuid) {
1022
- return "uuid";
1023
- }
1024
- if (zodStringChecks.datetime) {
1025
- return "date-time";
1026
- }
1027
- if (zodStringChecks.date) {
1028
- return "date";
1029
- }
1030
- if (zodStringChecks.time) {
1031
- return "time";
1032
- }
1033
- if (zodStringChecks.duration) {
1034
- return "duration";
1035
- }
1036
- if (zodStringChecks.email) {
1037
- return "email";
1038
- }
1039
- if (zodStringChecks.url) {
1040
- return "uri";
1041
- }
1042
- return void 0;
1043
- };
1044
- const mapContentEncoding = (zodStringChecks) => {
1045
- if (zodStringChecks.base64) {
1046
- return "base64";
1047
- }
1048
- return void 0;
1049
- };
1050
- const createTupleSchema = (zodTuple, state) => {
1051
- const items = zodTuple.items;
1052
- const rest = zodTuple._def.rest;
1053
- const prefixItems = mapPrefixItems(items, state);
1054
- if (satisfiesVersion(state.components.openapi, "3.1.0")) {
1055
- if (!rest) {
1056
- return {
1057
- type: "schema",
1058
- schema: {
1059
- type: "array",
1060
- maxItems: items.length,
1061
- minItems: items.length,
1062
- ...prefixItems && {
1063
- prefixItems: prefixItems.schemas.map((item) => item.schema)
1064
- }
1065
- },
1066
- effects: prefixItems == null ? void 0 : prefixItems.effects
1067
- };
1068
- }
1069
- const itemSchema = createSchemaObject(rest, state, ["tuple items"]);
1070
- return {
1071
- type: "schema",
1072
- schema: {
1073
- type: "array",
1074
- items: itemSchema.schema,
1075
- ...prefixItems && {
1076
- prefixItems: prefixItems.schemas.map((item) => item.schema)
1077
- }
1078
- },
1079
- effects: flattenEffects([prefixItems == null ? void 0 : prefixItems.effects, itemSchema.effects])
1080
- };
1081
- }
1082
- if (!rest) {
1083
- return {
1084
- type: "schema",
1085
- schema: {
1086
- type: "array",
1087
- maxItems: items.length,
1088
- minItems: items.length,
1089
- ...prefixItems && {
1090
- items: { oneOf: prefixItems.schemas.map((item) => item.schema) }
1091
- }
1092
- },
1093
- effects: prefixItems == null ? void 0 : prefixItems.effects
1094
- };
1095
- }
1096
- if (prefixItems) {
1097
- const restSchema = createSchemaObject(rest, state, ["tuple items"]);
1098
- return {
1099
- type: "schema",
1100
- schema: {
1101
- type: "array",
1102
- items: {
1103
- oneOf: [
1104
- ...prefixItems.schemas.map((item) => item.schema),
1105
- restSchema.schema
1106
- ]
1107
- }
1108
- },
1109
- effects: flattenEffects([restSchema.effects, prefixItems.effects])
1110
- };
1111
- }
1112
- return {
1113
- type: "schema",
1114
- schema: {
1115
- type: "array"
1116
- }
1117
- };
1118
- };
1119
- const mapPrefixItems = (items, state) => {
1120
- if (items.length) {
1121
- const schemas = items.map(
1122
- (item, index) => createSchemaObject(item, state, [`tuple item ${index}`])
1123
- );
1124
- return {
1125
- effects: flattenEffects(schemas.map((s) => s.effects)),
1126
- schemas
1127
- };
1128
- }
1129
- return void 0;
1130
- };
1131
- const createUnionSchema = (zodUnion, state) => {
1132
- var _a;
1133
- const schemas = zodUnion.options.map(
1134
- (option, index) => createSchemaObject(option, state, [`union option ${index}`])
1135
- );
1136
- if ((_a = zodUnion._def.openapi) == null ? void 0 : _a.unionOneOf) {
1137
- return {
1138
- type: "schema",
1139
- schema: {
1140
- oneOf: schemas.map((s) => s.schema)
1141
- },
1142
- effects: flattenEffects(schemas.map((s) => s.effects))
1143
- };
1144
- }
1145
- return {
1146
- type: "schema",
1147
- schema: {
1148
- anyOf: schemas.map((s) => s.schema)
1149
- },
1150
- effects: flattenEffects(schemas.map((s) => s.effects))
1151
- };
1152
- };
1153
- const createUnknownSchema = (_zodUnknown) => ({
1154
- type: "schema",
1155
- schema: {}
1156
- });
1157
- const createSchemaSwitch = (zodSchema, state) => {
1158
- var _a;
1159
- if ((_a = zodSchema._def.openapi) == null ? void 0 : _a.type) {
1160
- return createManualTypeSchema(zodSchema, state);
1161
- }
1162
- if (isZodType(zodSchema, "ZodString")) {
1163
- return createStringSchema(zodSchema, state);
1164
- }
1165
- if (isZodType(zodSchema, "ZodNumber")) {
1166
- return createNumberSchema(zodSchema, state);
1167
- }
1168
- if (isZodType(zodSchema, "ZodBoolean")) {
1169
- return createBooleanSchema();
1170
- }
1171
- if (isZodType(zodSchema, "ZodEnum")) {
1172
- return createEnumSchema(zodSchema);
1173
- }
1174
- if (isZodType(zodSchema, "ZodLiteral")) {
1175
- return createLiteralSchema(zodSchema, state);
1176
- }
1177
- if (isZodType(zodSchema, "ZodNativeEnum")) {
1178
- return createNativeEnumSchema(zodSchema, state);
1179
- }
1180
- if (isZodType(zodSchema, "ZodArray")) {
1181
- return createArraySchema(zodSchema, state);
1182
- }
1183
- if (isZodType(zodSchema, "ZodObject")) {
1184
- return createObjectSchema(zodSchema, state);
1185
- }
1186
- if (isZodType(zodSchema, "ZodUnion")) {
1187
- return createUnionSchema(zodSchema, state);
1188
- }
1189
- if (isZodType(zodSchema, "ZodDiscriminatedUnion")) {
1190
- return createDiscriminatedUnionSchema(zodSchema, state);
1191
- }
1192
- if (isZodType(zodSchema, "ZodNull")) {
1193
- return createNullSchema();
1194
- }
1195
- if (isZodType(zodSchema, "ZodNullable")) {
1196
- return createNullableSchema(zodSchema, state);
1197
- }
1198
- if (isZodType(zodSchema, "ZodOptional")) {
1199
- return createOptionalSchema(zodSchema, state);
1200
- }
1201
- if (isZodType(zodSchema, "ZodReadonly")) {
1202
- return createReadonlySchema(zodSchema, state);
1203
- }
1204
- if (isZodType(zodSchema, "ZodDefault")) {
1205
- return createDefaultSchema(zodSchema, state);
1206
- }
1207
- if (isZodType(zodSchema, "ZodRecord")) {
1208
- return createRecordSchema(zodSchema, state);
1209
- }
1210
- if (isZodType(zodSchema, "ZodTuple")) {
1211
- return createTupleSchema(zodSchema, state);
1212
- }
1213
- if (isZodType(zodSchema, "ZodDate")) {
1214
- return createDateSchema();
1215
- }
1216
- if (isZodType(zodSchema, "ZodPipeline")) {
1217
- return createPipelineSchema(zodSchema, state);
1218
- }
1219
- if (isZodType(zodSchema, "ZodEffects") && zodSchema._def.effect.type === "transform") {
1220
- return createTransformSchema(zodSchema, state);
1221
- }
1222
- if (isZodType(zodSchema, "ZodEffects") && zodSchema._def.effect.type === "preprocess") {
1223
- return createPreprocessSchema(zodSchema, state);
1224
- }
1225
- if (isZodType(zodSchema, "ZodEffects") && zodSchema._def.effect.type === "refinement") {
1226
- return createRefineSchema(zodSchema, state);
1227
- }
1228
- if (isZodType(zodSchema, "ZodNativeEnum")) {
1229
- return createNativeEnumSchema(zodSchema, state);
1230
- }
1231
- if (isZodType(zodSchema, "ZodIntersection")) {
1232
- return createIntersectionSchema(zodSchema, state);
1233
- }
1234
- if (isZodType(zodSchema, "ZodCatch")) {
1235
- return createCatchSchema(zodSchema, state);
1236
- }
1237
- if (isZodType(zodSchema, "ZodUnknown") || isZodType(zodSchema, "ZodAny")) {
1238
- return createUnknownSchema();
1239
- }
1240
- if (isZodType(zodSchema, "ZodLazy")) {
1241
- return createLazySchema(zodSchema, state);
1242
- }
1243
- if (isZodType(zodSchema, "ZodBranded")) {
1244
- return createBrandedSchema(zodSchema, state);
1245
- }
1246
- if (isZodType(zodSchema, "ZodSet")) {
1247
- return createSetSchema(zodSchema, state);
1248
- }
1249
- return createManualTypeSchema(zodSchema, state);
1250
- };
1251
- const isDescriptionEqual = (schema, zodSchema) => schema.type === "ref" && zodSchema.description === schema.zodType.description;
1252
- const createNewSchema = (zodSchema, state) => {
1253
- if (state.visited.has(zodSchema)) {
1254
- throw new Error(
1255
- `The schema at ${state.path.join(
1256
- " > "
1257
- )} needs to be registered because it's circularly referenced`
1258
- );
1259
- }
1260
- state.visited.add(zodSchema);
1261
- const {
1262
- effectType,
1263
- param,
1264
- header,
1265
- ref,
1266
- refType,
1267
- unionOneOf,
1268
- ...additionalMetadata
1269
- } = zodSchema._def.openapi ?? {};
1270
- const schema = createSchemaSwitch(zodSchema, state);
1271
- const description = zodSchema.description && !isDescriptionEqual(schema, zodSchema) ? zodSchema.description : void 0;
1272
- const schemaWithMetadata = enhanceWithMetadata(schema, {
1273
- ...description && { description },
1274
- ...additionalMetadata
1275
- });
1276
- state.visited.delete(zodSchema);
1277
- return schemaWithMetadata;
1278
- };
1279
- const createNewRef = (ref, zodSchema, state) => {
1280
- state.components.schemas.set(zodSchema, {
1281
- type: "in-progress",
1282
- ref
1283
- });
1284
- const newSchema = createNewSchema(zodSchema, {
1285
- ...state,
1286
- visited: /* @__PURE__ */ new Set()
1287
- });
1288
- state.components.schemas.set(zodSchema, {
1289
- type: "complete",
1290
- ref,
1291
- schemaObject: newSchema.schema,
1292
- effects: newSchema.effects
1293
- });
1294
- return {
1295
- type: "ref",
1296
- schema: { $ref: createComponentSchemaRef(ref) },
1297
- effects: newSchema.effects ? [
1298
- {
1299
- type: "component",
1300
- zodType: zodSchema,
1301
- path: [...state.path]
1302
- }
1303
- ] : void 0,
1304
- zodType: zodSchema
1305
- };
1306
- };
1307
- const createExistingRef = (zodSchema, component, state) => {
1308
- if (component && component.type === "complete") {
1309
- return {
1310
- type: "ref",
1311
- schema: { $ref: createComponentSchemaRef(component.ref) },
1312
- effects: component.effects ? [
1313
- {
1314
- type: "component",
1315
- zodType: zodSchema,
1316
- path: [...state.path]
1317
- }
1318
- ] : void 0,
1319
- zodType: zodSchema
1320
- };
1321
- }
1322
- if (component && component.type === "in-progress") {
1323
- return {
1324
- type: "ref",
1325
- schema: { $ref: createComponentSchemaRef(component.ref) },
1326
- effects: [
1327
- {
1328
- type: "component",
1329
- zodType: zodSchema,
1330
- path: [...state.path]
1331
- }
1332
- ],
1333
- zodType: zodSchema
1334
- };
1335
- }
1336
- return;
1337
- };
1338
- const createSchemaOrRef = (zodSchema, state) => {
1339
- var _a;
1340
- const component = state.components.schemas.get(zodSchema);
1341
- const existingRef = createExistingRef(zodSchema, component, state);
1342
- if (existingRef) {
1343
- return existingRef;
1344
- }
1345
- const ref = ((_a = zodSchema._def.openapi) == null ? void 0 : _a.ref) ?? (component == null ? void 0 : component.ref);
1346
- if (ref) {
1347
- return createNewRef(ref, zodSchema, state);
1348
- }
1349
- return createNewSchema(zodSchema, state);
1350
- };
1351
- const createSchemaObject = (zodSchema, state, subpath) => {
1352
- state.path.push(...subpath);
1353
- const schema = createSchemaOrRef(zodSchema, state);
1354
- state.path.pop();
1355
- return schema;
1356
- };
1357
- const createSchema = (zodSchema, state, subpath) => {
1358
- const schema = createSchemaObject(zodSchema, state, subpath);
1359
- if (schema.effects) {
1360
- verifyEffects(schema.effects, state);
1361
- }
1362
- return schema.schema;
1363
- };
1364
- const createMediaTypeSchema = (schemaObject, components, type, subpath) => {
1365
- if (!schemaObject) {
1366
- return void 0;
1367
- }
1368
- if (!isAnyZodType(schemaObject)) {
1369
- return schemaObject;
1370
- }
1371
- return createSchema(
1372
- schemaObject,
1373
- {
1374
- components,
1375
- type,
1376
- path: [],
1377
- visited: /* @__PURE__ */ new Set()
1378
- },
1379
- subpath
1380
- );
1381
- };
1382
- const createMediaTypeObject = (mediaTypeObject, components, type, subpath) => {
1383
- if (!mediaTypeObject) {
1384
- return void 0;
1385
- }
1386
- return {
1387
- ...mediaTypeObject,
1388
- schema: createMediaTypeSchema(mediaTypeObject.schema, components, type, [
1389
- ...subpath,
1390
- "schema"
1391
- ])
1392
- };
1393
- };
1394
- const createContent = (contentObject, components, type, subpath) => Object.entries(contentObject).reduce(
1395
- (acc, [mediaType, zodOpenApiMediaTypeObject]) => {
1396
- const mediaTypeObject = createMediaTypeObject(
1397
- zodOpenApiMediaTypeObject,
1398
- components,
1399
- type,
1400
- [...subpath, mediaType]
1401
- );
1402
- if (mediaTypeObject) {
1403
- acc[mediaType] = mediaTypeObject;
1404
- }
1405
- return acc;
1406
- },
1407
- {}
1408
- );
1409
- const createComponentParamRef = (ref) => `#/components/parameters/${ref}`;
1410
- const createBaseParameter = (schema, components, subpath) => {
1411
- var _a, _b, _c;
1412
- const { ref, ...rest } = ((_a = schema._def.openapi) == null ? void 0 : _a.param) ?? {};
1413
- const state = {
1414
- components,
1415
- type: "input",
1416
- path: [],
1417
- visited: /* @__PURE__ */ new Set()
1418
- };
1419
- const schemaObject = createSchema(schema, state, [...subpath, "schema"]);
1420
- const required = !((_b = isOptionalSchema(schema, state)) == null ? void 0 : _b.optional);
1421
- const description = ((_c = schema._def.openapi) == null ? void 0 : _c.description) ?? schema._def.description;
1422
- return {
1423
- ...description && { description },
1424
- ...rest,
1425
- ...schema && { schema: schemaObject },
1426
- ...required && { required }
1427
- };
1428
- };
1429
- const createParamOrRef = (zodSchema, components, subpath, type, name) => {
1430
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1431
- const component = components.parameters.get(zodSchema);
1432
- const paramType = ((_c = (_b = (_a = zodSchema._def) == null ? void 0 : _a.openapi) == null ? void 0 : _b.param) == null ? void 0 : _c.in) ?? (component == null ? void 0 : component.in) ?? type;
1433
- const paramName = ((_f = (_e = (_d = zodSchema._def) == null ? void 0 : _d.openapi) == null ? void 0 : _e.param) == null ? void 0 : _f.name) ?? (component == null ? void 0 : component.name) ?? name;
1434
- if (!paramType) {
1435
- throw new Error("Parameter type missing");
1436
- }
1437
- if (!paramName) {
1438
- throw new Error("Parameter name missing");
1439
- }
1440
- if (component && component.type === "complete") {
1441
- if (!("$ref" in component.paramObject) && (component.in !== paramType || component.name !== paramName)) {
1442
- throw new Error(`parameterRef "${component.ref}" is already registered`);
1443
- }
1444
- return {
1445
- $ref: createComponentParamRef(component.ref)
1446
- };
1447
- }
1448
- const baseParamOrRef = createBaseParameter(zodSchema, components, subpath);
1449
- if ("$ref" in baseParamOrRef) {
1450
- throw new Error("Unexpected Error: received a reference object");
1451
- }
1452
- const ref = ((_i = (_h = (_g = zodSchema == null ? void 0 : zodSchema._def) == null ? void 0 : _g.openapi) == null ? void 0 : _h.param) == null ? void 0 : _i.ref) ?? (component == null ? void 0 : component.ref);
1453
- const paramObject = {
1454
- in: paramType,
1455
- name: paramName,
1456
- ...baseParamOrRef
1457
- };
1458
- if (ref) {
1459
- components.parameters.set(zodSchema, {
1460
- type: "complete",
1461
- paramObject,
1462
- ref,
1463
- in: paramType,
1464
- name: paramName
1465
- });
1466
- return {
1467
- $ref: createComponentParamRef(ref)
1468
- };
1469
- }
1470
- return paramObject;
1471
- };
1472
- const createParameters = (type, zodObjectType, components, subpath) => {
1473
- if (!zodObjectType) {
1474
- return [];
1475
- }
1476
- const zodObject = getZodObject(zodObjectType).shape;
1477
- return Object.entries(zodObject).map(
1478
- ([key, zodSchema]) => createParamOrRef(zodSchema, components, [...subpath, key], type, key)
1479
- );
1480
- };
1481
- const createRequestParams = (requestParams, components, subpath) => {
1482
- if (!requestParams) {
1483
- return [];
1484
- }
1485
- const pathParams = createParameters("path", requestParams.path, components, [
1486
- ...subpath,
1487
- "path"
1488
- ]);
1489
- const queryParams = createParameters(
1490
- "query",
1491
- requestParams.query,
1492
- components,
1493
- [...subpath, "query"]
1494
- );
1495
- const cookieParams = createParameters(
1496
- "cookie",
1497
- requestParams.cookie,
1498
- components,
1499
- [...subpath, "cookie"]
1500
- );
1501
- const headerParams = createParameters(
1502
- "header",
1503
- requestParams.header,
1504
- components,
1505
- [...subpath, "header"]
1506
- );
1507
- return [...pathParams, ...queryParams, ...cookieParams, ...headerParams];
1508
- };
1509
- const createManualParameters = (parameters, components, subpath) => (parameters == null ? void 0 : parameters.map((param, index) => {
1510
- if (isAnyZodType(param)) {
1511
- return createParamOrRef(param, components, [
1512
- ...subpath,
1513
- `param index ${index}`
1514
- ]);
1515
- }
1516
- return param;
1517
- })) ?? [];
1518
- const createParametersObject = (parameters, requestParams, components, subpath) => {
1519
- const manualParameters = createManualParameters(
1520
- parameters,
1521
- components,
1522
- subpath
1523
- );
1524
- const createdParams = createRequestParams(requestParams, components, subpath);
1525
- const combinedParameters = [
1526
- ...manualParameters,
1527
- ...createdParams
1528
- ];
1529
- return combinedParameters.length ? combinedParameters : void 0;
1530
- };
1531
- const getZodObject = (schema, type) => {
1532
- if (isZodType(schema, "ZodObject")) {
1533
- return schema;
1534
- }
1535
- if (isZodType(schema, "ZodLazy")) {
1536
- return getZodObject(schema.schema);
1537
- }
1538
- if (isZodType(schema, "ZodEffects")) {
1539
- return getZodObject(schema.innerType());
1540
- }
1541
- if (isZodType(schema, "ZodBranded")) {
1542
- return getZodObject(schema.unwrap());
1543
- }
1544
- if (isZodType(schema, "ZodPipeline")) {
1545
- {
1546
- return getZodObject(schema._def.in);
1547
- }
1548
- }
1549
- throw new Error("failed to find ZodObject in schema");
1550
- };
1551
- const isISpecificationExtension = (key) => key.startsWith("x-");
1552
- const createResponseHeaders = (responseHeaders, components) => {
1553
- if (!responseHeaders) {
1554
- return void 0;
1555
- }
1556
- if (isAnyZodType(responseHeaders)) {
1557
- return Object.entries(responseHeaders.shape).reduce((acc, [key, zodSchema]) => {
1558
- acc[key] = createHeaderOrRef(zodSchema, components);
1559
- return acc;
1560
- }, {});
1561
- }
1562
- return responseHeaders;
1563
- };
1564
- const createHeaderOrRef = (schema, components) => {
1565
- var _a, _b, _c;
1566
- const component = components.headers.get(schema);
1567
- if (component && component.type === "complete") {
1568
- return {
1569
- $ref: createComponentHeaderRef(component.ref)
1570
- };
1571
- }
1572
- const baseHeader = createBaseHeader(schema, components);
1573
- if ("$ref" in baseHeader) {
1574
- throw new Error("Unexpected Error: received a reference object");
1575
- }
1576
- const ref = ((_c = (_b = (_a = schema._def) == null ? void 0 : _a.openapi) == null ? void 0 : _b.header) == null ? void 0 : _c.ref) ?? (component == null ? void 0 : component.ref);
1577
- if (ref) {
1578
- components.headers.set(schema, {
1579
- type: "complete",
1580
- headerObject: baseHeader,
1581
- ref
1582
- });
1583
- return {
1584
- $ref: createComponentHeaderRef(ref)
1585
- };
1586
- }
1587
- return baseHeader;
1588
- };
1589
- const createBaseHeader = (schema, components) => {
1590
- var _a, _b;
1591
- const { ref, ...rest } = ((_a = schema._def.openapi) == null ? void 0 : _a.header) ?? {};
1592
- const state = {
1593
- components,
1594
- type: "output",
1595
- path: [],
1596
- visited: /* @__PURE__ */ new Set()
1597
- };
1598
- const schemaObject = createSchema(schema, state, ["header"]);
1599
- const required = !((_b = isOptionalSchema(schema, state)) == null ? void 0 : _b.optional);
1600
- return {
1601
- ...rest,
1602
- ...schema && { schema: schemaObject },
1603
- ...required && { required }
1604
- };
1605
- };
1606
- const createComponentHeaderRef = (ref) => `#/components/headers/${ref}`;
1607
- const createResponse = (responseObject, components, subpath) => {
1608
- if ("$ref" in responseObject) {
1609
- return responseObject;
1610
- }
1611
- const component = components.responses.get(responseObject);
1612
- if (component && component.type === "complete") {
1613
- return { $ref: createComponentResponseRef(component.ref) };
1614
- }
1615
- const { content, headers, ref, ...rest } = responseObject;
1616
- const maybeHeaders = createResponseHeaders(headers, components);
1617
- const response = {
1618
- ...rest,
1619
- ...maybeHeaders && { headers: maybeHeaders },
1620
- ...content && {
1621
- content: createContent(content, components, "output", [
1622
- ...subpath,
1623
- "content"
1624
- ])
1625
- }
1626
- };
1627
- const responseRef = ref ?? (component == null ? void 0 : component.ref);
1628
- if (responseRef) {
1629
- components.responses.set(responseObject, {
1630
- responseObject: response,
1631
- ref: responseRef,
1632
- type: "complete"
1633
- });
1634
- return {
1635
- $ref: createComponentResponseRef(responseRef)
1636
- };
1637
- }
1638
- return response;
1639
- };
1640
- const createResponses = (responsesObject, components, subpath) => Object.entries(responsesObject).reduce(
1641
- (acc, [statusCode, responseObject]) => {
1642
- if (isISpecificationExtension(statusCode)) {
1643
- acc[statusCode] = responseObject;
1644
- return acc;
1645
- }
1646
- acc[statusCode] = createResponse(responseObject, components, [
1647
- ...subpath,
1648
- statusCode
1649
- ]);
1650
- return acc;
1651
- },
1652
- {}
1653
- );
1654
- const createRequestBody = (requestBodyObject, components, subpath) => {
1655
- if (!requestBodyObject) {
1656
- return void 0;
1657
- }
1658
- const component = components.requestBodies.get(requestBodyObject);
1659
- if (component && component.type === "complete") {
1660
- return {
1661
- $ref: createComponentRequestBodyRef(component.ref)
1662
- };
1663
- }
1664
- const ref = requestBodyObject.ref ?? (component == null ? void 0 : component.ref);
1665
- const requestBody = {
1666
- ...requestBodyObject,
1667
- content: createContent(requestBodyObject.content, components, "input", [
1668
- ...subpath,
1669
- "content"
1670
- ])
1671
- };
1672
- if (ref) {
1673
- components.requestBodies.set(requestBodyObject, {
1674
- type: "complete",
1675
- ref,
1676
- requestBodyObject: requestBody
1677
- });
1678
- return {
1679
- $ref: createComponentRequestBodyRef(ref)
1680
- };
1681
- }
1682
- return requestBody;
1683
- };
1684
- const createOperation = (operationObject, components, subpath) => {
1685
- const { parameters, requestParams, requestBody, responses, ...rest } = operationObject;
1686
- const maybeParameters = createParametersObject(
1687
- parameters,
1688
- requestParams,
1689
- components,
1690
- [...subpath, "parameters"]
1691
- );
1692
- const maybeRequestBody = createRequestBody(
1693
- operationObject.requestBody,
1694
- components,
1695
- [...subpath, "request body"]
1696
- );
1697
- const maybeResponses = createResponses(
1698
- operationObject.responses,
1699
- components,
1700
- [...subpath, "responses"]
1701
- );
1702
- const maybeCallbacks = createCallbacks(
1703
- operationObject.callbacks,
1704
- components,
1705
- [...subpath, "callbacks"]
1706
- );
1707
- return {
1708
- ...rest,
1709
- ...maybeParameters && { parameters: maybeParameters },
1710
- ...maybeRequestBody && { requestBody: maybeRequestBody },
1711
- ...maybeResponses && { responses: maybeResponses },
1712
- ...maybeCallbacks && { callbacks: maybeCallbacks }
1713
- };
1714
- };
1715
- const createPathItem = (pathObject, components, path) => Object.entries(pathObject).reduce(
1716
- (acc, [key, value]) => {
1717
- if (!value) {
1718
- return acc;
1719
- }
1720
- if (key === "get" || key === "put" || key === "post" || key === "delete" || key === "options" || key === "head" || key === "patch" || key === "trace") {
1721
- acc[key] = createOperation(
1722
- value,
1723
- components,
1724
- [...path, key]
1725
- );
1726
- return acc;
1727
- }
1728
- acc[key] = value;
1729
- return acc;
1730
- },
1731
- {}
1732
- );
1733
- const createPaths = (pathsObject, components) => {
1734
- if (!pathsObject) {
1735
- return void 0;
1736
- }
1737
- return Object.entries(pathsObject).reduce(
1738
- (acc, [path, pathItemObject]) => {
1739
- if (isISpecificationExtension(path)) {
1740
- acc[path] = pathItemObject;
1741
- return acc;
1742
- }
1743
- acc[path] = createPathItem(pathItemObject, components, [path]);
1744
- return acc;
1745
- },
1746
- {}
1747
- );
1748
- };
1749
- const createCallback = (callbackObject, components, subpath) => {
1750
- const { ref, ...callbacks } = callbackObject;
1751
- const callback = Object.entries(
1752
- callbacks
1753
- ).reduce((acc, [callbackName, pathItemObject]) => {
1754
- if (isISpecificationExtension(callbackName)) {
1755
- acc[callbackName] = pathItemObject;
1756
- return acc;
1757
- }
1758
- acc[callbackName] = createPathItem(pathItemObject, components, [
1759
- ...subpath,
1760
- callbackName
1761
- ]);
1762
- return acc;
1763
- }, {});
1764
- if (ref) {
1765
- components.callbacks.set(callbackObject, {
1766
- type: "complete",
1767
- ref,
1768
- callbackObject: callback
1769
- });
1770
- return {
1771
- $ref: createComponentCallbackRef(ref)
1772
- };
1773
- }
1774
- return callback;
1775
- };
1776
- const createCallbacks = (callbacksObject, components, subpath) => {
1777
- if (!callbacksObject) {
1778
- return void 0;
1779
- }
1780
- return Object.entries(callbacksObject).reduce(
1781
- (acc, [callbackName, callbackObject]) => {
1782
- if (isISpecificationExtension(callbackName)) {
1783
- acc[callbackName] = callbackObject;
1784
- return acc;
1785
- }
1786
- acc[callbackName] = createCallback(callbackObject, components, [
1787
- ...subpath,
1788
- callbackName
1789
- ]);
1790
- return acc;
1791
- },
1792
- {}
1793
- );
1794
- };
1795
- const getDefaultComponents = (componentsObject, openapi = "3.1.0") => {
1796
- const defaultComponents = {
1797
- schemas: /* @__PURE__ */ new Map(),
1798
- parameters: /* @__PURE__ */ new Map(),
1799
- headers: /* @__PURE__ */ new Map(),
1800
- requestBodies: /* @__PURE__ */ new Map(),
1801
- responses: /* @__PURE__ */ new Map(),
1802
- callbacks: /* @__PURE__ */ new Map(),
1803
- openapi
1804
- };
1805
- if (!componentsObject) {
1806
- return defaultComponents;
1807
- }
1808
- getSchemas(componentsObject.schemas, defaultComponents);
1809
- getParameters(componentsObject.parameters, defaultComponents);
1810
- getRequestBodies(componentsObject.requestBodies, defaultComponents);
1811
- getHeaders(componentsObject.headers, defaultComponents);
1812
- getResponses(componentsObject.responses, defaultComponents);
1813
- getCallbacks(componentsObject.callbacks, defaultComponents);
1814
- return defaultComponents;
1815
- };
1816
- const getSchemas = (schemas, components) => {
1817
- if (!schemas) {
1818
- return;
1819
- }
1820
- Object.entries(schemas).forEach(([key, schema]) => {
1821
- var _a;
1822
- if (isAnyZodType(schema)) {
1823
- if (components.schemas.has(schema)) {
1824
- throw new Error(
1825
- `Schema ${JSON.stringify(schema._def)} is already registered`
1826
- );
1827
- }
1828
- const ref = ((_a = schema._def.openapi) == null ? void 0 : _a.ref) ?? key;
1829
- components.schemas.set(schema, {
1830
- type: "manual",
1831
- ref
1832
- });
1833
- }
1834
- });
1835
- };
1836
- const getParameters = (parameters, components) => {
1837
- if (!parameters) {
1838
- return;
1839
- }
1840
- Object.entries(parameters).forEach(([key, schema]) => {
1841
- var _a, _b, _c, _d, _e, _f;
1842
- if (isAnyZodType(schema)) {
1843
- if (components.parameters.has(schema)) {
1844
- throw new Error(
1845
- `Parameter ${JSON.stringify(schema._def)} is already registered`
1846
- );
1847
- }
1848
- const ref = ((_b = (_a = schema._def.openapi) == null ? void 0 : _a.param) == null ? void 0 : _b.ref) ?? key;
1849
- const name = (_d = (_c = schema._def.openapi) == null ? void 0 : _c.param) == null ? void 0 : _d.name;
1850
- const location = (_f = (_e = schema._def.openapi) == null ? void 0 : _e.param) == null ? void 0 : _f.in;
1851
- if (!name || !location) {
1852
- throw new Error("`name` or `in` missing in .openapi()");
1853
- }
1854
- components.parameters.set(schema, {
1855
- type: "manual",
1856
- ref,
1857
- in: location,
1858
- name
1859
- });
1860
- }
1861
- });
1862
- };
1863
- const getHeaders = (responseHeaders, components) => {
1864
- if (!responseHeaders) {
1865
- return;
1866
- }
1867
- Object.entries(responseHeaders).forEach(([key, schema]) => {
1868
- var _a, _b;
1869
- if (isAnyZodType(schema)) {
1870
- if (components.parameters.has(schema)) {
1871
- throw new Error(
1872
- `Header ${JSON.stringify(schema._def)} is already registered`
1873
- );
1874
- }
1875
- const ref = ((_b = (_a = schema._def.openapi) == null ? void 0 : _a.param) == null ? void 0 : _b.ref) ?? key;
1876
- components.headers.set(schema, {
1877
- type: "manual",
1878
- ref
1879
- });
1880
- }
1881
- });
1882
- };
1883
- const getResponses = (responses, components) => {
1884
- if (!responses) {
1885
- return;
1886
- }
1887
- Object.entries(responses).forEach(([key, responseObject]) => {
1888
- if (components.responses.has(responseObject)) {
1889
- throw new Error(
1890
- `Header ${JSON.stringify(responseObject)} is already registered`
1891
- );
1892
- }
1893
- const ref = (responseObject == null ? void 0 : responseObject.ref) ?? key;
1894
- components.responses.set(responseObject, {
1895
- type: "manual",
1896
- ref
1897
- });
1898
- });
1899
- };
1900
- const getRequestBodies = (requestBodies, components) => {
1901
- if (!requestBodies) {
1902
- return;
1903
- }
1904
- Object.entries(requestBodies).forEach(([key, requestBody]) => {
1905
- if (components.requestBodies.has(requestBody)) {
1906
- throw new Error(
1907
- `Header ${JSON.stringify(requestBody)} is already registered`
1908
- );
1909
- }
1910
- const ref = (requestBody == null ? void 0 : requestBody.ref) ?? key;
1911
- components.requestBodies.set(requestBody, {
1912
- type: "manual",
1913
- ref
1914
- });
1915
- });
1916
- };
1917
- const getCallbacks = (callbacks, components) => {
1918
- if (!callbacks) {
1919
- return;
1920
- }
1921
- Object.entries(callbacks).forEach(([key, callback]) => {
1922
- if (components.callbacks.has(callback)) {
1923
- throw new Error(
1924
- `Callback ${JSON.stringify(callback)} is already registered`
1925
- );
1926
- }
1927
- const ref = (callback == null ? void 0 : callback.ref) ?? key;
1928
- components.callbacks.set(callback, {
1929
- type: "manual",
1930
- ref
1931
- });
1932
- });
1933
- };
1934
- const createComponentSchemaRef = (schemaRef) => `#/components/schemas/${schemaRef}`;
1935
- const createComponentResponseRef = (responseRef) => `#/components/responses/${responseRef}`;
1936
- const createComponentRequestBodyRef = (requestBodyRef) => `#/components/requestBodies/${requestBodyRef}`;
1937
- const createComponentCallbackRef = (callbackRef) => `#/components/callbacks/${callbackRef}`;
1938
- const createComponents = (componentsObject, components) => {
1939
- const combinedSchemas = createSchemaComponents(componentsObject, components);
1940
- const combinedParameters = createParamComponents(
1941
- componentsObject,
1942
- components
1943
- );
1944
- const combinedHeaders = createHeaderComponents(componentsObject, components);
1945
- const combinedResponses = createResponseComponents(components);
1946
- const combinedRequestBodies = createRequestBodiesComponents(components);
1947
- const combinedCallbacks = createCallbackComponents(components);
1948
- const { schemas, parameters, headers, responses, requestBodies, ...rest } = componentsObject;
1949
- const finalComponents = {
1950
- ...rest,
1951
- ...combinedSchemas && { schemas: combinedSchemas },
1952
- ...combinedParameters && { parameters: combinedParameters },
1953
- ...combinedRequestBodies && { requestBodies: combinedRequestBodies },
1954
- ...combinedHeaders && { headers: combinedHeaders },
1955
- ...combinedResponses && { responses: combinedResponses },
1956
- ...combinedCallbacks && { callbacks: combinedCallbacks }
1957
- };
1958
- return Object.keys(finalComponents).length ? finalComponents : void 0;
1959
- };
1960
- const createSchemaComponents = (componentsObject, components) => {
1961
- Array.from(components.schemas).forEach(([schema, { type }], index) => {
1962
- var _a;
1963
- if (type === "manual") {
1964
- const state = {
1965
- components,
1966
- type: ((_a = schema._def.openapi) == null ? void 0 : _a.refType) ?? "output",
1967
- path: [],
1968
- visited: /* @__PURE__ */ new Set()
1969
- };
1970
- createSchema(schema, state, [`component schema index ${index}`]);
1971
- }
1972
- });
1973
- const customComponents = Object.entries(
1974
- componentsObject.schemas ?? {}
1975
- ).reduce(
1976
- (acc, [key, value]) => {
1977
- if (isAnyZodType(value)) {
1978
- return acc;
1979
- }
1980
- if (acc[key]) {
1981
- throw new Error(`Schema "${key}" is already registered`);
1982
- }
1983
- acc[key] = value;
1984
- return acc;
1985
- },
1986
- {}
1987
- );
1988
- const finalComponents = Array.from(components.schemas).reduce((acc, [_zodType, component]) => {
1989
- if (component.type === "complete") {
1990
- if (acc[component.ref]) {
1991
- throw new Error(`Schema "${component.ref}" is already registered`);
1992
- }
1993
- acc[component.ref] = component.schemaObject;
1994
- }
1995
- return acc;
1996
- }, customComponents);
1997
- return Object.keys(finalComponents).length ? finalComponents : void 0;
1998
- };
1999
- const createParamComponents = (componentsObject, components) => {
2000
- Array.from(components.parameters).forEach(([schema, component], index) => {
2001
- if (component.type === "manual") {
2002
- createParamOrRef(
2003
- schema,
2004
- components,
2005
- [`component parameter index ${index}`],
2006
- component.in,
2007
- component.ref
2008
- );
2009
- }
2010
- });
2011
- const customComponents = Object.entries(
2012
- componentsObject.parameters ?? {}
2013
- ).reduce(
2014
- (acc, [key, value]) => {
2015
- if (!isAnyZodType(value)) {
2016
- if (acc[key]) {
2017
- throw new Error(`Parameter "${key}" is already registered`);
2018
- }
2019
- acc[key] = value;
2020
- }
2021
- return acc;
2022
- },
2023
- {}
2024
- );
2025
- const finalComponents = Array.from(components.parameters).reduce((acc, [_zodType, component]) => {
2026
- if (component.type === "complete") {
2027
- if (acc[component.ref]) {
2028
- throw new Error(`Parameter "${component.ref}" is already registered`);
2029
- }
2030
- acc[component.ref] = component.paramObject;
2031
- }
2032
- return acc;
2033
- }, customComponents);
2034
- return Object.keys(finalComponents).length ? finalComponents : void 0;
2035
- };
2036
- const createHeaderComponents = (componentsObject, components) => {
2037
- Array.from(components.headers).forEach(([schema, component]) => {
2038
- if (component.type === "manual") {
2039
- createHeaderOrRef(schema, components);
2040
- }
2041
- });
2042
- const headers = componentsObject.headers ?? {};
2043
- const customComponents = Object.entries(headers).reduce((acc, [key, value]) => {
2044
- if (!isAnyZodType(value)) {
2045
- if (acc[key]) {
2046
- throw new Error(`Header Ref "${key}" is already registered`);
2047
- }
2048
- acc[key] = value;
2049
- }
2050
- return acc;
2051
- }, {});
2052
- const finalComponents = Array.from(components.headers).reduce((acc, [_zodType, component]) => {
2053
- if (component.type === "complete") {
2054
- if (acc[component.ref]) {
2055
- throw new Error(`Header "${component.ref}" is already registered`);
2056
- }
2057
- acc[component.ref] = component.headerObject;
2058
- }
2059
- return acc;
2060
- }, customComponents);
2061
- return Object.keys(finalComponents).length ? finalComponents : void 0;
2062
- };
2063
- const createResponseComponents = (components) => {
2064
- Array.from(components.responses).forEach(([schema, component], index) => {
2065
- if (component.type === "manual") {
2066
- createResponse(schema, components, [`component response index ${index}`]);
2067
- }
2068
- });
2069
- const finalComponents = Array.from(components.responses).reduce((acc, [_zodType, component]) => {
2070
- if (component.type === "complete") {
2071
- if (acc[component.ref]) {
2072
- throw new Error(`Response "${component.ref}" is already registered`);
2073
- }
2074
- acc[component.ref] = component.responseObject;
2075
- }
2076
- return acc;
2077
- }, {});
2078
- return Object.keys(finalComponents).length ? finalComponents : void 0;
2079
- };
2080
- const createRequestBodiesComponents = (components) => {
2081
- Array.from(components.requestBodies).forEach(([schema, component], index) => {
2082
- if (component.type === "manual") {
2083
- createRequestBody(schema, components, [
2084
- `component request body ${index}`
2085
- ]);
2086
- }
2087
- });
2088
- const finalComponents = Array.from(components.requestBodies).reduce((acc, [_zodType, component]) => {
2089
- if (component.type === "complete") {
2090
- if (acc[component.ref]) {
2091
- throw new Error(`RequestBody "${component.ref}" is already registered`);
2092
- }
2093
- acc[component.ref] = component.requestBodyObject;
2094
- }
2095
- return acc;
2096
- }, {});
2097
- return Object.keys(finalComponents).length ? finalComponents : void 0;
2098
- };
2099
- const createCallbackComponents = (components) => {
2100
- Array.from(components.callbacks).forEach(([schema, component], index) => {
2101
- if (component.type === "manual") {
2102
- createCallback(schema, components, [`component callback ${index}`]);
2103
- }
2104
- });
2105
- const finalComponents = Array.from(components.callbacks).reduce((acc, [_zodType, component]) => {
2106
- if (component.type === "complete") {
2107
- if (acc[component.ref]) {
2108
- throw new Error(`Callback "${component.ref}" is already registered`);
2109
- }
2110
- acc[component.ref] = component.callbackObject;
2111
- }
2112
- return acc;
2113
- }, {});
2114
- return Object.keys(finalComponents).length ? finalComponents : void 0;
2115
- };
2116
3
  const createDocument = (zodOpenApiObject) => {
2117
4
  const { paths, webhooks, components = {}, ...rest } = zodOpenApiObject;
2118
5
  const defaultComponents = getDefaultComponents(
@@ -2135,15 +22,7 @@ const oas30 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
2135
22
  const oas31 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
2136
23
  __proto__: null
2137
24
  }, Symbol.toStringTag, { value: "Module" }));
2138
- const api = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
2139
- __proto__: null,
2140
- createComponents,
2141
- createMediaTypeSchema,
2142
- createParamOrRef,
2143
- getDefaultComponents
2144
- }, Symbol.toStringTag, { value: "Module" }));
2145
25
  export {
2146
- api,
2147
26
  createDocument,
2148
27
  extendZodWithOpenApi,
2149
28
  oas30,