@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,345 @@
1
+ import type { AnyProcedureContract, AnySchema, ErrorMap, MetaPlugin } from "@orpc/contract";
2
+ import type { Lazy } from "@orpc/server";
3
+ import type { Value } from "@orpc/shared";
4
+ import type { StandardBodyHint } from "@standard-server/core";
5
+ import type { OpenAPIV3_2 } from "./types.mjs";
6
+ export interface OpenAPIMeta {
7
+ /**
8
+ * HTTP method accepted by this procedure.
9
+ *
10
+ * @default 'POST'
11
+ */
12
+ method?: "HEAD" | "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "QUERY" | undefined;
13
+ /**
14
+ * URL path for this procedure. Supports dynamic parameters via `{param}` syntax,
15
+ * and `{+param}` to allow slashes in the matched value.
16
+ *
17
+ * @example `/users`, `/users/{id}`, `/files/{+path}`
18
+ * @default Router segments joined by `'/`
19
+ */
20
+ path?: `/${string}` | undefined;
21
+ /**
22
+ * Unique identifier for this operation in the OpenAPI spec.
23
+ *
24
+ * @default Router segments joined by `.`
25
+ */
26
+ operationId?: string | undefined;
27
+ /**
28
+ * Short summary of the procedure, used as the operation summary in the generated spec.
29
+ */
30
+ summary?: string | undefined;
31
+ /**
32
+ * Detailed description of the procedure, used as the operation description in the generated spec.
33
+ */
34
+ description?: string | undefined;
35
+ /**
36
+ * Marks the procedure as deprecated in the generated spec.
37
+ */
38
+ deprecated?: boolean | undefined;
39
+ /**
40
+ * Tags associated with this procedure.
41
+ *
42
+ * **Merging**: When defined multiple times, tags are concatenated in definition order.
43
+ * Explicitly setting `undefined` resets the tags instead of merging.
44
+ */
45
+ tags?: string[] | undefined;
46
+ /**
47
+ * HTTP status code returned on success.
48
+ * Should be in the `2xx` range and must be less than `400`.
49
+ *
50
+ * @default 200
51
+ */
52
+ successStatus?: number | undefined;
53
+ /**
54
+ * Description of the successful response.
55
+ *
56
+ * @default 'OK'
57
+ */
58
+ successDescription?: string | undefined;
59
+ /**
60
+ * Controls how individual path parameters are decoded.
61
+ *
62
+ * **Merging**: When defined multiple times, styles are merged per parameter.
63
+ * The most recent style defined for a parameter wins.
64
+ * Explicitly setting `undefined` resets the styles instead of merging.
65
+ *
66
+ * Each key maps a path parameter name to one of the following strategies:
67
+ *
68
+ * | Strategy | Encoded path segment | Decoded | OpenAPI Parameter Style |
69
+ * |--------------------------|----------------------|------------------------------|----------------------------------|
70
+ * | `primitive` *(default)* | `/users/42` | `{ id: '42' }` | `simple` |
71
+ * | `comma-delimited-array` | `/users/a,b,c` | `{ id: ['a', 'b', 'c'] }` | `simple` |
72
+ * | `comma-delimited-object` | `/users/a,1,b,2` | `{ id: { a: '1', b: '2' } }` | `simple` |
73
+ *
74
+ * **Strategy details:**
75
+ *
76
+ * - **`primitive`**: Keeps the decoded path segment as a string.
77
+ * - **`comma-delimited-array`**: Splits the decoded path segment on `,` into an array.
78
+ * - **`comma-delimited-object`**: Splits the decoded path segment on `,` into alternating key-value pairs.
79
+ *
80
+ * **Note**: `*-delimited-*` strategies do not support keys or values containing the delimiter character.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * // openapi.path = '/users/{id}/{tags}/{filters}'
85
+ * // GET /users/42/red,blue/size,large,brand,nike
86
+ *
87
+ * const paramsStyles = {
88
+ * id: 'primitive',
89
+ * tags: 'comma-delimited-array',
90
+ * filters: 'comma-delimited-object',
91
+ * }
92
+ *
93
+ * const inputSchema = z.object({
94
+ * id: z.string(),
95
+ * tags: z.array(z.string()),
96
+ * filters: z.object({
97
+ * size: z.string(),
98
+ * brand: z.string(),
99
+ * }),
100
+ * })
101
+ * ```
102
+ *
103
+ * @default `primitive` for all parameters
104
+ */
105
+ paramsStyles?: Record<string, "primitive" | "comma-delimited-array" | "comma-delimited-object" | undefined> | undefined;
106
+ /**
107
+ * Controls how individual query parameters are encoding/decoding.
108
+ *
109
+ * **Merging**: When defined multiple times, styles are merged per parameter.
110
+ * The most recent style defined for a parameter wins.
111
+ * Explicitly setting `undefined` resets the styles instead of merging.
112
+ *
113
+ * Each key maps a query parameter name to one of the following strategies:
114
+ *
115
+ * | Strategy | Encoded | Decoded | OpenAPI Parameter Style |
116
+ * |--------------------------|---------------------------|--------------------------------|------------------------------------|
117
+ * | `primitive` | `?a=1&a=2` | `{ a: '2' }` | `form` / `explode: false` |
118
+ * | `array` | `?a=1&a=2` | `{ a: ['1', '2'] }` | `form` / `explode: true` |
119
+ * | `comma-delimited-array` | `?a=1,2,3` | `{ a: ['1', '2', '3'] }` | `form` / `explode: false` |
120
+ * | `comma-delimited-object` | `?a=A,1,B,2` | `{ a: { A: '1', B: '2' } }` | `form` / `explode: false` |
121
+ * | `space-delimited-array` | `?a=1 2 3` | `{ a: ['1', '2', '3'] }` | `spaceDelimited` / `explode: false`|
122
+ * | `space-delimited-object` | `?a=A 1 B 2` | `{ a: { A: '1', B: '2' } }` | `spaceDelimited` / `explode: false`|
123
+ * | `pipe-delimited-array` | `?a=1\|2\|3` | `{ a: ['1', '2', '3'] }` | `pipeDelimited` / `explode: false` |
124
+ * | `pipe-delimited-object` | `?a=A\|1\|B\|2` | `{ a: { A: '1', B: '2' } }` | `pipeDelimited` / `explode: false` |
125
+ * | `json` | `?meta={"key":"value"}` | `{ meta: { key: 'value' } }` | `content: application/json` |
126
+ * | _default_ | `?a[]=1&a[]=2&b=3&c[d]=4` | `{a:['1', '2'], b:3, c:{d:4}}` | `deepObject` / `explode: true` |
127
+ *
128
+ * **Strategy details:**
129
+ *
130
+ * - **`primitive`**: Takes the last occurrence of a repeated parameter.
131
+ * - **`array`**: Always produces an array, even for a single occurrence.
132
+ * - **`*-delimited-array`**: Splits the last value on the delimiter (`,`, space, or `|`) into an array.
133
+ * - **`*-delimited-object`**: Splits the last value on the delimiter into alternating key–value pairs.
134
+ * - **`json`**: Parses the last value as JSON; falls back to the raw string if parsing fails.
135
+ * - **`undefined`**: Standard bracket-notation decoding This is the default.
136
+ *
137
+ * **Note**: `*-delimited-*` strategies do not support keys or values containing the delimiter character.
138
+ *
139
+ * @example
140
+ * ```ts
141
+ * // GET /search?keyword=abc&tags=a,b,c&meta={"key":"value"}
142
+ * const queryParsing = {
143
+ * keyword: 'primitive',
144
+ * tags: 'comma-delimited-array',
145
+ * meta: 'json',
146
+ * }
147
+ *
148
+ * const inputSchema = z.object({
149
+ * keyword: z.string(),
150
+ * tags: z.array(z.string()),
151
+ * meta: z.object({ key: z.string() }),
152
+ * })
153
+ * ```
154
+ *
155
+ * @default `undefined` for all parameters (bracket-notation decoding)
156
+ */
157
+ queryStyles?: Record<string, "primitive" | "array" | "comma-delimited-array" | "comma-delimited-object" | "space-delimited-array" | "space-delimited-object" | "pipe-delimited-array" | "pipe-delimited-object" | "json" | undefined> | undefined;
158
+ /**
159
+ * Hint for how to parse the incoming request body.
160
+ *
161
+ * Note: This option takes priority over the `standard-server` and `Content-Type` headers.
162
+ * `form-data` and `url-search-params` are decoded using bracket notation,
163
+ * so the resulting value will be an object or array.
164
+ *
165
+ * @default Inferred from `Content-Type`, `Content-Disposition`, and `Content-Length`
166
+ */
167
+ requestBodyHint?: StandardBodyHint | undefined;
168
+ /**
169
+ * Hint for how to parse a successful response body (status below 400).
170
+ * Error response bodies are always parsed from their headers.
171
+ *
172
+ * Note: This option takes priority over the `standard-server` and `Content-Type` headers.
173
+ * `form-data` and `url-search-params` are decoded using bracket notation,
174
+ * so the resulting value will be an object or array.
175
+ *
176
+ * @default Inferred from `Content-Type`, `Content-Disposition`, and `Content-Length`
177
+ */
178
+ responseBodyHint?: StandardBodyHint | undefined;
179
+ /**
180
+ * Determines how the input should be structured
181
+ * based on params, query, headers, and body.
182
+ *
183
+ * - `compact` — Merges params with either query or body
184
+ * (depending on the HTTP method) into a single flat object.
185
+ * Use this when you don't need access to headers and your
186
+ * param/query/body keys don't conflict.
187
+ *
188
+ * ```ts
189
+ * // GET /users/42?search=hello
190
+ * const inputValue = { id: 42, search: 'hello' }
191
+ *
192
+ * const inputSchema = z.object({
193
+ * id: z.coerce.number(), // from params
194
+ * search: z.string(), // from query
195
+ * })
196
+ * ```
197
+ *
198
+ * - `detailed` — Keeps each part of the request as a
199
+ * separate nested field. Use this when you need access
200
+ * to headers, or when params and query/body keys
201
+ * might conflict.
202
+ *
203
+ * ```ts
204
+ * const inputValue = {
205
+ * params: { id: 1 },
206
+ * query: { search: 'hello' },
207
+ * headers: { 'content-type': 'application/json' },
208
+ * body: 'body value',
209
+ * }
210
+ *
211
+ * const inputSchema = z.object({
212
+ * params: z.object({ id: z.coerce.number() }),
213
+ * query: z.object({ search: z.string() }),
214
+ * headers: z.object({ 'content-type': z.string() }),
215
+ * body: z.string(),
216
+ * })
217
+ * ```
218
+ *
219
+ * @default 'compact'
220
+ */
221
+ inputStructure?: "compact" | "detailed" | undefined;
222
+ /**
223
+ * Determines how the output should be structured
224
+ * into the HTTP response.
225
+ *
226
+ * - `compact` — The return value is sent directly as the
227
+ * response body. Status code comes from successStatus.
228
+ *
229
+ * ```ts
230
+ * const outputValue = { id: 1, name: 'Alice' }
231
+ *
232
+ * const outputSchema = z.object({
233
+ * id: z.number(),
234
+ * name: z.string(),
235
+ * })
236
+ * ```
237
+ *
238
+ * - `detailed` — Return an object with optional properties:
239
+ * - status: HTTP status code (200–399). Defaults to
240
+ * successStatus if omitted. Use a literal type
241
+ * (e.g. z.literal(201)) so the generated spec can reflects
242
+ * the exact code.
243
+ * - headers: Custom headers to merge into the response
244
+ * (Record<string, string | string[] | undefined>).
245
+ * - body: The response body.
246
+ *
247
+ * ```ts
248
+ * const outputValue = {
249
+ * status: 201,
250
+ * headers: { 'x-custom-header': 'value' },
251
+ * body: 'body value',
252
+ * }
253
+ *
254
+ * const outputSchema = z.object({
255
+ * status: z.literal(201).meta({ description: 'Record Created' }),
256
+ * headers: z.object({ 'x-custom-header': z.string() }),
257
+ * body: z.string(),
258
+ * })
259
+ * ```
260
+ *
261
+ * @default 'compact'
262
+ */
263
+ outputStructure?: "compact" | "detailed" | undefined;
264
+ /**
265
+ * Override or extend the generated OpenAPI operation object for this procedure.
266
+ *
267
+ * Pass a plain object to replace entire operation object, or a function that receives the current
268
+ * operation object and returns the modified version.
269
+ *
270
+ * The operation object always follows OpenAPI 3.2, `OpenAPIGenerator` downgrades it with the
271
+ * rest of the document when an older version is requested.
272
+ *
273
+ * **Merging**: When defined multiple times:
274
+ *
275
+ * - Two functions are chained: the most recent function receives the result of the previous one.
276
+ * - A function combined with an object: the function is applied to that object.
277
+ * - Two objects: the most recent object wins.
278
+ *
279
+ * Explicitly setting `undefined` resets the spec instead of merging.
280
+ */
281
+ spec?: Value<OpenAPIV3_2.OperationObject, [current: OpenAPIV3_2.OperationObject]> | undefined;
282
+ /**
283
+ * Prefix for the path. Useful when you want to apply a common path prefix across multiple procedures.
284
+ *
285
+ * **Merging**: When defined multiple times, prefixes are concatenated in definition order.
286
+ * Explicitly setting `undefined` resets the prefix instead of merging.
287
+ */
288
+ prefix?: `/${string}` | undefined;
289
+ }
290
+ export interface OpenAPIMetaPlugin<
291
+ TInputSchema extends AnySchema,
292
+ TOutputSchema extends AnySchema,
293
+ TErrorMap extends ErrorMap
294
+ > extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
295
+ name: "~openapi";
296
+ }
297
+ export interface OpenAPIMethodMetaPlugin<
298
+ TInputSchema extends AnySchema,
299
+ TOutputSchema extends AnySchema,
300
+ TErrorMap extends ErrorMap
301
+ > extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
302
+ name: "~openapi/method";
303
+ }
304
+ export interface OpenAPIPathMetaPlugin<
305
+ TInputSchema extends AnySchema,
306
+ TOutputSchema extends AnySchema,
307
+ TErrorMap extends ErrorMap
308
+ > extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
309
+ name: "~openapi/path";
310
+ }
311
+ export interface OpenAPISpecMetaPlugin<
312
+ TInputSchema extends AnySchema,
313
+ TOutputSchema extends AnySchema,
314
+ TErrorMap extends ErrorMap
315
+ > extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
316
+ name: "~openapi/spec";
317
+ }
318
+ export interface OpenAPIPrefixMetaPlugin<
319
+ TInputSchema extends AnySchema,
320
+ TOutputSchema extends AnySchema,
321
+ TErrorMap extends ErrorMap
322
+ > extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
323
+ name: "~openapi/prefix";
324
+ }
325
+ export interface OpenAPIFunction {
326
+ (meta: OpenAPIMeta): OpenAPIMetaPlugin<any, any, any>;
327
+ method(method: OpenAPIMeta["method"]): OpenAPIMethodMetaPlugin<any, any, any>;
328
+ path(method: OpenAPIMeta["path"]): OpenAPIPathMetaPlugin<any, any, any>;
329
+ spec(method: OpenAPIMeta["spec"]): OpenAPISpecMetaPlugin<any, any, any>;
330
+ prefix(method: OpenAPIMeta["prefix"]): OpenAPIPrefixMetaPlugin<any, any, any>;
331
+ }
332
+ /**
333
+ * Creates OpenAPI meta plugins that control how a procedure is exposed over HTTP,
334
+ * such as its method, path, prefix, and OpenAPI operation spec.
335
+ *
336
+ * @see {@link https://orpc.dev/docs/openapi/routing | OpenAPI Routing}
337
+ * @see {@link https://orpc.dev/docs/openapi/specification | OpenAPI Specification}
338
+ */
339
+ export declare const openapi: OpenAPIFunction;
340
+ /**
341
+ * Retrieves the OpenAPI metadata attached to a procedure or router, or `undefined` if not set.
342
+ *
343
+ * @see {@link https://orpc.dev/docs/rpc/handler#enabling-the-get-method | RPC Handler - Enabling the GET Method}
344
+ */
345
+ export declare function getOpenAPIMeta(procedureOrLazy: AnyProcedureContract | Lazy<any>): OpenAPIMeta | undefined;
package/dist/meta.mjs ADDED
@@ -0,0 +1,56 @@
1
+ import { mergeHttpPath } from "@orpc/shared";
2
+
3
+ export const openapi = (incoming) => ({
4
+ name: "~openapi",
5
+ init(meta) {
6
+ const existing = meta["~openapi"];
7
+ const tags = existing?.tags && incoming.tags ? [...existing.tags, ...incoming.tags] : "tags" in incoming ? incoming.tags : existing?.tags;
8
+ const queryStyles = existing?.queryStyles && incoming.queryStyles ? {
9
+ ...existing.queryStyles,
10
+ ...incoming.queryStyles
11
+ } : "queryStyles" in incoming ? incoming.queryStyles : existing?.queryStyles;
12
+ const paramsStyles = existing?.paramsStyles && incoming.paramsStyles ? {
13
+ ...existing.paramsStyles,
14
+ ...incoming.paramsStyles
15
+ } : "paramsStyles" in incoming ? incoming.paramsStyles : existing?.paramsStyles;
16
+ const existingSpec = existing?.spec;
17
+ const incomingSpec = incoming.spec;
18
+
19
+ const spec = typeof existingSpec === "function" && typeof incomingSpec === "function" ? (current) => incomingSpec(existingSpec(current)) : typeof existingSpec === "function" && typeof incomingSpec === "object" ? existingSpec(incomingSpec) : typeof existingSpec === "object" && typeof incomingSpec === "function" ? incomingSpec(existingSpec) : "spec" in incoming ? incomingSpec : existingSpec;
20
+ const prefix = existing?.prefix && incoming.prefix ? mergeHttpPath(existing.prefix, incoming.prefix) : "prefix" in incoming ? incoming.prefix : existing?.prefix;
21
+
22
+ const merged = {
23
+ ...existing,
24
+ ...incoming,
25
+ tags,
26
+ queryStyles,
27
+ paramsStyles,
28
+ spec,
29
+ prefix
30
+ };
31
+ return {
32
+ ...meta,
33
+ "~openapi": merged
34
+ };
35
+ }
36
+ });
37
+ openapi.method = (method) => ({
38
+ ...openapi({ method }),
39
+ name: "~openapi/method"
40
+ });
41
+ openapi.path = (path) => ({
42
+ ...openapi({ path }),
43
+ name: "~openapi/path"
44
+ });
45
+ openapi.spec = (spec) => ({
46
+ ...openapi({ spec }),
47
+ name: "~openapi/spec"
48
+ });
49
+ openapi.prefix = (prefix) => ({
50
+ ...openapi({ prefix }),
51
+ name: "~openapi/prefix"
52
+ });
53
+
54
+ export function getOpenAPIMeta(procedureOrLazy) {
55
+ return procedureOrLazy["~orpc"].meta["~openapi"];
56
+ }
@@ -0,0 +1,24 @@
1
+ import type { JsonSchema, JsonSchemaConverterDirection } from "@orpc/json-schema";
2
+ import type { OpenAPIV3_2 } from "./types.mjs";
3
+ /**
4
+ * Collects reusable schemas into `doc.components.schemas`.
5
+ *
6
+ * Equivalent schemas (including recursive ones) reuse a single component, and different
7
+ * schemas competing for the same name get direction-suffixed or numbered postfixes.
8
+ */
9
+ export declare class OpenAPIComponentRegistry {
10
+ private readonly doc;
11
+ private readonly componentName;
12
+ constructor(doc: OpenAPIV3_2.OpenAPIObject, componentName: ((defName: string, defSchema: JsonSchema) => string | undefined) | undefined);
13
+ /**
14
+ * Registers `schema` as a component under `preferredName` (or an equivalent/postfixed name)
15
+ * and returns a `$ref` to it.
16
+ */
17
+ register(preferredName: string, schema: Exclude<JsonSchema, boolean>): JsonSchema;
18
+ /**
19
+ * Moves a schema's root-level `$defs` into `doc.components.schemas` and rewrites
20
+ * its refs accordingly.
21
+ */
22
+ hoistDefs(schema: JsonSchema, direction?: JsonSchemaConverterDirection): JsonSchema;
23
+ toOpenAPISchema(schema: JsonSchema, direction?: JsonSchemaConverterDirection): OpenAPIV3_2.SchemaObject;
24
+ }
@@ -0,0 +1,227 @@
1
+ import { decodeJsonPointerSegment, encodeJsonPointerSegment, ensureJsonSchemaObject, mapJsonSchemaRefs } from "@orpc/json-schema";
2
+ import { getOwn, isDeepEqual, isPlainObject, setOwn } from "@orpc/shared";
3
+ const DEFS_REF_PREFIX = "#/$defs/";
4
+ const COMPONENTS_REF_PREFIX = "#/components/schemas/";
5
+
6
+ export class OpenAPIComponentRegistry {
7
+ doc;
8
+ componentName;
9
+ constructor(doc, componentName) {
10
+ this.doc = doc;
11
+ this.componentName = componentName;
12
+ }
13
+
14
+ register(preferredName, schema) {
15
+ const { $defs, ...body } = schema;
16
+
17
+ let defName = preferredName;
18
+ if ($defs) {
19
+ for (let i = 2; Object.hasOwn($defs, defName); i++) {
20
+ defName = `${preferredName}${i}`;
21
+ }
22
+ }
23
+ return this.hoistDefs({
24
+ $defs: {
25
+ ...$defs,
26
+ [defName]: body
27
+ },
28
+ $ref: `${DEFS_REF_PREFIX}${encodeJsonPointerSegment(defName)}`
29
+ });
30
+ }
31
+
32
+ hoistDefs(schema, direction) {
33
+ if (typeof schema !== "object" || !schema.$defs) {
34
+ return schema;
35
+ }
36
+ const { $defs, ...rest } = schema;
37
+ const defs = new Map();
38
+ for (const defName of Object.keys($defs)) {
39
+ const defSchema = $defs[defName];
40
+ if (defSchema !== undefined) {
41
+ defs.set(defName, ensureJsonSchemaObject(defSchema));
42
+ }
43
+ }
44
+ if (defs.size === 0) {
45
+ return schema;
46
+ }
47
+ this.doc.components ??= {};
48
+ this.doc.components.schemas ??= {};
49
+ const componentsSchemas = this.doc.components.schemas;
50
+ const renameMap = new Map();
51
+ const pendingSchemas = [];
52
+ for (const [defName, cleanSchema] of defs) {
53
+ const [componentName, reuseExisting] = resolveComponentName(componentsSchemas, new Set(renameMap.values()), defName, this.componentName?.(defName, cleanSchema) ?? defName, defs, direction);
54
+ renameMap.set(defName, componentName);
55
+ if (!reuseExisting) {
56
+ pendingSchemas.push({
57
+ cleanSchema,
58
+ componentName
59
+ });
60
+ }
61
+ }
62
+ for (const { cleanSchema, componentName } of pendingSchemas) {
63
+ setOwn(componentsSchemas, componentName, rewriteComponentSchemaRefs(cleanSchema, renameMap));
64
+ }
65
+ return rewriteComponentSchemaRefs(rest, renameMap);
66
+ }
67
+ toOpenAPISchema(schema, direction) {
68
+ return ensureJsonSchemaObject(this.hoistDefs(schema, direction));
69
+ }
70
+ }
71
+
72
+ function resolveComponentName(componentsSchemas, claimedNames, defName, preferredName, defs, direction) {
73
+ let mintName;
74
+ for (let i = 1;; i++) {
75
+ const [componentName, mintable, tail] = componentNameCandidate(preferredName, direction, i);
76
+ const existingSchema = getOwn(componentsSchemas, componentName);
77
+ if (existingSchema === undefined) {
78
+
79
+ if (mintable && !claimedNames.has(componentName)) {
80
+ mintName ??= componentName;
81
+ if (tail) {
82
+ return [mintName, false];
83
+ }
84
+ }
85
+ continue;
86
+ }
87
+ if (areSchemaRefsEquivalentForReuse(DEFS_REF_PREFIX + encodeJsonPointerSegment(defName), COMPONENTS_REF_PREFIX + encodeJsonPointerSegment(componentName), {
88
+ defs,
89
+ componentsSchemas,
90
+ candidateToExistingKeys: new Map(),
91
+ pairedExistingKeys: new Set(),
92
+ visited: new WeakMap()
93
+ })) {
94
+ return [componentName, true];
95
+ }
96
+ }
97
+ }
98
+ function componentNameCandidate(preferredName, direction, attempt) {
99
+ if (attempt === 1) {
100
+ return [
101
+ preferredName,
102
+ true,
103
+ false
104
+ ];
105
+ }
106
+ if (direction !== undefined) {
107
+ if (attempt === 2) {
108
+ return [
109
+ `${preferredName}${direction === "input" ? "Input" : "Output"}`,
110
+ true,
111
+ false
112
+ ];
113
+ }
114
+
115
+ if (attempt === 3) {
116
+ return [
117
+ `${preferredName}${direction === "input" ? "Output" : "Input"}`,
118
+ false,
119
+ false
120
+ ];
121
+ }
122
+ return [
123
+ `${preferredName}${attempt - 2}`,
124
+ true,
125
+ true
126
+ ];
127
+ }
128
+ return [
129
+ `${preferredName}${attempt}`,
130
+ true,
131
+ true
132
+ ];
133
+ }
134
+ function definedKeysOf(object) {
135
+
136
+
137
+ return Object.keys(object).filter((key) => object[key] !== undefined).sort();
138
+ }
139
+ function isSchemaContainer(value) {
140
+ return Array.isArray(value) || isPlainObject(value);
141
+ }
142
+ function areSchemasEquivalentForReuse(candidate, existing, ctx) {
143
+ if (candidate === existing) {
144
+ return true;
145
+ }
146
+
147
+ if (!isSchemaContainer(candidate) || !isSchemaContainer(existing)) {
148
+ return isDeepEqual(candidate, existing);
149
+ }
150
+ const seenExisting = ctx.visited.get(candidate);
151
+ if (seenExisting?.has(existing)) {
152
+ return true;
153
+ }
154
+ if (seenExisting) {
155
+ seenExisting.add(existing);
156
+ } else {
157
+ ctx.visited.set(candidate, new WeakSet([existing]));
158
+ }
159
+ if (Array.isArray(candidate) || Array.isArray(existing)) {
160
+ if (!Array.isArray(candidate) || !Array.isArray(existing) || candidate.length !== existing.length) {
161
+ return false;
162
+ }
163
+ return candidate.every((item, index) => areSchemasEquivalentForReuse(item, existing[index], ctx));
164
+ }
165
+ const candidateObject = candidate;
166
+ const existingObject = existing;
167
+ const candidateKeys = definedKeysOf(candidateObject);
168
+ const existingKeys = definedKeysOf(existingObject);
169
+ if (!isDeepEqual(candidateKeys, existingKeys)) {
170
+ return false;
171
+ }
172
+ return candidateKeys.every((key) => {
173
+ const candidateValue = candidateObject[key];
174
+ const existingValue = existingObject[key];
175
+ if (key === "$ref" && typeof candidateValue === "string" && typeof existingValue === "string") {
176
+ return areSchemaRefsEquivalentForReuse(candidateValue, existingValue, ctx);
177
+ }
178
+ return areSchemasEquivalentForReuse(candidateValue, existingValue, ctx);
179
+ });
180
+ }
181
+ function parseRefName(ref, prefix) {
182
+ if (!ref.startsWith(prefix)) {
183
+ return undefined;
184
+ }
185
+ return ref.slice(prefix.length).split("/").map(decodeJsonPointerSegment).join("/");
186
+ }
187
+ function resolveNamedRef(ref, prefix, getNamed) {
188
+ const name = parseRefName(ref, prefix);
189
+ if (name === undefined) {
190
+ return undefined;
191
+ }
192
+ const schema = getNamed(name);
193
+ return schema === undefined ? undefined : {
194
+ key: prefix + name,
195
+ schema
196
+ };
197
+ }
198
+ function areSchemaRefsEquivalentForReuse(candidateRef, existingRef, ctx) {
199
+ const getComponent = (name) => getOwn(ctx.componentsSchemas, name);
200
+ const candidate = resolveNamedRef(candidateRef, DEFS_REF_PREFIX, (name) => ctx.defs.get(name)) ?? resolveNamedRef(candidateRef, COMPONENTS_REF_PREFIX, getComponent);
201
+ const existing = resolveNamedRef(existingRef, COMPONENTS_REF_PREFIX, getComponent);
202
+ if (candidate === undefined || existing === undefined) {
203
+ return !candidate && !existing && candidateRef === existingRef;
204
+ }
205
+ const pairedExisting = ctx.candidateToExistingKeys.get(candidate.key);
206
+ if (pairedExisting !== existing.key) {
207
+ if (pairedExisting !== undefined || ctx.pairedExistingKeys.has(existing.key)) {
208
+ return false;
209
+ }
210
+ ctx.candidateToExistingKeys.set(candidate.key, existing.key);
211
+ ctx.pairedExistingKeys.add(existing.key);
212
+ }
213
+ return areSchemasEquivalentForReuse(candidate.schema, existing.schema, ctx);
214
+ }
215
+ function rewriteComponentSchemaRefs(schema, renameMap) {
216
+ return mapJsonSchemaRefs(schema, (ref) => {
217
+ const refName = parseRefName(ref, DEFS_REF_PREFIX);
218
+ if (refName === undefined) {
219
+ return ref;
220
+ }
221
+ const renamedName = renameMap.get(refName);
222
+ if (renamedName === undefined) {
223
+ return ref;
224
+ }
225
+ return COMPONENTS_REF_PREFIX + encodeJsonPointerSegment(renamedName);
226
+ });
227
+ }
@@ -0,0 +1,29 @@
1
+ import type { AnyProcedureContract, AnySchema } from "@orpc/contract";
2
+ import type { JsonSchema, JsonSchemaConverterDirection } from "@orpc/json-schema";
3
+ import type { Value } from "@orpc/shared";
4
+ import type { OpenAPIMeta } from "./meta.mjs";
5
+ import type { OpenAPIComponentRegistry } from "./openapi-generator-components.mjs";
6
+ import type { OpenAPIV3_2 } from "./types.mjs";
7
+ import type { getDynamicPathParams } from "./utils.mjs";
8
+ export type DynamicPathParam = NonNullable<ReturnType<typeof getDynamicPathParams>>[number];
9
+ export declare class OpenAPIGeneratorError extends TypeError {}
10
+ export interface OpenAPIErrorBodyDefinition {
11
+ code: string;
12
+ defaultMessage: string | undefined;
13
+ dataOptional: boolean;
14
+ dataJsonSchema: JsonSchema;
15
+ }
16
+ /**
17
+ * Everything the operation builders need from the surrounding `generate()` call.
18
+ */
19
+ export interface OpenAPIOperationContext {
20
+ registry: OpenAPIComponentRegistry;
21
+ convertSchemas: (schemas: AnySchema[] | undefined, direction: JsonSchemaConverterDirection) => [JsonSchema, boolean];
22
+ errorStatusMap: Record<string, number>;
23
+ errorResponseBodySchema: Value<JsonSchema | null | undefined, [definedErrors: OpenAPIErrorBodyDefinition[], status: number, defaultSchema: () => JsonSchema]> | undefined;
24
+ errorResponseContentType: string;
25
+ }
26
+ export declare function toOpenAPIPath(path: `/${string}`, dynamicPathParams: DynamicPathParam[] | undefined): `/${string}`;
27
+ export declare function buildRequest(ctx: OpenAPIOperationContext, operation: OpenAPIV3_2.OperationObject, def: AnyProcedureContract["~orpc"], meta: OpenAPIMeta | undefined, dynamicPathParams: DynamicPathParam[] | undefined): void;
28
+ export declare function buildSuccessResponse(ctx: OpenAPIOperationContext, operation: OpenAPIV3_2.OperationObject, def: AnyProcedureContract["~orpc"], meta: OpenAPIMeta | undefined): void;
29
+ export declare function buildErrorResponse(ctx: OpenAPIOperationContext, operation: OpenAPIV3_2.OperationObject, def: AnyProcedureContract["~orpc"]): void;