zod-openapi 5.0.0-beta.0 → 5.0.0-beta.10

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,1078 +0,0 @@
1
- "use strict";
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);
17
- }
18
- return unwrapZodObject(def.out, io, path);
19
- }
20
- }
21
- throw new Error(
22
- `Failed to unwrap ZodObject from type: ${zodType._zod.def.type} at ${path.join(" > ")}`
23
- );
24
- };
25
- const isRequired = (zodType, io) => {
26
- if (io === "input") {
27
- return zodType._zod.optin === void 0;
28
- }
29
- return zodType._zod.optout === void 0;
30
- };
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) {
41
- throw new Error(
42
- `Parameter at ${path.join(" > ")} is missing \`.meta({ param: { name, in } })\` information`
43
- );
44
- }
45
- const computedPath = [...path, inLocation, name].join(" > ");
46
- const schemaObject = ctx.registry.schemas.setSchema(
47
- computedPath,
48
- parameter,
49
- ctx.io
50
- );
51
- const { id, ...rest } = (meta == null ? void 0 : meta.param) ?? {};
52
- const parameterObject = {
53
- ...rest,
54
- name,
55
- in: inLocation,
56
- schema: schemaObject
57
- };
58
- if (isRequired(parameter, ctx.io)) {
59
- parameterObject.required = true;
60
- }
61
- if (!parameterObject.description && (meta == null ? void 0 : meta.description)) {
62
- parameterObject.description = meta.description;
63
- }
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;
71
- }
72
- ctx.registry.parameters.seen.set(parameter, parameterObject);
73
- return parameterObject;
74
- };
75
- const createManualParameters = (parameters, ctx, path) => {
76
- if (!parameters) {
77
- return void 0;
78
- }
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;
86
- }
87
- const paramObject = createParameter(parameter, void 0, ctx, [
88
- ...path,
89
- "parameters"
90
- ]);
91
- parameterObjects.push(paramObject);
92
- continue;
93
- }
94
- parameterObjects.push(parameter);
95
- }
96
- return parameterObjects;
97
- };
98
- const createParameters = (requestParams, ctx, path) => {
99
- if (!requestParams) {
100
- return void 0;
101
- }
102
- const parameterObjects = [];
103
- for (const [location, schema] of Object.entries(requestParams ?? {})) {
104
- if (!schema) {
105
- continue;
106
- }
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
119
- },
120
- ctx,
121
- [...path, location, name]
122
- );
123
- parameterObjects.push(paramObject);
124
- }
125
- }
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
- );
136
- return {
137
- ...mediaTypeObject,
138
- schema: schemaObject
139
- };
140
- }
141
- return mediaTypeObject;
142
- };
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
- ]);
151
- }
152
- }
153
- return contentObject;
154
- };
155
- const createRequestBody = (requestBody, ctx, path) => {
156
- if (!requestBody) {
157
- return void 0;
158
- }
159
- const seenRequestBody = ctx.registry.requestBodies.seen.get(requestBody);
160
- if (seenRequestBody) {
161
- return seenRequestBody;
162
- }
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
198
- );
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;
206
- }
207
- ctx.registry.headers.seen.set(header, headerObject);
208
- return headerObject;
209
- };
210
- const createHeaders = (headers, ctx, path) => {
211
- if (!headers) {
212
- return void 0;
213
- }
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;
220
- }
221
- return headersObject;
222
- }
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;
230
- }
231
- const { content, headers, id, ...rest } = response;
232
- const responseObject = rest;
233
- if (id) {
234
- ctx.registry.responses.ids.set(id, responseObject);
235
- }
236
- ctx.registry.responses.seen.set(response, responseObject);
237
- const maybeHeaders = createHeaders(headers, ctx, [...path, "headers"]);
238
- if (maybeHeaders) {
239
- responseObject.headers = maybeHeaders;
240
- }
241
- if (content) {
242
- responseObject.content = createContent(content, ctx, [...path, "content"]);
243
- }
244
- return responseObject;
245
- };
246
- const createResponses = (responses, ctx, path) => {
247
- if (!responses) {
248
- return void 0;
249
- }
250
- const responsesObject = {};
251
- for (const [statusCode, response] of Object.entries(responses)) {
252
- if (!response) {
253
- continue;
254
- }
255
- if (isISpecificationExtension(statusCode)) {
256
- responsesObject[statusCode] = response;
257
- continue;
258
- }
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;
269
- }
270
- return responsesObject;
271
- };
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"]
289
- );
290
- const maybeRequestParams = createParameters(
291
- requestParams,
292
- {
293
- registry,
294
- io: "input"
295
- },
296
- [...path, "requestParams"]
297
- );
298
- if (maybeRequestParams || maybeManualParameters) {
299
- operation.parameters = [
300
- ...maybeRequestParams ?? [],
301
- ...maybeManualParameters ?? []
302
- ];
303
- }
304
- const maybeRequestBody = createRequestBody(
305
- requestBody,
306
- {
307
- registry,
308
- io: "input"
309
- },
310
- [...path, "requestBody"]
311
- );
312
- if (maybeRequestBody) {
313
- operation.requestBody = maybeRequestBody;
314
- }
315
- const maybeResponses = createResponses(
316
- responses,
317
- {
318
- registry,
319
- io: "output"
320
- },
321
- [...path, "responses"]
322
- );
323
- if (maybeResponses) {
324
- operation.responses = maybeResponses;
325
- }
326
- const maybeCallbacks = createCallbacks(callbacks, registry, [
327
- ...path,
328
- "callbacks"
329
- ]);
330
- if (maybeCallbacks) {
331
- operation.callbacks = maybeCallbacks;
332
- }
333
- return operation;
334
- };
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;
346
- }
347
- if (key === "parameters") {
348
- pathItemObject[key] = createManualParameters(
349
- value,
350
- {
351
- registry,
352
- io: "input"
353
- },
354
- [...path, key]
355
- );
356
- continue;
357
- }
358
- pathItemObject[key] = value;
359
- }
360
- if (id) {
361
- const ref = {
362
- $ref: `#/components/pathItems/${id}`
363
- };
364
- registry.pathItems.ids.set(id, pathItemObject);
365
- registry.pathItems.seen.set(pathItem, ref);
366
- return ref;
367
- }
368
- return pathItemObject;
369
- };
370
- const createPaths = (paths, registry, path) => {
371
- if (!paths) {
372
- return void 0;
373
- }
374
- const pathsObject = {};
375
- for (const [singlePath, pathItemObject] of Object.entries(paths)) {
376
- if (isISpecificationExtension(singlePath)) {
377
- pathsObject[singlePath] = pathItemObject;
378
- continue;
379
- }
380
- pathsObject[singlePath] = createPathItem(pathItemObject, registry, [
381
- ...path,
382
- singlePath
383
- ]);
384
- }
385
- return pathsObject;
386
- };
387
- const createCallback = (callbackObject, registry, path) => {
388
- const seenCallback = registry.callbacks.seen.get(callbackObject);
389
- if (seenCallback) {
390
- return seenCallback;
391
- }
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;
398
- }
399
- callback[name] = createPathItem(
400
- pathItem,
401
- registry,
402
- [...path, name]
403
- );
404
- }
405
- if (id) {
406
- const ref = {
407
- $ref: `#/components/callbacks/${id}`
408
- };
409
- registry.callbacks.ids.set(id, callback);
410
- registry.callbacks.seen.set(callbackObject, ref);
411
- return ref;
412
- }
413
- registry.callbacks.seen.set(callbackObject, callback);
414
- return callback;
415
- };
416
- const createCallbacks = (callbacks, registry, path) => {
417
- if (!callbacks) {
418
- return void 0;
419
- }
420
- const callbacksObject = {};
421
- for (const [name, value] of Object.entries(callbacks)) {
422
- if (isISpecificationExtension(name)) {
423
- callbacksObject[name] = value;
424
- continue;
425
- }
426
- callbacksObject[name] = createCallback(
427
- value,
428
- registry,
429
- [...path, name]
430
- );
431
- }
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
- }
492
- };
493
- const validate = (ctx, opts) => {
494
- var _a;
495
- if (Object.keys(ctx.jsonSchema).length) {
496
- return;
497
- }
498
- const def = ctx.zodSchema._zod.def;
499
- if ((_a = opts.allowEmptySchema) == null ? void 0 : _a[def.type]) {
500
- return;
501
- }
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;
530
- }
531
- }
532
- throw new Error(
533
- `Zod schema of type \`${def.type}\` cannot be represented in OpenAPI. Please assign it metadata with \`.meta()\``
534
- );
535
- };
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
- });
554
- }
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;
573
- }
574
- return componentsToRename;
575
- };
576
- const isDependencyPure = (componentDependencies, stringifiedComponents, registry, key, visited = /* @__PURE__ */ new Set()) => {
577
- if (visited.has(key)) {
578
- return true;
579
- }
580
- const dependencies = componentDependencies.get(key);
581
- if (dependencies.pure !== void 0) {
582
- return dependencies.pure;
583
- }
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;
589
- }
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 }
623
- };
624
- Object.assign(schemas, registrySchemas);
625
- const jsonSchemas = createSchemas(schemas, {
626
- registry: ctx.registry,
627
- io: ctx.io,
628
- opts: ctx.opts
629
- });
630
- return {
631
- schema: jsonSchemas.schemas.zodOpenApiCreateSchema,
632
- components: jsonSchemas.components
633
- };
634
- };
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;
692
- }
693
- componentsToReplace.set(`__shared#/$defs/${key}`, key);
694
- }
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);
736
- }
737
- }
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}`
745
- };
746
- components[value] = component;
747
- }
748
- const renamedComponents = renameComponents(components, outputIds, {
749
- registry
750
- });
751
- if (renamedComponents.size === 0) {
752
- delete patchedJsonSchema.schemas.__shared;
753
- return {
754
- schemas: patchedJsonSchema.schemas,
755
- components
756
- };
757
- }
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
- }
767
- );
768
- const renamedJsonSchema = JSON.parse(renamedStringified);
769
- const renamedJsonSchemaComponents = ((_f = renamedJsonSchema.schemas.__shared) == null ? void 0 : _f.$defs) ?? {};
770
- delete renamedJsonSchema.schemas.__shared;
771
- return {
772
- schemas: renamedJsonSchema.schemas,
773
- components: renamedJsonSchemaComponents
774
- };
775
- };
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;
811
- }
812
- },
813
- headers: {
814
- ids: /* @__PURE__ */ new Map(),
815
- seen: /* @__PURE__ */ new WeakMap()
816
- },
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
- }
837
- };
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) => {
848
- if (!schemas) {
849
- return;
850
- }
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
- }
855
- if (isAnyZodType(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, {
873
- type: "manual",
874
- schemaObject: outputSchemaObject,
875
- id: identifier
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;
890
- }
891
- registry.schemas.ids.set(key, schema);
892
- }
893
- };
894
- const registerParameters = (parameters, registry) => {
895
- if (!parameters) {
896
- return;
897
- }
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
- }
902
- if (isAnyZodType(schema)) {
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;
916
- }
917
- registry.parameters.ids.set(key, schema);
918
- }
919
- };
920
- const registerHeaders = (headers, registry) => {
921
- if (!headers) {
922
- return;
923
- }
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
- }
928
- if (isAnyZodType(schema)) {
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;
941
- }
942
- registry.headers.ids.set(key, schema);
943
- }
944
- };
945
- const registerResponses = (responses, registry) => {
946
- if (!responses) {
947
- return;
948
- }
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`);
953
- }
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
- }
965
- };
966
- const registerRequestBodies = (requestBodies, registry) => {
967
- if (!requestBodies) {
968
- return;
969
- }
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
983
- );
984
- registry.requestBodies.ids.set(key, requestBodyObject);
985
- continue;
986
- }
987
- registry.requestBodies.ids.set(key, schema);
988
- }
989
- };
990
- const registerCallbacks = (callbacks, registry) => {
991
- if (!callbacks) {
992
- return;
993
- }
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`);
997
- }
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
- }
1003
- };
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`);
1011
- }
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
- }
1018
- };
1019
- const createIOSchemas = (ctx) => {
1020
- const { schemas, components } = createSchemas(
1021
- Object.fromEntries(ctx.registry.schemas[ctx.io].schemas),
1022
- ctx
1023
- );
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);
1031
- }
1032
- }
1033
- };
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);
1041
- }
1042
- }
1043
- };
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;
1071
- };
1072
- exports.createComponents = createComponents;
1073
- exports.createMediaTypeObject = createMediaTypeObject;
1074
- exports.createParameter = createParameter;
1075
- exports.createPaths = createPaths;
1076
- exports.createRegistry = createRegistry;
1077
- exports.createSchema = createSchema;
1078
- exports.unwrapZodObject = unwrapZodObject;