@macss/modular-api 0.4.5 → 0.4.8
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 +70 -8
- package/dist/core/body_parser_error_handler.d.ts +15 -0
- package/dist/core/body_parser_error_handler.js +35 -0
- package/dist/core/logger/logger.d.ts +1 -0
- package/dist/core/logger/logger.js +1 -0
- package/dist/core/logger/logging_middleware.js +11 -0
- package/dist/core/modular_api.d.ts +17 -0
- package/dist/core/modular_api.js +107 -43
- package/dist/core/official_plugins.d.ts +35 -0
- package/dist/core/official_plugins.js +213 -0
- package/dist/core/plugin.d.ts +163 -0
- package/dist/core/plugin.js +304 -0
- package/dist/core/request_pipeline_audit.d.ts +15 -0
- package/dist/core/request_pipeline_audit.js +29 -0
- package/dist/core/schema/field.d.ts +2 -1
- package/dist/core/schema/field.js +4 -0
- package/dist/core/unhandled_request_error_handler.d.ts +2 -0
- package/dist/core/unhandled_request_error_handler.js +17 -0
- package/dist/core/usecase.js +1 -0
- package/dist/core/usecase_handler.js +3 -2
- package/dist/graphql/catalog/graphql_catalog_builder.d.ts +149 -0
- package/dist/graphql/catalog/graphql_catalog_builder.js +564 -0
- package/dist/graphql/metadata/graphql_metadata_parser.d.ts +53 -0
- package/dist/graphql/metadata/graphql_metadata_parser.js +373 -0
- package/dist/graphql/read/sql_read_contract.d.ts +155 -0
- package/dist/graphql/read/sql_read_contract.js +194 -0
- package/dist/graphql/read/sqlserver_read_compiler.d.ts +58 -0
- package/dist/graphql/read/sqlserver_read_compiler.js +279 -0
- package/dist/graphql/runtime/graphql_artifacts.d.ts +43 -0
- package/dist/graphql/runtime/graphql_artifacts.js +512 -0
- package/dist/graphql/runtime/graphql_runtime_options.d.ts +52 -0
- package/dist/graphql/runtime/graphql_runtime_options.js +60 -0
- package/dist/graphql/runtime/graphql_runtime_plugin.d.ts +18 -0
- package/dist/graphql/runtime/graphql_runtime_plugin.js +946 -0
- package/dist/graphql/schema/graphql_schema_sdl_generator.d.ts +17 -0
- package/dist/graphql/schema/graphql_schema_sdl_generator.js +221 -0
- package/dist/graphql/sqlserver/physical_model.d.ts +28 -0
- package/dist/graphql/sqlserver/physical_model.js +8 -0
- package/dist/graphql/sqlserver/sql_server_connection_settings.d.ts +15 -0
- package/dist/graphql/sqlserver/sql_server_connection_settings.js +28 -0
- package/dist/graphql/sqlserver/sql_server_metadata_reader.d.ts +39 -0
- package/dist/graphql/sqlserver/sql_server_metadata_reader.js +294 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +58 -1
- package/dist/openapi/swagger_docs.d.ts +11 -6
- package/dist/openapi/swagger_docs.js +16 -193
- package/package.json +9 -6
- package/dist/core/usecase_test_handler.d.ts +0 -27
- package/dist/core/usecase_test_handler.js +0 -60
package/README.md
CHANGED
|
@@ -35,10 +35,10 @@ curl -X POST http://localhost:8080/api/greetings/hello \
|
|
|
35
35
|
{ "message": "Hello, World!" }
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
-
**Docs** → `http://localhost:8080/docs`
|
|
39
|
-
**Health** → `http://localhost:8080/health`
|
|
40
|
-
**OpenAPI JSON** → `http://localhost:8080/openapi.json` _(also /openapi.yaml)_
|
|
41
|
-
**Metrics** → `http://localhost:8080/metrics` _(opt-in)_
|
|
38
|
+
**Docs** → `http://localhost:8080/api/docs`
|
|
39
|
+
**Health** → `http://localhost:8080/api/health`
|
|
40
|
+
**OpenAPI JSON** → `http://localhost:8080/api/openapi.json` _(also /api/openapi.yaml)_
|
|
41
|
+
**Metrics** → `http://localhost:8080/api/metrics` _(opt-in)_
|
|
42
42
|
|
|
43
43
|
See `example/example.ts` for the full implementation including Input, Output, UseCase with `validate()`, and the builder.
|
|
44
44
|
|
|
@@ -53,22 +53,84 @@ See `example/example.ts` for the full implementation including Input, Output, Us
|
|
|
53
53
|
- `ModularApi` + `ModuleBuilder` — module registration and routing
|
|
54
54
|
- Constructor-based unit testing with fake dependency injection
|
|
55
55
|
- `cors()` middleware — built-in CORS support
|
|
56
|
-
-
|
|
57
|
-
-
|
|
58
|
-
-
|
|
59
|
-
-
|
|
56
|
+
- All public endpoints resolve under the configured `basePath`.
|
|
57
|
+
- Swagger UI at `/{basePath}/docs` — auto-generated from registered use cases
|
|
58
|
+
- OpenAPI spec at `/{basePath}/openapi.json` and `/{basePath}/openapi.yaml` — raw spec download
|
|
59
|
+
- Health check at `GET /{basePath}/health` — [IETF Health Check Response Format](doc/health_check_guide.md)
|
|
60
|
+
- Prometheus metrics at `GET /{basePath}/metrics` — [Prometheus exposition format](doc/metrics_guide.md)
|
|
60
61
|
- Structured JSON logging — Loki/Grafana compatible, [request-scoped with trace_id](doc/logger_guide.md)
|
|
61
62
|
- All endpoints default to `POST` (configurable per use case)
|
|
62
63
|
- Full TypeScript declarations (`.d.ts`) included
|
|
63
64
|
|
|
64
65
|
---
|
|
65
66
|
|
|
67
|
+
## Plugin host
|
|
68
|
+
|
|
69
|
+
The public plugin contract is available from the package exports and is already
|
|
70
|
+
used by the official health, metrics, OpenAPI, and docs plugins.
|
|
71
|
+
|
|
72
|
+
Current lifecycle behavior:
|
|
73
|
+
|
|
74
|
+
- `api.plugin(...)` registers a plugin instance without running setup yet
|
|
75
|
+
- `setup(host)` runs during `serve()` in dependency order
|
|
76
|
+
- `validate(host)` runs after registration freeze and can abort startup
|
|
77
|
+
- `shutdown()` runs in reverse setup order on normal shutdown and on partial
|
|
78
|
+
startup rollback
|
|
79
|
+
- plugin routes always resolve under the configured `basePath`
|
|
80
|
+
- all three public middleware slots are active with deterministic ordering
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import {
|
|
84
|
+
ModularApi,
|
|
85
|
+
type Plugin,
|
|
86
|
+
type PluginHost,
|
|
87
|
+
type PluginManifest,
|
|
88
|
+
} from '@macss/modular-api';
|
|
89
|
+
|
|
90
|
+
class HelloPlugin implements Plugin {
|
|
91
|
+
readonly manifest: PluginManifest = {
|
|
92
|
+
id: 'acme.hello',
|
|
93
|
+
displayName: 'Hello Plugin',
|
|
94
|
+
version: '0.1.0',
|
|
95
|
+
hostApiVersion: '>=0.1.0 <0.2.0',
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
setup(host: PluginHost): void {
|
|
99
|
+
host.registerRoute({
|
|
100
|
+
id: 'hello-plugin',
|
|
101
|
+
method: 'GET',
|
|
102
|
+
path: '/hello-plugin',
|
|
103
|
+
visibility: 'custom',
|
|
104
|
+
handler: () => ({
|
|
105
|
+
status: 200,
|
|
106
|
+
body: { ok: true, basePath: host.metadata().basePath },
|
|
107
|
+
}),
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
validate() {
|
|
112
|
+
return [];
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const api = new ModularApi({ basePath: '/api' }).plugin(new HelloPlugin());
|
|
117
|
+
await api.serve({ port: 8080 });
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
66
122
|
## Installation
|
|
67
123
|
|
|
68
124
|
```bash
|
|
69
125
|
npm install @macss/modular-api
|
|
70
126
|
```
|
|
71
127
|
|
|
128
|
+
If you use `SqlServerMetadataReader` for SQL Server introspection, install `mssql` explicitly:
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
npm install @macss/modular-api mssql
|
|
132
|
+
```
|
|
133
|
+
|
|
72
134
|
---
|
|
73
135
|
|
|
74
136
|
## Error handling
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from 'express';
|
|
2
|
+
/**
|
|
3
|
+
* Express error-handling middleware for body-parser SyntaxErrors.
|
|
4
|
+
*
|
|
5
|
+
* When `express.json()` encounters malformed JSON, it calls `next(err)`
|
|
6
|
+
* with a `SyntaxError` whose `type` is `'entity.parse.failed'`.
|
|
7
|
+
* This handler intercepts that specific error, logs it through the
|
|
8
|
+
* request-scoped logger (so it carries `trace_id`), and returns a
|
|
9
|
+
* structured 400 response.
|
|
10
|
+
*
|
|
11
|
+
* Any other error is forwarded to the next error handler via `next(err)`.
|
|
12
|
+
*/
|
|
13
|
+
export declare function bodyParserErrorHandler(err: SyntaxError & {
|
|
14
|
+
type?: string;
|
|
15
|
+
}, req: Request, res: Response, next: NextFunction): void;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ============================================================
|
|
3
|
+
// core/body_parser_error_handler.ts
|
|
4
|
+
// Express error middleware — catches SyntaxError from
|
|
5
|
+
// express.json() (body-parser) and returns a structured 400
|
|
6
|
+
// with scoped-logger warning (trace_id preserved).
|
|
7
|
+
//
|
|
8
|
+
// Must be mounted immediately after express.json() in serve().
|
|
9
|
+
// ============================================================
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.bodyParserErrorHandler = bodyParserErrorHandler;
|
|
12
|
+
const logging_middleware_1 = require("./logger/logging_middleware");
|
|
13
|
+
/**
|
|
14
|
+
* Express error-handling middleware for body-parser SyntaxErrors.
|
|
15
|
+
*
|
|
16
|
+
* When `express.json()` encounters malformed JSON, it calls `next(err)`
|
|
17
|
+
* with a `SyntaxError` whose `type` is `'entity.parse.failed'`.
|
|
18
|
+
* This handler intercepts that specific error, logs it through the
|
|
19
|
+
* request-scoped logger (so it carries `trace_id`), and returns a
|
|
20
|
+
* structured 400 response.
|
|
21
|
+
*
|
|
22
|
+
* Any other error is forwarded to the next error handler via `next(err)`.
|
|
23
|
+
*/
|
|
24
|
+
function bodyParserErrorHandler(err, req, res, next) {
|
|
25
|
+
if (err instanceof SyntaxError && err.type === 'entity.parse.failed') {
|
|
26
|
+
const logger = res.locals[logging_middleware_1.LOGGER_LOCALS_KEY];
|
|
27
|
+
logger?.warning('Invalid JSON in request body', {
|
|
28
|
+
error: err.message,
|
|
29
|
+
status: 400,
|
|
30
|
+
});
|
|
31
|
+
res.status(400).json({ error: 'Invalid JSON in request body' });
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
next(err);
|
|
35
|
+
}
|
|
@@ -68,6 +68,7 @@ export declare class RequestScopedLogger implements ModularLogger {
|
|
|
68
68
|
route: string;
|
|
69
69
|
statusCode: number;
|
|
70
70
|
durationMs: number;
|
|
71
|
+
extra?: Record<string, unknown>;
|
|
71
72
|
}): void;
|
|
72
73
|
/** Emits an "unhandled exception" log at `error` level. No stack trace. */
|
|
73
74
|
logUnhandledException(opts: {
|
|
@@ -9,6 +9,7 @@ exports.LOGGER_LOCALS_KEY = void 0;
|
|
|
9
9
|
exports.loggingMiddleware = loggingMiddleware;
|
|
10
10
|
const node_crypto_1 = require("node:crypto");
|
|
11
11
|
const logger_1 = require("./logger");
|
|
12
|
+
const request_pipeline_audit_1 = require("../request_pipeline_audit");
|
|
12
13
|
/** Key used in `res.locals` to propagate the logger to downstream handlers. */
|
|
13
14
|
exports.LOGGER_LOCALS_KEY = 'modularLogger';
|
|
14
15
|
/**
|
|
@@ -42,17 +43,27 @@ function loggingMiddleware(opts) {
|
|
|
42
43
|
logger.logRequest({ method, route });
|
|
43
44
|
// 4. Propagate logger via res.locals
|
|
44
45
|
res.locals[exports.LOGGER_LOCALS_KEY] = logger;
|
|
46
|
+
(0, request_pipeline_audit_1.ensureRequestPipelineAudit)(res);
|
|
45
47
|
// 5. Attach X-Request-ID to response
|
|
46
48
|
res.setHeader('X-Request-ID', traceId);
|
|
47
49
|
// 6. Capture timing and emit response log on finish
|
|
48
50
|
const startNs = process.hrtime.bigint();
|
|
49
51
|
res.on('finish', () => {
|
|
50
52
|
const durationMs = Number(process.hrtime.bigint() - startNs) / 1e6;
|
|
53
|
+
const shortCircuit = (0, request_pipeline_audit_1.readShortCircuitCandidate)(res);
|
|
51
54
|
logger.logResponse({
|
|
52
55
|
method,
|
|
53
56
|
route,
|
|
54
57
|
statusCode: res.statusCode,
|
|
55
58
|
durationMs,
|
|
59
|
+
extra: shortCircuit
|
|
60
|
+
? {
|
|
61
|
+
short_circuit: true,
|
|
62
|
+
short_circuit_plugin_id: shortCircuit.pluginId,
|
|
63
|
+
short_circuit_middleware_id: shortCircuit.middlewareId,
|
|
64
|
+
short_circuit_slot: shortCircuit.slot,
|
|
65
|
+
}
|
|
66
|
+
: undefined,
|
|
56
67
|
});
|
|
57
68
|
});
|
|
58
69
|
next();
|
|
@@ -3,6 +3,8 @@ import { ModuleBuilder } from './module_builder';
|
|
|
3
3
|
import type { HealthCheck } from './health/health_check';
|
|
4
4
|
import { MetricsRegistrar } from './metrics/metric_registry';
|
|
5
5
|
import { LogLevel } from './logger/logger';
|
|
6
|
+
import { type Plugin } from './plugin';
|
|
7
|
+
import type { GraphqlOptions } from '../graphql/runtime/graphql_runtime_options';
|
|
6
8
|
export interface ModularApiOptions {
|
|
7
9
|
/** Base path prefix for all module routes. Default: '/api' */
|
|
8
10
|
basePath?: string;
|
|
@@ -26,6 +28,16 @@ export interface ModularApiOptions {
|
|
|
26
28
|
* Default: LogLevel.info (emits emergency..info, suppresses debug).
|
|
27
29
|
*/
|
|
28
30
|
logLevel?: LogLevel;
|
|
31
|
+
/**
|
|
32
|
+
* OpenAPI `servers` list. Each entry has a `url` and optional `description`.
|
|
33
|
+
* When omitted, `serve()` generates `[{url: 'http://localhost:{port}'}]`.
|
|
34
|
+
*/
|
|
35
|
+
servers?: Array<{
|
|
36
|
+
url: string;
|
|
37
|
+
description?: string;
|
|
38
|
+
}>;
|
|
39
|
+
/** GraphQL runtime integration. Disabled by default. */
|
|
40
|
+
graphql?: GraphqlOptions;
|
|
29
41
|
}
|
|
30
42
|
/**
|
|
31
43
|
* Main entry point for modular_api.
|
|
@@ -53,8 +65,10 @@ export declare class ModularApi {
|
|
|
53
65
|
private readonly rootRouter;
|
|
54
66
|
private readonly basePath;
|
|
55
67
|
private readonly title;
|
|
68
|
+
private readonly version;
|
|
56
69
|
private readonly middlewares;
|
|
57
70
|
private readonly healthService;
|
|
71
|
+
private readonly plugins;
|
|
58
72
|
private readonly metricsEnabled;
|
|
59
73
|
private readonly metricsPath;
|
|
60
74
|
private readonly excludedMetricsRoutes;
|
|
@@ -64,6 +78,8 @@ export declare class ModularApi {
|
|
|
64
78
|
private readonly httpRequestsInFlight?;
|
|
65
79
|
private readonly httpRequestDuration?;
|
|
66
80
|
private readonly logLevel;
|
|
81
|
+
private readonly servers?;
|
|
82
|
+
private readonly graphql?;
|
|
67
83
|
/** Public accessor for custom-metric registration. Undefined when metrics are disabled. */
|
|
68
84
|
get metrics(): MetricsRegistrar | undefined;
|
|
69
85
|
constructor(options?: ModularApiOptions);
|
|
@@ -100,6 +116,7 @@ export declare class ModularApi {
|
|
|
100
116
|
* ```
|
|
101
117
|
*/
|
|
102
118
|
use(middleware: RequestHandler): this;
|
|
119
|
+
plugin(plugin: Plugin): this;
|
|
103
120
|
/**
|
|
104
121
|
* Starts the Express server on the given port.
|
|
105
122
|
*
|
package/dist/core/modular_api.js
CHANGED
|
@@ -11,15 +11,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
11
11
|
exports.ModularApi = void 0;
|
|
12
12
|
const express_1 = __importDefault(require("express"));
|
|
13
13
|
const module_builder_1 = require("./module_builder");
|
|
14
|
-
const openapi_1 = require("../openapi/openapi");
|
|
15
|
-
const swagger_docs_1 = require("../openapi/swagger_docs");
|
|
16
14
|
const health_service_1 = require("./health/health_service");
|
|
17
|
-
const health_handler_1 = require("./health/health_handler");
|
|
18
15
|
const metric_registry_1 = require("./metrics/metric_registry");
|
|
19
|
-
const metrics_middleware_1 = require("./metrics/metrics_middleware");
|
|
20
16
|
const logging_middleware_1 = require("./logger/logging_middleware");
|
|
21
17
|
const logger_1 = require("./logger/logger");
|
|
22
|
-
const
|
|
18
|
+
const body_parser_error_handler_1 = require("./body_parser_error_handler");
|
|
19
|
+
const unhandled_request_error_handler_1 = require("./unhandled_request_error_handler");
|
|
20
|
+
const official_plugins_1 = require("./official_plugins");
|
|
21
|
+
const plugin_1 = require("./plugin");
|
|
23
22
|
/**
|
|
24
23
|
* Main entry point for modular_api.
|
|
25
24
|
*
|
|
@@ -46,8 +45,10 @@ class ModularApi {
|
|
|
46
45
|
rootRouter;
|
|
47
46
|
basePath;
|
|
48
47
|
title;
|
|
48
|
+
version;
|
|
49
49
|
middlewares = [];
|
|
50
50
|
healthService;
|
|
51
|
+
plugins = [];
|
|
51
52
|
// Metrics
|
|
52
53
|
metricsEnabled;
|
|
53
54
|
metricsPath;
|
|
@@ -59,6 +60,9 @@ class ModularApi {
|
|
|
59
60
|
httpRequestDuration;
|
|
60
61
|
// Logging
|
|
61
62
|
logLevel;
|
|
63
|
+
// OpenAPI
|
|
64
|
+
servers;
|
|
65
|
+
graphql;
|
|
62
66
|
/** Public accessor for custom-metric registration. Undefined when metrics are disabled. */
|
|
63
67
|
get metrics() {
|
|
64
68
|
return this._metricsRegistrar;
|
|
@@ -66,8 +70,9 @@ class ModularApi {
|
|
|
66
70
|
constructor(options = {}) {
|
|
67
71
|
this.basePath = options.basePath ?? '/api';
|
|
68
72
|
this.title = options.title ?? 'Modular API';
|
|
73
|
+
this.version = options.version ?? 'x.y.z';
|
|
69
74
|
this.healthService = new health_service_1.HealthService({
|
|
70
|
-
version:
|
|
75
|
+
version: this.version,
|
|
71
76
|
releaseId: options.releaseId,
|
|
72
77
|
});
|
|
73
78
|
// Metrics setup
|
|
@@ -76,6 +81,9 @@ class ModularApi {
|
|
|
76
81
|
this.excludedMetricsRoutes = options.excludedMetricsRoutes ?? ['/metrics', '/health', '/docs'];
|
|
77
82
|
// Logging
|
|
78
83
|
this.logLevel = options.logLevel ?? logger_1.LogLevel.info;
|
|
84
|
+
// OpenAPI servers
|
|
85
|
+
this.servers = options.servers;
|
|
86
|
+
this.graphql = options.graphql;
|
|
79
87
|
if (this.metricsEnabled) {
|
|
80
88
|
this.metricRegistry = new metric_registry_1.MetricRegistry();
|
|
81
89
|
this._metricsRegistrar = new metric_registry_1.MetricsRegistrar(this.metricRegistry);
|
|
@@ -95,7 +103,6 @@ class ModularApi {
|
|
|
95
103
|
});
|
|
96
104
|
}
|
|
97
105
|
this.app = (0, express_1.default)();
|
|
98
|
-
this.app.use(express_1.default.json());
|
|
99
106
|
this.rootRouter = express_1.default.Router();
|
|
100
107
|
}
|
|
101
108
|
/**
|
|
@@ -142,6 +149,10 @@ class ModularApi {
|
|
|
142
149
|
this.middlewares.push(middleware);
|
|
143
150
|
return this;
|
|
144
151
|
}
|
|
152
|
+
plugin(plugin) {
|
|
153
|
+
this.plugins.push(plugin);
|
|
154
|
+
return this;
|
|
155
|
+
}
|
|
145
156
|
/**
|
|
146
157
|
* Starts the Express server on the given port.
|
|
147
158
|
*
|
|
@@ -151,59 +162,112 @@ class ModularApi {
|
|
|
151
162
|
*
|
|
152
163
|
* @returns The Node.js http.Server instance
|
|
153
164
|
*/
|
|
154
|
-
serve(options) {
|
|
165
|
+
async serve(options) {
|
|
155
166
|
const { port, host = '0.0.0.0' } = options;
|
|
156
|
-
|
|
167
|
+
const operationalPaths = (0, official_plugins_1.operationalRoutePaths)(this.basePath, this.metricsEnabled ? this.metricsPath : undefined);
|
|
168
|
+
const runtimePlugins = [
|
|
169
|
+
...this.plugins,
|
|
170
|
+
...(0, official_plugins_1.buildRuntimePlugins)({
|
|
171
|
+
basePath: this.basePath,
|
|
172
|
+
title: this.title,
|
|
173
|
+
version: this.version,
|
|
174
|
+
port,
|
|
175
|
+
servers: this.servers,
|
|
176
|
+
healthService: this.healthService,
|
|
177
|
+
graphql: this.graphql,
|
|
178
|
+
metrics: this.metricsEnabled &&
|
|
179
|
+
this.metricRegistry &&
|
|
180
|
+
this.httpRequestsTotal &&
|
|
181
|
+
this.httpRequestsInFlight &&
|
|
182
|
+
this.httpRequestDuration
|
|
183
|
+
? {
|
|
184
|
+
path: this.metricsPath,
|
|
185
|
+
registry: this.metricRegistry,
|
|
186
|
+
requestsTotal: this.httpRequestsTotal,
|
|
187
|
+
requestsInFlight: this.httpRequestsInFlight,
|
|
188
|
+
requestDuration: this.httpRequestDuration,
|
|
189
|
+
excludedRoutes: this.excludedMetricsRoutes,
|
|
190
|
+
}
|
|
191
|
+
: undefined,
|
|
192
|
+
}),
|
|
193
|
+
];
|
|
194
|
+
const seenPluginIds = new Set();
|
|
195
|
+
for (const plugin of runtimePlugins) {
|
|
196
|
+
if (seenPluginIds.has(plugin.manifest.id)) {
|
|
197
|
+
throw new plugin_1.PluginHostError('PLUGIN_ID_CONFLICT', `Duplicate plugin id: ${plugin.manifest.id}`, plugin.manifest.id, plugin.manifest.id);
|
|
198
|
+
}
|
|
199
|
+
seenPluginIds.add(plugin.manifest.id);
|
|
200
|
+
}
|
|
201
|
+
const orderedPlugins = (0, plugin_1.orderPlugins)(runtimePlugins);
|
|
202
|
+
const pluginHost = new plugin_1.RuntimePluginHost({
|
|
203
|
+
basePath: this.basePath,
|
|
204
|
+
title: this.title,
|
|
205
|
+
version: this.version,
|
|
206
|
+
});
|
|
207
|
+
try {
|
|
208
|
+
for (const plugin of orderedPlugins) {
|
|
209
|
+
pluginHost.beginPluginSetup(plugin.manifest.id);
|
|
210
|
+
try {
|
|
211
|
+
plugin.setup(pluginHost);
|
|
212
|
+
}
|
|
213
|
+
finally {
|
|
214
|
+
pluginHost.endPluginSetup();
|
|
215
|
+
}
|
|
216
|
+
if (plugin.shutdown) {
|
|
217
|
+
pluginHost.onShutdown(() => plugin.shutdown());
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
pluginHost.freeze();
|
|
221
|
+
const validationResults = (await Promise.all(orderedPlugins.map(async (plugin) => plugin.validate?.(pluginHost) ?? []))).flat();
|
|
222
|
+
pluginHost.assertValid(validationResults);
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
await pluginHost.shutdown();
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
return await new Promise((resolve) => {
|
|
157
229
|
// Logging middleware FIRST — trace_id + structured JSON logs.
|
|
158
|
-
const excludedLogRoutes = [
|
|
230
|
+
const excludedLogRoutes = [
|
|
231
|
+
operationalPaths.healthPath,
|
|
232
|
+
operationalPaths.docsPath,
|
|
233
|
+
operationalPaths.openApiJsonPath,
|
|
234
|
+
operationalPaths.openApiYamlPath,
|
|
235
|
+
...(operationalPaths.metricsPath ? [operationalPaths.metricsPath] : []),
|
|
236
|
+
];
|
|
159
237
|
this.app.use((0, logging_middleware_1.loggingMiddleware)({
|
|
160
238
|
logLevel: this.logLevel,
|
|
161
239
|
serviceName: this.title,
|
|
162
240
|
excludedRoutes: excludedLogRoutes,
|
|
163
241
|
}));
|
|
164
|
-
//
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
this.httpRequestsInFlight &&
|
|
169
|
-
this.httpRequestDuration) {
|
|
170
|
-
const registeredPaths = registry_1.apiRegistry.routes.map((r) => r.path);
|
|
171
|
-
this.app.use((0, metrics_middleware_1.metricsMiddleware)({
|
|
172
|
-
requestsTotal: this.httpRequestsTotal,
|
|
173
|
-
requestsInFlight: this.httpRequestsInFlight,
|
|
174
|
-
requestDuration: this.httpRequestDuration,
|
|
175
|
-
excludedRoutes: this.excludedMetricsRoutes,
|
|
176
|
-
registeredPaths,
|
|
177
|
-
}));
|
|
178
|
-
}
|
|
242
|
+
// Body parsing AFTER loggingMiddleware — SyntaxErrors now have trace_id.
|
|
243
|
+
this.app.use(express_1.default.json());
|
|
244
|
+
this.app.use(body_parser_error_handler_1.bodyParserErrorHandler);
|
|
245
|
+
pluginHost.applyMiddlewares('preRouting', this.app);
|
|
179
246
|
// Register middlewares before routes
|
|
180
247
|
for (const mw of this.middlewares) {
|
|
181
248
|
this.app.use(mw);
|
|
182
249
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
}
|
|
187
|
-
// Health endpoint — IETF Health Check Response Format
|
|
188
|
-
this.app.get('/health', (0, health_handler_1.healthHandler)(this.healthService));
|
|
250
|
+
pluginHost.applyMiddlewares('preHandler', this.app);
|
|
251
|
+
pluginHost.applyMiddlewares('postHandler', this.app);
|
|
252
|
+
pluginHost.applyRoutes(this.rootRouter);
|
|
189
253
|
// Module use case routes.
|
|
190
254
|
this.app.use(this.rootRouter);
|
|
191
|
-
|
|
192
|
-
this.app.get('/docs', (0, swagger_docs_1.swaggerDocsHandler)({ title: this.title }));
|
|
193
|
-
// Raw spec endpoints
|
|
194
|
-
const spec = (0, openapi_1.buildOpenApiSpec)({ title: this.title, port });
|
|
195
|
-
this.app.get('/openapi.json', (0, openapi_1.openApiJsonHandler)(spec));
|
|
196
|
-
this.app.get('/openapi.yaml', (0, openapi_1.openApiYamlHandler)(spec));
|
|
255
|
+
this.app.use(unhandled_request_error_handler_1.unhandledRequestErrorHandler);
|
|
197
256
|
const server = this.app.listen(port, host, () => {
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
console.log(`
|
|
201
|
-
console.log(`
|
|
202
|
-
|
|
203
|
-
|
|
257
|
+
const address = server.address();
|
|
258
|
+
const resolvedPort = typeof address === 'object' && address ? address.port : port;
|
|
259
|
+
console.log(`Docs → http://localhost:${resolvedPort}${operationalPaths.docsPath}`);
|
|
260
|
+
console.log(`Health → http://localhost:${resolvedPort}${operationalPaths.healthPath}`);
|
|
261
|
+
console.log(`OpenAPI JSON → http://localhost:${resolvedPort}${operationalPaths.openApiJsonPath}`);
|
|
262
|
+
console.log(`OpenAPI YAML → http://localhost:${resolvedPort}${operationalPaths.openApiYamlPath}`);
|
|
263
|
+
if (operationalPaths.metricsPath) {
|
|
264
|
+
console.log(`Metrics → http://localhost:${resolvedPort}${operationalPaths.metricsPath}`);
|
|
204
265
|
}
|
|
205
266
|
resolve(server);
|
|
206
267
|
});
|
|
268
|
+
server.on('close', () => {
|
|
269
|
+
void pluginHost.shutdown();
|
|
270
|
+
});
|
|
207
271
|
});
|
|
208
272
|
}
|
|
209
273
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { GraphqlOptions } from '../graphql/runtime/graphql_runtime_options';
|
|
2
|
+
import type { HealthService } from './health/health_service';
|
|
3
|
+
import type { Counter, Gauge, Histogram } from './metrics/metric';
|
|
4
|
+
import type { MetricRegistry } from './metrics/metric_registry';
|
|
5
|
+
import type { Plugin } from './plugin';
|
|
6
|
+
export interface OperationalRoutePaths {
|
|
7
|
+
healthPath: string;
|
|
8
|
+
docsPath: string;
|
|
9
|
+
openApiJsonPath: string;
|
|
10
|
+
openApiYamlPath: string;
|
|
11
|
+
metricsPath?: string;
|
|
12
|
+
}
|
|
13
|
+
interface BuildRuntimePluginsOptions {
|
|
14
|
+
basePath: string;
|
|
15
|
+
title: string;
|
|
16
|
+
version: string;
|
|
17
|
+
port: number;
|
|
18
|
+
servers?: Array<{
|
|
19
|
+
url: string;
|
|
20
|
+
description?: string;
|
|
21
|
+
}>;
|
|
22
|
+
healthService: HealthService;
|
|
23
|
+
graphql?: GraphqlOptions;
|
|
24
|
+
metrics?: {
|
|
25
|
+
path: string;
|
|
26
|
+
registry: MetricRegistry;
|
|
27
|
+
requestsTotal: Counter;
|
|
28
|
+
requestsInFlight: Gauge;
|
|
29
|
+
requestDuration: Histogram;
|
|
30
|
+
excludedRoutes: string[];
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export declare function operationalRoutePaths(basePath: string, metricsPath?: string): OperationalRoutePaths;
|
|
34
|
+
export declare function buildRuntimePlugins(options: BuildRuntimePluginsOptions): Plugin[];
|
|
35
|
+
export {};
|