@orpc/openapi 2.0.0-beta.5 → 2.0.0-beta.50

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 (90) hide show
  1. package/README.md +137 -102
  2. package/dist/adapters/aws-lambda/index.d.ts +3 -0
  3. package/dist/adapters/aws-lambda/index.js +1 -0
  4. package/dist/adapters/aws-lambda/openapi-handler.d.ts +17 -0
  5. package/dist/adapters/aws-lambda/openapi-handler.js +20 -0
  6. package/dist/adapters/fastify/index.d.ts +2 -0
  7. package/dist/adapters/fastify/index.js +1 -0
  8. package/dist/adapters/fastify/openapi-handler.d.ts +14 -0
  9. package/dist/adapters/fastify/openapi-handler.js +17 -0
  10. package/dist/adapters/fetch/index.d.ts +3 -27
  11. package/dist/adapters/fetch/index.js +2 -0
  12. package/dist/adapters/fetch/openapi-handler.d.ts +14 -0
  13. package/dist/adapters/fetch/openapi-handler.js +17 -0
  14. package/dist/adapters/fetch/openapi-link.d.ts +20 -0
  15. package/dist/adapters/fetch/openapi-link.js +22 -0
  16. package/dist/adapters/node/index.d.ts +2 -18
  17. package/dist/adapters/node/index.js +1 -0
  18. package/dist/adapters/node/openapi-handler.d.ts +14 -0
  19. package/dist/adapters/node/openapi-handler.js +17 -0
  20. package/dist/adapters/standard/index.d.ts +4 -50
  21. package/dist/adapters/standard/index.js +3 -0
  22. package/dist/adapters/standard/openapi-handler-codec.d.ts +61 -0
  23. package/dist/adapters/standard/openapi-handler-codec.js +158 -0
  24. package/dist/adapters/standard/openapi-link-codec.d.ts +58 -0
  25. package/dist/adapters/standard/openapi-link-codec.js +290 -0
  26. package/dist/adapters/standard/openapi-matcher.d.ts +29 -0
  27. package/dist/adapters/standard/openapi-matcher.js +78 -0
  28. package/dist/adapters/standard/utils.js +31 -0
  29. package/dist/bracket-notation.d.ts +26 -0
  30. package/dist/bracket-notation.js +135 -0
  31. package/dist/client-factory.d.ts +24 -0
  32. package/dist/client-factory.js +15 -0
  33. package/dist/constants.d.ts +1 -0
  34. package/dist/constants.js +5 -0
  35. package/dist/extensions/route.d.ts +36 -42
  36. package/dist/extensions/route.js +13 -0
  37. package/dist/helpers/{index.d.mts → form-data.d.ts} +11 -5
  38. package/dist/helpers/form-data.js +78 -0
  39. package/dist/helpers/index.d.ts +2 -51
  40. package/dist/helpers/index.js +1 -0
  41. package/dist/index.d.ts +15 -120
  42. package/dist/index.js +11 -0
  43. package/dist/meta.d.ts +325 -0
  44. package/dist/meta.js +66 -0
  45. package/dist/openapi-generator-components.d.ts +2 -0
  46. package/dist/openapi-generator-components.js +227 -0
  47. package/dist/openapi-generator-operation.d.ts +13 -0
  48. package/dist/openapi-generator-operation.js +401 -0
  49. package/dist/openapi-generator.d.ts +87 -0
  50. package/dist/openapi-generator.js +119 -0
  51. package/dist/openapi-json-serializer.d.ts +79 -0
  52. package/dist/openapi-json-serializer.js +221 -0
  53. package/dist/openapi-serializer.d.ts +42 -0
  54. package/dist/openapi-serializer.js +69 -0
  55. package/dist/plugins/index.d.ts +2 -90
  56. package/dist/plugins/index.js +1 -0
  57. package/dist/plugins/openapi-reference.d.ts +112 -0
  58. package/dist/plugins/openapi-reference.js +164 -0
  59. package/dist/router-utils.d.ts +17 -0
  60. package/dist/router-utils.js +32 -0
  61. package/dist/types.d.ts +27 -0
  62. package/dist/utils.d.ts +9 -0
  63. package/dist/utils.js +44 -0
  64. package/package.json +87 -49
  65. package/dist/adapters/fetch/index.d.mts +0 -27
  66. package/dist/adapters/fetch/index.mjs +0 -34
  67. package/dist/adapters/node/index.d.mts +0 -18
  68. package/dist/adapters/node/index.mjs +0 -21
  69. package/dist/adapters/standard/index.d.mts +0 -50
  70. package/dist/adapters/standard/index.mjs +0 -12
  71. package/dist/extensions/route.d.mts +0 -43
  72. package/dist/extensions/route.mjs +0 -14
  73. package/dist/helpers/index.mjs +0 -39
  74. package/dist/index.d.mts +0 -120
  75. package/dist/index.mjs +0 -930
  76. package/dist/plugins/index.d.mts +0 -90
  77. package/dist/plugins/index.mjs +0 -162
  78. package/dist/shared/openapi.7vgmPxca.d.ts +0 -82
  79. package/dist/shared/openapi.B2SK0ZAr.mjs +0 -359
  80. package/dist/shared/openapi.B9PQzqBn.mjs +0 -49
  81. package/dist/shared/openapi.BQzzr4-4.d.ts +0 -299
  82. package/dist/shared/openapi.BcEtAxQj.d.mts +0 -299
  83. package/dist/shared/openapi.Bt87OzTt.mjs +0 -131
  84. package/dist/shared/openapi.C7m7NAmH.d.mts +0 -142
  85. package/dist/shared/openapi.C7m7NAmH.d.ts +0 -142
  86. package/dist/shared/openapi.CTlpLuKN.mjs +0 -318
  87. package/dist/shared/openapi.CX6Ri5dP.d.mts +0 -82
  88. package/dist/shared/openapi.CYgMBSUF.d.mts +0 -18
  89. package/dist/shared/openapi.CYgMBSUF.d.ts +0 -18
  90. package/dist/shared/openapi.DmAa7YPO.mjs +0 -275
