@orpc/openapi 0.0.0-next.68378b4 → 0.0.0-next.683f2ee
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.
- package/README.md +148 -28
- package/dist/adapters/aws-lambda/index.d.mts +20 -0
- package/dist/adapters/aws-lambda/index.d.ts +20 -0
- package/dist/adapters/aws-lambda/index.mjs +18 -0
- package/dist/adapters/fastify/index.d.mts +23 -0
- package/dist/adapters/fastify/index.d.ts +23 -0
- package/dist/adapters/fastify/index.mjs +18 -0
- package/dist/adapters/fetch/index.d.mts +18 -8
- package/dist/adapters/fetch/index.d.ts +18 -8
- package/dist/adapters/fetch/index.mjs +12 -4
- package/dist/adapters/node/index.d.mts +18 -8
- package/dist/adapters/node/index.d.ts +18 -8
- package/dist/adapters/node/index.mjs +8 -22
- package/dist/adapters/standard/index.d.mts +18 -21
- package/dist/adapters/standard/index.d.ts +18 -21
- package/dist/adapters/standard/index.mjs +5 -2
- package/dist/index.d.mts +103 -155
- package/dist/index.d.ts +103 -155
- package/dist/index.mjs +34 -654
- package/dist/plugins/index.d.mts +86 -0
- package/dist/plugins/index.d.ts +86 -0
- package/dist/plugins/index.mjs +157 -0
- package/dist/shared/{openapi.C_biOx82.mjs → openapi.BB-W-NKv.mjs} +86 -29
- package/dist/shared/openapi.BGy4N6eR.d.mts +120 -0
- package/dist/shared/openapi.BGy4N6eR.d.ts +120 -0
- package/dist/shared/openapi.BwdtJjDu.mjs +878 -0
- package/dist/shared/openapi.DwaweYRb.d.mts +54 -0
- package/dist/shared/openapi.DwaweYRb.d.ts +54 -0
- package/package.json +30 -26
- package/dist/adapters/hono/index.d.mts +0 -6
- package/dist/adapters/hono/index.d.ts +0 -6
- package/dist/adapters/hono/index.mjs +0 -10
- package/dist/adapters/next/index.d.mts +0 -6
- package/dist/adapters/next/index.d.ts +0 -6
- package/dist/adapters/next/index.mjs +0 -10
- package/dist/shared/openapi.B6uueFtN.mjs +0 -29
- package/dist/shared/openapi.BHG_gu5Z.mjs +0 -8
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { OpenAPI } from '@orpc/contract';
|
|
2
|
+
import { Context, HTTPPath, Router } from '@orpc/server';
|
|
3
|
+
import { StandardHandlerInterceptorOptions, StandardHandlerPlugin, StandardHandlerOptions } from '@orpc/server/standard';
|
|
4
|
+
import { Value, Promisable } from '@orpc/shared';
|
|
5
|
+
import { O as OpenAPIGeneratorOptions, a as OpenAPIGeneratorGenerateOptions } from '../shared/openapi.BGy4N6eR.mjs';
|
|
6
|
+
import '@orpc/openapi-client/standard';
|
|
7
|
+
import 'json-schema-typed/draft-2020-12';
|
|
8
|
+
|
|
9
|
+
interface OpenAPIReferencePluginOptions<T extends Context> extends OpenAPIGeneratorOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Options to pass to the OpenAPI generate.
|
|
12
|
+
*
|
|
13
|
+
*/
|
|
14
|
+
specGenerateOptions?: Value<Promisable<OpenAPIGeneratorGenerateOptions>, [StandardHandlerInterceptorOptions<T>]>;
|
|
15
|
+
/**
|
|
16
|
+
* The URL path at which to serve the OpenAPI JSON.
|
|
17
|
+
*
|
|
18
|
+
* @default '/spec.json'
|
|
19
|
+
*/
|
|
20
|
+
specPath?: HTTPPath;
|
|
21
|
+
/**
|
|
22
|
+
* The URL path at which to serve the API reference UI.
|
|
23
|
+
*
|
|
24
|
+
* @default '/'
|
|
25
|
+
*/
|
|
26
|
+
docsPath?: HTTPPath;
|
|
27
|
+
/**
|
|
28
|
+
* The document title for the API reference UI.
|
|
29
|
+
*
|
|
30
|
+
* @default 'API Reference'
|
|
31
|
+
*/
|
|
32
|
+
docsTitle?: Value<Promisable<string>, [StandardHandlerInterceptorOptions<T>]>;
|
|
33
|
+
/**
|
|
34
|
+
* The UI library to use for rendering the API reference.
|
|
35
|
+
*
|
|
36
|
+
* @default 'scalar'
|
|
37
|
+
*/
|
|
38
|
+
docsProvider?: 'scalar' | 'swagger';
|
|
39
|
+
/**
|
|
40
|
+
* Arbitrary configuration object for the UI.
|
|
41
|
+
*/
|
|
42
|
+
docsConfig?: Value<Promisable<Record<string, unknown>>, [StandardHandlerInterceptorOptions<T>]>;
|
|
43
|
+
/**
|
|
44
|
+
* HTML to inject into the <head> of the docs page.
|
|
45
|
+
*
|
|
46
|
+
* @warning This is not escaped special characters, so must be used with caution to avoid XSS vulnerabilities.
|
|
47
|
+
*
|
|
48
|
+
* @default ''
|
|
49
|
+
*/
|
|
50
|
+
docsHead?: Value<Promisable<string>, [StandardHandlerInterceptorOptions<T>]>;
|
|
51
|
+
/**
|
|
52
|
+
* URL of the external script bundle for the reference UI.
|
|
53
|
+
*
|
|
54
|
+
* - For Scalar: defaults to 'https://cdn.jsdelivr.net/npm/@scalar/api-reference'
|
|
55
|
+
* - For Swagger UI: defaults to 'https://unpkg.com/swagger-ui-dist@5.17.14/swagger-ui-bundle.js'
|
|
56
|
+
*/
|
|
57
|
+
docsScriptUrl?: Value<Promisable<string>, [StandardHandlerInterceptorOptions<T>]>;
|
|
58
|
+
/**
|
|
59
|
+
* URL of the external CSS bundle for the reference UI (used by Swagger UI).
|
|
60
|
+
*
|
|
61
|
+
* @default 'https://unpkg.com/swagger-ui-dist@5.17.14/swagger-ui.css' (if swagger)
|
|
62
|
+
*/
|
|
63
|
+
docsCssUrl?: Value<Promisable<string>, [StandardHandlerInterceptorOptions<T>]>;
|
|
64
|
+
/**
|
|
65
|
+
* Override function to generate the full HTML for the docs page.
|
|
66
|
+
*/
|
|
67
|
+
renderDocsHtml?: (specUrl: string, title: string, head: string, scriptUrl: string, config: Record<string, unknown> | undefined, spec: OpenAPI.Document, docsProvider: 'scalar' | 'swagger', cssUrl: string | undefined) => string;
|
|
68
|
+
}
|
|
69
|
+
declare class OpenAPIReferencePlugin<T extends Context> implements StandardHandlerPlugin<T> {
|
|
70
|
+
private readonly generator;
|
|
71
|
+
private readonly specGenerateOptions;
|
|
72
|
+
private readonly specPath;
|
|
73
|
+
private readonly docsPath;
|
|
74
|
+
private readonly docsTitle;
|
|
75
|
+
private readonly docsHead;
|
|
76
|
+
private readonly docsProvider;
|
|
77
|
+
private readonly docsScriptUrl;
|
|
78
|
+
private readonly docsCssUrl;
|
|
79
|
+
private readonly docsConfig;
|
|
80
|
+
private readonly renderDocsHtml;
|
|
81
|
+
constructor(options?: OpenAPIReferencePluginOptions<T>);
|
|
82
|
+
init(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export { OpenAPIReferencePlugin };
|
|
86
|
+
export type { OpenAPIReferencePluginOptions };
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { OpenAPI } from '@orpc/contract';
|
|
2
|
+
import { Context, HTTPPath, Router } from '@orpc/server';
|
|
3
|
+
import { StandardHandlerInterceptorOptions, StandardHandlerPlugin, StandardHandlerOptions } from '@orpc/server/standard';
|
|
4
|
+
import { Value, Promisable } from '@orpc/shared';
|
|
5
|
+
import { O as OpenAPIGeneratorOptions, a as OpenAPIGeneratorGenerateOptions } from '../shared/openapi.BGy4N6eR.js';
|
|
6
|
+
import '@orpc/openapi-client/standard';
|
|
7
|
+
import 'json-schema-typed/draft-2020-12';
|
|
8
|
+
|
|
9
|
+
interface OpenAPIReferencePluginOptions<T extends Context> extends OpenAPIGeneratorOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Options to pass to the OpenAPI generate.
|
|
12
|
+
*
|
|
13
|
+
*/
|
|
14
|
+
specGenerateOptions?: Value<Promisable<OpenAPIGeneratorGenerateOptions>, [StandardHandlerInterceptorOptions<T>]>;
|
|
15
|
+
/**
|
|
16
|
+
* The URL path at which to serve the OpenAPI JSON.
|
|
17
|
+
*
|
|
18
|
+
* @default '/spec.json'
|
|
19
|
+
*/
|
|
20
|
+
specPath?: HTTPPath;
|
|
21
|
+
/**
|
|
22
|
+
* The URL path at which to serve the API reference UI.
|
|
23
|
+
*
|
|
24
|
+
* @default '/'
|
|
25
|
+
*/
|
|
26
|
+
docsPath?: HTTPPath;
|
|
27
|
+
/**
|
|
28
|
+
* The document title for the API reference UI.
|
|
29
|
+
*
|
|
30
|
+
* @default 'API Reference'
|
|
31
|
+
*/
|
|
32
|
+
docsTitle?: Value<Promisable<string>, [StandardHandlerInterceptorOptions<T>]>;
|
|
33
|
+
/**
|
|
34
|
+
* The UI library to use for rendering the API reference.
|
|
35
|
+
*
|
|
36
|
+
* @default 'scalar'
|
|
37
|
+
*/
|
|
38
|
+
docsProvider?: 'scalar' | 'swagger';
|
|
39
|
+
/**
|
|
40
|
+
* Arbitrary configuration object for the UI.
|
|
41
|
+
*/
|
|
42
|
+
docsConfig?: Value<Promisable<Record<string, unknown>>, [StandardHandlerInterceptorOptions<T>]>;
|
|
43
|
+
/**
|
|
44
|
+
* HTML to inject into the <head> of the docs page.
|
|
45
|
+
*
|
|
46
|
+
* @warning This is not escaped special characters, so must be used with caution to avoid XSS vulnerabilities.
|
|
47
|
+
*
|
|
48
|
+
* @default ''
|
|
49
|
+
*/
|
|
50
|
+
docsHead?: Value<Promisable<string>, [StandardHandlerInterceptorOptions<T>]>;
|
|
51
|
+
/**
|
|
52
|
+
* URL of the external script bundle for the reference UI.
|
|
53
|
+
*
|
|
54
|
+
* - For Scalar: defaults to 'https://cdn.jsdelivr.net/npm/@scalar/api-reference'
|
|
55
|
+
* - For Swagger UI: defaults to 'https://unpkg.com/swagger-ui-dist@5.17.14/swagger-ui-bundle.js'
|
|
56
|
+
*/
|
|
57
|
+
docsScriptUrl?: Value<Promisable<string>, [StandardHandlerInterceptorOptions<T>]>;
|
|
58
|
+
/**
|
|
59
|
+
* URL of the external CSS bundle for the reference UI (used by Swagger UI).
|
|
60
|
+
*
|
|
61
|
+
* @default 'https://unpkg.com/swagger-ui-dist@5.17.14/swagger-ui.css' (if swagger)
|
|
62
|
+
*/
|
|
63
|
+
docsCssUrl?: Value<Promisable<string>, [StandardHandlerInterceptorOptions<T>]>;
|
|
64
|
+
/**
|
|
65
|
+
* Override function to generate the full HTML for the docs page.
|
|
66
|
+
*/
|
|
67
|
+
renderDocsHtml?: (specUrl: string, title: string, head: string, scriptUrl: string, config: Record<string, unknown> | undefined, spec: OpenAPI.Document, docsProvider: 'scalar' | 'swagger', cssUrl: string | undefined) => string;
|
|
68
|
+
}
|
|
69
|
+
declare class OpenAPIReferencePlugin<T extends Context> implements StandardHandlerPlugin<T> {
|
|
70
|
+
private readonly generator;
|
|
71
|
+
private readonly specGenerateOptions;
|
|
72
|
+
private readonly specPath;
|
|
73
|
+
private readonly docsPath;
|
|
74
|
+
private readonly docsTitle;
|
|
75
|
+
private readonly docsHead;
|
|
76
|
+
private readonly docsProvider;
|
|
77
|
+
private readonly docsScriptUrl;
|
|
78
|
+
private readonly docsCssUrl;
|
|
79
|
+
private readonly docsConfig;
|
|
80
|
+
private readonly renderDocsHtml;
|
|
81
|
+
constructor(options?: OpenAPIReferencePluginOptions<T>);
|
|
82
|
+
init(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export { OpenAPIReferencePlugin };
|
|
86
|
+
export type { OpenAPIReferencePluginOptions };
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { stringifyJSON, once, value } from '@orpc/shared';
|
|
2
|
+
import { O as OpenAPIGenerator } from '../shared/openapi.BwdtJjDu.mjs';
|
|
3
|
+
import '@orpc/client';
|
|
4
|
+
import '@orpc/client/standard';
|
|
5
|
+
import '@orpc/contract';
|
|
6
|
+
import '@orpc/openapi-client/standard';
|
|
7
|
+
import '@orpc/server';
|
|
8
|
+
import 'json-schema-typed/draft-2020-12';
|
|
9
|
+
|
|
10
|
+
class OpenAPIReferencePlugin {
|
|
11
|
+
generator;
|
|
12
|
+
specGenerateOptions;
|
|
13
|
+
specPath;
|
|
14
|
+
docsPath;
|
|
15
|
+
docsTitle;
|
|
16
|
+
docsHead;
|
|
17
|
+
docsProvider;
|
|
18
|
+
docsScriptUrl;
|
|
19
|
+
docsCssUrl;
|
|
20
|
+
docsConfig;
|
|
21
|
+
renderDocsHtml;
|
|
22
|
+
constructor(options = {}) {
|
|
23
|
+
this.specGenerateOptions = options.specGenerateOptions;
|
|
24
|
+
this.docsPath = options.docsPath ?? "/";
|
|
25
|
+
this.docsTitle = options.docsTitle ?? "API Reference";
|
|
26
|
+
this.docsConfig = options.docsConfig ?? void 0;
|
|
27
|
+
this.docsProvider = options.docsProvider ?? "scalar";
|
|
28
|
+
this.docsScriptUrl = options.docsScriptUrl ?? (this.docsProvider === "swagger" ? "https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js" : "https://cdn.jsdelivr.net/npm/@scalar/api-reference");
|
|
29
|
+
this.docsCssUrl = options.docsCssUrl ?? (this.docsProvider === "swagger" ? "https://unpkg.com/swagger-ui-dist/swagger-ui.css" : void 0);
|
|
30
|
+
this.docsHead = options.docsHead ?? "";
|
|
31
|
+
this.specPath = options.specPath ?? "/spec.json";
|
|
32
|
+
this.generator = new OpenAPIGenerator(options);
|
|
33
|
+
const escapeHtmlEntities = (s) => s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
34
|
+
const escapeJsonForHtml = (obj) => stringifyJSON(obj).replace(/&/g, "\\u0026").replace(/'/g, "\\u0027").replace(/</g, "\\u003C").replace(/>/g, "\\u003E").replace(/\//g, "\\u002F");
|
|
35
|
+
this.renderDocsHtml = options.renderDocsHtml ?? ((specUrl, title, head, scriptUrl, config, spec, docsProvider, cssUrl) => {
|
|
36
|
+
let body;
|
|
37
|
+
if (docsProvider === "swagger") {
|
|
38
|
+
const swaggerConfig = {
|
|
39
|
+
dom_id: "#app",
|
|
40
|
+
spec,
|
|
41
|
+
deepLinking: true,
|
|
42
|
+
presets: [
|
|
43
|
+
"SwaggerUIBundle.presets.apis",
|
|
44
|
+
"SwaggerUIBundle.presets.standalone"
|
|
45
|
+
],
|
|
46
|
+
plugins: [
|
|
47
|
+
"SwaggerUIBundle.plugins.DownloadUrl"
|
|
48
|
+
],
|
|
49
|
+
...config
|
|
50
|
+
};
|
|
51
|
+
body = `
|
|
52
|
+
<body>
|
|
53
|
+
<div id="app"></div>
|
|
54
|
+
|
|
55
|
+
<script src="${escapeHtmlEntities(scriptUrl)}"><\/script>
|
|
56
|
+
|
|
57
|
+
<!-- IMPORTANT: assign to a variable first to prevent ), ( in values breaking the call expression. -->
|
|
58
|
+
<!-- IMPORTANT: escapeJsonForHtml ensures <, > cannot terminate the <\/script> tag prematurely. -->
|
|
59
|
+
<script>
|
|
60
|
+
const swaggerConfig = ${escapeJsonForHtml(swaggerConfig).replace(/"(SwaggerUIBundle\.[^"]+)"/g, "$1")}
|
|
61
|
+
|
|
62
|
+
window.onload = () => {
|
|
63
|
+
window.ui = SwaggerUIBundle(swaggerConfig)
|
|
64
|
+
}
|
|
65
|
+
<\/script>
|
|
66
|
+
</body>
|
|
67
|
+
`;
|
|
68
|
+
} else {
|
|
69
|
+
const scalarConfig = {
|
|
70
|
+
content: stringifyJSON(spec),
|
|
71
|
+
...config
|
|
72
|
+
};
|
|
73
|
+
body = `
|
|
74
|
+
<body>
|
|
75
|
+
<div id="app"></div>
|
|
76
|
+
|
|
77
|
+
<script src="${escapeHtmlEntities(scriptUrl)}"><\/script>
|
|
78
|
+
|
|
79
|
+
<!-- IMPORTANT: assign to a variable first to prevent ), ( in values breaking the call expression. -->
|
|
80
|
+
<!-- IMPORTANT: escapeJsonForHtml ensures <, > cannot terminate the <\/script> tag prematurely. -->
|
|
81
|
+
<script>
|
|
82
|
+
const scalarConfig = ${escapeJsonForHtml(scalarConfig)}
|
|
83
|
+
|
|
84
|
+
Scalar.createApiReference('#app', scalarConfig)
|
|
85
|
+
<\/script>
|
|
86
|
+
</body>
|
|
87
|
+
`;
|
|
88
|
+
}
|
|
89
|
+
return `
|
|
90
|
+
<!doctype html>
|
|
91
|
+
<html>
|
|
92
|
+
<head>
|
|
93
|
+
<meta charset="utf-8" />
|
|
94
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
95
|
+
<title>${escapeHtmlEntities(title)}</title>
|
|
96
|
+
${cssUrl ? `<link rel="stylesheet" type="text/css" href="${escapeHtmlEntities(cssUrl)}" />` : ""}
|
|
97
|
+
${head}
|
|
98
|
+
</head>
|
|
99
|
+
${body}
|
|
100
|
+
</html>
|
|
101
|
+
`;
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
init(options, router) {
|
|
105
|
+
options.interceptors ??= [];
|
|
106
|
+
options.interceptors.push(async (options2) => {
|
|
107
|
+
const res = await options2.next();
|
|
108
|
+
if (res.matched || options2.request.method !== "GET") {
|
|
109
|
+
return res;
|
|
110
|
+
}
|
|
111
|
+
const prefix = options2.prefix ?? "";
|
|
112
|
+
const requestPathname = options2.request.url.pathname.replace(/\/$/, "") || "/";
|
|
113
|
+
const docsUrl = new URL(`${prefix}${this.docsPath}`.replace(/\/$/, ""), options2.request.url.origin);
|
|
114
|
+
const specUrl = new URL(`${prefix}${this.specPath}`.replace(/\/$/, ""), options2.request.url.origin);
|
|
115
|
+
const generateSpec = once(async () => {
|
|
116
|
+
return await this.generator.generate(router, {
|
|
117
|
+
servers: [{ url: new URL(prefix, options2.request.url.origin).toString() }],
|
|
118
|
+
...await value(this.specGenerateOptions, options2)
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
if (requestPathname === specUrl.pathname) {
|
|
122
|
+
const spec = await generateSpec();
|
|
123
|
+
return {
|
|
124
|
+
matched: true,
|
|
125
|
+
response: {
|
|
126
|
+
status: 200,
|
|
127
|
+
headers: {},
|
|
128
|
+
body: new File([stringifyJSON(spec)], "spec.json", { type: "application/json" })
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
if (requestPathname === docsUrl.pathname) {
|
|
133
|
+
const html = this.renderDocsHtml(
|
|
134
|
+
specUrl.toString(),
|
|
135
|
+
await value(this.docsTitle, options2),
|
|
136
|
+
await value(this.docsHead, options2),
|
|
137
|
+
await value(this.docsScriptUrl, options2),
|
|
138
|
+
await value(this.docsConfig, options2),
|
|
139
|
+
await generateSpec(),
|
|
140
|
+
this.docsProvider,
|
|
141
|
+
await value(this.docsCssUrl, options2)
|
|
142
|
+
);
|
|
143
|
+
return {
|
|
144
|
+
matched: true,
|
|
145
|
+
response: {
|
|
146
|
+
status: 200,
|
|
147
|
+
headers: {},
|
|
148
|
+
body: new File([html], "api-reference.html", { type: "text/html" })
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
return res;
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export { OpenAPIReferencePlugin };
|
|
@@ -1,13 +1,18 @@
|
|
|
1
|
+
import { standardizeHTTPPath, StandardOpenAPIJsonSerializer, StandardBracketNotationSerializer, StandardOpenAPISerializer } from '@orpc/openapi-client/standard';
|
|
2
|
+
import { StandardHandler } from '@orpc/server/standard';
|
|
3
|
+
import { isORPCErrorStatus } from '@orpc/client';
|
|
1
4
|
import { fallbackContractConfig } from '@orpc/contract';
|
|
2
|
-
import { isObject } from '@orpc/shared';
|
|
3
|
-
import {
|
|
5
|
+
import { isObject, stringifyJSON, tryDecodeURIComponent, value } from '@orpc/shared';
|
|
6
|
+
import { toHttpPath } from '@orpc/client/standard';
|
|
7
|
+
import { traverseContractProcedures, isProcedure, getLazyMeta, unlazy, getRouter, createContractedProcedure } from '@orpc/server';
|
|
4
8
|
import { createRouter, addRoute, findRoute } from 'rou3';
|
|
5
|
-
import { s as standardizeHTTPPath } from './openapi.BHG_gu5Z.mjs';
|
|
6
9
|
|
|
7
|
-
class
|
|
8
|
-
constructor(serializer) {
|
|
10
|
+
class StandardOpenAPICodec {
|
|
11
|
+
constructor(serializer, options = {}) {
|
|
9
12
|
this.serializer = serializer;
|
|
13
|
+
this.customErrorResponseBodyEncoder = options.customErrorResponseBodyEncoder;
|
|
10
14
|
}
|
|
15
|
+
customErrorResponseBodyEncoder;
|
|
11
16
|
async decode(request, params, procedure) {
|
|
12
17
|
const inputStructure = fallbackContractConfig("defaultInputStructure", procedure["~orpc"].route.inputStructure);
|
|
13
18
|
if (inputStructure === "compact") {
|
|
@@ -44,42 +49,89 @@ class OpenAPICodec {
|
|
|
44
49
|
const successStatus = fallbackContractConfig("defaultSuccessStatus", procedure["~orpc"].route.successStatus);
|
|
45
50
|
const outputStructure = fallbackContractConfig("defaultOutputStructure", procedure["~orpc"].route.outputStructure);
|
|
46
51
|
if (outputStructure === "compact") {
|
|
52
|
+
if (output instanceof ReadableStream) {
|
|
53
|
+
return {
|
|
54
|
+
status: successStatus,
|
|
55
|
+
headers: {},
|
|
56
|
+
body: output
|
|
57
|
+
};
|
|
58
|
+
}
|
|
47
59
|
return {
|
|
48
60
|
status: successStatus,
|
|
49
61
|
headers: {},
|
|
50
62
|
body: this.serializer.serialize(output)
|
|
51
63
|
};
|
|
52
64
|
}
|
|
53
|
-
if (!
|
|
54
|
-
throw new Error(
|
|
55
|
-
|
|
56
|
-
|
|
65
|
+
if (!this.#isDetailedOutput(output)) {
|
|
66
|
+
throw new Error(`
|
|
67
|
+
Invalid "detailed" output structure:
|
|
68
|
+
\u2022 Expected an object with optional properties:
|
|
69
|
+
- status (number 200-399)
|
|
70
|
+
- headers (Record<string, string | string[]>)
|
|
71
|
+
- body (any)
|
|
72
|
+
\u2022 No extra keys allowed.
|
|
73
|
+
|
|
74
|
+
Actual value:
|
|
75
|
+
${stringifyJSON(output)}
|
|
76
|
+
`);
|
|
77
|
+
}
|
|
78
|
+
if (output.body instanceof ReadableStream) {
|
|
79
|
+
return {
|
|
80
|
+
status: output.status ?? successStatus,
|
|
81
|
+
headers: output.headers ?? {},
|
|
82
|
+
body: output.body
|
|
83
|
+
};
|
|
57
84
|
}
|
|
58
85
|
return {
|
|
59
|
-
status: successStatus,
|
|
86
|
+
status: output.status ?? successStatus,
|
|
60
87
|
headers: output.headers ?? {},
|
|
61
88
|
body: this.serializer.serialize(output.body)
|
|
62
89
|
};
|
|
63
90
|
}
|
|
64
91
|
encodeError(error) {
|
|
92
|
+
const body = this.customErrorResponseBodyEncoder?.(error) ?? error.toJSON();
|
|
65
93
|
return {
|
|
66
94
|
status: error.status,
|
|
67
95
|
headers: {},
|
|
68
|
-
body: this.serializer.serialize(
|
|
96
|
+
body: this.serializer.serialize(body, { outputFormat: "plain" })
|
|
69
97
|
};
|
|
70
98
|
}
|
|
99
|
+
#isDetailedOutput(output) {
|
|
100
|
+
if (!isObject(output)) {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
if (output.headers && !isObject(output.headers)) {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
if (output.status !== void 0 && (typeof output.status !== "number" || !Number.isInteger(output.status) || isORPCErrorStatus(output.status))) {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
71
111
|
}
|
|
72
112
|
|
|
73
|
-
|
|
113
|
+
function toRou3Pattern(path) {
|
|
114
|
+
return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
|
|
115
|
+
}
|
|
116
|
+
function decodeParams(params) {
|
|
117
|
+
return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, tryDecodeURIComponent(value)]));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
class StandardOpenAPIMatcher {
|
|
121
|
+
filter;
|
|
74
122
|
tree = createRouter();
|
|
75
123
|
pendingRouters = [];
|
|
124
|
+
constructor(options = {}) {
|
|
125
|
+
this.filter = options.filter ?? true;
|
|
126
|
+
}
|
|
76
127
|
init(router, path = []) {
|
|
77
|
-
const laziedOptions =
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
128
|
+
const laziedOptions = traverseContractProcedures({ router, path }, (traverseOptions) => {
|
|
129
|
+
if (!value(this.filter, traverseOptions)) {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const { path: path2, contract } = traverseOptions;
|
|
81
133
|
const method = fallbackContractConfig("defaultMethod", contract["~orpc"].route.method);
|
|
82
|
-
const httpPath =
|
|
134
|
+
const httpPath = toRou3Pattern(contract["~orpc"].route.path ?? toHttpPath(path2));
|
|
83
135
|
if (isProcedure(contract)) {
|
|
84
136
|
addRoute(this.tree, method, httpPath, {
|
|
85
137
|
path: path2,
|
|
@@ -99,8 +151,8 @@ class OpenAPIMatcher {
|
|
|
99
151
|
});
|
|
100
152
|
this.pendingRouters.push(...laziedOptions.map((option) => ({
|
|
101
153
|
...option,
|
|
102
|
-
httpPathPrefix:
|
|
103
|
-
laziedPrefix:
|
|
154
|
+
httpPathPrefix: toHttpPath(option.path),
|
|
155
|
+
laziedPrefix: getLazyMeta(option.router).prefix
|
|
104
156
|
})));
|
|
105
157
|
}
|
|
106
158
|
async match(method, pathname) {
|
|
@@ -108,7 +160,7 @@ class OpenAPIMatcher {
|
|
|
108
160
|
const newPendingRouters = [];
|
|
109
161
|
for (const pendingRouter of this.pendingRouters) {
|
|
110
162
|
if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
|
|
111
|
-
const { default: router } = await unlazy(pendingRouter.
|
|
163
|
+
const { default: router } = await unlazy(pendingRouter.router);
|
|
112
164
|
this.init(router, pendingRouter.path);
|
|
113
165
|
} else {
|
|
114
166
|
newPendingRouters.push(pendingRouter);
|
|
@@ -121,14 +173,14 @@ class OpenAPIMatcher {
|
|
|
121
173
|
return void 0;
|
|
122
174
|
}
|
|
123
175
|
if (!match.data.procedure) {
|
|
124
|
-
const { default: maybeProcedure } = await unlazy(
|
|
176
|
+
const { default: maybeProcedure } = await unlazy(getRouter(match.data.router, match.data.path));
|
|
125
177
|
if (!isProcedure(maybeProcedure)) {
|
|
126
178
|
throw new Error(`
|
|
127
|
-
[Contract-First] Missing or invalid implementation for procedure at path: ${
|
|
179
|
+
[Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.data.path)}.
|
|
128
180
|
Ensure that the procedure is correctly defined and matches the expected contract.
|
|
129
181
|
`);
|
|
130
182
|
}
|
|
131
|
-
match.data.procedure = createContractedProcedure(match.data.contract
|
|
183
|
+
match.data.procedure = createContractedProcedure(maybeProcedure, match.data.contract);
|
|
132
184
|
}
|
|
133
185
|
return {
|
|
134
186
|
path: match.data.path,
|
|
@@ -137,11 +189,16 @@ class OpenAPIMatcher {
|
|
|
137
189
|
};
|
|
138
190
|
}
|
|
139
191
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
192
|
+
|
|
193
|
+
class StandardOpenAPIHandler extends StandardHandler {
|
|
194
|
+
constructor(router, options) {
|
|
195
|
+
const jsonSerializer = new StandardOpenAPIJsonSerializer(options);
|
|
196
|
+
const bracketNotationSerializer = new StandardBracketNotationSerializer(options);
|
|
197
|
+
const serializer = new StandardOpenAPISerializer(jsonSerializer, bracketNotationSerializer);
|
|
198
|
+
const matcher = new StandardOpenAPIMatcher(options);
|
|
199
|
+
const codec = new StandardOpenAPICodec(serializer, options);
|
|
200
|
+
super(router, matcher, codec, options);
|
|
201
|
+
}
|
|
145
202
|
}
|
|
146
203
|
|
|
147
|
-
export {
|
|
204
|
+
export { StandardOpenAPICodec as S, StandardOpenAPIHandler as a, StandardOpenAPIMatcher as b, decodeParams as d, toRou3Pattern as t };
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { AnySchema, OpenAPI, AnyContractProcedure, AnyContractRouter } from '@orpc/contract';
|
|
2
|
+
import { StandardOpenAPIJsonSerializerOptions } from '@orpc/openapi-client/standard';
|
|
3
|
+
import { AnyProcedure, TraverseContractProcedureCallbackOptions, AnyRouter } from '@orpc/server';
|
|
4
|
+
import { Promisable, Value } from '@orpc/shared';
|
|
5
|
+
import { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
6
|
+
|
|
7
|
+
interface SchemaConverterComponent {
|
|
8
|
+
allowedStrategies: readonly SchemaConvertOptions['strategy'][];
|
|
9
|
+
schema: AnySchema;
|
|
10
|
+
required: boolean;
|
|
11
|
+
ref: string;
|
|
12
|
+
}
|
|
13
|
+
interface SchemaConvertOptions {
|
|
14
|
+
strategy: 'input' | 'output';
|
|
15
|
+
/**
|
|
16
|
+
* Common components should use `$ref` to represent themselves if matched.
|
|
17
|
+
*/
|
|
18
|
+
components?: readonly SchemaConverterComponent[];
|
|
19
|
+
/**
|
|
20
|
+
* Minimum schema structure depth required before using `$ref` for components.
|
|
21
|
+
*
|
|
22
|
+
* For example, if set to 2, `$ref` will only be used for schemas nested at depth 2 or greater.
|
|
23
|
+
*
|
|
24
|
+
* @default 0 - No depth limit;
|
|
25
|
+
*/
|
|
26
|
+
minStructureDepthForRef?: number;
|
|
27
|
+
}
|
|
28
|
+
interface SchemaConverter {
|
|
29
|
+
convert(schema: AnySchema | undefined, options: SchemaConvertOptions): Promisable<[required: boolean, jsonSchema: JSONSchema]>;
|
|
30
|
+
}
|
|
31
|
+
interface ConditionalSchemaConverter extends SchemaConverter {
|
|
32
|
+
condition(schema: AnySchema | undefined, options: SchemaConvertOptions): Promisable<boolean>;
|
|
33
|
+
}
|
|
34
|
+
declare class CompositeSchemaConverter implements SchemaConverter {
|
|
35
|
+
private readonly converters;
|
|
36
|
+
constructor(converters: readonly ConditionalSchemaConverter[]);
|
|
37
|
+
convert(schema: AnySchema | undefined, options: SchemaConvertOptions): Promise<[required: boolean, jsonSchema: JSONSchema]>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface OpenAPIGeneratorOptions extends StandardOpenAPIJsonSerializerOptions {
|
|
41
|
+
schemaConverters?: ConditionalSchemaConverter[];
|
|
42
|
+
}
|
|
43
|
+
interface OpenAPIGeneratorGenerateOptions extends Partial<Omit<OpenAPI.Document, 'openapi'>> {
|
|
44
|
+
/**
|
|
45
|
+
* Exclude procedures from the OpenAPI specification.
|
|
46
|
+
*
|
|
47
|
+
* @deprecated Use `filter` option instead.
|
|
48
|
+
* @default () => false
|
|
49
|
+
*/
|
|
50
|
+
exclude?: (procedure: AnyProcedure | AnyContractProcedure, path: readonly string[]) => boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Filter procedures. Return `false` to exclude a procedure from the OpenAPI specification.
|
|
53
|
+
*
|
|
54
|
+
* @default true
|
|
55
|
+
*/
|
|
56
|
+
filter?: Value<boolean, [options: TraverseContractProcedureCallbackOptions]>;
|
|
57
|
+
/**
|
|
58
|
+
* Common schemas to be used for $ref resolution.
|
|
59
|
+
*/
|
|
60
|
+
commonSchemas?: Record<string, {
|
|
61
|
+
/**
|
|
62
|
+
* Determines which schema definition to use when input and output schemas differ.
|
|
63
|
+
* This is needed because some schemas transform data differently between input and output,
|
|
64
|
+
* making it impossible to use a single $ref for both cases.
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```ts
|
|
68
|
+
* // This schema transforms a string input into a number output
|
|
69
|
+
* const Schema = z.string()
|
|
70
|
+
* .transform(v => Number(v))
|
|
71
|
+
* .pipe(z.number())
|
|
72
|
+
*
|
|
73
|
+
* // Input schema: { type: 'string' }
|
|
74
|
+
* // Output schema: { type: 'number' }
|
|
75
|
+
* ```
|
|
76
|
+
*
|
|
77
|
+
* When schemas differ between input and output, you must explicitly choose
|
|
78
|
+
* which version to use for the OpenAPI specification.
|
|
79
|
+
*
|
|
80
|
+
* @default 'input' - Uses the input schema definition by default
|
|
81
|
+
*/
|
|
82
|
+
strategy?: SchemaConvertOptions['strategy'];
|
|
83
|
+
schema: AnySchema;
|
|
84
|
+
} | {
|
|
85
|
+
error: 'UndefinedError';
|
|
86
|
+
schema?: never;
|
|
87
|
+
}>;
|
|
88
|
+
/**
|
|
89
|
+
* Define a custom JSON schema for the error response body when using
|
|
90
|
+
* type-safe errors. Helps align ORPC error formatting with existing API
|
|
91
|
+
* response standards or conventions.
|
|
92
|
+
*
|
|
93
|
+
* @remarks
|
|
94
|
+
* - Return `null | undefined` to use the default error response body shaper.
|
|
95
|
+
*/
|
|
96
|
+
customErrorResponseBodySchema?: Value<JSONSchema | undefined | null, [
|
|
97
|
+
definedErrors: [code: string, defaultMessage: string, dataRequired: boolean, dataSchema: JSONSchema][],
|
|
98
|
+
status: number
|
|
99
|
+
]>;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The generator that converts oRPC routers/contracts to OpenAPI specifications.
|
|
103
|
+
*
|
|
104
|
+
* @see {@link https://orpc.dev/docs/openapi/openapi-specification OpenAPI Specification Docs}
|
|
105
|
+
*/
|
|
106
|
+
declare class OpenAPIGenerator {
|
|
107
|
+
#private;
|
|
108
|
+
private readonly serializer;
|
|
109
|
+
private readonly converter;
|
|
110
|
+
constructor(options?: OpenAPIGeneratorOptions);
|
|
111
|
+
/**
|
|
112
|
+
* Generates OpenAPI specifications from oRPC routers/contracts.
|
|
113
|
+
*
|
|
114
|
+
* @see {@link https://orpc.dev/docs/openapi/openapi-specification OpenAPI Specification Docs}
|
|
115
|
+
*/
|
|
116
|
+
generate(router: AnyContractRouter | AnyRouter, { customErrorResponseBodySchema, commonSchemas, filter: baseFilter, exclude, ...baseDoc }?: OpenAPIGeneratorGenerateOptions): Promise<OpenAPI.Document>;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export { OpenAPIGenerator as b, CompositeSchemaConverter as e };
|
|
120
|
+
export type { ConditionalSchemaConverter as C, OpenAPIGeneratorOptions as O, SchemaConverterComponent as S, OpenAPIGeneratorGenerateOptions as a, SchemaConvertOptions as c, SchemaConverter as d };
|