@orpc/openapi 2.0.0-beta.46 → 2.0.0-beta.48

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.
Files changed (88) hide show
  1. package/README.md +6 -4
  2. package/dist/adapters/aws-lambda/index.d.mts +14 -26
  3. package/dist/adapters/aws-lambda/index.mjs +1 -21
  4. package/dist/adapters/aws-lambda/openapi-handler.d.mts +17 -0
  5. package/dist/adapters/aws-lambda/openapi-handler.mjs +11 -0
  6. package/dist/adapters/fastify/index.d.mts +1 -23
  7. package/dist/adapters/fastify/index.mjs +1 -21
  8. package/dist/adapters/fastify/openapi-handler.d.mts +14 -0
  9. package/dist/adapters/fastify/openapi-handler.mjs +11 -0
  10. package/dist/adapters/fetch/index.d.mts +2 -37
  11. package/dist/adapters/fetch/index.mjs +2 -34
  12. package/dist/adapters/fetch/openapi-handler.d.mts +14 -0
  13. package/dist/adapters/fetch/openapi-handler.mjs +11 -0
  14. package/dist/adapters/fetch/openapi-link.d.mts +15 -0
  15. package/dist/adapters/fetch/openapi-link.mjs +11 -0
  16. package/dist/adapters/node/index.d.mts +1 -23
  17. package/dist/adapters/node/index.mjs +1 -21
  18. package/dist/adapters/node/openapi-handler.d.mts +14 -0
  19. package/dist/adapters/node/openapi-handler.mjs +11 -0
  20. package/dist/adapters/standard/index.d.mts +3 -48
  21. package/dist/adapters/standard/index.mjs +3 -12
  22. package/dist/adapters/standard/openapi-handler-codec.d.mts +61 -0
  23. package/dist/adapters/standard/openapi-handler-codec.mjs +203 -0
  24. package/dist/adapters/standard/openapi-link-codec.d.mts +53 -0
  25. package/dist/adapters/standard/openapi-link-codec.mjs +356 -0
  26. package/dist/adapters/standard/openapi-matcher.d.mts +29 -0
  27. package/dist/adapters/standard/openapi-matcher.mjs +105 -0
  28. package/dist/adapters/standard/utils.d.mts +4 -0
  29. package/dist/adapters/standard/utils.mjs +36 -0
  30. package/dist/bracket-notation.d.mts +26 -0
  31. package/dist/bracket-notation.mjs +156 -0
  32. package/dist/client-factory.d.mts +24 -0
  33. package/dist/client-factory.mjs +5 -0
  34. package/dist/constants.d.mts +4 -0
  35. package/dist/constants.mjs +4 -0
  36. package/dist/extensions/route.d.mts +74 -39
  37. package/dist/extensions/route.mjs +8 -10
  38. package/dist/helpers/form-data.d.mts +57 -0
  39. package/dist/helpers/form-data.mjs +36 -0
  40. package/dist/helpers/index.d.mts +1 -59
  41. package/dist/helpers/index.mjs +1 -39
  42. package/dist/index.d.mts +13 -159
  43. package/dist/index.mjs +11 -778
  44. package/dist/meta.d.mts +345 -0
  45. package/dist/meta.mjs +56 -0
  46. package/dist/openapi-generator-components.d.mts +24 -0
  47. package/dist/openapi-generator-components.mjs +227 -0
  48. package/dist/openapi-generator-operation.d.mts +29 -0
  49. package/dist/openapi-generator-operation.mjs +447 -0
  50. package/dist/openapi-generator.d.mts +87 -0
  51. package/dist/openapi-generator.mjs +115 -0
  52. package/dist/openapi-json-serializer.d.mts +86 -0
  53. package/dist/openapi-json-serializer.mjs +229 -0
  54. package/dist/openapi-serializer.d.mts +43 -0
  55. package/dist/openapi-serializer.mjs +87 -0
  56. package/dist/plugins/index.d.mts +1 -121
  57. package/dist/plugins/index.mjs +1 -167
  58. package/dist/plugins/openapi-reference.d.mts +118 -0
  59. package/dist/plugins/openapi-reference.mjs +157 -0
  60. package/dist/router-utils.d.mts +18 -0
  61. package/dist/router-utils.mjs +29 -0
  62. package/dist/types.d.mts +27 -0
  63. package/dist/types.mjs +1 -0
  64. package/dist/utils.d.mts +14 -0
  65. package/dist/utils.mjs +40 -0
  66. package/package.json +15 -15
  67. package/dist/adapters/aws-lambda/index.d.ts +0 -27
  68. package/dist/adapters/fastify/index.d.ts +0 -23
  69. package/dist/adapters/fetch/index.d.ts +0 -37
  70. package/dist/adapters/node/index.d.ts +0 -23
  71. package/dist/adapters/standard/index.d.ts +0 -48
  72. package/dist/extensions/route.d.ts +0 -41
  73. package/dist/helpers/index.d.ts +0 -59
  74. package/dist/index.d.ts +0 -159
  75. package/dist/plugins/index.d.ts +0 -121
  76. package/dist/shared/openapi.B9PQzqBn.mjs +0 -49
  77. package/dist/shared/openapi.BCrrWRbv.d.mts +0 -87
  78. package/dist/shared/openapi.BNe1y1cD.mjs +0 -360
  79. package/dist/shared/openapi.B_SoJfYz.d.mts +0 -328
  80. package/dist/shared/openapi.B_SoJfYz.d.ts +0 -328
  81. package/dist/shared/openapi.BkjX_6hE.d.ts +0 -87
  82. package/dist/shared/openapi.Covi8zVE.d.mts +0 -33
  83. package/dist/shared/openapi.Covi8zVE.d.ts +0 -33
  84. package/dist/shared/openapi.DXqJL3gB.mjs +0 -408
  85. package/dist/shared/openapi.DtEVcxuW.mjs +0 -149
  86. package/dist/shared/openapi.E3ZBiweM.mjs +0 -353
  87. package/dist/shared/openapi.YMRD3b4R.d.mts +0 -157
  88. package/dist/shared/openapi.YMRD3b4R.d.ts +0 -157