@@ -0,0 +1,401 @@
1
+ import "./constants.js";
2
+ import { isBodylessMethod } from "./utils.js";
3
+ import { getOwn, stringifyJSON, value } from "@orpc/shared";
4
+ import { getAsyncIteratorObjectSchemasDetails } from "@orpc/contract";
5
+ import { combineJsonObjectSchemaEntries, combineJsonSchemasWithComposition, containsJsonFileSchema, extractJsonObjectSchemaAdditionalProperties, extractJsonObjectSchemaEntries, flattenJsonUnionSchema, isJsonFileSchema, isJsonPrimitiveSchema, isUnconstrainedSchema, matchArrayableJsonSchema, resolveJsonSchemaRootLocalRef } from "@orpc/json-schema";
6
+ import { DEFAULT_ERROR_STATUS, DEFAULT_SUCCESS_STATUS } from "@orpc/server";
7
+ // src/openapi-generator-operation.ts
8
+ var OpenAPIGeneratorError = class extends TypeError {};
9
+ function toOpenAPIPath(path, dynamicPathParams) {
10
+ if (!dynamicPathParams?.length) return path;
11
+ let normalized = "";
12
+ let currentIndex = 0;
13
+ for (const param of dynamicPathParams) {
14
+ normalized += path.slice(currentIndex, param.startIndex);
15
+ normalized += `{${param.parameterName}}`;
16
+ currentIndex = param.startIndex + param.segment.length;
17
+ }
18
+ normalized += path.slice(currentIndex);
19
+ return normalized;
20
+ }
21
+ function buildRequest(ctx, operation, def, meta, dynamicPathParams) {
22
+ const method = meta?.method ?? "POST";
23
+ const inputStructure = meta?.inputStructure ?? "compact";
24
+ const dynamicParams = dynamicPathParams?.map((v) => v.parameterName);
25
+ if (inputStructure === "compact") {
26
+ const iteratorDetails = getAsyncIteratorObjectSchemasDetails(def.inputSchemas);
27
+ if (iteratorDetails) {
28
+ renderPathParameters(ctx, operation, dynamicParams, void 0, void 0);
29
+ operation.requestBody = {
30
+ required: true,
31
+ content: toAsyncIteratorObjectContent(ctx, "input", ctx.convertSchemas(iteratorDetails.yieldSchemas, "input"), ctx.convertSchemas(iteratorDetails.returnSchemas, "input"))
32
+ };
33
+ return;
34
+ }
35
+ }
36
+ const [schema, optional] = ctx.convertSchemas(def.inputSchemas, "input");
37
+ if (isUnconstrainedSchema(schema) && !dynamicParams?.length) return;
38
+ const parts = inputStructure === "compact" ? extractCompactRequestParts(schema, optional, method, dynamicParams) : extractDetailedRequestParts(schema);
39
+ renderPathParameters(ctx, operation, dynamicParams, parts.paramsEntries, meta?.paramsStyles);
40
+ renderQueryParameters(ctx, operation, parts.queryEntries, meta?.queryStyles);
41
+ renderHeaderParameters(ctx, operation, parts.headersEntries);
42
+ if (parts.bodySchema !== void 0) operation.requestBody = {
43
+ required: parts.bodyOptional ? void 0 : true,
44
+ content: toBodyContent(ctx, "input", parts.bodySchema)
45
+ };
46
+ }
47
+ function extractCompactRequestParts(schema, optional, method, dynamicParams) {
48
+ const entries = extractJsonObjectSchemaEntries(schema);
49
+ if (!entries && isBodylessMethod(method)) 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).`);
50
+ const paramsEntries = entries?.filter(([name]) => dynamicParams?.includes(name));
51
+ const restEntries = entries?.filter(([name]) => !dynamicParams?.includes(name));
52
+ const bodySchema = !!isBodylessMethod(method) ? void 0 : !dynamicParams?.length ? schema : restEntries ? combineJsonObjectSchemaEntries(restEntries, extractJsonObjectSchemaAdditionalProperties(schema)) : void 0;
53
+ return {
54
+ paramsEntries,
55
+ queryEntries: isBodylessMethod(method) ? restEntries : void 0,
56
+ headersEntries: void 0,
57
+ bodySchema,
58
+ bodyOptional: !dynamicParams?.length ? optional : restEntries?.every(([, , optional]) => optional)
59
+ };
60
+ }
61
+ function extractDetailedRequestParts(schema) {
62
+ const entries = extractJsonObjectSchemaEntries(schema);
63
+ if (!entries) 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 }");
64
+ const section = (name) => entries.find(([entryName]) => entryName === name);
65
+ return {
66
+ paramsEntries: extractJsonObjectSchemaEntries(section("params")?.[1] ?? false),
67
+ queryEntries: extractJsonObjectSchemaEntries(section("query")?.[1] ?? false),
68
+ headersEntries: extractJsonObjectSchemaEntries(section("headers")?.[1] ?? false),
69
+ bodySchema: section("body")?.[1],
70
+ bodyOptional: section("body")?.[2]
71
+ };
72
+ }
73
+ function renderPathParameters(ctx, operation, dynamicParams, paramsEntries, paramsStyles) {
74
+ if (!dynamicParams?.length) return;
75
+ if (!paramsEntries) 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.`);
76
+ for (const name of dynamicParams) {
77
+ const entry = paramsEntries.find(([entryName]) => entryName === name);
78
+ if (!entry) 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)"}`);
79
+ if (entry[2]) throw new OpenAPIGeneratorError(`dynamic param "${name}" is optional in the input schema.\n OpenAPI requires path params to be required. Make "${name}" required.`);
80
+ const style = paramsStyles?.[name];
81
+ const parameter = {
82
+ in: "path",
83
+ required: true,
84
+ name,
85
+ schema: ctx.registry.toOpenAPISchema(entry[1], "input")
86
+ };
87
+ if (style === "comma-delimited-array" || style === "comma-delimited-object") {
88
+ parameter.style = "simple";
89
+ parameter.explode = false;
90
+ }
91
+ operation.parameters ??= [];
92
+ operation.parameters.push(parameter);
93
+ }
94
+ }
95
+ function renderQueryParameters(ctx, operation, queryEntries, queryStyles) {
96
+ for (const [name, schema, optional] of queryEntries ?? []) {
97
+ const style = queryStyles?.[name];
98
+ const parameter = {
99
+ in: "query",
100
+ name,
101
+ schema: ctx.registry.toOpenAPISchema(schema, "input"),
102
+ allowEmptyValue: true,
103
+ allowReserved: true
104
+ };
105
+ if (!optional) parameter.required = true;
106
+ if (style === "comma-delimited-array" || style === "comma-delimited-object") parameter.explode = false;
107
+ else if (style === "pipe-delimited-array" || style === "pipe-delimited-object") parameter.style = "pipeDelimited";
108
+ else if (style === "space-delimited-array" || style === "space-delimited-object") parameter.style = "spaceDelimited";
109
+ else if (style === "json") {
110
+ parameter.content = { "application/json": { schema: parameter.schema } };
111
+ delete parameter.schema;
112
+ delete parameter.allowReserved;
113
+ } else if (style === void 0) {
114
+ if (!flattenJsonUnionSchema(schema).every(isPrimitive)) {
115
+ const arrayable = matchArrayableJsonSchema(schema);
116
+ if (!arrayable || !flattenJsonUnionSchema(arrayable[0]).every(isPrimitive)) {
117
+ parameter.style = "deepObject";
118
+ parameter.explode = true;
119
+ }
120
+ }
121
+ }
122
+ operation.parameters ??= [];
123
+ operation.parameters.push(parameter);
124
+ }
125
+ }
126
+ function renderHeaderParameters(ctx, operation, headersEntries) {
127
+ for (const [name, schema, optional] of headersEntries ?? []) {
128
+ operation.parameters ??= [];
129
+ operation.parameters.push({
130
+ in: "header",
131
+ name,
132
+ required: optional ? void 0 : true,
133
+ schema: ctx.registry.toOpenAPISchema(schema, "input")
134
+ });
135
+ }
136
+ }
137
+ function buildSuccessResponse(ctx, operation, def, meta) {
138
+ const status = meta?.successStatus ?? DEFAULT_SUCCESS_STATUS;
139
+ const description = meta?.successDescription ?? "OK";
140
+ const outputStructure = meta?.outputStructure ?? "compact";
141
+ if (outputStructure === "compact") {
142
+ const iteratorDetails = getAsyncIteratorObjectSchemasDetails(def.outputSchemas);
143
+ if (iteratorDetails) {
144
+ operation.responses ??= {};
145
+ operation.responses[toResponseStatusKey(status)] = {
146
+ description,
147
+ content: toAsyncIteratorObjectContent(ctx, "output", ctx.convertSchemas(iteratorDetails.yieldSchemas, "output"), ctx.convertSchemas(iteratorDetails.returnSchemas, "output"))
148
+ };
149
+ return;
150
+ }
151
+ }
152
+ const [schema] = ctx.convertSchemas(def.outputSchemas, "output");
153
+ if (isUnconstrainedSchema(schema) || outputStructure === "compact") {
154
+ operation.responses ??= {};
155
+ operation.responses[toResponseStatusKey(status)] = {
156
+ description,
157
+ content: toBodyContent(ctx, "output", schema)
158
+ };
159
+ return;
160
+ }
161
+ for (const [responseStatus, parts] of extractDetailedResponseParts(schema, status)) {
162
+ const responseObject = { description: parts.descriptions.length ? parts.descriptions.join(", ") : description };
163
+ if (parts.bodies.length) responseObject.content = toBodyContent(ctx, "output", combineJsonSchemasWithComposition("anyOf", parts.bodies));
164
+ if (parts.headers.length) extractJsonObjectSchemaEntries(combineJsonSchemasWithComposition("anyOf", parts.headers))?.forEach(([name, schema, optional]) => {
165
+ responseObject.headers ??= {};
166
+ responseObject.headers[name] = {
167
+ required: optional ? void 0 : true,
168
+ schema: ctx.registry.toOpenAPISchema(schema, "output")
169
+ };
170
+ });
171
+ operation.responses ??= {};
172
+ operation.responses[toResponseStatusKey(responseStatus)] = responseObject;
173
+ }
174
+ }
175
+ /**
176
+ * Formats a numeric HTTP status as a Responses Object key.
177
+ */
178
+ function toResponseStatusKey(status) {
179
+ return String(status);
180
+ }
181
+ /**
182
+ * Flattens a detailed output schema (a union of `{ status?, headers?, body? }` objects)
183
+ * into per-status response pieces.
184
+ */
185
+ function extractDetailedResponseParts(schema, defaultStatus) {
186
+ const partsByStatus = /* @__PURE__ */ new Map();
187
+ for (const item of flattenJsonUnionSchema(schema)) {
188
+ const entries = extractJsonObjectSchemaEntries(item);
189
+ if (!entries) 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 }");
190
+ const [, statusSchema, statusOptional = true] = entries.find(([name]) => name === "status") ?? [];
191
+ const statuses = statusSchema === void 0 ? /* @__PURE__ */ new Map() : extractDetailedStatuses(statusSchema);
192
+ if (!statuses) throw new OpenAPIGeneratorError(`invalid "status" field in the detailed output schema.
193
+ Expected: literal integers below 400 (const, enum, or a union of them)
194
+ Received: ${stringifyJSON(statusSchema)}`);
195
+ if (statusOptional && !statuses.has(defaultStatus)) statuses.set(defaultStatus, void 0);
196
+ const headersSchema = entries.find(([name]) => name === "headers")?.[1];
197
+ const bodySchema = entries.find(([name]) => name === "body")?.[1];
198
+ for (const [status, description] of statuses) {
199
+ let parts = partsByStatus.get(status);
200
+ if (!parts) {
201
+ parts = {
202
+ descriptions: [],
203
+ bodies: [],
204
+ headers: []
205
+ };
206
+ partsByStatus.set(status, parts);
207
+ }
208
+ if (description !== void 0) parts.descriptions.push(description);
209
+ if (headersSchema !== void 0) parts.headers.push(headersSchema);
210
+ if (bodySchema !== void 0) parts.bodies.push(bodySchema);
211
+ }
212
+ }
213
+ return partsByStatus;
214
+ }
215
+ /**
216
+ * Collects every status a detailed output `status` schema allows, mapped to its description.
217
+ * Accepts `const`, `enum` (how Effect, arktype, and valibot `picklist` emit literals), or a union of them.
218
+ * Returns `undefined` when any member is not a literal integer below 400.
219
+ */
220
+ function extractDetailedStatuses(schema) {
221
+ const statuses = /* @__PURE__ */ new Map();
222
+ for (const member of flattenJsonUnionSchema(schema)) {
223
+ if (typeof member !== "object") return;
224
+ const values = member.const !== void 0 ? [member.const] : member.enum;
225
+ if (!values?.length) return;
226
+ for (const value of values) {
227
+ if (!Number.isInteger(value) || value >= 400) return;
228
+ if (!statuses.has(value)) statuses.set(value, member.description);
229
+ }
230
+ }
231
+ return statuses.size ? statuses : void 0;
232
+ }
233
+ function buildErrorResponse(ctx, operation, def) {
234
+ const definitionsByStatus = /* @__PURE__ */ new Map();
235
+ for (const code of Object.keys(def.errorMap)) {
236
+ const config = def.errorMap[code];
237
+ if (!config) continue;
238
+ const status = getOwn(ctx.errorStatusMap, code) ?? DEFAULT_ERROR_STATUS;
239
+ const [dataJsonSchema, dataOptional] = ctx.convertSchemas(config.data !== void 0 ? [config.data] : void 0, "output");
240
+ let definitions = definitionsByStatus.get(status);
241
+ if (!definitions) {
242
+ definitions = [];
243
+ definitionsByStatus.set(status, definitions);
244
+ }
245
+ definitions.push({
246
+ code,
247
+ dataJsonSchema,
248
+ dataOptional,
249
+ defaultMessage: config.message
250
+ });
251
+ }
252
+ if (!definitionsByStatus.size) return;
253
+ const undefinedErrorSchema = ctx.registry.register("UndefinedError", {
254
+ title: "UndefinedError",
255
+ type: "object",
256
+ properties: {
257
+ defined: { const: false },
258
+ code: { type: "string" },
259
+ message: { type: "string" },
260
+ data: {}
261
+ },
262
+ required: [
263
+ "defined",
264
+ "code",
265
+ "message"
266
+ ]
267
+ });
268
+ for (const [status, definitions] of definitionsByStatus.entries()) {
269
+ const descriptions = definitions.map(({ defaultMessage }) => defaultMessage).filter((m) => m !== void 0);
270
+ const definedErrors = definitions.map((def) => ({
271
+ ...def,
272
+ dataJsonSchema: ctx.registry.hoistDefs(def.dataJsonSchema, "output")
273
+ }));
274
+ const defaultSchema = () => combineJsonSchemasWithComposition("oneOf", [...definedErrors.map(({ code, dataJsonSchema, dataOptional }) => {
275
+ return ctx.registry.register(toErrorComponentName(code), {
276
+ title: code,
277
+ ...combineJsonObjectSchemaEntries([
278
+ [
279
+ "defined",
280
+ { const: true },
281
+ false
282
+ ],
283
+ [
284
+ "code",
285
+ { const: code },
286
+ false
287
+ ],
288
+ [
289
+ "message",
290
+ { type: "string" },
291
+ false
292
+ ],
293
+ [
294
+ "data",
295
+ dataJsonSchema,
296
+ dataOptional
297
+ ]
298
+ ])
299
+ });
300
+ }), undefinedErrorSchema]);
301
+ const responseSchema = ctx.errorResponseBodySchema === void 0 ? defaultSchema() : value(ctx.errorResponseBodySchema, definedErrors, status, defaultSchema);
302
+ const responseObject = { description: descriptions.length ? descriptions.join(", ") : status.toString() };
303
+ if (responseSchema !== void 0 && responseSchema !== null) responseObject.content = { [ctx.errorResponseContentType]: { schema: ctx.registry.toOpenAPISchema(responseSchema, "output") } };
304
+ operation.responses ??= {};
305
+ operation.responses[toResponseStatusKey(status)] = responseObject;
306
+ }
307
+ }
308
+ /**
309
+ * Converts an error code into a component name, e.g. `BAD_REQUEST` -> `BadRequest`.
310
+ */
311
+ function toErrorComponentName(code) {
312
+ return code.split(/[^a-z0-9]+/i).filter(Boolean).map((part) => {
313
+ const rest = part.slice(1);
314
+ return part.charAt(0).toUpperCase() + (rest === rest.toUpperCase() ? rest.toLowerCase() : rest);
315
+ }).join("") || "Error";
316
+ }
317
+ function toAsyncIteratorObjectContent(ctx, direction, [yieldSchema, yieldOptional], [returnSchema, returnOptional]) {
318
+ const schema = combineJsonSchemasWithComposition("oneOf", [
319
+ combineJsonObjectSchemaEntries([
320
+ [
321
+ "event",
322
+ { const: "message" },
323
+ false
324
+ ],
325
+ [
326
+ "data",
327
+ yieldSchema,
328
+ yieldOptional
329
+ ],
330
+ [
331
+ "id",
332
+ { type: "string" },
333
+ true
334
+ ],
335
+ [
336
+ "retry",
337
+ { type: "number" },
338
+ true
339
+ ]
340
+ ]),
341
+ combineJsonObjectSchemaEntries([
342
+ [
343
+ "event",
344
+ { const: "close" },
345
+ false
346
+ ],
347
+ [
348
+ "data",
349
+ returnSchema,
350
+ returnOptional
351
+ ],
352
+ [
353
+ "id",
354
+ { type: "string" },
355
+ true
356
+ ],
357
+ [
358
+ "retry",
359
+ { type: "number" },
360
+ true
361
+ ]
362
+ ]),
363
+ {
364
+ type: "object",
365
+ properties: {
366
+ event: { const: "error" },
367
+ data: {},
368
+ id: { type: "string" },
369
+ retry: { type: "number" }
370
+ },
371
+ required: ["event"]
372
+ }
373
+ ]);
374
+ return { "text/event-stream": { schema: ctx.registry.toOpenAPISchema(schema, direction) } };
375
+ }
376
+ function toBodyContent(ctx, direction, schema) {
377
+ const fileSchemasByMediaType = /* @__PURE__ */ new Map();
378
+ const rest = flattenJsonUnionSchema(schema).filter((s) => {
379
+ const resolved = resolveJsonSchemaRootLocalRef(s);
380
+ if (!isJsonFileSchema(resolved)) return !isUnconstrainedSchema(s);
381
+ const contentMediaType = resolved.contentMediaType ?? "*/*";
382
+ const schemas = fileSchemasByMediaType.get(contentMediaType);
383
+ if (schemas) schemas.push(s);
384
+ else fileSchemasByMediaType.set(contentMediaType, [s]);
385
+ return false;
386
+ });
387
+ const content = {};
388
+ if (rest.length > 0) {
389
+ const restSchema = fileSchemasByMediaType.size ? combineJsonSchemasWithComposition("anyOf", rest) : schema;
390
+ const contentType = containsJsonFileSchema(restSchema) ? "multipart/form-data" : "application/json";
391
+ const fileSchemas = fileSchemasByMediaType.get(contentType);
392
+ fileSchemasByMediaType.delete(contentType);
393
+ content[contentType] = { schema: ctx.registry.toOpenAPISchema(combineJsonSchemasWithComposition("anyOf", [restSchema, ...fileSchemas ?? []]), direction) };
394
+ }
395
+ for (const [contentType, schemas] of fileSchemasByMediaType.entries()) content[contentType] = { schema: ctx.registry.toOpenAPISchema(combineJsonSchemasWithComposition("anyOf", schemas), direction) };
396
+ return content;
397
+ }
398
+ function isPrimitive(schema) {
399
+ return isJsonPrimitiveSchema(resolveJsonSchemaRootLocalRef(schema));
400
+ }
401
+ export { OpenAPIGeneratorError, buildErrorResponse, buildRequest, buildSuccessResponse, toOpenAPIPath };
@@ -0,0 +1,87 @@
1
+ import { OpenAPIErrorBodyDefinition, OpenAPIGeneratorError } from "./openapi-generator-operation.js";
2
+ import { OpenAPIJsonSerializer } from "./openapi-json-serializer.js";
3
+ import { OpenAPIDocument, OpenAPIV3_2, OpenAPIVersion } from "./types.js";
4
+ import { Public, Value } from "@orpc/shared";
5
+ import { AnyProcedureContract, RouterContract } from "@orpc/contract";
6
+ import { JsonSchema, JsonSchemaConverter } from "@orpc/json-schema";
7
+ import { AnyProcedure, AnyRouter } from "@orpc/server";
8
+ export interface OpenAPIGeneratorOptions {
9
+ converters?: JsonSchemaConverter[] | undefined;
10
+ /**
11
+ * The serializer used to serialize the generated OpenAPI documentation
12
+ */
13
+ serializer?: Public<OpenAPIJsonSerializer> | undefined;
14
+ }
15
+ export interface OpenAPIGeneratorGenerateOptions<TVersion extends OpenAPIVersion> {
16
+ /**
17
+ * The OpenAPI version of the generated document.
18
+ * The document is generated as OpenAPI 3.2 and downgraded when an older version is requested.
19
+ * The minor version selects the conversion, the document carries the exact value, such as `3.1.0`.
20
+ *
21
+ * @default '3.2.0'
22
+ */
23
+ version?: TVersion | undefined;
24
+ /**
25
+ * OpenAPI 3.2 document fields to start from, such as `info`, `servers`, or `components`.
26
+ * They are downgraded with the rest of the document when an older `version` is requested.
27
+ * The `openapi` field is derived from `version`.
28
+ */
29
+ base?: Partial<Omit<OpenAPIV3_2.OpenAPIObject, "openapi">> | undefined;
30
+ /**
31
+ * Root-level `$defs` are always moved into `components.schemas`.
32
+ * Use this to customize the component name of a hoisted def.
33
+ *
34
+ * @remarks
35
+ * - Characters OpenAPI does not allow in component keys (anything but `a-z`, `A-Z`, `0-9`, `.`, `_`, `-`)
36
+ * are replaced by `_` in the returned name, e.g. `User Profile` becomes `User_Profile`.
37
+ * - The returned name is a preference, conflicting names are still postfixed (`Planet`, `PlanetInput`, `Planet2`, ...).
38
+ *
39
+ * @default defName => defName
40
+ */
41
+ componentName?: ((defName: string, defSchema: JsonSchema) => string) | undefined;
42
+ /**
43
+ * Filter procedures. Return `false` to exclude a procedure from the OpenAPI specification.
44
+ *
45
+ * @default true
46
+ */
47
+ filter?: Value<boolean, [contract: AnyProcedureContract | AnyProcedure, path: string[]]> | undefined;
48
+ /**
49
+ * Define a custom JSON schema for the error response body when using
50
+ * type-safe errors. Helps align ORPC error formatting with existing API
51
+ * response standards or conventions.
52
+ *
53
+ * @remarks
54
+ * - Return `defaultSchema()` to keep the default schema, or `null | undefined` to document an empty body, matching an `errorResponseBodyEncoder` that returns `undefined`.
55
+ * - The schema is an OpenAPI 3.2 Schema Object, it is downgraded with the rest of the document when an older `version` is requested.
56
+ */
57
+ errorResponseBodySchema?: Value<JsonSchema | null | undefined, [definedErrors: OpenAPIErrorBodyDefinition[], status: number, defaultSchema: () => JsonSchema]> | undefined;
58
+ /**
59
+ * Media type of error responses in the generated document, e.g. `application/problem+json`.
60
+ * Should match the handler's `errorResponseContentType`.
61
+ *
62
+ * @default 'application/json'
63
+ */
64
+ errorResponseContentType?: string | undefined;
65
+ /**
66
+ * Mapping ORPCError Code -> HTTP Status Code
67
+ * Codes missing from the map fall back to `DEFAULT_ERROR_STATUS` (400).
68
+ *
69
+ * @default COMMON_ERROR_STATUS_MAP
70
+ */
71
+ errorStatusMap?: Record<string, number> | undefined;
72
+ }
73
+ /**
74
+ * Generates an OpenAPI document from a contract or router.
75
+ * Relies on JSON schema converters to translate input, output, and error schemas into JSON Schemas.
76
+ *
77
+ * @see {@link https://orpc.dev/docs/openapi/specification#openapi-generator | OpenAPI Specification - OpenAPI Generator}
78
+ */
79
+ export declare class OpenAPIGenerator {
80
+ private readonly serializer;
81
+ private readonly converter;
82
+ constructor(options?: OpenAPIGeneratorOptions);
83
+ generate<TVersion extends OpenAPIVersion = "3.2.0">(router: RouterContract | AnyRouter, options?: OpenAPIGeneratorGenerateOptions<TVersion>): Promise<OpenAPIDocument<TVersion>>;
84
+ private convertSchema;
85
+ private convertSchemas;
86
+ }
87
+ export { type OpenAPIErrorBodyDefinition, OpenAPIGeneratorError };
@@ -0,0 +1,119 @@
1
+ import "./constants.js";
2
+ import { getOpenAPIMeta } from "./meta.js";
3
+ import { OpenAPIComponentRegistry } from "./openapi-generator-components.js";
4
+ import { OpenAPIGeneratorError, buildErrorResponse, buildRequest, buildSuccessResponse, toOpenAPIPath } from "./openapi-generator-operation.js";
5
+ import { OpenAPIJsonSerializer } from "./openapi-json-serializer.js";
6
+ import { getDynamicPathParams } from "./utils.js";
7
+ import { clone, mergeHttpPath, pathToHttpPath, toArray, value } from "@orpc/shared";
8
+ import { downgradeSpecV31ToV30, downgradeSpecV32ToV31 } from "@openapi-spec/downgrader";
9
+ import { COMMON_ERROR_STATUS_MAP } from "@orpc/client";
10
+ import { DelegatingJsonSchemaConverter, StandardJsonSchemaConverter, combineJsonSchemasWithComposition, hoistRecursiveRefToDef } from "@orpc/json-schema";
11
+ import { walkProcedureContractsAsync } from "@orpc/server";
12
+ // src/openapi-generator.ts
13
+ /**
14
+ * Generates an OpenAPI document from a contract or router.
15
+ * Relies on JSON schema converters to translate input, output, and error schemas into JSON Schemas.
16
+ *
17
+ * @see {@link https://orpc.dev/docs/openapi/specification#openapi-generator | OpenAPI Specification - OpenAPI Generator}
18
+ */
19
+ var OpenAPIGenerator = class {
20
+ serializer;
21
+ converter;
22
+ constructor(options = {}) {
23
+ this.serializer = options.serializer ?? new OpenAPIJsonSerializer();
24
+ this.converter = new DelegatingJsonSchemaConverter([...toArray(options.converters), new StandardJsonSchemaConverter()]);
25
+ }
26
+ async generate(router, options = {}) {
27
+ const version = options.version ?? "3.2.0";
28
+ const doc = {
29
+ ...clone(options.base),
30
+ openapi: "3.2.0",
31
+ info: options.base?.info ?? {
32
+ title: "API Reference",
33
+ version: "0.0.0"
34
+ }
35
+ };
36
+ const ctx = {
37
+ registry: new OpenAPIComponentRegistry(doc, options.componentName),
38
+ convertSchemas: (schemas, direction) => this.convertSchemas(schemas, direction),
39
+ errorStatusMap: options.errorStatusMap ?? COMMON_ERROR_STATUS_MAP,
40
+ errorResponseBodySchema: options.errorResponseBodySchema,
41
+ errorResponseContentType: options.errorResponseContentType ?? "application/json"
42
+ };
43
+ const errors = [];
44
+ const routeOwners = /* @__PURE__ */ new Map();
45
+ const operationIdOwners = /* @__PURE__ */ new Map();
46
+ await walkProcedureContractsAsync(router, (contract, path) => {
47
+ if (value(options.filter, contract, path) === false) return;
48
+ const procedurePath = path.length ? path.join(".") : "(root)";
49
+ try {
50
+ const def = contract["~orpc"];
51
+ const meta = getOpenAPIMeta(contract);
52
+ const method = (meta?.method ?? "POST").toLowerCase();
53
+ if (method === "query" && !version.startsWith("3.2.")) throw new OpenAPIGeneratorError(`QUERY operations require OpenAPI 3.2, but version "${version}" was requested.`);
54
+ const postPath = meta?.path ?? pathToHttpPath(path);
55
+ const httpPath = meta?.prefix ? mergeHttpPath(meta.prefix, postPath) : postPath;
56
+ const dynamicPathParams = getDynamicPathParams(httpPath);
57
+ const openApiPath = toOpenAPIPath(httpPath, dynamicPathParams);
58
+ let operation;
59
+ if (meta?.spec !== void 0 && typeof meta.spec !== "function") operation = meta.spec;
60
+ else {
61
+ operation = {
62
+ operationId: meta?.operationId ?? path.join("."),
63
+ summary: meta?.summary,
64
+ description: meta?.description,
65
+ deprecated: meta?.deprecated,
66
+ tags: meta?.tags?.map((tag) => tag)
67
+ };
68
+ buildRequest(ctx, operation, def, meta, dynamicPathParams);
69
+ buildSuccessResponse(ctx, operation, def, meta);
70
+ buildErrorResponse(ctx, operation, def);
71
+ }
72
+ if (typeof meta?.spec === "function") operation = meta.spec(operation);
73
+ const routeKey = `${method} ${toOpenAPIPath(httpPath, dynamicPathParams?.map((p) => ({
74
+ ...p,
75
+ parameterName: ""
76
+ })))}`;
77
+ const routeOwner = routeOwners.get(routeKey);
78
+ if (routeOwner !== void 0) throw new OpenAPIGeneratorError(`${method.toUpperCase()} ${openApiPath} is already documented by the procedure at ${routeOwner}.\n OpenAPI allows one operation per method and path (path param names are ignored).\n Fix: change the method or path of one of them.`);
79
+ const { operationId } = operation;
80
+ if (operationId !== void 0) {
81
+ const operationIdOwner = operationIdOwners.get(operationId);
82
+ if (operationIdOwner !== void 0) throw new OpenAPIGeneratorError(`operationId "${operationId}" is already used by the procedure at ${operationIdOwner}.\n OpenAPI requires operationIds to be unique. Fix: give one of them a different operationId.`);
83
+ operationIdOwners.set(operationId, procedurePath);
84
+ }
85
+ routeOwners.set(routeKey, procedurePath);
86
+ doc.paths ??= {};
87
+ doc.paths[openApiPath] ??= {};
88
+ doc.paths[openApiPath][method] = operation;
89
+ } catch (e) {
90
+ if (!(e instanceof OpenAPIGeneratorError)) throw e;
91
+ errors.push(`Procedure at ${procedurePath}: ${e.message}`);
92
+ }
93
+ });
94
+ if (errors.length) throw new OpenAPIGeneratorError(`[OpenAPIGenerator] Failed to generate the OpenAPI document (${errors.length} error${errors.length === 1 ? "" : "s"}):\n\n${errors.join("\n\n")}`);
95
+ const serialized = this.serializer.serializeJson(doc).json;
96
+ return toVersionedOpenAPIDocument(serialized, version);
97
+ }
98
+ convertSchema(schema, direction) {
99
+ const [jsonSchema, optional] = this.converter.convert(schema, direction);
100
+ return [hoistRecursiveRefToDef(strip$schemaField(jsonSchema)), optional];
101
+ }
102
+ convertSchemas(schemas, direction) {
103
+ if (!schemas || schemas.length <= 1) return this.convertSchema(schemas?.[0], direction);
104
+ const results = schemas.map((s) => this.convertSchema(s, direction));
105
+ return [combineJsonSchemasWithComposition("allOf", results.map(([jsonSchema]) => jsonSchema)), results.every(([, optional]) => optional)];
106
+ }
107
+ };
108
+ function toVersionedOpenAPIDocument(doc, version) {
109
+ return {
110
+ ...version.startsWith("3.2.") ? doc : version.startsWith("3.1.") ? downgradeSpecV32ToV31(doc) : downgradeSpecV31ToV30(downgradeSpecV32ToV31(doc)),
111
+ openapi: version
112
+ };
113
+ }
114
+ function strip$schemaField(schema) {
115
+ if (typeof schema !== "object") return schema;
116
+ const { $schema: _schema, ...rest } = schema;
117
+ return rest;
118
+ }
119
+ export { OpenAPIGenerator, OpenAPIGeneratorError };
@@ -0,0 +1,79 @@
1
+ import { Segment } from "@orpc/shared";
2
+ export type OpenAPIJsonSerialization = {
3
+ json: unknown;
4
+ maps?: undefined;
5
+ blobs?: undefined;
6
+ } | {
7
+ json: unknown;
8
+ maps: Segment[][];
9
+ blobs: Blob[];
10
+ };
11
+ export interface OpenAPIJsonSerializerHandler {
12
+ condition(value: unknown): boolean;
13
+ serialize(value: any): unknown;
14
+ /**
15
+ * If false, the result of this serializer will not be further processed by other serializers,
16
+ * even if it matches their conditions and treat it as final serialized value.
17
+ * This can be useful for serializers that return primitive values, which should not be further processed.
18
+ * to improve performance and avoid potential issues with other serializers.
19
+ *
20
+ * @default false
21
+ */
22
+ isTerminal?: boolean | undefined;
23
+ }
24
+ export interface OpenAPIJsonSerializerOptions {
25
+ /**
26
+ * Extend or override the built-in type handlers used during serialization.
27
+ *
28
+ * Each key is a unique type identifier (e.g. `"date"`, `"bigint"`) and maps to a handler
29
+ * that defines how to detect and serialize values of that type.
30
+ *
31
+ * **Extending:** Add new keys to support custom types:
32
+ * ```ts
33
+ * handlers: {
34
+ * buffer: {
35
+ * condition: (v) => v instanceof Buffer,
36
+ * serialize: (v: Buffer) => v.toString('base64'),
37
+ * isTerminal: true,
38
+ * }
39
+ * }
40
+ * ```
41
+ *
42
+ * **Overriding:** Use an existing key to replace a built-in handler:
43
+ * ```ts
44
+ * handlers: {
45
+ * date: {
46
+ * condition: (v) => v instanceof Date,
47
+ * serialize: (v: Date) => v.getTime(),
48
+ * isTerminal: true,
49
+ * }
50
+ * }
51
+ * ```
52
+ *
53
+ * **Disabling:** Set a key to `undefined` to remove a built-in handler:
54
+ * ```ts
55
+ * handlers: { url: undefined }
56
+ * ```
57
+ *
58
+ * Built-in type keys: `undefined`, `bigint`, `date`, `nan`, `infinity`, `url`, `set`, `map`.
59
+ */
60
+ handlers?: Record<string, undefined | OpenAPIJsonSerializerHandler> | undefined;
61
+ }
62
+ /**
63
+ * The JSON layer behind `OpenAPISerializer`: one-way serialization of types like `Date`, `BigInt`,
64
+ * and `Set` into JSON-friendly values, for places that only accept JSON.
65
+ *
66
+ * @see {@link https://orpc.dev/docs/openapi/serializer#openapi-json-serializer | OpenAPI Serializer - OpenAPI JSON Serializer}
67
+ */
68
+ export declare class OpenAPIJsonSerializer {
69
+ private readonly inlineBuiltInHandlers;
70
+ private readonly handlerEntries;
71
+ constructor(options?: OpenAPIJsonSerializerOptions);
72
+ serializeJson(data: unknown): OpenAPIJsonSerialization;
73
+ /**
74
+ * `segments` is a shared mutable stack (push/pop while walking),
75
+ * so it must be copied before being stored in `maps`.
76
+ */
77
+ private serializeValue;
78
+ deserializeJson(serialized: OpenAPIJsonSerialization): unknown;
79
+ }