@orpc/openapi 0.0.0-next.f4d410a → 0.0.0-next.f4ed9ab

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/dist/index.mjs CHANGED
@@ -1,303 +1,41 @@
1
- import { isProcedure, resolveContractProcedures, toHttpPath } from '@orpc/server';
2
- import { fallbackORPCErrorStatus, fallbackORPCErrorMessage } from '@orpc/client';
3
- import { fallbackContractConfig, getEventIteratorSchemaDetails } from '@orpc/contract';
4
- import { StandardOpenAPIJsonSerializer } from '@orpc/openapi-client/standard';
5
- import { clone } from '@orpc/shared';
6
- import { t as toOpenAPIMethod, a as toOpenAPIPath, b as toOpenAPIEventIteratorContent, g as getDynamicParams, i as isAnySchema, c as isObjectSchema, d as separateObjectSchema, e as checkParamsSchema, f as toOpenAPIParameters, h as toOpenAPIContent, j as toOpenAPISchema } from './shared/openapi.DZzpQAb-.mjs';
7
- export { L as LOGIC_KEYWORDS, l as filterSchemaBranches, k as isFileSchema, s as standardizeHTTPPath } from './shared/openapi.DZzpQAb-.mjs';
8
- export { Format as JSONSchemaFormat } from 'json-schema-typed/draft-2020-12';
1
+ import { c as customOpenAPIOperation } from './shared/openapi.PDTdnRIU.mjs';
2
+ export { C as CompositeSchemaConverter, L as LOGIC_KEYWORDS, O as OpenAPIGenerator, a as applyCustomOpenAPIOperation, n as applySchemaOptionality, h as checkParamsSchema, o as expandUnionSchema, m as filterSchemaBranches, g as getCustomOpenAPIOperation, l as isAnySchema, j as isFileSchema, k as isObjectSchema, s as separateObjectSchema, d as toOpenAPIContent, e as toOpenAPIEventIteratorContent, b as toOpenAPIMethod, f as toOpenAPIParameters, t as toOpenAPIPath, i as toOpenAPISchema } from './shared/openapi.PDTdnRIU.mjs';
3
+ import { createORPCErrorFromJson } from '@orpc/client';
4
+ import { StandardOpenAPISerializer, StandardOpenAPIJsonSerializer, StandardBracketNotationSerializer } from '@orpc/openapi-client/standard';
5
+ import { ORPCError, createRouterClient } from '@orpc/server';
6
+ import { resolveMaybeOptionalOptions } from '@orpc/shared';
7
+ export { ContentEncoding as JSONSchemaContentEncoding, Format as JSONSchemaFormat } from 'json-schema-typed/draft-2020-12';
8
+ import '@orpc/client/standard';
9
+ import '@orpc/contract';
9
10
 