@@ -0,0 +1,447 @@
1
+ import { getAsyncIteratorObjectSchemasDetails } from "@orpc/contract";
2
+ import { combineJsonObjectSchemaEntries, combineJsonSchemasWithComposition, containsJsonFileSchema, extractJsonObjectSchemaAdditionalProperties, extractJsonObjectSchemaEntries, flattenJsonUnionSchema, isJsonFileSchema, isJsonPrimitiveSchema, isUnconstrainedSchema, matchArrayableJsonSchema } from "@orpc/json-schema";
3
+ import { DEFAULT_ERROR_STATUS, DEFAULT_SUCCESS_STATUS } from "@orpc/server";
4
+ import { stringifyJSON, value } from "@orpc/shared";
5
+ import { DEFAULT_OPENAPI_INPUT_STRUCTURE, DEFAULT_OPENAPI_METHOD, DEFAULT_OPENAPI_OUTPUT_STRUCTURE, DEFAULT_OPENAPI_SUCCESS_DESCRIPTION } from "./constants.mjs";
6
+ import { isBodylessMethod } from "./utils.mjs";
7
+ export class OpenAPIGeneratorError extends TypeError {}
8
+ export function toOpenAPIPath(path, dynamicPathParams) {
9
+ if (!dynamicPathParams?.length) {
10
+ return path;
11
+ }
12
+ let normalized = "";
13
+ let currentIndex = 0;
14
+ for (const param of dynamicPathParams) {
15
+ normalized += path.slice(currentIndex, param.startIndex);
16
+ normalized += `{${param.parameterName}}`;
17
+ currentIndex = param.startIndex + param.segment.length;
18
+ }
19
+ normalized += path.slice(currentIndex);
20
+ return normalized;
21
+ }
22
+ export function buildRequest(ctx, operation, def, meta, dynamicPathParams) {
23
+ const method = meta?.method ?? DEFAULT_OPENAPI_METHOD;
24
+ const inputStructure = meta?.inputStructure ?? DEFAULT_OPENAPI_INPUT_STRUCTURE;
25
+ if (inputStructure === "compact") {
26
+ const iteratorDetails = getAsyncIteratorObjectSchemasDetails(def.inputSchemas);
27
+ if (iteratorDetails) {
28
+ operation.requestBody = {
29
+ required: true,
30
+ content: toAsyncIteratorObjectContent(ctx, "input", ctx.convertSchemas(iteratorDetails.yieldSchemas, "input"), ctx.convertSchemas(iteratorDetails.returnSchemas, "input"))
31
+ };
32
+ return;
33
+ }
34
+ }
35
+ const dynamicParams = dynamicPathParams?.map((v) => v.parameterName);
36
+ const [schema, optional] = ctx.convertSchemas(def.inputSchemas, "input");
37
+ if (isUnconstrainedSchema(schema) && !dynamicParams?.length) {
38
+ return;
39
+ }
40
+ const parts = inputStructure === "compact" ? extractCompactRequestParts(schema, optional, method, dynamicParams) : extractDetailedRequestParts(schema);
41
+ renderPathParameters(ctx, operation, dynamicParams, parts.paramsEntries, meta?.paramsStyles);
42
+ renderQueryParameters(ctx, operation, parts.queryEntries, meta?.queryStyles);
43
+ renderHeaderParameters(ctx, operation, parts.headersEntries);
44
+ if (parts.bodySchema !== undefined) {
45
+ operation.requestBody = {
46
+ required: parts.bodyOptional ? undefined : true,
47
+ content: toBodyContent(ctx, "input", parts.bodySchema)
48
+ };
49
+ }
50
+ }
51
+ function extractCompactRequestParts(schema, optional, method, dynamicParams) {
52
+ const entries = extractJsonObjectSchemaEntries(schema);
53
+ if (!entries && isBodylessMethod(method)) {
54
+ throw new OpenAPIGeneratorError(`method is ${method} but the input schema is not an object.\n` + ` ${method} sends every input field as a query parameter, so the input must be an object schema.\n` + ` Fix: make the input an object, or use a method with a request body (POST, PUT, PATCH, DELETE).`);
55
+ }
56
+ const paramsEntries = entries?.filter(([name]) => dynamicParams?.includes(name));
57
+ const restEntries = entries?.filter(([name]) => !dynamicParams?.includes(name));
58
+ const hasBody = !isBodylessMethod(method);
59
+ const bodySchema = !hasBody ? undefined : !dynamicParams?.length ? schema : restEntries ? combineJsonObjectSchemaEntries(restEntries, extractJsonObjectSchemaAdditionalProperties(schema)) : undefined;
60
+ return {
61
+ paramsEntries,
62
+ queryEntries: isBodylessMethod(method) ? restEntries : undefined,
63
+ headersEntries: undefined,
64
+ bodySchema,
65
+ bodyOptional: !dynamicParams?.length ? optional : restEntries?.every(([, , optional]) => optional)
66
+ };
67
+ }
68
+ function extractDetailedRequestParts(schema) {
69
+ const entries = extractJsonObjectSchemaEntries(schema);
70
+ if (!entries) {
71
+ throw new OpenAPIGeneratorError(`inputStructure is "detailed" but the input schema is not an object.\n` + ` Expected an object shaped like: { params?: object, query?: object, headers?: object, body?: unknown }`);
72
+ }
73
+ const section = (name) => entries.find(([entryName]) => entryName === name);
74
+ return {
75
+ paramsEntries: extractJsonObjectSchemaEntries(section("params")?.[1] ?? false),
76
+ queryEntries: extractJsonObjectSchemaEntries(section("query")?.[1] ?? false),
77
+ headersEntries: extractJsonObjectSchemaEntries(section("headers")?.[1] ?? false),
78
+ bodySchema: section("body")?.[1],
79
+ bodyOptional: section("body")?.[2]
80
+ };
81
+ }
82
+ function renderPathParameters(ctx, operation, dynamicParams, paramsEntries, paramsStyles) {
83
+ if (!dynamicParams?.length) {
84
+ return;
85
+ }
86
+ if (!paramsEntries) {
87
+ throw new OpenAPIGeneratorError(`the route declares path params (${dynamicParams.map((p) => `{${p}}`).join(", ")}) but there is no object schema to source them from.\n` + ` compact mode: the input schema must be an object containing each param.\n` + ` detailed mode: the input's "params" section must be an object containing each param.`);
88
+ }
89
+ for (const name of dynamicParams) {
90
+ const entry = paramsEntries.find(([entryName]) => entryName === name);
91
+ if (!entry) {
92
+ throw new OpenAPIGeneratorError(`dynamic param "{${name}}" is missing from the input schema.\n` + ` Route params: ${dynamicParams.map((p) => `{${p}}`).join(", ")}\n` + ` Schema keys: ${paramsEntries.map(([n]) => n).join(", ") || "(none)"}`);
93
+ }
94
+ if (entry[2]) {
95
+ throw new OpenAPIGeneratorError(`dynamic param "${name}" is optional in the input schema.\n` + ` OpenAPI requires path params to be required. Make "${name}" required.`);
96
+ }
97
+ const style = paramsStyles?.[name];
98
+ const parameter = {
99
+ in: "path",
100
+ required: true,
101
+ name,
102
+ schema: ctx.registry.toOpenAPISchema(entry[1], "input")
103
+ };
104
+ if (style === "comma-delimited-array" || style === "comma-delimited-object") {
105
+ parameter.style = "simple";
106
+ parameter.explode = false;
107
+ } else {
108
+ const _expect = style;
109
+ }
110
+ operation.parameters ??= [];
111
+ operation.parameters.push(parameter);
112
+ }
113
+ }
114
+ function renderQueryParameters(ctx, operation, queryEntries, queryStyles) {
115
+ for (const [name, schema, optional] of queryEntries ?? []) {
116
+ const style = queryStyles?.[name];
117
+ const parameter = {
118
+ in: "query",
119
+ name,
120
+ schema: ctx.registry.toOpenAPISchema(schema, "input"),
121
+ allowEmptyValue: true,
122
+ allowReserved: true
123
+ };
124
+ if (!optional) {
125
+ parameter.required = true;
126
+ }
127
+ if (style === "comma-delimited-array" || style === "comma-delimited-object") {
128
+ parameter.explode = false;
129
+ } else if (style === "pipe-delimited-array" || style === "pipe-delimited-object") {
130
+ parameter.style = "pipeDelimited";
131
+ } else if (style === "space-delimited-array" || style === "space-delimited-object") {
132
+ parameter.style = "spaceDelimited";
133
+ } else if (style === "json") {
134
+ parameter.content = { "application/json": { schema: parameter.schema } };
135
+ delete parameter.schema;
136
+ delete parameter.allowReserved;
137
+ } else if (style === undefined) {
138
+ if (flattenJsonUnionSchema(schema).some((s) => !isJsonPrimitiveSchema(s))) {
139
+ const arrayable = matchArrayableJsonSchema(schema);
140
+ if (!arrayable || flattenJsonUnionSchema(arrayable[0]).some((s) => !isJsonPrimitiveSchema(s))) {
141
+ parameter.style = "deepObject";
142
+ parameter.explode = true;
143
+ }
144
+ }
145
+ } else {
146
+ const _expect = style;
147
+ }
148
+ operation.parameters ??= [];
149
+ operation.parameters.push(parameter);
150
+ }
151
+ }
152
+ function renderHeaderParameters(ctx, operation, headersEntries) {
153
+ for (const [name, schema, optional] of headersEntries ?? []) {
154
+ operation.parameters ??= [];
155
+ operation.parameters.push({
156
+ in: "header",
157
+ name,
158
+ required: optional ? undefined : true,
159
+ schema: ctx.registry.toOpenAPISchema(schema, "input")
160
+ });
161
+ }
162
+ }
163
+ export function buildSuccessResponse(ctx, operation, def, meta) {
164
+ const status = meta?.successStatus ?? DEFAULT_SUCCESS_STATUS;
165
+ const description = meta?.successDescription ?? DEFAULT_OPENAPI_SUCCESS_DESCRIPTION;
166
+ const outputStructure = meta?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
167
+ if (outputStructure === "compact") {
168
+ const iteratorDetails = getAsyncIteratorObjectSchemasDetails(def.outputSchemas);
169
+ if (iteratorDetails) {
170
+ operation.responses ??= {};
171
+ operation.responses[toResponseStatusKey(status)] = {
172
+ description,
173
+ content: toAsyncIteratorObjectContent(ctx, "output", ctx.convertSchemas(iteratorDetails.yieldSchemas, "output"), ctx.convertSchemas(iteratorDetails.returnSchemas, "output"))
174
+ };
175
+ return;
176
+ }
177
+ }
178
+ const [schema] = ctx.convertSchemas(def.outputSchemas, "output");
179
+ if (isUnconstrainedSchema(schema) || outputStructure === "compact") {
180
+ operation.responses ??= {};
181
+ operation.responses[toResponseStatusKey(status)] = {
182
+ description,
183
+ content: toBodyContent(ctx, "output", schema)
184
+ };
185
+ return;
186
+ }
187
+ for (const [responseStatus, parts] of extractDetailedResponseParts(schema, status)) {
188
+ const responseObject = { description: parts.descriptions.length ? parts.descriptions.join(", ") : description };
189
+ if (parts.bodies.length) {
190
+ responseObject.content = toBodyContent(ctx, "output", combineJsonSchemasWithComposition("anyOf", parts.bodies));
191
+ }
192
+ if (parts.headers.length) {
193
+ const entries = extractJsonObjectSchemaEntries(combineJsonSchemasWithComposition("anyOf", parts.headers));
194
+ entries?.forEach(([name, schema, optional]) => {
195
+ responseObject.headers ??= {};
196
+ responseObject.headers[name] = {
197
+ required: optional ? undefined : true,
198
+ schema: ctx.registry.toOpenAPISchema(schema, "output")
199
+ };
200
+ });
201
+ }
202
+ operation.responses ??= {};
203
+ operation.responses[toResponseStatusKey(responseStatus)] = responseObject;
204
+ }
205
+ }
206
+
207
+ function toResponseStatusKey(status) {
208
+ return String(status);
209
+ }
210
+
211
+ function extractDetailedResponseParts(schema, defaultStatus) {
212
+ const partsByStatus = new Map();
213
+ for (const item of flattenJsonUnionSchema(schema)) {
214
+ const entries = extractJsonObjectSchemaEntries(item);
215
+ if (!entries) {
216
+ throw new OpenAPIGeneratorError(`outputStructure is "detailed" but the output schema (or one of its union members) is not an object.\n` + ` Expected each member shaped like: { status?: number (< 400), headers?: object, body?: unknown }`);
217
+ }
218
+ const statusSchema = entries.find(([name]) => name === "status")?.[1];
219
+ const statuses = statusSchema === undefined ? new Map([[defaultStatus, undefined]]) : extractDetailedStatuses(statusSchema);
220
+ if (!statuses) {
221
+ throw new OpenAPIGeneratorError(`invalid "status" field in the detailed output schema.\n` + ` Expected: literal integers below 400 (const, enum, or a union of them)\n` + ` Received: ${stringifyJSON(statusSchema)}`);
222
+ }
223
+ const headersSchema = entries.find(([name]) => name === "headers")?.[1];
224
+ const bodySchema = entries.find(([name]) => name === "body")?.[1];
225
+ for (const [status, description] of statuses) {
226
+ let parts = partsByStatus.get(status);
227
+ if (!parts) {
228
+ parts = {
229
+ descriptions: [],
230
+ bodies: [],
231
+ headers: []
232
+ };
233
+ partsByStatus.set(status, parts);
234
+ }
235
+ if (description !== undefined) {
236
+ parts.descriptions.push(description);
237
+ }
238
+ if (headersSchema !== undefined) {
239
+ parts.headers.push(headersSchema);
240
+ }
241
+ if (bodySchema !== undefined) {
242
+ parts.bodies.push(bodySchema);
243
+ }
244
+ }
245
+ }
246
+ return partsByStatus;
247
+ }
248
+
249
+ function extractDetailedStatuses(schema) {
250
+ const statuses = new Map();
251
+ for (const member of flattenJsonUnionSchema(schema)) {
252
+ if (typeof member !== "object") {
253
+ return undefined;
254
+ }
255
+ const values = member.const !== undefined ? [member.const] : member.enum;
256
+ if (!values?.length) {
257
+ return undefined;
258
+ }
259
+ for (const value of values) {
260
+ if (!Number.isInteger(value) || value >= 400) {
261
+ return undefined;
262
+ }
263
+ if (!statuses.has(value)) {
264
+ statuses.set(value, member.description);
265
+ }
266
+ }
267
+ }
268
+ return statuses.size ? statuses : undefined;
269
+ }
270
+ export function buildErrorResponse(ctx, operation, def) {
271
+ const definitionsByStatus = new Map();
272
+ for (const code of Object.keys(def.errorMap)) {
273
+ const config = def.errorMap[code];
274
+ if (!config) {
275
+ continue;
276
+ }
277
+ const status = ctx.errorStatusMap[code] ?? DEFAULT_ERROR_STATUS;
278
+ const [dataJsonSchema, dataOptional] = ctx.convertSchemas(config.data !== undefined ? [config.data] : undefined, "output");
279
+ let definitions = definitionsByStatus.get(status);
280
+ if (!definitions) {
281
+ definitions = [];
282
+ definitionsByStatus.set(status, definitions);
283
+ }
284
+ definitions.push({
285
+ code,
286
+ dataJsonSchema,
287
+ dataOptional,
288
+ defaultMessage: config.message
289
+ });
290
+ }
291
+ if (!definitionsByStatus.size) {
292
+ return;
293
+ }
294
+ const undefinedErrorSchema = ctx.registry.register("UndefinedError", {
295
+ title: "UndefinedError",
296
+ type: "object",
297
+ properties: {
298
+ defined: { const: false },
299
+ code: { type: "string" },
300
+ message: { type: "string" },
301
+ data: {}
302
+ },
303
+ required: [
304
+ "defined",
305
+ "code",
306
+ "message"
307
+ ]
308
+ });
309
+ for (const [status, definitions] of definitionsByStatus.entries()) {
310
+ const descriptions = definitions.map(({ defaultMessage }) => defaultMessage).filter((m) => m !== undefined);
311
+ const definedErrors = definitions.map((def) => ({
312
+ ...def,
313
+ dataJsonSchema: ctx.registry.hoistDefs(def.dataJsonSchema, "output")
314
+ }));
315
+
316
+ const defaultSchema = () => combineJsonSchemasWithComposition("oneOf", [...definedErrors.map(({ code, dataJsonSchema, dataOptional }) => {
317
+ return ctx.registry.register(toErrorComponentName(code), {
318
+ title: code,
319
+ ...combineJsonObjectSchemaEntries([
320
+ [
321
+ "defined",
322
+ { const: true },
323
+ false
324
+ ],
325
+ [
326
+ "code",
327
+ { const: code },
328
+ false
329
+ ],
330
+ [
331
+ "message",
332
+ { type: "string" },
333
+ false
334
+ ],
335
+ [
336
+ "data",
337
+ dataJsonSchema,
338
+ dataOptional
339
+ ]
340
+ ])
341
+ });
342
+ }), undefinedErrorSchema]);
343
+ const responseSchema = ctx.errorResponseBodySchema === undefined ? defaultSchema() : value(ctx.errorResponseBodySchema, definedErrors, status, defaultSchema);
344
+ const responseObject = { description: descriptions.length ? descriptions.join(", ") : status.toString() };
345
+ if (responseSchema !== undefined && responseSchema !== null) {
346
+ responseObject.content = { [ctx.errorResponseContentType]: { schema: ctx.registry.toOpenAPISchema(responseSchema, "output") } };
347
+ }
348
+ operation.responses ??= {};
349
+ operation.responses[toResponseStatusKey(status)] = responseObject;
350
+ }
351
+ }
352
+
353
+ function toErrorComponentName(code) {
354
+ const name = code.split(/[^a-z0-9]+/i).filter(Boolean).map((part) => {
355
+ const rest = part.slice(1);
356
+ return part.charAt(0).toUpperCase() + (rest === rest.toUpperCase() ? rest.toLowerCase() : rest);
357
+ }).join("");
358
+ return name || "Error";
359
+ }
360
+ function toAsyncIteratorObjectContent(ctx, direction, [yieldSchema, yieldOptional], [returnSchema, returnOptional]) {
361
+ const schema = combineJsonSchemasWithComposition("oneOf", [
362
+ combineJsonObjectSchemaEntries([
363
+ [
364
+ "event",
365
+ { const: "message" },
366
+ false
367
+ ],
368
+ [
369
+ "data",
370
+ yieldSchema,
371
+ yieldOptional
372
+ ],
373
+ [
374
+ "id",
375
+ { type: "string" },
376
+ true
377
+ ],
378
+ [
379
+ "retry",
380
+ { type: "number" },
381
+ true
382
+ ]
383
+ ]),
384
+ combineJsonObjectSchemaEntries([
385
+ [
386
+ "event",
387
+ { const: "close" },
388
+ false
389
+ ],
390
+ [
391
+ "data",
392
+ returnSchema,
393
+ returnOptional
394
+ ],
395
+ [
396
+ "id",
397
+ { type: "string" },
398
+ true
399
+ ],
400
+ [
401
+ "retry",
402
+ { type: "number" },
403
+ true
404
+ ]
405
+ ]),
406
+ {
407
+ type: "object",
408
+ properties: {
409
+ event: { const: "error" },
410
+ data: {},
411
+ id: { type: "string" },
412
+ retry: { type: "number" }
413
+ },
414
+ required: ["event"]
415
+ }
416
+ ]);
417
+ return { "text/event-stream": { schema: ctx.registry.toOpenAPISchema(schema, direction) } };
418
+ }
419
+ function toBodyContent(ctx, direction, schema) {
420
+ const fileSchemasByMediaType = new Map();
421
+ const rest = flattenJsonUnionSchema(schema).filter((s) => {
422
+ if (!isJsonFileSchema(s)) {
423
+ return !isUnconstrainedSchema(s);
424
+ }
425
+ const contentMediaType = s.contentMediaType ?? "*/*";
426
+ const schemas = fileSchemasByMediaType.get(contentMediaType);
427
+ if (schemas) {
428
+ schemas.push(s);
429
+ } else {
430
+ fileSchemasByMediaType.set(contentMediaType, [s]);
431
+ }
432
+ return false;
433
+ });
434
+ const content = {};
435
+ if (rest.length > 0) {
436
+ const restSchema = fileSchemasByMediaType.size ? combineJsonSchemasWithComposition("anyOf", rest) : schema;
437
+ const hasNestedFiles = containsJsonFileSchema(restSchema);
438
+ const contentType = hasNestedFiles ? "multipart/form-data" : "application/json";
439
+ const fileSchemas = fileSchemasByMediaType.get(contentType);
440
+ fileSchemasByMediaType.delete(contentType);
441
+ content[contentType] = { schema: ctx.registry.toOpenAPISchema(combineJsonSchemasWithComposition("anyOf", [restSchema, ...fileSchemas ?? []]), direction) };
442
+ }
443
+ for (const [contentType, schemas] of fileSchemasByMediaType.entries()) {
444
+ content[contentType] = { schema: ctx.registry.toOpenAPISchema(combineJsonSchemasWithComposition("anyOf", schemas), direction) };
445
+ }
446
+ return content;
447
+ }
@@ -0,0 +1,87 @@
1
+ import type { AnyProcedureContract, RouterContract } from "@orpc/contract";
2
+ import type { JsonSchema, JsonSchemaConverter } from "@orpc/json-schema";
3
+ import type { AnyProcedure, AnyRouter } from "@orpc/server";
4
+ import type { Public, Value } from "@orpc/shared";
5
+ import type { OpenAPIErrorBodyDefinition } from "./openapi-generator-operation.mjs";
6
+ import type { OpenAPIDocument, OpenAPIV3_2, OpenAPIVersion } from "./types.mjs";
7
+ import { OpenAPIJsonSerializer } from "./openapi-json-serializer.mjs";
8
+ export { OpenAPIGeneratorError } from "./openapi-generator-operation.mjs";
9
+ export type { OpenAPIErrorBodyDefinition } from "./openapi-generator-operation.mjs";
10
+ export interface OpenAPIGeneratorOptions {
11
+ converters?: JsonSchemaConverter[] | undefined;
12
+ /**
13
+ * The serializer used to serialize the generated OpenAPI documentation
14
+ */
15
+ serializer?: Public<OpenAPIJsonSerializer> | undefined;
16
+ }
17
+ export interface OpenAPIGeneratorGenerateOptions<TVersion extends OpenAPIVersion> {
18
+ /**
19
+ * The OpenAPI version of the generated document.
20
+ * The document is generated as OpenAPI 3.2 and downgraded when an older version is requested.
21
+ * The minor version selects the conversion, the document carries the exact value, such as `3.1.0`.
22
+ *
23
+ * @default '3.2.0'
24
+ */
25
+ version?: TVersion | undefined;
26
+ /**
27
+ * OpenAPI 3.2 document fields to start from, such as `info`, `servers`, or `components`.
28
+ * They are downgraded with the rest of the document when an older `version` is requested.
29
+ * The `openapi` field is derived from `version`.
30
+ */
31
+ base?: Partial<Omit<OpenAPIV3_2.OpenAPIObject, "openapi">> | undefined;
32
+ /**
33
+ * Root-level `$defs` are always moved into `components.schemas`.
34
+ * Use this to customize the component name of a hoisted def.
35
+ *
36
+ * @remarks
37
+ * - The returned name is a preference, conflicting names are still postfixed (`Planet`, `PlanetInput`, `Planet2`, ...).
38
+ * - Return `undefined` to keep the original def name.
39
+ *
40
+ * @default defName => defName
41
+ */
42
+ componentName?: ((defName: string, defSchema: JsonSchema) => string | undefined) | undefined;
43
+ /**
44
+ * Filter procedures. Return `false` to exclude a procedure from the OpenAPI specification.
45
+ *
46
+ * @default true
47
+ */
48
+ filter?: Value<boolean, [contract: AnyProcedureContract | AnyProcedure, path: string[]]> | undefined;
49
+ /**
50
+ * Define a custom JSON schema for the error response body when using
51
+ * type-safe errors. Helps align ORPC error formatting with existing API
52
+ * response standards or conventions.
53
+ *
54
+ * @remarks
55
+ * - Return `defaultSchema()` to keep the default schema, or `null | undefined` to document an empty body, matching an `errorResponseBodyEncoder` that returns `undefined`.
56
+ * - The schema is an OpenAPI 3.2 Schema Object, it is downgraded with the rest of the document when an older `version` is requested.
57
+ */
58
+ errorResponseBodySchema?: Value<JsonSchema | null | undefined, [definedErrors: OpenAPIErrorBodyDefinition[], status: number, defaultSchema: () => JsonSchema]> | undefined;
59
+ /**
60
+ * Media type of error responses in the generated document, e.g. `application/problem+json`.
61
+ * Should match the handler's `errorResponseContentType`.
62
+ *
63
+ * @default 'application/json'
64
+ */
65
+ errorResponseContentType?: string | undefined;
66
+ /**
67
+ * Mapping ORPCError Code -> HTTP Status Code
68
+ * Codes missing from the map fall back to `DEFAULT_ERROR_STATUS` (400).
69
+ *
70
+ * @default COMMON_ERROR_STATUS_MAP
71
+ */
72
+ errorStatusMap?: Record<string, number> | undefined;
73
+ }
74
+ /**
75
+ * Generates an OpenAPI document from a contract or router.
76
+ * Relies on JSON schema converters to translate input, output, and error schemas into JSON Schemas.
77
+ *
78
+ * @see {@link https://orpc.dev/docs/openapi/specification#openapi-generator | OpenAPI Specification - OpenAPI Generator}
79
+ */
80
+ export declare class OpenAPIGenerator {
81
+ private readonly serializer;
82
+ private readonly converter;
83
+ constructor(options?: OpenAPIGeneratorOptions);
84
+ generate<TVersion extends OpenAPIVersion = "3.2.0">(router: RouterContract | AnyRouter, options?: OpenAPIGeneratorGenerateOptions<TVersion>): Promise<OpenAPIDocument<TVersion>>;
85
+ private convertSchema;
86
+ private convertSchemas;
87
+ }
@@ -0,0 +1,115 @@
1
+ import { downgradeSpecV31ToV30, downgradeSpecV32ToV31 } from "@openapi-spec/downgrader";
2
+ import { COMMON_ERROR_STATUS_MAP } from "@orpc/client";
3
+ import { combineJsonSchemasWithComposition, DelegatingJsonSchemaConverter, hoistRecursiveRefToDef, StandardJsonSchemaConverter } from "@orpc/json-schema";
4
+ import { walkProcedureContractsAsync } from "@orpc/server";
5
+ import { clone, mergeHttpPath, pathToHttpPath, toArray, value } from "@orpc/shared";
6
+ import { DEFAULT_OPENAPI_METHOD } from "./constants.mjs";
7
+ import { getOpenAPIMeta } from "./meta.mjs";
8
+ import { OpenAPIComponentRegistry } from "./openapi-generator-components.mjs";
9
+ import { buildErrorResponse, buildRequest, buildSuccessResponse, OpenAPIGeneratorError, toOpenAPIPath } from "./openapi-generator-operation.mjs";
10
+ import { OpenAPIJsonSerializer } from "./openapi-json-serializer.mjs";
11
+ import { getDynamicPathParams } from "./utils.mjs";
12
+ export { OpenAPIGeneratorError } from "./openapi-generator-operation.mjs";
13
+
14
+ export class OpenAPIGenerator {
15
+ serializer;
16
+ converter;
17
+ constructor(options = {}) {
18
+ this.serializer = options.serializer ?? new OpenAPIJsonSerializer();
19
+ this.converter = new DelegatingJsonSchemaConverter([...toArray(options.converters), new StandardJsonSchemaConverter()]);
20
+ }
21
+ async generate(router, options = {}) {
22
+ const version = options.version ?? "3.2.0";
23
+ const doc = {
24
+ ...clone(options.base),
25
+ openapi: "3.2.0",
26
+ info: options.base?.info ?? {
27
+ title: "API Reference",
28
+ version: "0.0.0"
29
+ }
30
+ };
31
+ const ctx = {
32
+ registry: new OpenAPIComponentRegistry(doc, options.componentName),
33
+ convertSchemas: (schemas, direction) => this.convertSchemas(schemas, direction),
34
+ errorStatusMap: options.errorStatusMap ?? COMMON_ERROR_STATUS_MAP,
35
+ errorResponseBodySchema: options.errorResponseBodySchema,
36
+ errorResponseContentType: options.errorResponseContentType ?? "application/json"
37
+ };
38
+ const errors = [];
39
+ await walkProcedureContractsAsync(router, (contract, path) => {
40
+ if (value(options.filter, contract, path) === false) {
41
+ return;
42
+ }
43
+ try {
44
+ const def = contract["~orpc"];
45
+ const meta = getOpenAPIMeta(contract);
46
+ const method = (meta?.method ?? DEFAULT_OPENAPI_METHOD).toLowerCase();
47
+ if (method === "query" && !version.startsWith("3.2.")) {
48
+ throw new OpenAPIGeneratorError(`QUERY operations require OpenAPI 3.2, but version "${version}" was requested.`);
49
+ }
50
+ const postPath = meta?.path ?? pathToHttpPath(path);
51
+ const httpPath = meta?.prefix ? mergeHttpPath(meta.prefix, postPath) : postPath;
52
+ const dynamicPathParams = getDynamicPathParams(httpPath);
53
+ const openApiPath = toOpenAPIPath(httpPath, dynamicPathParams);
54
+ let operation;
55
+ if (meta?.spec !== undefined && typeof meta.spec !== "function") {
56
+ operation = meta.spec;
57
+ } else {
58
+ operation = {
59
+ operationId: meta?.operationId ?? path.join("."),
60
+ summary: meta?.summary,
61
+ description: meta?.description,
62
+ deprecated: meta?.deprecated,
63
+ tags: meta?.tags?.map((tag) => tag)
64
+ };
65
+ buildRequest(ctx, operation, def, meta, dynamicPathParams);
66
+ buildSuccessResponse(ctx, operation, def, meta);
67
+ buildErrorResponse(ctx, operation, def);
68
+ }
69
+ if (typeof meta?.spec === "function") {
70
+ operation = meta.spec(operation);
71
+ }
72
+ doc.paths ??= {};
73
+ doc.paths[openApiPath] ??= {};
74
+ doc.paths[openApiPath][method] = operation;
75
+ } catch (e) {
76
+ if (!(e instanceof OpenAPIGeneratorError)) {
77
+ throw e;
78
+ }
79
+ errors.push(`Procedure at ${path.join(".") || "(root)"}: ${e.message}`);
80
+ }
81
+ });
82
+ if (errors.length) {
83
+ throw new OpenAPIGeneratorError(`[OpenAPIGenerator] Failed to generate the OpenAPI document (${errors.length} error${errors.length === 1 ? "" : "s"}):\n\n${errors.join("\n\n")}`);
84
+ }
85
+ const versioned = toVersionedOpenAPIDocument(doc, version);
86
+ return this.serializer.serializeJson(versioned).json;
87
+ }
88
+ convertSchema(schema, direction) {
89
+ const [jsonSchema, optional] = this.converter.convert(schema, direction);
90
+
91
+
92
+ return [hoistRecursiveRefToDef(strip$schemaField(jsonSchema)), optional];
93
+ }
94
+ convertSchemas(schemas, direction) {
95
+ if (!schemas || schemas.length <= 1) {
96
+ return this.convertSchema(schemas?.[0], direction);
97
+ }
98
+ const results = schemas.map((s) => this.convertSchema(s, direction));
99
+ return [combineJsonSchemasWithComposition("allOf", results.map(([jsonSchema]) => jsonSchema)), results.every(([, optional]) => optional)];
100
+ }
101
+ }
102
+ function toVersionedOpenAPIDocument(doc, version) {
103
+ const downgraded = version.startsWith("3.2.") ? doc : version.startsWith("3.1.") ? downgradeSpecV32ToV31(doc) : downgradeSpecV31ToV30(downgradeSpecV32ToV31(doc));
104
+ return {
105
+ ...downgraded,
106
+ openapi: version
107
+ };
108
+ }
109
+ function strip$schemaField(schema) {
110
+ if (typeof schema !== "object") {
111
+ return schema;
112
+ }
113
+ const { $schema, ...rest } = schema;
114
+ return rest;
115
+ }