zod-openapi 5.0.0-beta.9 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,900 @@
1
+ import { globalRegistry } from "zod/v4/core";
2
+ import { object, registry, toJSONSchema } from "zod/v4";
3
+
4
+ //#region src/zod.ts
5
+ const isAnyZodType = (schema) => typeof schema === "object" && schema !== null && "_zod" in schema;
6
+
7
+ //#endregion
8
+ //#region src/create/examples.ts
9
+ const createExamples = (examples, registry$1, path) => {
10
+ if (!examples) return void 0;
11
+ const examplesObject = {};
12
+ for (const [name, example] of Object.entries(examples)) {
13
+ const exampleObject = registry$1.addExample(example, [...path, name]);
14
+ examplesObject[name] = exampleObject;
15
+ }
16
+ return examplesObject;
17
+ };
18
+
19
+ //#endregion
20
+ //#region src/create/content.ts
21
+ const createMediaTypeObject = (mediaType, ctx, path) => {
22
+ const { schema, examples,...rest } = mediaType;
23
+ const mediaTypeObject = rest;
24
+ if (isAnyZodType(schema)) {
25
+ const schemaObject = ctx.registry.addSchema(schema, [...path, "schema"], {
26
+ io: ctx.io,
27
+ source: { type: "mediaType" }
28
+ });
29
+ mediaTypeObject.schema = schemaObject;
30
+ }
31
+ if (examples) mediaTypeObject.examples = createExamples(examples, ctx.registry, [...path, "examples"]);
32
+ return mediaTypeObject;
33
+ };
34
+ const createContent = (content, ctx, path) => {
35
+ const contentObject = {};
36
+ for (const [mediaType, mediaTypeObject] of Object.entries(content)) if (mediaTypeObject) contentObject[mediaType] = createMediaTypeObject(mediaTypeObject, ctx, [...path, mediaType]);
37
+ return contentObject;
38
+ };
39
+
40
+ //#endregion
41
+ //#region src/create/object.ts
42
+ const unwrapZodObject = (zodType, io, path) => {
43
+ const def = zodType._zod.def;
44
+ switch (def.type) {
45
+ case "object": return zodType;
46
+ case "lazy": return unwrapZodObject(def.getter(), io, path);
47
+ case "pipe": {
48
+ if (io === "input") return unwrapZodObject(def.in, io, path);
49
+ return unwrapZodObject(def.out, io, path);
50
+ }
51
+ }
52
+ throw new Error(`Failed to unwrap ZodObject from type: ${zodType._zod.def.type} at ${path.join(" > ")}`);
53
+ };
54
+ const isRequired = (zodType, io) => {
55
+ if (io === "input") return zodType._zod.optin === void 0;
56
+ return zodType._zod.optout === void 0;
57
+ };
58
+
59
+ //#endregion
60
+ //#region src/create/headers.ts
61
+ const createHeaders = (headers, registry$1, path) => {
62
+ if (!headers) return void 0;
63
+ if (isAnyZodType(headers)) {
64
+ const zodObject = unwrapZodObject(headers, "output", path);
65
+ const headersObject = {};
66
+ for (const [key, zodSchema] of Object.entries(zodObject._zod.def.shape)) {
67
+ const header = registry$1.addHeader(zodSchema, [...path, key]);
68
+ headersObject[key] = header;
69
+ }
70
+ return headersObject;
71
+ }
72
+ return headers;
73
+ };
74
+
75
+ //#endregion
76
+ //#region src/create/links.ts
77
+ const createLinks = (links, registry$1, path) => {
78
+ if (!links) return void 0;
79
+ const linksObject = {};
80
+ for (const [name, link] of Object.entries(links)) {
81
+ const linkObject = registry$1.addLink(link, [...path, name]);
82
+ linksObject[name] = linkObject;
83
+ }
84
+ return linksObject;
85
+ };
86
+
87
+ //#endregion
88
+ //#region src/create/parameters.ts
89
+ const createManualParameters = (parameters, registry$1, path) => {
90
+ if (!parameters) return void 0;
91
+ const parameterObjects = [];
92
+ for (const parameter of parameters) {
93
+ if (isAnyZodType(parameter)) {
94
+ const paramObject = registry$1.addParameter(parameter, [...path, "parameters"]);
95
+ parameterObjects.push(paramObject);
96
+ continue;
97
+ }
98
+ parameterObjects.push(parameter);
99
+ }
100
+ return parameterObjects;
101
+ };
102
+ const createParameters = (requestParams, registry$1, path) => {
103
+ if (!requestParams) return void 0;
104
+ const parameterObjects = [];
105
+ for (const [location, schema] of Object.entries(requestParams ?? {})) {
106
+ const zodObject = unwrapZodObject(schema, "input", path);
107
+ for (const [name, zodSchema] of Object.entries(zodObject._zod.def.shape)) {
108
+ const paramObject = registry$1.addParameter(zodSchema, [
109
+ ...path,
110
+ location,
111
+ name
112
+ ], { location: {
113
+ in: location,
114
+ name
115
+ } });
116
+ parameterObjects.push(paramObject);
117
+ }
118
+ }
119
+ return parameterObjects;
120
+ };
121
+
122
+ //#endregion
123
+ //#region src/create/specificationExtension.ts
124
+ const isISpecificationExtension = (key) => key.startsWith("x-");
125
+
126
+ //#endregion
127
+ //#region src/create/callbacks.ts
128
+ const createCallbacks = (callbacks, registry$1, path) => {
129
+ if (!callbacks) return void 0;
130
+ const callbacksObject = {};
131
+ for (const [name, value] of Object.entries(callbacks)) {
132
+ if (isISpecificationExtension(name)) {
133
+ callbacksObject[name] = value;
134
+ continue;
135
+ }
136
+ callbacksObject[name] = registry$1.addCallback(value, [...path, name]);
137
+ }
138
+ return callbacksObject;
139
+ };
140
+
141
+ //#endregion
142
+ //#region src/create/responses.ts
143
+ const createResponses = (responses, registry$1, path) => {
144
+ if (!responses) return void 0;
145
+ const responsesObject = {};
146
+ for (const [statusCode, response] of Object.entries(responses)) {
147
+ if (!response) continue;
148
+ if (isISpecificationExtension(statusCode)) {
149
+ responsesObject[statusCode] = response;
150
+ continue;
151
+ }
152
+ if ("$ref" in response) {
153
+ responsesObject[statusCode] = response;
154
+ continue;
155
+ }
156
+ const responseObject = registry$1.addResponse(response, [...path, statusCode]);
157
+ responsesObject[statusCode] = responseObject;
158
+ }
159
+ return responsesObject;
160
+ };
161
+
162
+ //#endregion
163
+ //#region src/create/paths.ts
164
+ const createOperation = (operation, registry$1, path) => {
165
+ const { parameters, requestParams, requestBody, responses, callbacks,...rest } = operation;
166
+ const operationObject = rest;
167
+ const maybeManualParameters = createManualParameters(parameters, registry$1, [...path, "parameters"]);
168
+ const maybeRequestParams = createParameters(requestParams, registry$1, [...path, "requestParams"]);
169
+ if (maybeRequestParams || maybeManualParameters) operationObject.parameters = [...maybeRequestParams ?? [], ...maybeManualParameters ?? []];
170
+ const maybeRequestBody = requestBody && registry$1.addRequestBody(requestBody, path);
171
+ if (maybeRequestBody) operationObject.requestBody = maybeRequestBody;
172
+ const maybeResponses = createResponses(responses, registry$1, [...path, "responses"]);
173
+ if (maybeResponses) operationObject.responses = maybeResponses;
174
+ const maybeCallbacks = createCallbacks(callbacks, registry$1, [...path, "callbacks"]);
175
+ if (maybeCallbacks) operationObject.callbacks = maybeCallbacks;
176
+ return operationObject;
177
+ };
178
+ const createPaths = (paths, registry$1, path) => {
179
+ if (!paths) return void 0;
180
+ const pathsObject = {};
181
+ for (const [singlePath, pathItemObject] of Object.entries(paths)) {
182
+ if (isISpecificationExtension(singlePath)) {
183
+ pathsObject[singlePath] = pathItemObject;
184
+ continue;
185
+ }
186
+ pathsObject[singlePath] = registry$1.addPathItem(pathItemObject, [...path, singlePath]);
187
+ }
188
+ return pathsObject;
189
+ };
190
+
191
+ //#endregion
192
+ //#region src/create/schema/override.ts
193
+ const override = (ctx) => {
194
+ const def = ctx.zodSchema._zod.def;
195
+ switch (def.type) {
196
+ case "bigint": {
197
+ ctx.jsonSchema.type = "integer";
198
+ ctx.jsonSchema.format = "int64";
199
+ break;
200
+ }
201
+ case "union": {
202
+ if ("discriminator" in def && typeof def.discriminator === "string") {
203
+ ctx.jsonSchema.oneOf = ctx.jsonSchema.anyOf;
204
+ delete ctx.jsonSchema.anyOf;
205
+ ctx.jsonSchema.type = "object";
206
+ ctx.jsonSchema.discriminator = { propertyName: def.discriminator };
207
+ const mapping = {};
208
+ for (const [index, obj] of Object.entries(ctx.jsonSchema.oneOf)) {
209
+ const ref = obj.$ref;
210
+ if (!ref) {
211
+ delete ctx.jsonSchema.discriminator;
212
+ return;
213
+ }
214
+ const discriminatorValues = def.options[Number(index)]._zod.propValues?.[def.discriminator];
215
+ if (!discriminatorValues?.size) return;
216
+ for (const value of [...discriminatorValues ?? []]) {
217
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") return;
218
+ mapping[String(value)] = ref;
219
+ }
220
+ }
221
+ ctx.jsonSchema.discriminator.mapping = mapping;
222
+ }
223
+ const meta = ctx.zodSchema.meta();
224
+ if (typeof meta?.unionOneOf === "boolean") {
225
+ if (meta.unionOneOf) {
226
+ ctx.jsonSchema.oneOf = ctx.jsonSchema.anyOf;
227
+ delete ctx.jsonSchema.anyOf;
228
+ }
229
+ delete ctx.jsonSchema.unionOneOf;
230
+ }
231
+ break;
232
+ }
233
+ case "date": {
234
+ ctx.jsonSchema.type = "string";
235
+ break;
236
+ }
237
+ case "literal": {
238
+ if (def.values.includes(void 0)) break;
239
+ break;
240
+ }
241
+ }
242
+ };
243
+ const validate = (ctx, opts) => {
244
+ if (Object.keys(ctx.jsonSchema).length) return;
245
+ const def = ctx.zodSchema._zod.def;
246
+ const allowEmptySchema = opts.allowEmptySchema?.[def.type];
247
+ if (allowEmptySchema === true || allowEmptySchema?.[ctx.io]) return;
248
+ switch (def.type) {
249
+ case "any": return;
250
+ case "unknown": return;
251
+ case "pipe": {
252
+ if (ctx.io === "output") throw new Error("Zod transform schemas are not supported in output schemas. Please use `.overwrite()` or wrap the schema in a `.pipe()`");
253
+ return;
254
+ }
255
+ case "transform": {
256
+ if (ctx.io === "output") return;
257
+ break;
258
+ }
259
+ case "literal": {
260
+ if (def.values.includes(void 0)) throw new Error("Zod literal schemas cannot include `undefined` as a value. Please use `z.undefined()` or `.optional()` instead.");
261
+ return;
262
+ }
263
+ }
264
+ throw new Error(`Zod schema of type \`${def.type}\` cannot be represented in OpenAPI. Please assign it metadata with \`.meta()\``);
265
+ };
266
+
267
+ //#endregion
268
+ //#region src/create/schema/rename.ts
269
+ const renameComponents = (components, outputIds, ctx, refPath) => {
270
+ const componentsToRename = /* @__PURE__ */ new Map();
271
+ if (ctx.io === "input") return componentsToRename;
272
+ const componentDependencies = /* @__PURE__ */ new Map();
273
+ const stringifiedComponents = /* @__PURE__ */ new Map();
274
+ for (const [key, value] of Object.entries(components)) {
275
+ const stringified = JSON.stringify(value);
276
+ const regex = new RegExp(`"${refPath}([^"]+)"`, "g");
277
+ const matches = stringified.matchAll(regex);
278
+ const dependencies = /* @__PURE__ */ new Set();
279
+ for (const match of matches) {
280
+ const dep = match[1];
281
+ if (dep !== key) dependencies.add(dep);
282
+ }
283
+ stringifiedComponents.set(key, stringified);
284
+ componentDependencies.set(key, { dependencies });
285
+ }
286
+ for (const [key] of stringifiedComponents) {
287
+ const registeredComponent = ctx.registry.components.schemas.ids.get(key);
288
+ if (!registeredComponent) continue;
289
+ if (isDependencyPure(componentDependencies, stringifiedComponents, ctx.registry, key)) continue;
290
+ const newName = outputIds.get(key) ?? `${key}${ctx.opts.outputIdSuffix ?? "Output"}`;
291
+ componentsToRename.set(key, newName);
292
+ components[newName] = components[key];
293
+ delete components[key];
294
+ continue;
295
+ }
296
+ return componentsToRename;
297
+ };
298
+ const isDependencyPure = (componentDependencies, stringifiedComponents, registry$1, key, visited = /* @__PURE__ */ new Set()) => {
299
+ if (visited.has(key)) return true;
300
+ const dependencies = componentDependencies.get(key);
301
+ if (dependencies.pure !== void 0) return dependencies.pure;
302
+ const stringified = stringifiedComponents.get(key);
303
+ const component = registry$1.components.schemas.ids.get(key);
304
+ if (component && stringified !== JSON.stringify(component)) {
305
+ dependencies.pure = false;
306
+ return false;
307
+ }
308
+ visited.add(key);
309
+ const result = [...dependencies.dependencies].every((dep) => isDependencyPure(componentDependencies, stringifiedComponents, registry$1, dep, new Set(visited)));
310
+ dependencies.pure = result;
311
+ return result;
312
+ };
313
+
314
+ //#endregion
315
+ //#region src/create/schema/schema.ts
316
+ const createSchema = (schema, ctx = {
317
+ registry: createRegistry(),
318
+ io: "output",
319
+ opts: {}
320
+ }) => {
321
+ ctx.registry ??= createRegistry({ schemas: ctx.schemaComponents });
322
+ ctx.opts ??= {};
323
+ ctx.io ??= "output";
324
+ const registrySchemas = Object.fromEntries(ctx.registry.components.schemas[ctx.io]);
325
+ const schemas = { zodOpenApiCreateSchema: { zodType: schema } };
326
+ Object.assign(schemas, registrySchemas);
327
+ const jsonSchemas = createSchemas(schemas, {
328
+ registry: ctx.registry,
329
+ io: ctx.io,
330
+ opts: {
331
+ ...ctx.opts,
332
+ schemaRefPath: ctx.schemaRefPath
333
+ }
334
+ });
335
+ return {
336
+ schema: jsonSchemas.schemas.zodOpenApiCreateSchema,
337
+ components: jsonSchemas.components
338
+ };
339
+ };
340
+ const zodOpenApiMetadataFields = [
341
+ "param",
342
+ "header",
343
+ "unusedIO",
344
+ "override",
345
+ "outputId"
346
+ ];
347
+ const deleteZodOpenApiMeta = (jsonSchema) => {
348
+ zodOpenApiMetadataFields.forEach((field) => {
349
+ delete jsonSchema[field];
350
+ });
351
+ };
352
+ const deleteInvalidJsonSchemaFields = (jsonSchema) => {
353
+ delete jsonSchema.$schema;
354
+ delete jsonSchema.id;
355
+ };
356
+ const createSchemas = (schemas, ctx) => {
357
+ const refPath = ctx.opts.schemaRefPath ?? "#/components/schemas/";
358
+ const entries = {};
359
+ for (const [name, { zodType }] of Object.entries(schemas)) entries[name] = zodType;
360
+ const zodRegistry = registry();
361
+ zodRegistry.add(object(entries), { id: "zodOpenApiCreateSchema" });
362
+ for (const [id, { zodType }] of ctx.registry.components.schemas.manual) zodRegistry.add(zodType, { id });
363
+ const outputIds = /* @__PURE__ */ new Map();
364
+ const jsonSchema = toJSONSchema(zodRegistry, {
365
+ override(context) {
366
+ const meta = context.zodSchema.meta();
367
+ if (meta?.outputId && meta?.id) outputIds.set(meta.id, meta.outputId);
368
+ if (context.jsonSchema.$ref) return;
369
+ const enrichedContext = {
370
+ ...context,
371
+ io: ctx.io
372
+ };
373
+ override(enrichedContext);
374
+ if (typeof ctx.opts.override === "function") ctx.opts.override(enrichedContext);
375
+ if (typeof meta?.override === "function") {
376
+ meta.override(enrichedContext);
377
+ delete context.jsonSchema.override;
378
+ }
379
+ if (typeof meta?.override === "object" && meta.override !== null) {
380
+ Object.assign(context.jsonSchema, meta.override);
381
+ delete context.jsonSchema.override;
382
+ }
383
+ deleteInvalidJsonSchemaFields(context.jsonSchema);
384
+ deleteZodOpenApiMeta(context.jsonSchema);
385
+ validate(enrichedContext, ctx.opts);
386
+ },
387
+ io: ctx.io,
388
+ unrepresentable: "any",
389
+ reused: ctx.opts.reused,
390
+ cycles: ctx.opts.cycles,
391
+ uri: (id) => id === "__shared" ? `#ZOD_OPENAPI/${id}` : `#ZOD_OPENAPI/__shared#/$defs/${id}`
392
+ });
393
+ const components = jsonSchema.schemas.__shared?.$defs ?? {};
394
+ jsonSchema.schemas.__shared ??= { $defs: components };
395
+ const dynamicComponents = /* @__PURE__ */ new Map();
396
+ for (const [key, value] of Object.entries(components)) if (/^schema\d+$/.test(key)) {
397
+ const newName = `__schema${ctx.registry.components.schemas.dynamicSchemaCount++}`;
398
+ dynamicComponents.set(key, `"${refPath}${newName}"`);
399
+ if (newName !== key) {
400
+ components[newName] = value;
401
+ delete components[key];
402
+ }
403
+ }
404
+ const manualUsed = {};
405
+ const parsedJsonSchema = JSON.parse(JSON.stringify(jsonSchema).replace(/"#ZOD_OPENAPI\/__shared#\/\$defs\/([^"]+)"/g, (_, match) => {
406
+ const dynamic = dynamicComponents.get(match);
407
+ if (dynamic) return dynamic;
408
+ const manualComponent = ctx.registry.components.schemas.manual.get(match);
409
+ if (manualComponent) manualUsed[match] = true;
410
+ return `"${refPath}${match}"`;
411
+ }));
412
+ const parsedComponents = parsedJsonSchema.schemas.__shared?.$defs ?? {};
413
+ parsedJsonSchema.schemas.__shared ??= { $defs: parsedComponents };
414
+ for (const [key] of ctx.registry.components.schemas.manual) {
415
+ const manualComponent = parsedJsonSchema.schemas[key];
416
+ if (!manualComponent) continue;
417
+ deleteInvalidJsonSchemaFields(manualComponent);
418
+ if (manualUsed[key]) {
419
+ if (parsedComponents[key]) throw new Error(`Component "${key}" is already registered as a component in the registry`);
420
+ parsedComponents[key] = manualComponent;
421
+ }
422
+ }
423
+ const componentsToRename = renameComponents(parsedComponents, outputIds, ctx, refPath);
424
+ if (!componentsToRename.size) {
425
+ const parsedSchemas = parsedJsonSchema.schemas.zodOpenApiCreateSchema?.properties;
426
+ delete parsedJsonSchema.schemas.zodOpenApiCreateSchema;
427
+ delete parsedJsonSchema.schemas.__shared;
428
+ return {
429
+ schemas: parsedSchemas,
430
+ components: parsedComponents,
431
+ manual: parsedJsonSchema.schemas
432
+ };
433
+ }
434
+ const renamedJsonSchema = JSON.parse(JSON.stringify(parsedJsonSchema).replace(new RegExp(`"${refPath}([^"]+)"`, "g"), (_, match) => {
435
+ const replacement = componentsToRename.get(match);
436
+ if (replacement) return `"${refPath}${replacement}"`;
437
+ return `"${refPath}${match}"`;
438
+ }));
439
+ const renamedSchemas = renamedJsonSchema.schemas.zodOpenApiCreateSchema?.properties;
440
+ const renamedComponents = renamedJsonSchema.schemas.__shared?.$defs ?? {};
441
+ delete renamedJsonSchema.schemas.zodOpenApiCreateSchema;
442
+ delete renamedJsonSchema.schemas.__shared;
443
+ return {
444
+ schemas: renamedSchemas,
445
+ components: renamedComponents,
446
+ manual: renamedJsonSchema.schemas
447
+ };
448
+ };
449
+
450
+ //#endregion
451
+ //#region src/create/components.ts
452
+ const createRegistry = (components) => {
453
+ const registry$1 = {
454
+ components: {
455
+ schemas: {
456
+ dynamicSchemaCount: 0,
457
+ input: /* @__PURE__ */ new Map(),
458
+ output: /* @__PURE__ */ new Map(),
459
+ ids: /* @__PURE__ */ new Map(),
460
+ manual: /* @__PURE__ */ new Map()
461
+ },
462
+ headers: {
463
+ ids: /* @__PURE__ */ new Map(),
464
+ seen: /* @__PURE__ */ new WeakMap()
465
+ },
466
+ requestBodies: {
467
+ ids: /* @__PURE__ */ new Map(),
468
+ seen: /* @__PURE__ */ new WeakMap()
469
+ },
470
+ responses: {
471
+ ids: /* @__PURE__ */ new Map(),
472
+ seen: /* @__PURE__ */ new WeakMap()
473
+ },
474
+ parameters: {
475
+ ids: /* @__PURE__ */ new Map(),
476
+ seen: /* @__PURE__ */ new WeakMap()
477
+ },
478
+ callbacks: {
479
+ ids: /* @__PURE__ */ new Map(),
480
+ seen: /* @__PURE__ */ new WeakMap()
481
+ },
482
+ pathItems: {
483
+ ids: /* @__PURE__ */ new Map(),
484
+ seen: /* @__PURE__ */ new WeakMap()
485
+ },
486
+ securitySchemes: {
487
+ ids: /* @__PURE__ */ new Map(),
488
+ seen: /* @__PURE__ */ new WeakMap()
489
+ },
490
+ links: {
491
+ ids: /* @__PURE__ */ new Map(),
492
+ seen: /* @__PURE__ */ new WeakMap()
493
+ },
494
+ examples: {
495
+ ids: /* @__PURE__ */ new Map(),
496
+ seen: /* @__PURE__ */ new WeakMap()
497
+ }
498
+ },
499
+ addSchema: (schema, path, opts) => {
500
+ const schemaObject = {};
501
+ registry$1.components.schemas[opts.io].set(path.join(" > "), {
502
+ schemaObject,
503
+ zodType: schema,
504
+ source: {
505
+ path,
506
+ ...opts?.source
507
+ }
508
+ });
509
+ return schemaObject;
510
+ },
511
+ addParameter: (parameter, path, opts) => {
512
+ const seenParameter = registry$1.components.parameters.seen.get(parameter);
513
+ if (seenParameter) return seenParameter;
514
+ const meta = globalRegistry.get(parameter);
515
+ const name = opts?.location?.name ?? meta?.param?.name;
516
+ const inLocation = opts?.location?.in ?? meta?.param?.in;
517
+ if (opts?.location?.name && meta?.param?.name || opts?.location?.in && meta?.param?.in) throw new Error(`Parameter at ${path.join(" > ")} has both \`.meta({ param: { name, in } })\` and \`.meta({ param: { location: { in, name } } })\` information`);
518
+ if (!name || !inLocation) throw new Error(`Parameter at ${path.join(" > ")} is missing \`.meta({ param: { name, in } })\` information`);
519
+ const schemaObject = registry$1.addSchema(parameter, [
520
+ ...path,
521
+ inLocation,
522
+ name,
523
+ "schema"
524
+ ], {
525
+ io: "input",
526
+ source: {
527
+ type: "parameter",
528
+ location: {
529
+ in: inLocation,
530
+ name
531
+ }
532
+ }
533
+ });
534
+ const { id: metaId, examples,...rest } = meta?.param ?? {};
535
+ const parameterObject = {
536
+ in: inLocation,
537
+ name,
538
+ schema: schemaObject,
539
+ ...rest
540
+ };
541
+ const examplesObject = createExamples(examples, registry$1, [
542
+ ...path,
543
+ inLocation,
544
+ name,
545
+ "examples"
546
+ ]);
547
+ if (examplesObject) parameterObject.examples = examplesObject;
548
+ if (isRequired(parameter, "input")) parameterObject.required = true;
549
+ if (!parameterObject.description && meta?.description) parameterObject.description = meta.description;
550
+ const id = metaId ?? opts?.manualId;
551
+ if (id) {
552
+ if (registry$1.components.parameters.ids.has(id)) throw new Error(`Schema "${id}" at ${path.join(" > ")} is already registered`);
553
+ const ref = { $ref: `#/components/parameters/${id}` };
554
+ registry$1.components.parameters.seen.set(parameter, ref);
555
+ registry$1.components.parameters.ids.set(id, parameterObject);
556
+ return ref;
557
+ }
558
+ if (opts?.location?.name || opts?.location?.in) return parameterObject;
559
+ registry$1.components.parameters.seen.set(parameter, parameterObject);
560
+ return parameterObject;
561
+ },
562
+ addHeader: (header, path, opts) => {
563
+ const seenHeader = registry$1.components.headers.seen.get(header);
564
+ if (seenHeader) return seenHeader;
565
+ const meta = globalRegistry.get(header);
566
+ const { id: metaId,...rest } = meta?.header ?? {};
567
+ const id = metaId ?? opts?.manualId;
568
+ const headerObject = rest;
569
+ if (isRequired(header, "output")) headerObject.required = true;
570
+ if (!headerObject.description && meta?.description) headerObject.description = meta.description;
571
+ headerObject.schema = registry$1.addSchema(header, [...path, "schema"], {
572
+ io: "output",
573
+ source: { type: "header" }
574
+ });
575
+ if (id) {
576
+ if (registry$1.components.schemas.ids.has(id)) throw new Error(`Schema "${id}" at ${path.join(" > ")} is already registered`);
577
+ const ref = { $ref: `#/components/headers/${id}` };
578
+ registry$1.components.headers.ids.set(id, headerObject);
579
+ registry$1.components.headers.seen.set(header, ref);
580
+ return ref;
581
+ }
582
+ registry$1.components.headers.seen.set(header, headerObject);
583
+ return headerObject;
584
+ },
585
+ addRequestBody: (requestBody, path, opts) => {
586
+ const seenRequestBody = registry$1.components.requestBodies.seen.get(requestBody);
587
+ if (seenRequestBody) return seenRequestBody;
588
+ const { content, id: metaId,...rest } = requestBody;
589
+ const requestBodyObject = {
590
+ ...rest,
591
+ content: createContent(content, {
592
+ registry: registry$1,
593
+ io: "input"
594
+ }, [...path, "content"])
595
+ };
596
+ const id = metaId ?? opts?.manualId;
597
+ if (id) {
598
+ if (registry$1.components.requestBodies.ids.has(id)) throw new Error(`RequestBody "${id}" at ${path.join(" > ")} is already registered`);
599
+ const ref = { $ref: `#/components/requestBodies/${id}` };
600
+ registry$1.components.requestBodies.ids.set(id, requestBodyObject);
601
+ registry$1.components.requestBodies.seen.set(requestBody, ref);
602
+ return ref;
603
+ }
604
+ registry$1.components.requestBodies.seen.set(requestBody, requestBodyObject);
605
+ return requestBodyObject;
606
+ },
607
+ addPathItem: (pathItem, path, opts) => {
608
+ const seenPathItem = registry$1.components.pathItems.seen.get(pathItem);
609
+ if (seenPathItem) return seenPathItem;
610
+ const pathItemObject = {};
611
+ const { id: metaId,...rest } = pathItem;
612
+ const id = metaId ?? opts?.manualId;
613
+ for (const [key, value] of Object.entries(rest)) {
614
+ if (isISpecificationExtension(key)) {
615
+ pathItemObject[key] = value;
616
+ continue;
617
+ }
618
+ if (key === "get" || key === "put" || key === "post" || key === "delete" || key === "options" || key === "head" || key === "patch" || key === "trace") {
619
+ pathItemObject[key] = createOperation(value, registry$1, [...path, key]);
620
+ continue;
621
+ }
622
+ if (key === "parameters") {
623
+ pathItemObject[key] = createManualParameters(value, registry$1, [...path, key]);
624
+ continue;
625
+ }
626
+ pathItemObject[key] = value;
627
+ }
628
+ if (id) {
629
+ if (registry$1.components.pathItems.ids.has(id)) throw new Error(`PathItem "${id}" at ${path.join(" > ")} is already registered`);
630
+ const ref = { $ref: `#/components/pathItems/${id}` };
631
+ registry$1.components.pathItems.ids.set(id, pathItemObject);
632
+ registry$1.components.pathItems.seen.set(pathItem, ref);
633
+ return ref;
634
+ }
635
+ registry$1.components.pathItems.seen.set(pathItem, pathItemObject);
636
+ return pathItemObject;
637
+ },
638
+ addResponse: (response, path, opts) => {
639
+ const seenResponse = registry$1.components.responses.seen.get(response);
640
+ if (seenResponse) return seenResponse;
641
+ const { content, headers, links, id: metaId,...rest } = response;
642
+ const responseObject = rest;
643
+ const maybeHeaders = createHeaders(headers, registry$1, [...path, "headers"]);
644
+ if (maybeHeaders) responseObject.headers = maybeHeaders;
645
+ if (content) responseObject.content = createContent(content, {
646
+ registry: registry$1,
647
+ io: "output"
648
+ }, [...path, "content"]);
649
+ if (links) responseObject.links = createLinks(links, registry$1, [...path, "links"]);
650
+ const id = metaId ?? opts?.manualId;
651
+ if (id) {
652
+ if (registry$1.components.responses.ids.has(id)) throw new Error(`Response "${id}" at ${path.join(" > ")} is already registered`);
653
+ const ref = { $ref: `#/components/responses/${id}` };
654
+ registry$1.components.responses.ids.set(id, responseObject);
655
+ registry$1.components.responses.seen.set(response, ref);
656
+ return ref;
657
+ }
658
+ registry$1.components.responses.seen.set(response, responseObject);
659
+ return responseObject;
660
+ },
661
+ addCallback: (callback, path, opts) => {
662
+ const seenCallback = registry$1.components.callbacks.seen.get(callback);
663
+ if (seenCallback) return seenCallback;
664
+ const { id: metaId,...rest } = callback;
665
+ const callbackObject = {};
666
+ for (const [name, pathItem] of Object.entries(rest)) {
667
+ if (isISpecificationExtension(name)) {
668
+ callbackObject[name] = pathItem;
669
+ continue;
670
+ }
671
+ callbackObject[name] = registry$1.addPathItem(pathItem, [...path, name]);
672
+ }
673
+ const id = metaId ?? opts?.manualId;
674
+ if (id) {
675
+ if (registry$1.components.callbacks.ids.has(id)) throw new Error(`Callback "${id}" at ${path.join(" > ")} is already registered`);
676
+ const ref = { $ref: `#/components/callbacks/${id}` };
677
+ registry$1.components.callbacks.ids.set(id, callbackObject);
678
+ registry$1.components.callbacks.seen.set(callback, ref);
679
+ return ref;
680
+ }
681
+ registry$1.components.callbacks.seen.set(callback, callbackObject);
682
+ return callbackObject;
683
+ },
684
+ addSecurityScheme: (securityScheme, path, opts) => {
685
+ const seenSecurityScheme = registry$1.components.securitySchemes.seen.get(securityScheme);
686
+ if (seenSecurityScheme) return seenSecurityScheme;
687
+ const { id: metaId,...rest } = securityScheme;
688
+ const securitySchemeObject = rest;
689
+ const id = metaId ?? opts?.manualId;
690
+ if (id) {
691
+ if (registry$1.components.securitySchemes.ids.has(id)) throw new Error(`SecurityScheme "${id}" at ${path.join(" > ")} is already registered`);
692
+ const ref = { $ref: `#/components/securitySchemes/${id}` };
693
+ registry$1.components.securitySchemes.ids.set(id, securitySchemeObject);
694
+ registry$1.components.securitySchemes.seen.set(securityScheme, ref);
695
+ return ref;
696
+ }
697
+ registry$1.components.securitySchemes.seen.set(securityScheme, securitySchemeObject);
698
+ return securitySchemeObject;
699
+ },
700
+ addLink: (link, path, opts) => {
701
+ const seenLink = registry$1.components.links.seen.get(link);
702
+ if (seenLink) return seenLink;
703
+ const { id: metaId,...rest } = link;
704
+ const linkObject = rest;
705
+ const id = metaId ?? opts?.manualId;
706
+ if (id) {
707
+ if (registry$1.components.links.ids.has(id)) throw new Error(`Link "${id}" at ${path.join(" > ")} is already registered`);
708
+ const ref = { $ref: `#/components/links/${id}` };
709
+ registry$1.components.links.ids.set(id, linkObject);
710
+ registry$1.components.links.seen.set(link, ref);
711
+ return ref;
712
+ }
713
+ registry$1.components.links.seen.set(link, linkObject);
714
+ return linkObject;
715
+ },
716
+ addExample: (example, path, opts) => {
717
+ const seenExample = registry$1.components.examples.seen.get(example);
718
+ if (seenExample) return seenExample;
719
+ const { id: metaId,...rest } = example;
720
+ const exampleObject = rest;
721
+ const id = metaId ?? opts?.manualId;
722
+ if (id) {
723
+ if (registry$1.components.examples.ids.has(id)) throw new Error(`Example "${id}" at ${path.join(" > ")} is already registered`);
724
+ const ref = { $ref: `#/components/examples/${id}` };
725
+ registry$1.components.examples.ids.set(id, exampleObject);
726
+ registry$1.components.examples.seen.set(example, ref);
727
+ return ref;
728
+ }
729
+ registry$1.components.examples.seen.set(example, exampleObject);
730
+ return exampleObject;
731
+ }
732
+ };
733
+ registerSchemas(components?.schemas, registry$1);
734
+ registerParameters(components?.parameters, registry$1);
735
+ registerHeaders(components?.headers, registry$1);
736
+ registerResponses(components?.responses, registry$1);
737
+ registerPathItems(components?.pathItems, registry$1);
738
+ registerRequestBodies(components?.requestBodies, registry$1);
739
+ registerCallbacks(components?.callbacks, registry$1);
740
+ registerSecuritySchemes(components?.securitySchemes, registry$1);
741
+ registerLinks(components?.links, registry$1);
742
+ registerExamples(components?.examples, registry$1);
743
+ return registry$1;
744
+ };
745
+ const registerSchemas = (schemas, registry$1) => {
746
+ if (!schemas) return;
747
+ for (const [key, schema] of Object.entries(schemas)) {
748
+ if (isAnyZodType(schema)) {
749
+ const id = globalRegistry.get(schema)?.id ?? key;
750
+ registry$1.components.schemas.manual.set(id, {
751
+ input: { schemaObject: {} },
752
+ output: { schemaObject: {} },
753
+ zodType: schema
754
+ });
755
+ continue;
756
+ }
757
+ registry$1.components.schemas.ids.set(key, schema);
758
+ }
759
+ };
760
+ const registerParameters = (parameters, registry$1) => {
761
+ if (!parameters) return;
762
+ for (const [key, schema] of Object.entries(parameters)) {
763
+ if (isAnyZodType(schema)) {
764
+ const path = [
765
+ "components",
766
+ "parameters",
767
+ key
768
+ ];
769
+ registry$1.addParameter(schema, path, { manualId: key });
770
+ continue;
771
+ }
772
+ registry$1.components.parameters.ids.set(key, schema);
773
+ }
774
+ };
775
+ const registerHeaders = (headers, registry$1) => {
776
+ if (!headers) return;
777
+ for (const [key, schema] of Object.entries(headers)) {
778
+ if (isAnyZodType(schema)) {
779
+ const path = [
780
+ "components",
781
+ "headers",
782
+ key
783
+ ];
784
+ registry$1.addHeader(schema, path, { manualId: key });
785
+ continue;
786
+ }
787
+ registry$1.components.headers.ids.set(key, schema);
788
+ }
789
+ };
790
+ const registerResponses = (responses, registry$1) => {
791
+ if (!responses) return;
792
+ for (const [key, schema] of Object.entries(responses)) {
793
+ const responseObject = registry$1.addResponse(schema, [
794
+ "components",
795
+ "responses",
796
+ key
797
+ ], { manualId: key });
798
+ registry$1.components.responses.ids.set(key, responseObject);
799
+ registry$1.components.responses.seen.set(schema, responseObject);
800
+ }
801
+ };
802
+ const registerRequestBodies = (requestBodies, registry$1) => {
803
+ if (!requestBodies) return;
804
+ for (const [key, schema] of Object.entries(requestBodies)) {
805
+ if (isAnyZodType(schema)) {
806
+ registry$1.addRequestBody(schema, [
807
+ "components",
808
+ "requestBodies",
809
+ key
810
+ ], { manualId: key });
811
+ continue;
812
+ }
813
+ registry$1.components.requestBodies.ids.set(key, schema);
814
+ }
815
+ };
816
+ const registerCallbacks = (callbacks, registry$1) => {
817
+ if (!callbacks) return;
818
+ for (const [key, schema] of Object.entries(callbacks)) registry$1.addCallback(schema, [
819
+ "components",
820
+ "callbacks",
821
+ key
822
+ ], { manualId: key });
823
+ };
824
+ const registerPathItems = (pathItems, registry$1) => {
825
+ if (!pathItems) return;
826
+ for (const [key, schema] of Object.entries(pathItems)) registry$1.addPathItem(schema, [
827
+ "components",
828
+ "pathItems",
829
+ key
830
+ ], { manualId: key });
831
+ };
832
+ const registerSecuritySchemes = (securitySchemes, registry$1) => {
833
+ if (!securitySchemes) return;
834
+ for (const [key, schema] of Object.entries(securitySchemes)) registry$1.addSecurityScheme(schema, [
835
+ "components",
836
+ "securitySchemes",
837
+ key
838
+ ], { manualId: key });
839
+ };
840
+ const registerLinks = (links, registry$1) => {
841
+ if (!links) return;
842
+ for (const [key, schema] of Object.entries(links)) registry$1.addLink(schema, [
843
+ "components",
844
+ "links",
845
+ key
846
+ ], { manualId: key });
847
+ };
848
+ const registerExamples = (examples, registry$1) => {
849
+ if (!examples) return;
850
+ for (const [key, schema] of Object.entries(examples)) registry$1.components.examples.ids.set(key, schema);
851
+ };
852
+ const createIOSchemas = (ctx) => {
853
+ const { schemas, components, manual } = createSchemas(Object.fromEntries(ctx.registry.components.schemas[ctx.io]), ctx);
854
+ for (const [key, schema] of Object.entries(components)) ctx.registry.components.schemas.ids.set(key, schema);
855
+ for (const [key, schema] of Object.entries(schemas)) {
856
+ const ioSchema = ctx.registry.components.schemas[ctx.io].get(key);
857
+ if (ioSchema) Object.assign(ioSchema.schemaObject, schema);
858
+ }
859
+ for (const [key, value] of Object.entries(manual)) {
860
+ const manualSchema = ctx.registry.components.schemas.manual.get(key);
861
+ if (!manualSchema) continue;
862
+ if (components[key]) manualSchema[ctx.io].used = true;
863
+ Object.assign(manualSchema[ctx.io].schemaObject, value);
864
+ }
865
+ };
866
+ const createManualSchemas = (registry$1) => {
867
+ for (const [key, value] of registry$1.components.schemas.manual) if (!value.input.used) {
868
+ const io = globalRegistry.get(value.zodType)?.unusedIO ?? "output";
869
+ const schema = value[io].schemaObject;
870
+ registry$1.components.schemas.ids.set(key, schema);
871
+ }
872
+ };
873
+ const createComponents = (registry$1, opts) => {
874
+ createIOSchemas({
875
+ registry: registry$1,
876
+ io: "input",
877
+ opts
878
+ });
879
+ createIOSchemas({
880
+ registry: registry$1,
881
+ io: "output",
882
+ opts
883
+ });
884
+ createManualSchemas(registry$1);
885
+ const components = {};
886
+ if (registry$1.components.schemas.ids.size > 0) components.schemas = Object.fromEntries(registry$1.components.schemas.ids);
887
+ if (registry$1.components.headers.ids.size > 0) components.headers = Object.fromEntries(registry$1.components.headers.ids);
888
+ if (registry$1.components.requestBodies.ids.size > 0) components.requestBodies = Object.fromEntries(registry$1.components.requestBodies.ids);
889
+ if (registry$1.components.responses.ids.size > 0) components.responses = Object.fromEntries(registry$1.components.responses.ids);
890
+ if (registry$1.components.parameters.ids.size > 0) components.parameters = Object.fromEntries(registry$1.components.parameters.ids);
891
+ if (registry$1.components.callbacks.ids.size > 0) components.callbacks = Object.fromEntries(registry$1.components.callbacks.ids);
892
+ if (registry$1.components.pathItems.ids.size > 0) components.pathItems = Object.fromEntries(registry$1.components.pathItems.ids);
893
+ if (registry$1.components.securitySchemes.ids.size > 0) components.securitySchemes = Object.fromEntries(registry$1.components.securitySchemes.ids);
894
+ if (registry$1.components.links.ids.size > 0) components.links = Object.fromEntries(registry$1.components.links.ids);
895
+ if (registry$1.components.examples.ids.size > 0) components.examples = Object.fromEntries(registry$1.components.examples.ids);
896
+ return components;
897
+ };
898
+
899
+ //#endregion
900
+ export { createComponents, createPaths, createRegistry, createSchema, isAnyZodType, unwrapZodObject };