@orpc/openapi 0.0.0-next.f56d2b3 → 0.0.0-next.f635909
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 +100 -0
- package/dist/adapters/fetch/index.d.mts +17 -0
- package/dist/adapters/fetch/index.d.ts +17 -0
- package/dist/adapters/fetch/index.mjs +17 -0
- package/dist/adapters/node/index.d.mts +17 -0
- package/dist/adapters/node/index.d.ts +17 -0
- package/dist/adapters/node/index.mjs +17 -0
- package/dist/adapters/standard/index.d.mts +34 -0
- package/dist/adapters/standard/index.d.ts +34 -0
- package/dist/adapters/standard/index.mjs +8 -0
- package/dist/index.d.mts +96 -0
- package/dist/index.d.ts +96 -0
- package/dist/index.mjs +15 -0
- package/dist/plugins/index.d.mts +70 -0
- package/dist/plugins/index.d.ts +70 -0
- package/dist/plugins/index.mjs +97 -0
- package/dist/shared/openapi.D3j94c9n.d.mts +12 -0
- package/dist/shared/openapi.D3j94c9n.d.ts +12 -0
- package/dist/shared/openapi.DP97kr00.d.mts +47 -0
- package/dist/shared/openapi.DP97kr00.d.ts +47 -0
- package/dist/shared/openapi.fMEQd3Yd.mjs +544 -0
- package/dist/shared/openapi.p5tsmBXx.mjs +158 -0
- package/package.json +29 -38
- package/dist/chunk-Q2LSK6YZ.js +0 -102
- package/dist/chunk-SOVQ5ARD.js +0 -650
- package/dist/chunk-VFGNQS5W.js +0 -25
- package/dist/fetch.js +0 -34
- package/dist/hono.js +0 -34
- package/dist/index.js +0 -546
- package/dist/next.js +0 -34
- package/dist/node.js +0 -46
- package/dist/src/adapters/fetch/bracket-notation.d.ts +0 -84
- package/dist/src/adapters/fetch/index.d.ts +0 -10
- package/dist/src/adapters/fetch/input-structure-compact.d.ts +0 -6
- package/dist/src/adapters/fetch/input-structure-detailed.d.ts +0 -11
- package/dist/src/adapters/fetch/openapi-handler-server.d.ts +0 -7
- package/dist/src/adapters/fetch/openapi-handler-serverless.d.ts +0 -7
- package/dist/src/adapters/fetch/openapi-handler.d.ts +0 -32
- package/dist/src/adapters/fetch/openapi-payload-codec.d.ts +0 -15
- package/dist/src/adapters/fetch/openapi-procedure-matcher.d.ts +0 -19
- package/dist/src/adapters/fetch/schema-coercer.d.ts +0 -10
- package/dist/src/adapters/hono/index.d.ts +0 -2
- package/dist/src/adapters/next/index.d.ts +0 -2
- package/dist/src/adapters/node/index.d.ts +0 -5
- package/dist/src/adapters/node/openapi-handler-server.d.ts +0 -7
- package/dist/src/adapters/node/openapi-handler-serverless.d.ts +0 -7
- package/dist/src/adapters/node/openapi-handler.d.ts +0 -11
- package/dist/src/adapters/node/types.d.ts +0 -2
- package/dist/src/index.d.ts +0 -12
- package/dist/src/json-serializer.d.ts +0 -5
- package/dist/src/openapi-content-builder.d.ts +0 -10
- package/dist/src/openapi-error.d.ts +0 -3
- package/dist/src/openapi-generator.d.ts +0 -67
- package/dist/src/openapi-input-structure-parser.d.ts +0 -22
- package/dist/src/openapi-output-structure-parser.d.ts +0 -18
- package/dist/src/openapi-parameters-builder.d.ts +0 -12
- package/dist/src/openapi-path-parser.d.ts +0 -8
- package/dist/src/openapi.d.ts +0 -3
- package/dist/src/schema-converter.d.ts +0 -16
- package/dist/src/schema-utils.d.ts +0 -11
- package/dist/src/schema.d.ts +0 -12
- package/dist/src/utils.d.ts +0 -18
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
import { fallbackORPCErrorStatus, fallbackORPCErrorMessage } from '@orpc/client';
|
|
2
|
+
import { toHttpPath } from '@orpc/client/standard';
|
|
3
|
+
import { fallbackContractConfig, getEventIteratorSchemaDetails } from '@orpc/contract';
|
|
4
|
+
import { standardizeHTTPPath, StandardOpenAPIJsonSerializer, getDynamicParams } from '@orpc/openapi-client/standard';
|
|
5
|
+
import { isProcedure, resolveContractProcedures } from '@orpc/server';
|
|
6
|
+
import { isObject, findDeepMatches, toArray, clone } from '@orpc/shared';
|
|
7
|
+
import 'json-schema-typed/draft-2020-12';
|
|
8
|
+
|
|
9
|
+
const OPERATION_EXTENDER_SYMBOL = Symbol("ORPC_OPERATION_EXTENDER");
|
|
10
|
+
function customOpenAPIOperation(o, extend) {
|
|
11
|
+
return new Proxy(o, {
|
|
12
|
+
get(target, prop, receiver) {
|
|
13
|
+
if (prop === OPERATION_EXTENDER_SYMBOL) {
|
|
14
|
+
return extend;
|
|
15
|
+
}
|
|
16
|
+
return Reflect.get(target, prop, receiver);
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
function getCustomOpenAPIOperation(o) {
|
|
21
|
+
return o[OPERATION_EXTENDER_SYMBOL];
|
|
22
|
+
}
|
|
23
|
+
function applyCustomOpenAPIOperation(operation, contract) {
|
|
24
|
+
const operationCustoms = [];
|
|
25
|
+
for (const errorItem of Object.values(contract["~orpc"].errorMap)) {
|
|
26
|
+
const maybeExtender = errorItem ? getCustomOpenAPIOperation(errorItem) : void 0;
|
|
27
|
+
if (maybeExtender) {
|
|
28
|
+
operationCustoms.push(maybeExtender);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (isProcedure(contract)) {
|
|
32
|
+
for (const middleware of contract["~orpc"].middlewares) {
|
|
33
|
+
const maybeExtender = getCustomOpenAPIOperation(middleware);
|
|
34
|
+
if (maybeExtender) {
|
|
35
|
+
operationCustoms.push(maybeExtender);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
let currentOperation = operation;
|
|
40
|
+
for (const custom of operationCustoms) {
|
|
41
|
+
if (typeof custom === "function") {
|
|
42
|
+
currentOperation = custom(currentOperation, contract);
|
|
43
|
+
} else {
|
|
44
|
+
currentOperation = {
|
|
45
|
+
...currentOperation,
|
|
46
|
+
...custom
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return currentOperation;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const LOGIC_KEYWORDS = [
|
|
54
|
+
"$dynamicRef",
|
|
55
|
+
"$ref",
|
|
56
|
+
"additionalItems",
|
|
57
|
+
"additionalProperties",
|
|
58
|
+
"allOf",
|
|
59
|
+
"anyOf",
|
|
60
|
+
"const",
|
|
61
|
+
"contains",
|
|
62
|
+
"contentEncoding",
|
|
63
|
+
"contentMediaType",
|
|
64
|
+
"contentSchema",
|
|
65
|
+
"dependencies",
|
|
66
|
+
"dependentRequired",
|
|
67
|
+
"dependentSchemas",
|
|
68
|
+
"else",
|
|
69
|
+
"enum",
|
|
70
|
+
"exclusiveMaximum",
|
|
71
|
+
"exclusiveMinimum",
|
|
72
|
+
"format",
|
|
73
|
+
"if",
|
|
74
|
+
"items",
|
|
75
|
+
"maxContains",
|
|
76
|
+
"maximum",
|
|
77
|
+
"maxItems",
|
|
78
|
+
"maxLength",
|
|
79
|
+
"maxProperties",
|
|
80
|
+
"minContains",
|
|
81
|
+
"minimum",
|
|
82
|
+
"minItems",
|
|
83
|
+
"minLength",
|
|
84
|
+
"minProperties",
|
|
85
|
+
"multipleOf",
|
|
86
|
+
"not",
|
|
87
|
+
"oneOf",
|
|
88
|
+
"pattern",
|
|
89
|
+
"patternProperties",
|
|
90
|
+
"prefixItems",
|
|
91
|
+
"properties",
|
|
92
|
+
"propertyNames",
|
|
93
|
+
"required",
|
|
94
|
+
"then",
|
|
95
|
+
"type",
|
|
96
|
+
"unevaluatedItems",
|
|
97
|
+
"unevaluatedProperties",
|
|
98
|
+
"uniqueItems"
|
|
99
|
+
];
|
|
100
|
+
|
|
101
|
+
function isFileSchema(schema) {
|
|
102
|
+
return isObject(schema) && schema.type === "string" && typeof schema.contentMediaType === "string";
|
|
103
|
+
}
|
|
104
|
+
function isObjectSchema(schema) {
|
|
105
|
+
return isObject(schema) && schema.type === "object";
|
|
106
|
+
}
|
|
107
|
+
function isAnySchema(schema) {
|
|
108
|
+
if (schema === true) {
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
if (Object.keys(schema).every((k) => !LOGIC_KEYWORDS.includes(k))) {
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
function separateObjectSchema(schema, separatedProperties) {
|
|
117
|
+
if (Object.keys(schema).some((k) => k !== "type" && k !== "properties" && k !== "required" && LOGIC_KEYWORDS.includes(k))) {
|
|
118
|
+
return [{ type: "object" }, schema];
|
|
119
|
+
}
|
|
120
|
+
const matched = { ...schema };
|
|
121
|
+
const rest = { ...schema };
|
|
122
|
+
matched.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => separatedProperties.includes(key)).reduce((acc, [key, value]) => {
|
|
123
|
+
acc[key] = value;
|
|
124
|
+
return acc;
|
|
125
|
+
}, {});
|
|
126
|
+
matched.required = schema.required?.filter((key) => separatedProperties.includes(key));
|
|
127
|
+
matched.examples = schema.examples?.map((example) => {
|
|
128
|
+
if (!isObject(example)) {
|
|
129
|
+
return example;
|
|
130
|
+
}
|
|
131
|
+
return Object.entries(example).reduce((acc, [key, value]) => {
|
|
132
|
+
if (separatedProperties.includes(key)) {
|
|
133
|
+
acc[key] = value;
|
|
134
|
+
}
|
|
135
|
+
return acc;
|
|
136
|
+
}, {});
|
|
137
|
+
});
|
|
138
|
+
rest.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => !separatedProperties.includes(key)).reduce((acc, [key, value]) => {
|
|
139
|
+
acc[key] = value;
|
|
140
|
+
return acc;
|
|
141
|
+
}, {});
|
|
142
|
+
rest.required = schema.required?.filter((key) => !separatedProperties.includes(key));
|
|
143
|
+
rest.examples = schema.examples?.map((example) => {
|
|
144
|
+
if (!isObject(example)) {
|
|
145
|
+
return example;
|
|
146
|
+
}
|
|
147
|
+
return Object.entries(example).reduce((acc, [key, value]) => {
|
|
148
|
+
if (!separatedProperties.includes(key)) {
|
|
149
|
+
acc[key] = value;
|
|
150
|
+
}
|
|
151
|
+
return acc;
|
|
152
|
+
}, {});
|
|
153
|
+
});
|
|
154
|
+
return [matched, rest];
|
|
155
|
+
}
|
|
156
|
+
function filterSchemaBranches(schema, check, matches = []) {
|
|
157
|
+
if (check(schema)) {
|
|
158
|
+
matches.push(schema);
|
|
159
|
+
return [matches, void 0];
|
|
160
|
+
}
|
|
161
|
+
if (isObject(schema)) {
|
|
162
|
+
for (const keyword of ["anyOf", "oneOf"]) {
|
|
163
|
+
if (schema[keyword] && Object.keys(schema).every(
|
|
164
|
+
(k) => k === keyword || !LOGIC_KEYWORDS.includes(k)
|
|
165
|
+
)) {
|
|
166
|
+
const rest = schema[keyword].map((s) => filterSchemaBranches(s, check, matches)[1]).filter((v) => !!v);
|
|
167
|
+
if (rest.length === 1 && typeof rest[0] === "object") {
|
|
168
|
+
return [matches, { ...schema, [keyword]: void 0, ...rest[0] }];
|
|
169
|
+
}
|
|
170
|
+
return [matches, { ...schema, [keyword]: rest }];
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return [matches, schema];
|
|
175
|
+
}
|
|
176
|
+
function applySchemaOptionality(required, schema) {
|
|
177
|
+
if (required) {
|
|
178
|
+
return schema;
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
anyOf: [
|
|
182
|
+
schema,
|
|
183
|
+
{ not: {} }
|
|
184
|
+
]
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function toOpenAPIPath(path) {
|
|
189
|
+
return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/{$1}");
|
|
190
|
+
}
|
|
191
|
+
function toOpenAPIMethod(method) {
|
|
192
|
+
return method.toLocaleLowerCase();
|
|
193
|
+
}
|
|
194
|
+
function toOpenAPIContent(schema) {
|
|
195
|
+
const content = {};
|
|
196
|
+
const [matches, restSchema] = filterSchemaBranches(schema, isFileSchema);
|
|
197
|
+
for (const file of matches) {
|
|
198
|
+
content[file.contentMediaType] = {
|
|
199
|
+
schema: toOpenAPISchema(file)
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
if (restSchema !== void 0) {
|
|
203
|
+
content["application/json"] = {
|
|
204
|
+
schema: toOpenAPISchema(restSchema)
|
|
205
|
+
};
|
|
206
|
+
const isStillHasFileSchema = findDeepMatches((v) => isObject(v) && isFileSchema(v), restSchema).values.length > 0;
|
|
207
|
+
if (isStillHasFileSchema) {
|
|
208
|
+
content["multipart/form-data"] = {
|
|
209
|
+
schema: toOpenAPISchema(restSchema)
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return content;
|
|
214
|
+
}
|
|
215
|
+
function toOpenAPIEventIteratorContent([yieldsRequired, yieldsSchema], [returnsRequired, returnsSchema]) {
|
|
216
|
+
return {
|
|
217
|
+
"text/event-stream": {
|
|
218
|
+
schema: toOpenAPISchema({
|
|
219
|
+
oneOf: [
|
|
220
|
+
{
|
|
221
|
+
type: "object",
|
|
222
|
+
properties: {
|
|
223
|
+
event: { const: "message" },
|
|
224
|
+
data: yieldsSchema,
|
|
225
|
+
id: { type: "string" },
|
|
226
|
+
retry: { type: "number" }
|
|
227
|
+
},
|
|
228
|
+
required: yieldsRequired ? ["event", "data"] : ["event"]
|
|
229
|
+
},
|
|
230
|
+
{
|
|
231
|
+
type: "object",
|
|
232
|
+
properties: {
|
|
233
|
+
event: { const: "done" },
|
|
234
|
+
data: returnsSchema,
|
|
235
|
+
id: { type: "string" },
|
|
236
|
+
retry: { type: "number" }
|
|
237
|
+
},
|
|
238
|
+
required: returnsRequired ? ["event", "data"] : ["event"]
|
|
239
|
+
},
|
|
240
|
+
{
|
|
241
|
+
type: "object",
|
|
242
|
+
properties: {
|
|
243
|
+
event: { const: "error" },
|
|
244
|
+
data: {},
|
|
245
|
+
id: { type: "string" },
|
|
246
|
+
retry: { type: "number" }
|
|
247
|
+
},
|
|
248
|
+
required: ["event"]
|
|
249
|
+
}
|
|
250
|
+
]
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
function toOpenAPIParameters(schema, parameterIn) {
|
|
256
|
+
const parameters = [];
|
|
257
|
+
for (const key in schema.properties) {
|
|
258
|
+
const keySchema = schema.properties[key];
|
|
259
|
+
parameters.push({
|
|
260
|
+
name: key,
|
|
261
|
+
in: parameterIn,
|
|
262
|
+
required: schema.required?.includes(key),
|
|
263
|
+
style: parameterIn === "query" ? "deepObject" : void 0,
|
|
264
|
+
explode: parameterIn === "query" ? true : void 0,
|
|
265
|
+
schema: toOpenAPISchema(keySchema)
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
return parameters;
|
|
269
|
+
}
|
|
270
|
+
function checkParamsSchema(schema, params) {
|
|
271
|
+
const properties = Object.keys(schema.properties ?? {});
|
|
272
|
+
const required = schema.required ?? [];
|
|
273
|
+
if (properties.length !== params.length || properties.some((v) => !params.includes(v))) {
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
if (required.length !== params.length || required.some((v) => !params.includes(v))) {
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
return true;
|
|
280
|
+
}
|
|
281
|
+
function toOpenAPISchema(schema) {
|
|
282
|
+
return schema === true ? {} : schema === false ? { not: {} } : schema;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
class CompositeSchemaConverter {
|
|
286
|
+
converters;
|
|
287
|
+
constructor(converters) {
|
|
288
|
+
this.converters = converters;
|
|
289
|
+
}
|
|
290
|
+
async convert(schema, options) {
|
|
291
|
+
for (const converter of this.converters) {
|
|
292
|
+
if (await converter.condition(schema, options)) {
|
|
293
|
+
return converter.convert(schema, options);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return [false, {}];
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
class OpenAPIGeneratorError extends Error {
|
|
301
|
+
}
|
|
302
|
+
class OpenAPIGenerator {
|
|
303
|
+
serializer;
|
|
304
|
+
converter;
|
|
305
|
+
constructor(options = {}) {
|
|
306
|
+
this.serializer = new StandardOpenAPIJsonSerializer(options);
|
|
307
|
+
this.converter = new CompositeSchemaConverter(toArray(options.schemaConverters));
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Generates OpenAPI specifications from oRPC routers/contracts.
|
|
311
|
+
*
|
|
312
|
+
* @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
|
|
313
|
+
*/
|
|
314
|
+
async generate(router, options = {}) {
|
|
315
|
+
const doc = {
|
|
316
|
+
...clone(options),
|
|
317
|
+
info: options.info ?? { title: "API Reference", version: "0.0.0" },
|
|
318
|
+
openapi: "3.1.1"
|
|
319
|
+
};
|
|
320
|
+
const contracts = [];
|
|
321
|
+
await resolveContractProcedures({ path: [], router }, ({ contract, path }) => {
|
|
322
|
+
contracts.push({ contract, path });
|
|
323
|
+
});
|
|
324
|
+
const errors = [];
|
|
325
|
+
for (const { contract, path } of contracts) {
|
|
326
|
+
const operationId = path.join(".");
|
|
327
|
+
try {
|
|
328
|
+
const def = contract["~orpc"];
|
|
329
|
+
const method = toOpenAPIMethod(fallbackContractConfig("defaultMethod", def.route.method));
|
|
330
|
+
const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path));
|
|
331
|
+
const operationObjectRef = {
|
|
332
|
+
operationId,
|
|
333
|
+
summary: def.route.summary,
|
|
334
|
+
description: def.route.description,
|
|
335
|
+
deprecated: def.route.deprecated,
|
|
336
|
+
tags: def.route.tags?.map((tag) => tag)
|
|
337
|
+
};
|
|
338
|
+
await this.#request(operationObjectRef, def);
|
|
339
|
+
await this.#successResponse(operationObjectRef, def);
|
|
340
|
+
await this.#errorResponse(operationObjectRef, def);
|
|
341
|
+
doc.paths ??= {};
|
|
342
|
+
doc.paths[httpPath] ??= {};
|
|
343
|
+
doc.paths[httpPath][method] = applyCustomOpenAPIOperation(operationObjectRef, contract);
|
|
344
|
+
} catch (e) {
|
|
345
|
+
if (!(e instanceof OpenAPIGeneratorError)) {
|
|
346
|
+
throw e;
|
|
347
|
+
}
|
|
348
|
+
errors.push(
|
|
349
|
+
`[OpenAPIGenerator] Error occurred while generating OpenAPI for procedure at path: ${operationId}
|
|
350
|
+
${e.message}`
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
if (errors.length) {
|
|
355
|
+
throw new OpenAPIGeneratorError(
|
|
356
|
+
`Some error occurred during OpenAPI generation:
|
|
357
|
+
|
|
358
|
+
${errors.join("\n\n")}`
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
return this.serializer.serialize(doc)[0];
|
|
362
|
+
}
|
|
363
|
+
async #request(ref, def) {
|
|
364
|
+
const method = fallbackContractConfig("defaultMethod", def.route.method);
|
|
365
|
+
const details = getEventIteratorSchemaDetails(def.inputSchema);
|
|
366
|
+
if (details) {
|
|
367
|
+
ref.requestBody = {
|
|
368
|
+
required: true,
|
|
369
|
+
content: toOpenAPIEventIteratorContent(
|
|
370
|
+
await this.converter.convert(details.yields, { strategy: "input" }),
|
|
371
|
+
await this.converter.convert(details.returns, { strategy: "input" })
|
|
372
|
+
)
|
|
373
|
+
};
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const dynamicParams = getDynamicParams(def.route.path)?.map((v) => v.name);
|
|
377
|
+
const inputStructure = fallbackContractConfig("defaultInputStructure", def.route.inputStructure);
|
|
378
|
+
let [required, schema] = await this.converter.convert(def.inputSchema, { strategy: "input" });
|
|
379
|
+
if (isAnySchema(schema) && !dynamicParams?.length) {
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
if (inputStructure === "compact") {
|
|
383
|
+
if (dynamicParams?.length) {
|
|
384
|
+
const error2 = new OpenAPIGeneratorError(
|
|
385
|
+
'When input structure is "compact", and path has dynamic params, input schema must be an object with all dynamic params as required.'
|
|
386
|
+
);
|
|
387
|
+
if (!isObjectSchema(schema)) {
|
|
388
|
+
throw error2;
|
|
389
|
+
}
|
|
390
|
+
const [paramsSchema, rest] = separateObjectSchema(schema, dynamicParams);
|
|
391
|
+
schema = rest;
|
|
392
|
+
required = rest.required ? rest.required.length !== 0 : false;
|
|
393
|
+
if (!checkParamsSchema(paramsSchema, dynamicParams)) {
|
|
394
|
+
throw error2;
|
|
395
|
+
}
|
|
396
|
+
ref.parameters ??= [];
|
|
397
|
+
ref.parameters.push(...toOpenAPIParameters(paramsSchema, "path"));
|
|
398
|
+
}
|
|
399
|
+
if (method === "GET") {
|
|
400
|
+
if (!isObjectSchema(schema)) {
|
|
401
|
+
throw new OpenAPIGeneratorError(
|
|
402
|
+
'When method is "GET", input schema must satisfy: object | any | unknown'
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
ref.parameters ??= [];
|
|
406
|
+
ref.parameters.push(...toOpenAPIParameters(schema, "query"));
|
|
407
|
+
} else {
|
|
408
|
+
ref.requestBody = {
|
|
409
|
+
required,
|
|
410
|
+
content: toOpenAPIContent(schema)
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
const error = new OpenAPIGeneratorError(
|
|
416
|
+
'When input structure is "detailed", input schema must satisfy: { params?: Record<string, unknown>, query?: Record<string, unknown>, headers?: Record<string, unknown>, body?: unknown }'
|
|
417
|
+
);
|
|
418
|
+
if (!isObjectSchema(schema)) {
|
|
419
|
+
throw error;
|
|
420
|
+
}
|
|
421
|
+
if (dynamicParams?.length && (schema.properties?.params === void 0 || !isObjectSchema(schema.properties.params) || !checkParamsSchema(schema.properties.params, dynamicParams))) {
|
|
422
|
+
throw new OpenAPIGeneratorError(
|
|
423
|
+
'When input structure is "detailed" and path has dynamic params, the "params" schema must be an object with all dynamic params as required.'
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
for (const from of ["params", "query", "headers"]) {
|
|
427
|
+
const fromSchema = schema.properties?.[from];
|
|
428
|
+
if (fromSchema !== void 0) {
|
|
429
|
+
if (!isObjectSchema(fromSchema)) {
|
|
430
|
+
throw error;
|
|
431
|
+
}
|
|
432
|
+
const parameterIn = from === "params" ? "path" : from === "headers" ? "header" : "query";
|
|
433
|
+
ref.parameters ??= [];
|
|
434
|
+
ref.parameters.push(...toOpenAPIParameters(fromSchema, parameterIn));
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
if (schema.properties?.body !== void 0) {
|
|
438
|
+
ref.requestBody = {
|
|
439
|
+
required: schema.required?.includes("body"),
|
|
440
|
+
content: toOpenAPIContent(schema.properties.body)
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
async #successResponse(ref, def) {
|
|
445
|
+
const outputSchema = def.outputSchema;
|
|
446
|
+
const status = fallbackContractConfig("defaultSuccessStatus", def.route.successStatus);
|
|
447
|
+
const description = fallbackContractConfig("defaultSuccessDescription", def.route?.successDescription);
|
|
448
|
+
const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(outputSchema);
|
|
449
|
+
const outputStructure = fallbackContractConfig("defaultOutputStructure", def.route.outputStructure);
|
|
450
|
+
if (eventIteratorSchemaDetails) {
|
|
451
|
+
ref.responses ??= {};
|
|
452
|
+
ref.responses[status] = {
|
|
453
|
+
description,
|
|
454
|
+
content: toOpenAPIEventIteratorContent(
|
|
455
|
+
await this.converter.convert(eventIteratorSchemaDetails.yields, { strategy: "output" }),
|
|
456
|
+
await this.converter.convert(eventIteratorSchemaDetails.returns, { strategy: "output" })
|
|
457
|
+
)
|
|
458
|
+
};
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
const [required, json] = await this.converter.convert(outputSchema, { strategy: "output" });
|
|
462
|
+
ref.responses ??= {};
|
|
463
|
+
ref.responses[status] = {
|
|
464
|
+
description
|
|
465
|
+
};
|
|
466
|
+
if (outputStructure === "compact") {
|
|
467
|
+
ref.responses[status].content = toOpenAPIContent(applySchemaOptionality(required, json));
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
const error = new OpenAPIGeneratorError(
|
|
471
|
+
'When output structure is "detailed", output schema must satisfy: { headers?: Record<string, unknown>, body?: unknown }'
|
|
472
|
+
);
|
|
473
|
+
if (!isObjectSchema(json)) {
|
|
474
|
+
throw error;
|
|
475
|
+
}
|
|
476
|
+
if (json.properties?.headers !== void 0) {
|
|
477
|
+
if (!isObjectSchema(json.properties.headers)) {
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
for (const key in json.properties.headers.properties) {
|
|
481
|
+
ref.responses[status].headers ??= {};
|
|
482
|
+
ref.responses[status].headers[key] = {
|
|
483
|
+
schema: toOpenAPISchema(json.properties.headers.properties[key]),
|
|
484
|
+
required: json.properties.headers.required?.includes(key)
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
if (json.properties?.body !== void 0) {
|
|
489
|
+
ref.responses[status].content = toOpenAPIContent(
|
|
490
|
+
applySchemaOptionality(json.required?.includes("body") ?? false, json.properties.body)
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
async #errorResponse(ref, def) {
|
|
495
|
+
const errorMap = def.errorMap;
|
|
496
|
+
const errors = {};
|
|
497
|
+
for (const code in errorMap) {
|
|
498
|
+
const config = errorMap[code];
|
|
499
|
+
if (!config) {
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
const status = fallbackORPCErrorStatus(code, config.status);
|
|
503
|
+
const message = fallbackORPCErrorMessage(code, config.message);
|
|
504
|
+
const [dataRequired, dataSchema] = await this.converter.convert(config.data, { strategy: "output" });
|
|
505
|
+
errors[status] ??= [];
|
|
506
|
+
errors[status].push({
|
|
507
|
+
type: "object",
|
|
508
|
+
properties: {
|
|
509
|
+
defined: { const: true },
|
|
510
|
+
code: { const: code },
|
|
511
|
+
status: { const: status },
|
|
512
|
+
message: { type: "string", default: message },
|
|
513
|
+
data: dataSchema
|
|
514
|
+
},
|
|
515
|
+
required: dataRequired ? ["defined", "code", "status", "message", "data"] : ["defined", "code", "status", "message"]
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
ref.responses ??= {};
|
|
519
|
+
for (const status in errors) {
|
|
520
|
+
const schemas = errors[status];
|
|
521
|
+
ref.responses[status] = {
|
|
522
|
+
description: status,
|
|
523
|
+
content: toOpenAPIContent({
|
|
524
|
+
oneOf: [
|
|
525
|
+
...schemas,
|
|
526
|
+
{
|
|
527
|
+
type: "object",
|
|
528
|
+
properties: {
|
|
529
|
+
defined: { const: false },
|
|
530
|
+
code: { type: "string" },
|
|
531
|
+
status: { type: "number" },
|
|
532
|
+
message: { type: "string" },
|
|
533
|
+
data: {}
|
|
534
|
+
},
|
|
535
|
+
required: ["defined", "code", "status", "message"]
|
|
536
|
+
}
|
|
537
|
+
]
|
|
538
|
+
})
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
export { CompositeSchemaConverter as C, LOGIC_KEYWORDS as L, OpenAPIGenerator as O, applyCustomOpenAPIOperation as a, toOpenAPIMethod as b, customOpenAPIOperation as c, toOpenAPIContent as d, toOpenAPIEventIteratorContent as e, toOpenAPIParameters as f, getCustomOpenAPIOperation as g, checkParamsSchema as h, toOpenAPISchema as i, isFileSchema as j, isObjectSchema as k, isAnySchema as l, filterSchemaBranches as m, applySchemaOptionality as n, separateObjectSchema as s, toOpenAPIPath as t };
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { standardizeHTTPPath, StandardOpenAPIJsonSerializer, StandardBracketNotationSerializer, StandardOpenAPISerializer } from '@orpc/openapi-client/standard';
|
|
2
|
+
import { StandardHandler } from '@orpc/server/standard';
|
|
3
|
+
import { fallbackContractConfig } from '@orpc/contract';
|
|
4
|
+
import { isObject } from '@orpc/shared';
|
|
5
|
+
import { toHttpPath } from '@orpc/client/standard';
|
|
6
|
+
import { traverseContractProcedures, isProcedure, getLazyMeta, unlazy, getRouter, createContractedProcedure } from '@orpc/server';
|
|
7
|
+
import { createRouter, addRoute, findRoute } from 'rou3';
|
|
8
|
+
|
|
9
|
+
class StandardOpenAPICodec {
|
|
10
|
+
constructor(serializer) {
|
|
11
|
+
this.serializer = serializer;
|
|
12
|
+
}
|
|
13
|
+
async decode(request, params, procedure) {
|
|
14
|
+
const inputStructure = fallbackContractConfig("defaultInputStructure", procedure["~orpc"].route.inputStructure);
|
|
15
|
+
if (inputStructure === "compact") {
|
|
16
|
+
const data = request.method === "GET" ? this.serializer.deserialize(request.url.searchParams) : this.serializer.deserialize(await request.body());
|
|
17
|
+
if (data === void 0) {
|
|
18
|
+
return params;
|
|
19
|
+
}
|
|
20
|
+
if (isObject(data)) {
|
|
21
|
+
return {
|
|
22
|
+
...params,
|
|
23
|
+
...data
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
return data;
|
|
27
|
+
}
|
|
28
|
+
const deserializeSearchParams = () => {
|
|
29
|
+
return this.serializer.deserialize(request.url.searchParams);
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
params,
|
|
33
|
+
get query() {
|
|
34
|
+
const value = deserializeSearchParams();
|
|
35
|
+
Object.defineProperty(this, "query", { value, writable: true });
|
|
36
|
+
return value;
|
|
37
|
+
},
|
|
38
|
+
set query(value) {
|
|
39
|
+
Object.defineProperty(this, "query", { value, writable: true });
|
|
40
|
+
},
|
|
41
|
+
headers: request.headers,
|
|
42
|
+
body: this.serializer.deserialize(await request.body())
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
encode(output, procedure) {
|
|
46
|
+
const successStatus = fallbackContractConfig("defaultSuccessStatus", procedure["~orpc"].route.successStatus);
|
|
47
|
+
const outputStructure = fallbackContractConfig("defaultOutputStructure", procedure["~orpc"].route.outputStructure);
|
|
48
|
+
if (outputStructure === "compact") {
|
|
49
|
+
return {
|
|
50
|
+
status: successStatus,
|
|
51
|
+
headers: {},
|
|
52
|
+
body: this.serializer.serialize(output)
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
if (!isObject(output)) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
'Invalid output structure for "detailed" output. Expected format: { body: any, headers?: Record<string, string | string[] | undefined> }'
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
status: successStatus,
|
|
62
|
+
headers: output.headers ?? {},
|
|
63
|
+
body: this.serializer.serialize(output.body)
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
encodeError(error) {
|
|
67
|
+
return {
|
|
68
|
+
status: error.status,
|
|
69
|
+
headers: {},
|
|
70
|
+
body: this.serializer.serialize(error.toJSON(), { outputFormat: "plain" })
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function toRou3Pattern(path) {
|
|
76
|
+
return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
|
|
77
|
+
}
|
|
78
|
+
function decodeParams(params) {
|
|
79
|
+
return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, decodeURIComponent(value)]));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
class StandardOpenAPIMatcher {
|
|
83
|
+
tree = createRouter();
|
|
84
|
+
pendingRouters = [];
|
|
85
|
+
init(router, path = []) {
|
|
86
|
+
const laziedOptions = traverseContractProcedures({ router, path }, ({ path: path2, contract }) => {
|
|
87
|
+
const method = fallbackContractConfig("defaultMethod", contract["~orpc"].route.method);
|
|
88
|
+
const httpPath = toRou3Pattern(contract["~orpc"].route.path ?? toHttpPath(path2));
|
|
89
|
+
if (isProcedure(contract)) {
|
|
90
|
+
addRoute(this.tree, method, httpPath, {
|
|
91
|
+
path: path2,
|
|
92
|
+
contract,
|
|
93
|
+
procedure: contract,
|
|
94
|
+
// this mean dev not used contract-first so we can used contract as procedure directly
|
|
95
|
+
router
|
|
96
|
+
});
|
|
97
|
+
} else {
|
|
98
|
+
addRoute(this.tree, method, httpPath, {
|
|
99
|
+
path: path2,
|
|
100
|
+
contract,
|
|
101
|
+
procedure: void 0,
|
|
102
|
+
router
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
this.pendingRouters.push(...laziedOptions.map((option) => ({
|
|
107
|
+
...option,
|
|
108
|
+
httpPathPrefix: toHttpPath(option.path),
|
|
109
|
+
laziedPrefix: getLazyMeta(option.router).prefix
|
|
110
|
+
})));
|
|
111
|
+
}
|
|
112
|
+
async match(method, pathname) {
|
|
113
|
+
if (this.pendingRouters.length) {
|
|
114
|
+
const newPendingRouters = [];
|
|
115
|
+
for (const pendingRouter of this.pendingRouters) {
|
|
116
|
+
if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
|
|
117
|
+
const { default: router } = await unlazy(pendingRouter.router);
|
|
118
|
+
this.init(router, pendingRouter.path);
|
|
119
|
+
} else {
|
|
120
|
+
newPendingRouters.push(pendingRouter);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
this.pendingRouters = newPendingRouters;
|
|
124
|
+
}
|
|
125
|
+
const match = findRoute(this.tree, method, pathname);
|
|
126
|
+
if (!match) {
|
|
127
|
+
return void 0;
|
|
128
|
+
}
|
|
129
|
+
if (!match.data.procedure) {
|
|
130
|
+
const { default: maybeProcedure } = await unlazy(getRouter(match.data.router, match.data.path));
|
|
131
|
+
if (!isProcedure(maybeProcedure)) {
|
|
132
|
+
throw new Error(`
|
|
133
|
+
[Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.data.path)}.
|
|
134
|
+
Ensure that the procedure is correctly defined and matches the expected contract.
|
|
135
|
+
`);
|
|
136
|
+
}
|
|
137
|
+
match.data.procedure = createContractedProcedure(maybeProcedure, match.data.contract);
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
path: match.data.path,
|
|
141
|
+
procedure: match.data.procedure,
|
|
142
|
+
params: match.params ? decodeParams(match.params) : void 0
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
class StandardOpenAPIHandler extends StandardHandler {
|
|
148
|
+
constructor(router, options) {
|
|
149
|
+
const jsonSerializer = new StandardOpenAPIJsonSerializer(options);
|
|
150
|
+
const bracketNotationSerializer = new StandardBracketNotationSerializer();
|
|
151
|
+
const serializer = new StandardOpenAPISerializer(jsonSerializer, bracketNotationSerializer);
|
|
152
|
+
const matcher = new StandardOpenAPIMatcher();
|
|
153
|
+
const codec = new StandardOpenAPICodec(serializer);
|
|
154
|
+
super(router, matcher, codec, options);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export { StandardOpenAPICodec as S, StandardOpenAPIHandler as a, StandardOpenAPIMatcher as b, decodeParams as d, toRou3Pattern as t };
|