10
- const OPERATION_EXTENDER_SYMBOL = Symbol("ORPC_OPERATION_EXTENDER");
11
- function customOpenAPIOperation(o, extend) {
12
- return new Proxy(o, {
13
- get(target, prop, receiver) {
14
- if (prop === OPERATION_EXTENDER_SYMBOL) {
15
- return extend;
16
- }
17
- return Reflect.get(target, prop, receiver);
18
- }
19
- });
20
- }
21
- function getCustomOpenAPIOperation(o) {
22
- return o[OPERATION_EXTENDER_SYMBOL];
23
- }
24
- function applyCustomOpenAPIOperation(operation, contract) {
25
- const operationCustoms = [];
26
- for (const errorItem of Object.values(contract["~orpc"].errorMap)) {
27
- const maybeExtender = errorItem ? getCustomOpenAPIOperation(errorItem) : void 0;
28
- if (maybeExtender) {
29
- operationCustoms.push(maybeExtender);
30
- }
31
- }
32
- if (isProcedure(contract)) {
33
- for (const middleware of contract["~orpc"].middlewares) {
34
- const maybeExtender = getCustomOpenAPIOperation(middleware);
35
- if (maybeExtender) {
36
- operationCustoms.push(maybeExtender);
37
- }
38
- }
39
- }
40
- let currentOperation = operation;
41
- for (const custom of operationCustoms) {
42
- if (typeof custom === "function") {
43
- currentOperation = custom(currentOperation, contract);
44
- } else {
45
- currentOperation = {
46
- ...currentOperation,
47
- ...custom
48
- };
49
- }
50
- }
51
- return currentOperation;
52
- }
53
-
54
- class CompositeSchemaConverter {
55
- converters;
56
- constructor(converters) {
57
- this.converters = converters;
58
- }
59
- convert(schema, options) {
60
- for (const converter of this.converters) {
61
- if (converter.condition(schema, options)) {
62
- return converter.convert(schema, options);
63
- }
64
- }
65
- return [false, {}];
66
- }
67
- }
68
-
69
- class OpenAPIGeneratorError extends Error {
70
- }
71
- class OpenAPIGenerator {
72
- serializer;
73
- converter;
74
- constructor(options = {}) {
75
- this.serializer = new StandardOpenAPIJsonSerializer(options);
76
- this.converter = new CompositeSchemaConverter(options.schemaConverters ?? []);
77
- }
78
- async generate(router, base) {
79
- const doc = clone(base);
80
- doc.openapi = "3.1.1";
81
- const errors = [];
82
- await resolveContractProcedures({ path: [], router }, ({ contract, path }) => {
83
- const operationId = path.join(".");
84
- try {
85
- const def = contract["~orpc"];
86
- const method = toOpenAPIMethod(fallbackContractConfig("defaultMethod", def.route.method));
87
- const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path));
88
- const operationObjectRef = {
89
- operationId,
90
- summary: def.route.summary,
91
- description: def.route.description,
92
- deprecated: def.route.deprecated,
93
- tags: def.route.tags?.map((tag) => tag)
94
- };
95
- this.#request(operationObjectRef, def);
96
- this.#successResponse(operationObjectRef, def);
97
- this.#errorResponse(operationObjectRef, def);
98
- doc.paths ??= {};
99
- doc.paths[httpPath] ??= {};
100
- doc.paths[httpPath][method] = applyCustomOpenAPIOperation(operationObjectRef, contract);
101
- } catch (e) {
102
- if (!(e instanceof OpenAPIGeneratorError)) {
103
- throw e;
104
- }
105
- errors.push(
106
- `[OpenAPIGenerator] Error occurred while generating OpenAPI for procedure at path: ${operationId}
107
- ${e.message}`
108
- );
109
- }
110
- });
111
- if (errors.length) {
112
- throw new OpenAPIGeneratorError(
113
- `Some error occurred during OpenAPI generation:
114
-
115
- ${errors.join("\n\n")}`
116
- );
117
- }
118
- return this.serializer.serialize(doc)[0];
119
- }
120
- #request(ref, def) {
121
- const method = fallbackContractConfig("defaultMethod", def.route.method);
122
- const details = getEventIteratorSchemaDetails(def.inputSchema);
123
- if (details) {
124
- ref.requestBody = {
125
- required: true,
126
- content: toOpenAPIEventIteratorContent(
127
- this.converter.convert(details.yields, { strategy: "input" }),
128
- this.converter.convert(details.returns, { strategy: "input" })
11
+ function createJsonifiedRouterClient(router, ...rest) {
12
+ const options = resolveMaybeOptionalOptions(rest);
13
+ const serializer = new StandardOpenAPISerializer(new StandardOpenAPIJsonSerializer(), new StandardBracketNotationSerializer());
14
+ options.interceptors ??= [];
15
+ options.interceptors.unshift(async (options2) => {
16
+ try {
17
+ return serializer.deserialize(
18
+ serializer.serialize(
19
+ await options2.next()
129
20
  )
130
- };
131
- return;
132
- }
133
- const dynamicParams = getDynamicParams(def.route.path);
134
- const inputStructure = fallbackContractConfig("defaultInputStructure", def.route.inputStructure);
135
- let [required, schema] = this.converter.convert(def.inputSchema, { strategy: "input" });
136
- if (isAnySchema(schema) && !dynamicParams?.length) {
137
- return;
138
- }
139
- if (inputStructure === "compact") {
140
- if (dynamicParams?.length) {
141
- const error2 = new OpenAPIGeneratorError(
142
- 'When input structure is "compact", and path has dynamic params, input schema must be an object with all dynamic params as required.'
143
- );
144
- if (!isObjectSchema(schema)) {
145
- throw error2;
146
- }
147
- const [paramsSchema, rest] = separateObjectSchema(schema, dynamicParams);
148
- schema = rest;
149
- required = rest.required ? rest.required.length !== 0 : false;
150
- if (!checkParamsSchema(paramsSchema, dynamicParams)) {
151
- throw error2;
152
- }
153
- ref.parameters ??= [];
154
- ref.parameters.push(...toOpenAPIParameters(paramsSchema, "path"));
155
- }
156
- if (method === "GET") {
157
- if (!isObjectSchema(schema)) {
158
- throw new OpenAPIGeneratorError(
159
- 'When method is "GET", input schema must satisfy: object | any | unknown'
160
- );
161
- }
162
- ref.parameters ??= [];
163
- ref.parameters.push(...toOpenAPIParameters(schema, "query"));
164
- } else {
165
- ref.requestBody = {
166
- required,
167
- content: toOpenAPIContent(schema)
168
- };
169
- }
170
- return;
171
- }
172
- const error = new OpenAPIGeneratorError(
173
- 'When input structure is "detailed", input schema must satisfy: { params?: Record<string, unknown>, query?: Record<string, unknown>, headers?: Record<string, unknown>, body?: unknown }'
174
- );
175
- if (!isObjectSchema(schema)) {
176
- throw error;
177
- }
178
- if (dynamicParams?.length && (schema.properties?.params === void 0 || !isObjectSchema(schema.properties.params) || !checkParamsSchema(schema.properties.params, dynamicParams))) {
179
- throw new OpenAPIGeneratorError(
180
- 'When input structure is "detailed" and path has dynamic params, the "params" schema must be an object with all dynamic params as required.'
181
21
  );
182
- }
183
- for (const from of ["params", "query", "headers"]) {
184
- const fromSchema = schema.properties?.[from];
185
- if (fromSchema !== void 0) {
186
- if (!isObjectSchema(fromSchema)) {
187
- throw error;
188
- }
189
- const parameterIn = from === "params" ? "path" : from === "headers" ? "header" : "query";
190
- ref.parameters ??= [];
191
- ref.parameters.push(...toOpenAPIParameters(fromSchema, parameterIn));
192
- }
193
- }
194
- if (schema.properties?.body !== void 0) {
195
- ref.requestBody = {
196
- required: schema.required?.includes("body"),
197
- content: toOpenAPIContent(schema.properties.body)
198
- };
199
- }
200
- }
201
- #successResponse(ref, def) {
202
- const outputSchema = def.outputSchema;
203
- const status = fallbackContractConfig("defaultSuccessStatus", def.route.successStatus);
204
- const description = fallbackContractConfig("defaultSuccessDescription", def.route?.successDescription);
205
- const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(outputSchema);
206
- const outputStructure = fallbackContractConfig("defaultOutputStructure", def.route.outputStructure);
207
- if (eventIteratorSchemaDetails) {
208
- ref.responses ??= {};
209
- ref.responses[status] = {
210
- description,
211
- content: toOpenAPIEventIteratorContent(
212
- this.converter.convert(eventIteratorSchemaDetails.yields, { strategy: "output" }),
213
- this.converter.convert(eventIteratorSchemaDetails.returns, { strategy: "output" })
214
- )
215
- };
216
- return;
217
- }
218
- const [_, json] = this.converter.convert(outputSchema, { strategy: "output" });
219
- ref.responses ??= {};
220
- ref.responses[status] = {
221
- description
222
- };
223
- if (outputStructure === "compact") {
224
- ref.responses[status].content = toOpenAPIContent(json);
225
- return;
226
- }
227
- const error = new OpenAPIGeneratorError(
228
- 'When output structure is "detailed", output schema must satisfy: { headers?: Record<string, unknown>, body?: unknown }'
229
- );
230
- if (!isObjectSchema(json)) {
231
- throw error;
232
- }
233
- if (json.properties?.headers !== void 0) {
234
- if (!isObjectSchema(json.properties.headers)) {
235
- throw error;
236
- }
237
- for (const key in json.properties.headers.properties) {
238
- ref.responses[status].headers ??= {};
239
- ref.responses[status].headers[key] = {
240
- schema: toOpenAPISchema(json.properties.headers.properties[key]),
241
- required: json.properties.headers.required?.includes(key)
242
- };
22
+ } catch (e) {
23
+ if (e instanceof ORPCError) {
24
+ throw createORPCErrorFromJson(serializer.deserialize(
25
+ serializer.serialize(
26
+ e.toJSON(),
27
+ { outputFormat: "plain" }
28
+ )
29
+ ));
243
30
  }
31
+ throw e;
244
32
  }
245
- if (json.properties?.body !== void 0) {
246
- ref.responses[status].content = toOpenAPIContent(json.properties.body);
247
- }
248
- }
249
- #errorResponse(ref, def) {
250
- const errorMap = def.errorMap;
251
- const errors = {};
252
- for (const code in errorMap) {
253
- const config = errorMap[code];
254
- if (!config) {
255
- continue;
256
- }
257
- const status = fallbackORPCErrorStatus(code, config.status);
258
- const message = fallbackORPCErrorMessage(code, config.message);
259
- const [dataRequired, dataSchema] = this.converter.convert(config.data, { strategy: "output" });
260
- errors[status] ??= [];
261
- errors[status].push({
262
- type: "object",
263
- properties: {
264
- defined: { const: true },
265
- code: { const: code },
266
- status: { const: status },
267
- message: { type: "string", default: message },
268
- data: dataSchema
269
- },
270
- required: dataRequired ? ["defined", "code", "status", "message", "data"] : ["defined", "code", "status", "message"]
271
- });
272
- }
273
- ref.responses ??= {};
274
- for (const status in errors) {
275
- const schemas = errors[status];
276
- ref.responses[status] = {
277
- description: status,
278
- content: toOpenAPIContent({
279
- oneOf: [
280
- ...schemas,
281
- {
282
- type: "object",
283
- properties: {
284
- defined: { const: false },
285
- code: { type: "string" },
286
- status: { type: "number" },
287
- message: { type: "string" },
288
- data: {}
289
- },
290
- required: ["defined", "code", "status", "message"]
291
- }
292
- ]
293
- })
294
- };
295
- }
296
- }
33
+ });
34
+ return createRouterClient(router, options);
297
35
  }
298
36
 
299
37
  const oo = {
300
38
  spec: customOpenAPIOperation
301
39
  };
302
40
 
303
- export { CompositeSchemaConverter, OpenAPIGenerator, applyCustomOpenAPIOperation, checkParamsSchema, customOpenAPIOperation, getCustomOpenAPIOperation, getDynamicParams, isAnySchema, isObjectSchema, oo, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
41
+ export { createJsonifiedRouterClient, customOpenAPIOperation, oo };
@@ -0,0 +1,70 @@
1
+ import { Context, HTTPPath, Router } from '@orpc/server';
2
+ import { StandardHandlerInterceptorOptions, StandardHandlerPlugin, StandardHandlerOptions } from '@orpc/server/standard';
3
+ import { Value } from '@orpc/shared';
4
+ import { OpenAPIV3_1 } from 'openapi-types';
5
+ import { O as OpenAPIGeneratorOptions, a as OpenAPIGeneratorGenerateOptions } from '../shared/openapi.CwdCLgSU.mjs';
6
+ import '@orpc/contract';
7
+ import '@orpc/openapi-client/standard';
8
+ import 'json-schema-typed/draft-2020-12';
9
+
10
+ interface OpenAPIReferencePluginOptions<T extends Context> extends OpenAPIGeneratorOptions {
11
+ /**
12
+ * Options to pass to the OpenAPI generate.
13
+ *
14
+ */
15
+ specGenerateOptions?: Value<OpenAPIGeneratorGenerateOptions, [StandardHandlerInterceptorOptions<T>]>;
16
+ /**
17
+ * The URL path at which to serve the OpenAPI JSON.
18
+ *
19
+ * @default '/spec.json'
20
+ */
21
+ specPath?: HTTPPath;
22
+ /**
23
+ * The URL path at which to serve the API reference UI.
24
+ *
25
+ * @default '/'
26
+ */
27
+ docsPath?: HTTPPath;
28
+ /**
29
+ * The document title for the API reference UI.
30
+ *
31
+ * @default 'API Reference'
32
+ */
33
+ docsTitle?: Value<string, [StandardHandlerInterceptorOptions<T>]>;
34
+ /**
35
+ * Arbitrary configuration object for the UI.
36
+ */
37
+ docsConfig?: Value<Record<string, unknown>, [StandardHandlerInterceptorOptions<T>]>;
38
+ /**
39
+ * HTML to inject into the <head> of the docs page.
40
+ *
41
+ * @default ''
42
+ */
43
+ docsHead?: Value<string, [StandardHandlerInterceptorOptions<T>]>;
44
+ /**
45
+ * URL of the external script bundle for the reference UI.
46
+ *
47
+ * @default 'https://cdn.jsdelivr.net/npm/@scalar/api-reference'
48
+ */
49
+ docsScriptUrl?: Value<string, [StandardHandlerInterceptorOptions<T>]>;
50
+ /**
51
+ * Override function to generate the full HTML for the docs page.
52
+ */
53
+ renderDocsHtml?: (specUrl: string, title: string, head: string, scriptUrl: string, config: Record<string, unknown> | undefined, spec: OpenAPIV3_1.Document) => string;
54
+ }
55
+ declare class OpenAPIReferencePlugin<T extends Context> implements StandardHandlerPlugin<T> {
56
+ private readonly generator;
57
+ private readonly specGenerateOptions;
58
+ private readonly specPath;
59
+ private readonly docsPath;
60
+ private readonly docsTitle;
61
+ private readonly docsHead;
62
+ private readonly docsScriptUrl;
63
+ private readonly docsConfig;
64
+ private readonly renderDocsHtml;
65
+ constructor(options?: OpenAPIReferencePluginOptions<T>);
66
+ init(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
67
+ }
68
+
69
+ export { OpenAPIReferencePlugin };
70
+ export type { OpenAPIReferencePluginOptions };
@@ -0,0 +1,70 @@
1
+ import { Context, HTTPPath, Router } from '@orpc/server';
2
+ import { StandardHandlerInterceptorOptions, StandardHandlerPlugin, StandardHandlerOptions } from '@orpc/server/standard';
3
+ import { Value } from '@orpc/shared';
4
+ import { OpenAPIV3_1 } from 'openapi-types';
5
+ import { O as OpenAPIGeneratorOptions, a as OpenAPIGeneratorGenerateOptions } from '../shared/openapi.CwdCLgSU.js';
6
+ import '@orpc/contract';
7
+ import '@orpc/openapi-client/standard';
8
+ import 'json-schema-typed/draft-2020-12';
9
+
10
+ interface OpenAPIReferencePluginOptions<T extends Context> extends OpenAPIGeneratorOptions {
11
+ /**
12
+ * Options to pass to the OpenAPI generate.
13
+ *
14
+ */
15
+ specGenerateOptions?: Value<OpenAPIGeneratorGenerateOptions, [StandardHandlerInterceptorOptions<T>]>;
16
+ /**
17
+ * The URL path at which to serve the OpenAPI JSON.
18
+ *
19
+ * @default '/spec.json'
20
+ */
21
+ specPath?: HTTPPath;
22
+ /**
23
+ * The URL path at which to serve the API reference UI.
24
+ *
25
+ * @default '/'
26
+ */
27
+ docsPath?: HTTPPath;
28
+ /**
29
+ * The document title for the API reference UI.
30
+ *
31
+ * @default 'API Reference'
32
+ */
33
+ docsTitle?: Value<string, [StandardHandlerInterceptorOptions<T>]>;
34
+ /**
35
+ * Arbitrary configuration object for the UI.
36
+ */
37
+ docsConfig?: Value<Record<string, unknown>, [StandardHandlerInterceptorOptions<T>]>;
38
+ /**
39
+ * HTML to inject into the <head> of the docs page.
40
+ *
41
+ * @default ''
42
+ */
43
+ docsHead?: Value<string, [StandardHandlerInterceptorOptions<T>]>;
44
+ /**
45
+ * URL of the external script bundle for the reference UI.
46
+ *
47
+ * @default 'https://cdn.jsdelivr.net/npm/@scalar/api-reference'
48
+ */
49
+ docsScriptUrl?: Value<string, [StandardHandlerInterceptorOptions<T>]>;
50
+ /**
51
+ * Override function to generate the full HTML for the docs page.
52
+ */
53
+ renderDocsHtml?: (specUrl: string, title: string, head: string, scriptUrl: string, config: Record<string, unknown> | undefined, spec: OpenAPIV3_1.Document) => string;
54
+ }
55
+ declare class OpenAPIReferencePlugin<T extends Context> implements StandardHandlerPlugin<T> {
56
+ private readonly generator;
57
+ private readonly specGenerateOptions;
58
+ private readonly specPath;
59
+ private readonly docsPath;
60
+ private readonly docsTitle;
61
+ private readonly docsHead;
62
+ private readonly docsScriptUrl;
63
+ private readonly docsConfig;
64
+ private readonly renderDocsHtml;
65
+ constructor(options?: OpenAPIReferencePluginOptions<T>);
66
+ init(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
67
+ }
68
+
69
+ export { OpenAPIReferencePlugin };
70
+ export type { OpenAPIReferencePluginOptions };
@@ -0,0 +1,108 @@
1
+ import { stringifyJSON, once, value } from '@orpc/shared';
2
+ import { O as OpenAPIGenerator } from '../shared/openapi.PDTdnRIU.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
+ docsScriptUrl;
18
+ docsConfig;
19
+ renderDocsHtml;
20
+ constructor(options = {}) {
21
+ this.specGenerateOptions = options.specGenerateOptions;
22
+ this.docsPath = options.docsPath ?? "/";
23
+ this.docsTitle = options.docsTitle ?? "API Reference";
24
+ this.docsConfig = options.docsConfig ?? void 0;
25
+ this.docsScriptUrl = options.docsScriptUrl ?? "https://cdn.jsdelivr.net/npm/@scalar/api-reference";
26
+ this.docsHead = options.docsHead ?? "";
27
+ this.specPath = options.specPath ?? "/spec.json";
28
+ this.generator = new OpenAPIGenerator(options);
29
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
30
+ this.renderDocsHtml = options.renderDocsHtml ?? ((specUrl, title, head, scriptUrl, config, spec) => {
31
+ const finalConfig = {
32
+ content: stringifyJSON(spec),
33
+ ...config
34
+ };
35
+ return `
36
+ <!doctype html>
37
+ <html>
38
+ <head>
39
+ <meta charset="utf-8" />
40
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
41
+ <title>${esc(title)}</title>
42
+ ${head}
43
+ </head>
44
+ <body>
45
+ <div id="app" data-config="${esc(stringifyJSON(finalConfig))}"></div>
46
+
47
+ <script src="${esc(scriptUrl)}"><\/script>
48
+
49
+ <script>
50
+ Scalar.createApiReference('#app', JSON.parse(document.getElementById('app').dataset.config))
51
+ <\/script>
52
+ </body>
53
+ </html>
54
+ `;
55
+ });
56
+ }
57
+ init(options, router) {
58
+ options.interceptors ??= [];
59
+ options.interceptors.push(async (options2) => {
60
+ const res = await options2.next();
61
+ if (res.matched || options2.request.method !== "GET") {
62
+ return res;
63
+ }
64
+ const prefix = options2.prefix ?? "";
65
+ const requestPathname = options2.request.url.pathname.replace(/\/$/, "") || "/";
66
+ const docsUrl = new URL(`${prefix}${this.docsPath}`.replace(/\/$/, ""), options2.request.url.origin);
67
+ const specUrl = new URL(`${prefix}${this.specPath}`.replace(/\/$/, ""), options2.request.url.origin);
68
+ const generateSpec = once(async () => {
69
+ return await this.generator.generate(router, {
70
+ servers: [{ url: new URL(prefix, options2.request.url.origin).toString() }],
71
+ ...await value(this.specGenerateOptions, options2)
72
+ });
73
+ });
74
+ if (requestPathname === specUrl.pathname) {
75
+ const spec = await generateSpec();
76
+ return {
77
+ matched: true,
78
+ response: {
79
+ status: 200,
80
+ headers: {},
81
+ body: new File([stringifyJSON(spec)], "spec.json", { type: "application/json" })
82
+ }
83
+ };
84
+ }
85
+ if (requestPathname === docsUrl.pathname) {
86
+ const html = this.renderDocsHtml(
87
+ specUrl.toString(),
88
+ await value(this.docsTitle, options2),
89
+ await value(this.docsHead, options2),
90
+ await value(this.docsScriptUrl, options2),
91
+ await value(this.docsConfig, options2),
92
+ await generateSpec()
93
+ );
94
+ return {
95
+ matched: true,
96
+ response: {
97
+ status: 200,
98
+ headers: {},
99
+ body: new File([html], "api-reference.html", { type: "text/html" })
100
+ }
101
+ };
102
+ }
103
+ return res;
104
+ });
105
+ }
106
+ }
107
+
108
+ export { OpenAPIReferencePlugin };
@@ -1,8 +1,11 @@
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 { traverseContractProcedures, toHttpPath, isProcedure, getLazyMeta, unlazy, getRouter, createContractedProcedure } from '@orpc/server';
5
+ import { isObject, stringifyJSON } 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.DZzpQAb-.mjs';
6
9
 
7
10
  class StandardOpenAPICodec {
8
11
  constructor(serializer) {
@@ -50,13 +53,21 @@ class StandardOpenAPICodec {
50
53
  body: this.serializer.serialize(output)
51
54
  };
52
55
  }
53
- if (!isObject(output)) {
54
- throw new Error(
55
- 'Invalid output structure for "detailed" output. Expected format: { body: any, headers?: Record<string, string | string[] | undefined> }'
56
- );
56
+ if (!this.#isDetailedOutput(output)) {
57
+ throw new Error(`
58
+ Invalid "detailed" output structure:
59
+ \u2022 Expected an object with optional properties:
60
+ - status (number 200-399)
61
+ - headers (Record<string, string | string[]>)
62
+ - body (any)
63
+ \u2022 No extra keys allowed.
64
+
65
+ Actual value:
66
+ ${stringifyJSON(output)}
67
+ `);
57
68
  }
58
69
  return {
59
- status: successStatus,
70
+ status: output.status ?? successStatus,
60
71
  headers: output.headers ?? {},
61
72
  body: this.serializer.serialize(output.body)
62
73
  };
@@ -65,9 +76,21 @@ class StandardOpenAPICodec {
65
76
  return {
66
77
  status: error.status,
67
78
  headers: {},
68
- body: this.serializer.serialize(error.toJSON())
79
+ body: this.serializer.serialize(error.toJSON(), { outputFormat: "plain" })
69
80
  };
70
81
  }
82
+ #isDetailedOutput(output) {
83
+ if (!isObject(output)) {
84
+ return false;
85
+ }
86
+ if (output.headers && !isObject(output.headers)) {
87
+ return false;
88
+ }
89
+ if (output.status !== void 0 && (typeof output.status !== "number" || !Number.isInteger(output.status) || isORPCErrorStatus(output.status))) {
90
+ return false;
91
+ }
92
+ return true;
93
+ }
71
94
  }
72
95
 
73
96
  function toRou3Pattern(path) {
@@ -142,4 +165,15 @@ class StandardOpenAPIMatcher {
142
165
  }
143
166
  }
144
167
 
145
- export { StandardOpenAPICodec as S, StandardOpenAPIMatcher as a, decodeParams as d, toRou3Pattern as t };
168
+ class StandardOpenAPIHandler extends StandardHandler {
169
+ constructor(router, options) {
170
+ const jsonSerializer = new StandardOpenAPIJsonSerializer(options);
171
+ const bracketNotationSerializer = new StandardBracketNotationSerializer();
172
+ const serializer = new StandardOpenAPISerializer(jsonSerializer, bracketNotationSerializer);
173
+ const matcher = new StandardOpenAPIMatcher();
174
+ const codec = new StandardOpenAPICodec(serializer);
175
+ super(router, matcher, codec, options);
176
+ }
177
+ }
178
+
179
+ export { StandardOpenAPICodec as S, StandardOpenAPIHandler as a, StandardOpenAPIMatcher as b, decodeParams as d, toRou3Pattern as t };