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