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