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