@express-tools/oas 0.0.1
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/LICENSE +13 -0
- package/README.md +103 -0
- package/bin/definition.js +22 -0
- package/bin/documentation.js +10 -0
- package/bin/index.js +16 -0
- package/bin/response.js +21 -0
- package/bin/router.js +64 -0
- package/bin/utils.js +34 -0
- package/bin/validation.js +21 -0
- package/package.json +62 -0
- package/types.d.ts +315 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright 2025 Frederic Charette
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# Express tools OpenAPI compatibility
|
|
2
|
+
|
|
3
|
+
*Bring your Express API to the modern web*
|
|
4
|
+
|
|
5
|
+
- Express 5 compatible
|
|
6
|
+
- Request/response validation
|
|
7
|
+
- Dynamically generated documentation
|
|
8
|
+
- Define or redefine as much of your spec
|
|
9
|
+
|
|
10
|
+
## Getting started
|
|
11
|
+
|
|
12
|
+
### Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm i @express-tools/oas
|
|
16
|
+
```
|
|
17
|
+
### Usage
|
|
18
|
+
|
|
19
|
+
Add the plugin to your express app:
|
|
20
|
+
|
|
21
|
+
```javascript
|
|
22
|
+
|
|
23
|
+
import Express from 'express';
|
|
24
|
+
import {definition, documentation, response, router as OASRouter, validation} from '@express-tools/oas';
|
|
25
|
+
|
|
26
|
+
// Wraps an existing API router or subrouter and adds an OpenAPI spec
|
|
27
|
+
const server = OASRouter(express(), {
|
|
28
|
+
/* An OpenAPI spec */
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The definition middleware enables you to define or override the properties of a route
|
|
34
|
+
|
|
35
|
+
```javascript
|
|
36
|
+
|
|
37
|
+
server.get('/user/:id', definition({
|
|
38
|
+
description: 'Get a User by Id',
|
|
39
|
+
parameters: [
|
|
40
|
+
{
|
|
41
|
+
name: 'id',
|
|
42
|
+
in: 'path',
|
|
43
|
+
type: 'string',
|
|
44
|
+
}
|
|
45
|
+
],
|
|
46
|
+
responses: {
|
|
47
|
+
default: { schema: { $ref: '#/definitions/user' } },
|
|
48
|
+
},
|
|
49
|
+
}), (req, res, next) => { /* Your business logic handler */ });
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The validation middleware checks the request to make sure it matches the spec and overrides.
|
|
54
|
+
|
|
55
|
+
```javascript
|
|
56
|
+
|
|
57
|
+
server.post(
|
|
58
|
+
'/user',
|
|
59
|
+
validation(),
|
|
60
|
+
(req, res, next) => { /* Your business logic handler */ });
|
|
61
|
+
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The response middleware adds response validation to your route
|
|
65
|
+
|
|
66
|
+
```javascript
|
|
67
|
+
|
|
68
|
+
server.post(
|
|
69
|
+
'/user',
|
|
70
|
+
definition({
|
|
71
|
+
description: 'Creates a user',
|
|
72
|
+
parameters: [
|
|
73
|
+
{
|
|
74
|
+
name: 'body',
|
|
75
|
+
in: 'body',
|
|
76
|
+
schema: { $ref: 'user' },
|
|
77
|
+
}
|
|
78
|
+
],
|
|
79
|
+
responses: {
|
|
80
|
+
default: { schema: { $ref: 'user' } },
|
|
81
|
+
},
|
|
82
|
+
}),
|
|
83
|
+
response(),
|
|
84
|
+
(req, res, next) => { /* Your business logic handler */ });
|
|
85
|
+
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The documentation plugin prints out your spec and all overrides
|
|
89
|
+
|
|
90
|
+
```javascript
|
|
91
|
+
|
|
92
|
+
server.get('/docs', documentation());
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Contributing
|
|
97
|
+
|
|
98
|
+
Please do! This project is all about facilitating collaboration on complex projects and we intend to set the example ourselves.
|
|
99
|
+
If you want to contribute, feel free to ping @fed135.
|
|
100
|
+
|
|
101
|
+
## License
|
|
102
|
+
|
|
103
|
+
Apache-2.0 - 2025
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.default = Definition;
|
|
4
|
+
function Definition(routeDefinition) {
|
|
5
|
+
// Basic validation - TypeScript types handle detailed schema validation
|
|
6
|
+
if (!routeDefinition || typeof routeDefinition !== 'object') {
|
|
7
|
+
throw new Error('Route definition must be an object');
|
|
8
|
+
}
|
|
9
|
+
// Check if it's a valid operation or route definition structure
|
|
10
|
+
const hasHttpMethods = ['get', 'post', 'put', 'patch', 'delete', 'options', 'head'].some(method => Object.prototype.hasOwnProperty.call(routeDefinition, method));
|
|
11
|
+
const hasOperationFields = Object.keys(routeDefinition).some(key => ['summary', 'description', 'operationId', 'parameters', 'responses', 'requestBody', 'tags'].includes(key));
|
|
12
|
+
if (!hasHttpMethods && !hasOperationFields) {
|
|
13
|
+
throw new Error('Route definition must contain either HTTP method definitions or operation fields');
|
|
14
|
+
}
|
|
15
|
+
function OASDefinition(req, res, next) {
|
|
16
|
+
if (!req)
|
|
17
|
+
return routeDefinition;
|
|
18
|
+
return next?.();
|
|
19
|
+
}
|
|
20
|
+
OASDefinition.OASType = 'definition';
|
|
21
|
+
return OASDefinition;
|
|
22
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.default = documentation;
|
|
4
|
+
function documentation() {
|
|
5
|
+
function OASDocumentation(req, res) {
|
|
6
|
+
res.json(req._oas);
|
|
7
|
+
}
|
|
8
|
+
OASDocumentation.OASType = 'documentation';
|
|
9
|
+
return OASDocumentation;
|
|
10
|
+
}
|
package/bin/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.validation = exports.router = exports.response = exports.documentation = exports.definition = void 0;
|
|
7
|
+
const definition_1 = __importDefault(require("./definition"));
|
|
8
|
+
exports.definition = definition_1.default;
|
|
9
|
+
const documentation_1 = __importDefault(require("./documentation"));
|
|
10
|
+
exports.documentation = documentation_1.default;
|
|
11
|
+
const response_1 = __importDefault(require("./response"));
|
|
12
|
+
exports.response = response_1.default;
|
|
13
|
+
const router_1 = __importDefault(require("./router"));
|
|
14
|
+
exports.router = router_1.default;
|
|
15
|
+
const validation_1 = __importDefault(require("./validation"));
|
|
16
|
+
exports.validation = validation_1.default;
|
package/bin/response.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.default = response;
|
|
4
|
+
const swagger_route_validator_1 = require("swagger-route-validator");
|
|
5
|
+
const utils_1 = require("./utils");
|
|
6
|
+
function response() {
|
|
7
|
+
function OASResponse(req, res, next) {
|
|
8
|
+
if (!req.route)
|
|
9
|
+
throw new Error('Response validation middleware must be added to a route');
|
|
10
|
+
let operationId = (0, utils_1.formatPathToOAS)(req.route.path);
|
|
11
|
+
// substract spec basepath if exists
|
|
12
|
+
if (req._oas?.basePath && req._oas?.basePath !== '/' && operationId.indexOf(req._oas?.basePath) === 0)
|
|
13
|
+
operationId = operationId.replace(req._oas?.basePath, '');
|
|
14
|
+
const matchingSpec = req._oas?.paths?.[operationId]?.[req.method.toLowerCase()];
|
|
15
|
+
if (matchingSpec)
|
|
16
|
+
return (0, swagger_route_validator_1.expressResponseValidation)(matchingSpec, {}, req._oas)(req, res, next);
|
|
17
|
+
throw new Error(`Response validation middleware added, but no definition could be found for ${operationId}.${req.method.toLowerCase()}`);
|
|
18
|
+
}
|
|
19
|
+
OASResponse.OASType = 'response';
|
|
20
|
+
return OASResponse;
|
|
21
|
+
}
|
package/bin/router.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.default = router;
|
|
4
|
+
const utils_1 = require("./utils");
|
|
5
|
+
function router(expressApp, spec) {
|
|
6
|
+
let scanned = false;
|
|
7
|
+
// Store a working copy of the spec in express app
|
|
8
|
+
expressApp['_oas'] = {
|
|
9
|
+
openapi: '3.1.0',
|
|
10
|
+
info: {},
|
|
11
|
+
servers: [],
|
|
12
|
+
basePath: '/',
|
|
13
|
+
paths: {},
|
|
14
|
+
components: {},
|
|
15
|
+
tags: [],
|
|
16
|
+
};
|
|
17
|
+
(0, utils_1.mergeDefinitions)(expressApp['_oas'], spec);
|
|
18
|
+
// Append config to request to prevent gymnastics
|
|
19
|
+
function OASRouter(req, res, next) {
|
|
20
|
+
req._oas = expressApp['_oas'];
|
|
21
|
+
return next();
|
|
22
|
+
}
|
|
23
|
+
OASRouter.OASType = 'router';
|
|
24
|
+
expressApp.use(OASRouter);
|
|
25
|
+
if (spec.basePath && spec.basePath !== '/') {
|
|
26
|
+
expressApp.mountpath = spec.basePath;
|
|
27
|
+
}
|
|
28
|
+
function initOASRouter() {
|
|
29
|
+
if (scanned)
|
|
30
|
+
throw new Error('OAS Router has already scanned for routes. Make sure it is only invoked once.');
|
|
31
|
+
scanned = true;
|
|
32
|
+
const stack = expressApp.stack || expressApp.router.stack;
|
|
33
|
+
// Scan routes for definition middleware
|
|
34
|
+
for (let i = 0; i < stack.length; i++) {
|
|
35
|
+
if (stack[i].route) {
|
|
36
|
+
const definitionPlugin = stack[i].route.stack.find(middleware => middleware.handle.OASType === 'definition');
|
|
37
|
+
if (definitionPlugin) {
|
|
38
|
+
const override = definitionPlugin.handle();
|
|
39
|
+
let operationId = stack[i].route.path;
|
|
40
|
+
// substract spec baspath if exists
|
|
41
|
+
if (spec.basePath && spec.basePath !== '/' && operationId.indexOf(expressApp.mountpath) === 0)
|
|
42
|
+
operationId = operationId.replace(expressApp.mountpath, '');
|
|
43
|
+
// Check if path level or method level
|
|
44
|
+
expressApp['_oas'].paths[(0, utils_1.formatPathToOAS)(operationId)] = expressApp['_oas'].paths[(0, utils_1.formatPathToOAS)(operationId)] || {};
|
|
45
|
+
if (override[definitionPlugin.method])
|
|
46
|
+
(0, utils_1.mergeDefinitions)(expressApp['_oas'].paths[(0, utils_1.formatPathToOAS)(operationId)], override);
|
|
47
|
+
else
|
|
48
|
+
(0, utils_1.mergeDefinitions)(expressApp['_oas'].paths[(0, utils_1.formatPathToOAS)(operationId)], { [definitionPlugin.method]: override });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
expressApp.scan = initOASRouter;
|
|
54
|
+
if (expressApp.listen) {
|
|
55
|
+
// Override listen
|
|
56
|
+
const defaultListen = expressApp.listen;
|
|
57
|
+
function listen(...args) {
|
|
58
|
+
initOASRouter();
|
|
59
|
+
return defaultListen.apply(expressApp, args);
|
|
60
|
+
}
|
|
61
|
+
expressApp.listen = listen;
|
|
62
|
+
}
|
|
63
|
+
return expressApp;
|
|
64
|
+
}
|
package/bin/utils.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.formatPathToOAS = formatPathToOAS;
|
|
4
|
+
exports.formatPathFromOAS = formatPathFromOAS;
|
|
5
|
+
exports.mergeDefinitions = mergeDefinitions;
|
|
6
|
+
function formatPathToOAS(path) {
|
|
7
|
+
return path.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
|
|
8
|
+
}
|
|
9
|
+
function formatPathFromOAS(path) {
|
|
10
|
+
return path.replace(/\{([^}]+)\}/g, ':$1');
|
|
11
|
+
}
|
|
12
|
+
function mergeDefinitions(original, updates) {
|
|
13
|
+
original = original || {};
|
|
14
|
+
for (const key of Object.keys(updates)) {
|
|
15
|
+
if (!Object.hasOwn(original, key) || typeof updates[key] !== 'object')
|
|
16
|
+
original[key] = updates[key];
|
|
17
|
+
else if (original[key] instanceof Array && updates[key] instanceof Array) {
|
|
18
|
+
updates[key].reduce((list, item, index) => {
|
|
19
|
+
if (typeof item === 'object' && item.name) {
|
|
20
|
+
const needle = original[key].findIndex(i => i.name === item.name);
|
|
21
|
+
if (needle >= 0) {
|
|
22
|
+
mergeDefinitions(original[key][needle], list[index]);
|
|
23
|
+
return list;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
list.push(item);
|
|
27
|
+
return list;
|
|
28
|
+
}, original[key]);
|
|
29
|
+
}
|
|
30
|
+
else
|
|
31
|
+
mergeDefinitions(original[key], updates[key]);
|
|
32
|
+
}
|
|
33
|
+
return original;
|
|
34
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.default = validate;
|
|
4
|
+
const swagger_route_validator_1 = require("swagger-route-validator");
|
|
5
|
+
const utils_1 = require("./utils");
|
|
6
|
+
function validate() {
|
|
7
|
+
function OASValidation(req, res, next) {
|
|
8
|
+
if (!req.route)
|
|
9
|
+
throw new Error('Request validation middleware must be added to a route');
|
|
10
|
+
let operationId = (0, utils_1.formatPathToOAS)(req.route.path);
|
|
11
|
+
// substract spec baspath if exists
|
|
12
|
+
if (req._oas?.basePath && req._oas?.basePath !== '/' && operationId.indexOf(req._oas?.basePath) === 0)
|
|
13
|
+
operationId = operationId.replace(req._oas?.basePath, '');
|
|
14
|
+
const matchingSpec = req._oas?.paths?.[operationId]?.[req.method.toLowerCase()];
|
|
15
|
+
if (matchingSpec)
|
|
16
|
+
return (0, swagger_route_validator_1.expressRequestValidation)(matchingSpec, req._oas)(req, res, next);
|
|
17
|
+
throw new Error(`Request validation middleware added, but no definition could be found for ${operationId}.${req.method.toLowerCase()}`);
|
|
18
|
+
}
|
|
19
|
+
OASValidation.OASType = 'validation';
|
|
20
|
+
return OASValidation;
|
|
21
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@express-tools/oas",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "OpenAPI plugin for express",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"main": "bin/index.js",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"express",
|
|
9
|
+
"open",
|
|
10
|
+
"api",
|
|
11
|
+
"openapi",
|
|
12
|
+
"standard",
|
|
13
|
+
"plugin",
|
|
14
|
+
"validation",
|
|
15
|
+
"documentation",
|
|
16
|
+
"definition",
|
|
17
|
+
"schema"
|
|
18
|
+
],
|
|
19
|
+
"files": [
|
|
20
|
+
"bin",
|
|
21
|
+
"types.d.ts"
|
|
22
|
+
],
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"swagger-route-validator": "^3.1.0"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"express": "^5.1.0",
|
|
28
|
+
"undici": "^7.16.0"
|
|
29
|
+
},
|
|
30
|
+
"typings": "types.d.ts",
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "rm -rf ./bin && mkdir ./bin && tsc --project ./tsconfig.json",
|
|
33
|
+
"test:unit": "jest src/*",
|
|
34
|
+
"test:integration": "jest tests/*",
|
|
35
|
+
"test": "npm run test:unit && npm run test:integration",
|
|
36
|
+
"prepublishOnly": "npm run build && cp ../../LICENSE ./LICENSE"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "https://github.com/nerve-box/express-tools",
|
|
39
|
+
"contributors": [
|
|
40
|
+
"frederic charette <fredericcharette@gmail.com>"
|
|
41
|
+
],
|
|
42
|
+
"bugs": {
|
|
43
|
+
"url": "https://github.com/nerve-box/express-tools/issues"
|
|
44
|
+
},
|
|
45
|
+
"repository": {
|
|
46
|
+
"type": "git",
|
|
47
|
+
"url": "git+ssh://git@github.com/nerve-box/express-tools.git",
|
|
48
|
+
"directory": "packages/oas"
|
|
49
|
+
},
|
|
50
|
+
"jest": {
|
|
51
|
+
"preset": "ts-jest",
|
|
52
|
+
"testEnvironment": "node",
|
|
53
|
+
"transform": {
|
|
54
|
+
"^.+\\.m?[tj]sx?$": [
|
|
55
|
+
"ts-jest",
|
|
56
|
+
{
|
|
57
|
+
"diagnostics": false
|
|
58
|
+
}
|
|
59
|
+
]
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
package/types.d.ts
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { OpenApiSpecification } from 'swagger-route-validator';
|
|
2
|
+
import { Express, Request, RequestHandler } from 'express';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* OpenAPI parameter definition
|
|
6
|
+
*/
|
|
7
|
+
export interface OASParameter {
|
|
8
|
+
/** Parameter name */
|
|
9
|
+
name: string
|
|
10
|
+
/** Parameter location (path, query, header, cookie, body) */
|
|
11
|
+
in: 'path' | 'query' | 'header' | 'cookie' | 'body'
|
|
12
|
+
/** Parameter description */
|
|
13
|
+
description?: string
|
|
14
|
+
/** Whether the parameter is required */
|
|
15
|
+
required?: boolean
|
|
16
|
+
/** Parameter type (OpenAPI 2.0 style) */
|
|
17
|
+
type?: string
|
|
18
|
+
/** Parameter schema (OpenAPI 3.0 style) */
|
|
19
|
+
schema?: Record<string, unknown>
|
|
20
|
+
/** Parameter format */
|
|
21
|
+
format?: string
|
|
22
|
+
/** Default value */
|
|
23
|
+
default?: unknown
|
|
24
|
+
/** Example value */
|
|
25
|
+
example?: unknown
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* OpenAPI response definition
|
|
30
|
+
*/
|
|
31
|
+
export interface OASResponse {
|
|
32
|
+
/** Response description */
|
|
33
|
+
description?: string
|
|
34
|
+
/** Response schema */
|
|
35
|
+
schema?: Record<string, unknown>
|
|
36
|
+
/** Response headers */
|
|
37
|
+
headers?: Record<string, unknown>
|
|
38
|
+
/** Response examples */
|
|
39
|
+
examples?: Record<string, unknown>
|
|
40
|
+
/** Response content (OpenAPI 3.0 style) */
|
|
41
|
+
content?: Record<string, unknown>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* OpenAPI operation definition (method-level)
|
|
46
|
+
*/
|
|
47
|
+
export interface OASOperation {
|
|
48
|
+
/** Operation summary */
|
|
49
|
+
summary?: string
|
|
50
|
+
/** Operation description */
|
|
51
|
+
description?: string
|
|
52
|
+
/** Operation ID */
|
|
53
|
+
operationId?: string
|
|
54
|
+
/** Tags for this operation */
|
|
55
|
+
tags?: string[]
|
|
56
|
+
/** Parameters for this operation */
|
|
57
|
+
parameters?: OASParameter[]
|
|
58
|
+
/** Request body definition */
|
|
59
|
+
requestBody?: {
|
|
60
|
+
description?: string
|
|
61
|
+
required?: boolean
|
|
62
|
+
content?: Record<string, unknown>
|
|
63
|
+
}
|
|
64
|
+
/** Responses for this operation */
|
|
65
|
+
responses?: {
|
|
66
|
+
[statusCode: string]: OASResponse
|
|
67
|
+
}
|
|
68
|
+
/** Whether this operation is deprecated */
|
|
69
|
+
deprecated?: boolean
|
|
70
|
+
/** Security requirements for this operation */
|
|
71
|
+
security?: Array<Record<string, string[]>>
|
|
72
|
+
/** External documentation */
|
|
73
|
+
externalDocs?: {
|
|
74
|
+
description?: string
|
|
75
|
+
url: string
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Route definition that can contain multiple HTTP methods
|
|
81
|
+
*/
|
|
82
|
+
export interface OASRouteDefinition {
|
|
83
|
+
get?: OASOperation
|
|
84
|
+
post?: OASOperation
|
|
85
|
+
put?: OASOperation
|
|
86
|
+
patch?: OASOperation
|
|
87
|
+
delete?: OASOperation
|
|
88
|
+
options?: OASOperation
|
|
89
|
+
head?: OASOperation
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Definition override can be either:
|
|
94
|
+
* - A single operation (for use with specific method routes like app.get())
|
|
95
|
+
* - A route definition with multiple methods (for use with app.route())
|
|
96
|
+
*/
|
|
97
|
+
export type RouteDefinitionOverride = OASOperation | OASRouteDefinition;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* OpenAPI specification with components
|
|
101
|
+
*/
|
|
102
|
+
export interface OASSpec extends Partial<OpenApiSpecification> {
|
|
103
|
+
/** Base path for all routes (e.g., '/api') */
|
|
104
|
+
basePath?: string
|
|
105
|
+
/** OpenAPI components (schemas, responses, parameters, etc.) */
|
|
106
|
+
components?: {
|
|
107
|
+
schemas?: Record<string, unknown>
|
|
108
|
+
responses?: Record<string, unknown>
|
|
109
|
+
parameters?: Record<string, unknown>
|
|
110
|
+
examples?: Record<string, unknown>
|
|
111
|
+
requestBodies?: Record<string, unknown>
|
|
112
|
+
headers?: Record<string, unknown>
|
|
113
|
+
securitySchemes?: Record<string, unknown>
|
|
114
|
+
links?: Record<string, unknown>
|
|
115
|
+
callbacks?: Record<string, unknown>
|
|
116
|
+
[key: string]: unknown
|
|
117
|
+
}
|
|
118
|
+
/** OpenAPI version */
|
|
119
|
+
openapi?: string
|
|
120
|
+
/** API information */
|
|
121
|
+
info?: {
|
|
122
|
+
title?: string
|
|
123
|
+
version?: string
|
|
124
|
+
description?: string
|
|
125
|
+
termsOfService?: string
|
|
126
|
+
contact?: {
|
|
127
|
+
name?: string
|
|
128
|
+
url?: string
|
|
129
|
+
email?: string
|
|
130
|
+
}
|
|
131
|
+
license?: {
|
|
132
|
+
name?: string
|
|
133
|
+
url?: string
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/** Server definitions */
|
|
137
|
+
servers?: Array<{
|
|
138
|
+
url: string
|
|
139
|
+
description?: string
|
|
140
|
+
variables?: Record<string, unknown>
|
|
141
|
+
}>
|
|
142
|
+
/** API paths */
|
|
143
|
+
paths?: Record<string, OASRouteDefinition>
|
|
144
|
+
/** Tags */
|
|
145
|
+
tags?: Array<{
|
|
146
|
+
name: string
|
|
147
|
+
description?: string
|
|
148
|
+
externalDocs?: {
|
|
149
|
+
description?: string
|
|
150
|
+
url: string
|
|
151
|
+
}
|
|
152
|
+
}>
|
|
153
|
+
/** External documentation */
|
|
154
|
+
externalDocs?: {
|
|
155
|
+
description?: string
|
|
156
|
+
url: string
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Express router enhanced with OAS functionality
|
|
162
|
+
*/
|
|
163
|
+
export interface OASRouter extends Express {
|
|
164
|
+
/**
|
|
165
|
+
* Manually trigger route scanning to build the OpenAPI specification.
|
|
166
|
+
* This is automatically called when listen() is invoked.
|
|
167
|
+
* Use this when working with subrouters that won't call listen() directly.
|
|
168
|
+
*/
|
|
169
|
+
scan: () => void
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Internal OpenAPI specification (populated after scan)
|
|
173
|
+
* @internal
|
|
174
|
+
*/
|
|
175
|
+
_oas?: OASSpec
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Express Request extended with OAS context
|
|
180
|
+
*/
|
|
181
|
+
export interface OASRequest extends Request {
|
|
182
|
+
/**
|
|
183
|
+
* The OpenAPI specification for this request context
|
|
184
|
+
* @internal
|
|
185
|
+
*/
|
|
186
|
+
_oas?: OASSpec
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
declare module '@express-tools/oas' {
|
|
190
|
+
/**
|
|
191
|
+
* Define or override OpenAPI metadata for a route.
|
|
192
|
+
*
|
|
193
|
+
* @param override - The OpenAPI operation or route definition
|
|
194
|
+
* @returns Express middleware that stores the definition for scanning
|
|
195
|
+
*
|
|
196
|
+
* @example
|
|
197
|
+
* ```typescript
|
|
198
|
+
* server.get('/user/:id', definition({
|
|
199
|
+
* description: 'Get a user by ID',
|
|
200
|
+
* parameters: [{
|
|
201
|
+
* name: 'id',
|
|
202
|
+
* in: 'path',
|
|
203
|
+
* type: 'string',
|
|
204
|
+
* required: true
|
|
205
|
+
* }],
|
|
206
|
+
* responses: {
|
|
207
|
+
* 200: { schema: { $ref: '#/components/schemas/User' } }
|
|
208
|
+
* }
|
|
209
|
+
* }), (req, res) => {
|
|
210
|
+
* // handler
|
|
211
|
+
* });
|
|
212
|
+
* ```
|
|
213
|
+
*/
|
|
214
|
+
export function definition(override: RouteDefinitionOverride): RequestHandler;
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Generate and return the complete OpenAPI specification as JSON.
|
|
218
|
+
* Includes all route definitions and overrides.
|
|
219
|
+
*
|
|
220
|
+
* @returns Express middleware that responds with the OpenAPI spec
|
|
221
|
+
*
|
|
222
|
+
* @example
|
|
223
|
+
* ```typescript
|
|
224
|
+
* server.get('/docs', documentation());
|
|
225
|
+
* ```
|
|
226
|
+
*/
|
|
227
|
+
export function documentation(): RequestHandler;
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Validate the response body against the OpenAPI specification.
|
|
231
|
+
* Throws an error if the response doesn't match the defined schema.
|
|
232
|
+
*
|
|
233
|
+
* @returns Express middleware that validates responses
|
|
234
|
+
*
|
|
235
|
+
* @example
|
|
236
|
+
* ```typescript
|
|
237
|
+
* server.get('/user/:id',
|
|
238
|
+
* definition({ responses: { 200: { schema: { $ref: '#/components/schemas/User' } } } }),
|
|
239
|
+
* response(),
|
|
240
|
+
* (req, res) => {
|
|
241
|
+
* res.json({ id: '123', name: 'John' });
|
|
242
|
+
* }
|
|
243
|
+
* );
|
|
244
|
+
* ```
|
|
245
|
+
*/
|
|
246
|
+
export function response(): RequestHandler;
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Wrap an Express app or router with OpenAPI functionality.
|
|
250
|
+
* Automatically scans routes when listen() is called.
|
|
251
|
+
*
|
|
252
|
+
* @param app - Express application or router to enhance
|
|
253
|
+
* @param spec - OpenAPI specification (optional)
|
|
254
|
+
* @returns Enhanced Express router with OAS capabilities
|
|
255
|
+
*
|
|
256
|
+
* @example
|
|
257
|
+
* ```typescript
|
|
258
|
+
* const server = router(express(), {
|
|
259
|
+
* info: {
|
|
260
|
+
* title: 'My API',
|
|
261
|
+
* version: '1.0.0'
|
|
262
|
+
* },
|
|
263
|
+
* components: {
|
|
264
|
+
* schemas: {
|
|
265
|
+
* User: {
|
|
266
|
+
* type: 'object',
|
|
267
|
+
* properties: {
|
|
268
|
+
* id: { type: 'string' },
|
|
269
|
+
* name: { type: 'string' }
|
|
270
|
+
* }
|
|
271
|
+
* }
|
|
272
|
+
* }
|
|
273
|
+
* }
|
|
274
|
+
* });
|
|
275
|
+
* ```
|
|
276
|
+
*/
|
|
277
|
+
export function router(app: Express, spec?: OASSpec): OASRouter;
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Validate incoming requests against the OpenAPI specification.
|
|
281
|
+
* Validates path parameters, query parameters, headers, and request body.
|
|
282
|
+
*
|
|
283
|
+
* @returns Express middleware that validates requests
|
|
284
|
+
*
|
|
285
|
+
* @example
|
|
286
|
+
* ```typescript
|
|
287
|
+
* server.post('/user',
|
|
288
|
+
* definition({
|
|
289
|
+
* parameters: [{
|
|
290
|
+
* name: 'body',
|
|
291
|
+
* in: 'body',
|
|
292
|
+
* schema: { $ref: '#/components/schemas/User' }
|
|
293
|
+
* }]
|
|
294
|
+
* }),
|
|
295
|
+
* validation(),
|
|
296
|
+
* (req, res) => {
|
|
297
|
+
* // req.body is validated
|
|
298
|
+
* }
|
|
299
|
+
* );
|
|
300
|
+
* ```
|
|
301
|
+
*/
|
|
302
|
+
export function validation(): RequestHandler;
|
|
303
|
+
|
|
304
|
+
// Export types for external use
|
|
305
|
+
export type {
|
|
306
|
+
OASParameter,
|
|
307
|
+
OASResponse,
|
|
308
|
+
OASOperation,
|
|
309
|
+
OASRouteDefinition,
|
|
310
|
+
RouteDefinitionOverride,
|
|
311
|
+
OASSpec,
|
|
312
|
+
OASRouter,
|
|
313
|
+
OASRequest,
|
|
314
|
+
};
|
|
315
|
+
}
|