@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.
Files changed (49) hide show
  1. package/README.md +70 -8
  2. package/dist/core/body_parser_error_handler.d.ts +15 -0
  3. package/dist/core/body_parser_error_handler.js +35 -0
  4. package/dist/core/logger/logger.d.ts +1 -0
  5. package/dist/core/logger/logger.js +1 -0
  6. package/dist/core/logger/logging_middleware.js +11 -0
  7. package/dist/core/modular_api.d.ts +17 -0
  8. package/dist/core/modular_api.js +107 -43
  9. package/dist/core/official_plugins.d.ts +35 -0
  10. package/dist/core/official_plugins.js +213 -0
  11. package/dist/core/plugin.d.ts +163 -0
  12. package/dist/core/plugin.js +304 -0
  13. package/dist/core/request_pipeline_audit.d.ts +15 -0
  14. package/dist/core/request_pipeline_audit.js +29 -0
  15. package/dist/core/schema/field.d.ts +2 -1
  16. package/dist/core/schema/field.js +4 -0
  17. package/dist/core/unhandled_request_error_handler.d.ts +2 -0
  18. package/dist/core/unhandled_request_error_handler.js +17 -0
  19. package/dist/core/usecase.js +1 -0
  20. package/dist/core/usecase_handler.js +3 -2
  21. package/dist/graphql/catalog/graphql_catalog_builder.d.ts +149 -0
  22. package/dist/graphql/catalog/graphql_catalog_builder.js +564 -0
  23. package/dist/graphql/metadata/graphql_metadata_parser.d.ts +53 -0
  24. package/dist/graphql/metadata/graphql_metadata_parser.js +373 -0
  25. package/dist/graphql/read/sql_read_contract.d.ts +155 -0
  26. package/dist/graphql/read/sql_read_contract.js +194 -0
  27. package/dist/graphql/read/sqlserver_read_compiler.d.ts +58 -0
  28. package/dist/graphql/read/sqlserver_read_compiler.js +279 -0
  29. package/dist/graphql/runtime/graphql_artifacts.d.ts +43 -0
  30. package/dist/graphql/runtime/graphql_artifacts.js +512 -0
  31. package/dist/graphql/runtime/graphql_runtime_options.d.ts +52 -0
  32. package/dist/graphql/runtime/graphql_runtime_options.js +60 -0
  33. package/dist/graphql/runtime/graphql_runtime_plugin.d.ts +18 -0
  34. package/dist/graphql/runtime/graphql_runtime_plugin.js +946 -0
  35. package/dist/graphql/schema/graphql_schema_sdl_generator.d.ts +17 -0
  36. package/dist/graphql/schema/graphql_schema_sdl_generator.js +221 -0
  37. package/dist/graphql/sqlserver/physical_model.d.ts +28 -0
  38. package/dist/graphql/sqlserver/physical_model.js +8 -0
  39. package/dist/graphql/sqlserver/sql_server_connection_settings.d.ts +15 -0
  40. package/dist/graphql/sqlserver/sql_server_connection_settings.js +28 -0
  41. package/dist/graphql/sqlserver/sql_server_metadata_reader.d.ts +39 -0
  42. package/dist/graphql/sqlserver/sql_server_metadata_reader.js +294 -0
  43. package/dist/index.d.ts +17 -0
  44. package/dist/index.js +58 -1
  45. package/dist/openapi/swagger_docs.d.ts +11 -6
  46. package/dist/openapi/swagger_docs.js +16 -193
  47. package/package.json +9 -6
  48. package/dist/core/usecase_test_handler.d.ts +0 -27
  49. package/dist/core/usecase_test_handler.js +0 -60
@@ -0,0 +1,213 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.operationalRoutePaths = operationalRoutePaths;
4
+ exports.buildRuntimePlugins = buildRuntimePlugins;
5
+ const openapi_1 = require("../openapi/openapi");
6
+ const swagger_docs_1 = require("../openapi/swagger_docs");
7
+ const graphql_runtime_plugin_1 = require("../graphql/runtime/graphql_runtime_plugin");
8
+ const metrics_middleware_1 = require("./metrics/metrics_middleware");
9
+ const registry_1 = require("./registry");
10
+ const OPENAPI_SPEC_CAPABILITY_ID = 'modular_api.openapi.spec';
11
+ const OFFICIAL_PLUGIN_HOST_RANGE = '>=0.1.0 <0.2.0';
12
+ function operationalRoutePaths(basePath, metricsPath) {
13
+ return {
14
+ healthPath: joinPath(basePath, '/health'),
15
+ docsPath: joinPath(basePath, '/docs'),
16
+ openApiJsonPath: joinPath(basePath, '/openapi.json'),
17
+ openApiYamlPath: joinPath(basePath, '/openapi.yaml'),
18
+ metricsPath: metricsPath ? joinPath(basePath, metricsPath) : undefined,
19
+ };
20
+ }
21
+ function buildRuntimePlugins(options) {
22
+ const plugins = [
23
+ new HealthRuntimePlugin(options.healthService),
24
+ new graphql_runtime_plugin_1.GraphqlRuntimePlugin(options.graphql, options.healthService),
25
+ ];
26
+ if (options.metrics) {
27
+ plugins.push(new MetricsRuntimePlugin(options.basePath, options.metrics));
28
+ }
29
+ plugins.push(new OpenApiRuntimePlugin({
30
+ basePath: options.basePath,
31
+ title: options.title,
32
+ version: options.version,
33
+ port: options.port,
34
+ servers: options.servers,
35
+ }), new DocsRuntimePlugin());
36
+ return plugins;
37
+ }
38
+ class HealthRuntimePlugin {
39
+ healthService;
40
+ manifest = {
41
+ id: 'modular_api.health',
42
+ displayName: 'Health Plugin',
43
+ version: '0.1.0',
44
+ hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
45
+ };
46
+ constructor(healthService) {
47
+ this.healthService = healthService;
48
+ }
49
+ setup(host) {
50
+ host.registerRoute({
51
+ id: 'health.endpoint',
52
+ method: 'GET',
53
+ path: '/health',
54
+ visibility: 'operational',
55
+ handler: async () => {
56
+ const health = await this.healthService.evaluate();
57
+ return {
58
+ status: health.httpStatusCode,
59
+ contentType: 'application/health+json; charset=utf-8',
60
+ body: health.toJson(),
61
+ };
62
+ },
63
+ });
64
+ }
65
+ }
66
+ class MetricsRuntimePlugin {
67
+ basePath;
68
+ options;
69
+ manifest = {
70
+ id: 'modular_api.metrics',
71
+ displayName: 'Metrics Plugin',
72
+ version: '0.1.0',
73
+ hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
74
+ };
75
+ constructor(basePath, options) {
76
+ this.basePath = basePath;
77
+ this.options = options;
78
+ }
79
+ setup(host) {
80
+ if (!this.options) {
81
+ return;
82
+ }
83
+ const paths = operationalRoutePaths(this.basePath, this.options.path);
84
+ const configuredExcluded = this.options.excludedRoutes.map((route) => joinPath(this.basePath, route));
85
+ const excludedRoutes = [...new Set([
86
+ ...configuredExcluded,
87
+ paths.healthPath,
88
+ paths.docsPath,
89
+ paths.openApiJsonPath,
90
+ paths.openApiYamlPath,
91
+ ...(paths.metricsPath ? [paths.metricsPath] : []),
92
+ ])];
93
+ host.registerMiddleware({
94
+ id: 'metrics.middleware',
95
+ slot: 'preRouting',
96
+ order: 0,
97
+ handler: (0, metrics_middleware_1.metricsMiddleware)({
98
+ requestsTotal: this.options.requestsTotal,
99
+ requestsInFlight: this.options.requestsInFlight,
100
+ requestDuration: this.options.requestDuration,
101
+ excludedRoutes,
102
+ registeredPaths: registry_1.apiRegistry.routes.map((route) => route.path),
103
+ }),
104
+ });
105
+ host.registerRoute({
106
+ id: 'metrics.endpoint',
107
+ method: 'GET',
108
+ path: this.options.path,
109
+ visibility: 'operational',
110
+ handler: () => ({
111
+ status: 200,
112
+ contentType: 'text/plain; version=0.0.4; charset=utf-8',
113
+ body: this.options?.registry.serialize(),
114
+ }),
115
+ });
116
+ }
117
+ }
118
+ class OpenApiRuntimePlugin {
119
+ options;
120
+ manifest = {
121
+ id: 'modular_api.openapi',
122
+ displayName: 'OpenAPI Plugin',
123
+ version: '0.1.0',
124
+ hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
125
+ };
126
+ constructor(options) {
127
+ this.options = options;
128
+ }
129
+ setup(host) {
130
+ const spec = (0, openapi_1.buildOpenApiSpec)({
131
+ title: this.options.title,
132
+ port: this.options.port,
133
+ version: this.options.version,
134
+ servers: this.options.servers,
135
+ });
136
+ const yaml = (0, openapi_1.jsonToYaml)(spec);
137
+ const specUrl = operationalRoutePaths(this.options.basePath).openApiJsonPath;
138
+ host.exposeCapability({
139
+ id: OPENAPI_SPEC_CAPABILITY_ID,
140
+ version: '1.0.0',
141
+ value: { spec, yaml, specUrl },
142
+ });
143
+ host.registerRoute({
144
+ id: 'openapi.json.endpoint',
145
+ method: 'GET',
146
+ path: '/openapi.json',
147
+ visibility: 'operational',
148
+ handler: () => ({
149
+ status: 200,
150
+ contentType: 'application/json; charset=utf-8',
151
+ body: spec,
152
+ }),
153
+ });
154
+ host.registerRoute({
155
+ id: 'openapi.yaml.endpoint',
156
+ method: 'GET',
157
+ path: '/openapi.yaml',
158
+ visibility: 'operational',
159
+ handler: () => ({
160
+ status: 200,
161
+ contentType: 'application/x-yaml; charset=utf-8',
162
+ body: yaml,
163
+ }),
164
+ });
165
+ }
166
+ }
167
+ class DocsRuntimePlugin {
168
+ manifest = {
169
+ id: 'modular_api.docs',
170
+ displayName: 'Docs Plugin',
171
+ version: '0.1.0',
172
+ hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
173
+ };
174
+ setup(host) {
175
+ const specCapability = host.requireCapability(OPENAPI_SPEC_CAPABILITY_ID);
176
+ const html = (0, swagger_docs_1.buildSwaggerDocsHtml)({
177
+ title: host.metadata().title,
178
+ specUrl: specCapability.value.specUrl,
179
+ });
180
+ host.registerRoute({
181
+ id: 'docs.endpoint',
182
+ method: 'GET',
183
+ path: '/docs',
184
+ visibility: 'operational',
185
+ handler: () => ({
186
+ status: 200,
187
+ contentType: 'text/html; charset=utf-8',
188
+ body: html,
189
+ }),
190
+ });
191
+ }
192
+ }
193
+ function normalizeBasePath(basePath) {
194
+ if (!basePath || basePath === '/') {
195
+ return '/';
196
+ }
197
+ return `/${basePath.trim().replace(/^\/+|\/+$/g, '')}`;
198
+ }
199
+ function normalizeRelativePath(path) {
200
+ const trimmed = path.trim();
201
+ if (!trimmed) {
202
+ throw new Error('Plugin route path cannot be empty');
203
+ }
204
+ return `/${trimmed.replace(/^\/+|\/+$/g, '')}`;
205
+ }
206
+ function joinPath(basePath, relativePath) {
207
+ const normalizedBasePath = normalizeBasePath(basePath);
208
+ const normalizedRelativePath = normalizeRelativePath(relativePath);
209
+ if (normalizedBasePath === '/') {
210
+ return normalizedRelativePath;
211
+ }
212
+ return `${normalizedBasePath}${normalizedRelativePath}`.replace(/\/+/g, '/');
213
+ }
@@ -0,0 +1,163 @@
1
+ import type { RequestHandler, Router } from 'express';
2
+ import type { ModularLogger } from './logger/logger';
3
+ export declare const HOST_API_VERSION = "0.1.0";
4
+ export type PluginRequirementType = 'plugin' | 'capability';
5
+ export type PluginRouteVisibility = 'operational' | 'transport' | 'custom';
6
+ export type MiddlewareSlot = 'preRouting' | 'preHandler' | 'postHandler';
7
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
8
+ export interface PluginRequirement {
9
+ type: PluginRequirementType;
10
+ id: string;
11
+ version?: string;
12
+ }
13
+ export interface PluginManifest {
14
+ id: string;
15
+ displayName: string;
16
+ version: string;
17
+ hostApiVersion: string;
18
+ requires?: PluginRequirement[];
19
+ optional?: PluginRequirement[];
20
+ contributes?: Record<string, unknown>;
21
+ }
22
+ export interface HostMetadata {
23
+ basePath: string;
24
+ title: string;
25
+ version: string;
26
+ hostApiVersion: string;
27
+ }
28
+ export interface PluginValidationResult {
29
+ code: string;
30
+ message: string;
31
+ pluginId?: string;
32
+ resourceId?: string;
33
+ blocking?: boolean;
34
+ }
35
+ export interface Capability<T = unknown> {
36
+ id: string;
37
+ version: string;
38
+ value: T;
39
+ }
40
+ export interface CapabilityHandle<T = unknown> {
41
+ id: string;
42
+ version: string;
43
+ value: T;
44
+ }
45
+ export interface ModuleExtensionPoint {
46
+ id: string;
47
+ mode: 'single' | 'multi';
48
+ description?: string;
49
+ }
50
+ export interface ModuleExtensionContribution {
51
+ extensionPointId: string;
52
+ moduleName: string;
53
+ value: unknown;
54
+ }
55
+ export interface PluginRequestContext {
56
+ requestId: string;
57
+ logger?: ModularLogger;
58
+ method: string;
59
+ path: string;
60
+ headers: Record<string, string | string[] | undefined>;
61
+ query: Record<string, unknown>;
62
+ body?: unknown;
63
+ pathParams: Record<string, string>;
64
+ capabilities(): ReadonlyMap<string, CapabilityHandle>;
65
+ }
66
+ export interface PluginResponse {
67
+ status?: number;
68
+ headers?: Record<string, string>;
69
+ contentType?: string;
70
+ body?: unknown;
71
+ }
72
+ export interface PluginRoute {
73
+ id: string;
74
+ method: HttpMethod;
75
+ path: string;
76
+ visibility: PluginRouteVisibility;
77
+ handler(context: PluginRequestContext): PluginResponse | Promise<PluginResponse>;
78
+ }
79
+ export interface PluginMiddleware {
80
+ id: string;
81
+ slot: MiddlewareSlot;
82
+ order?: number;
83
+ handler: RequestHandler;
84
+ }
85
+ export interface RegisteredModuleView {
86
+ name: string;
87
+ }
88
+ export interface RegisteredUseCaseView {
89
+ module: string;
90
+ command: string;
91
+ method: string;
92
+ path: string;
93
+ }
94
+ export interface PluginHost {
95
+ metadata(): HostMetadata;
96
+ modules(): RegisteredModuleView[];
97
+ useCases(): RegisteredUseCaseView[];
98
+ registerRoute(route: PluginRoute): void;
99
+ registerMiddleware(middleware: PluginMiddleware): void;
100
+ exposeCapability(capability: Capability): void;
101
+ resolveCapability(id: string): CapabilityHandle | null;
102
+ requireCapability(id: string): CapabilityHandle;
103
+ declareModuleExtensionPoint(point: ModuleExtensionPoint): void;
104
+ contributeModuleExtension(contribution: ModuleExtensionContribution): void;
105
+ addStartupValidation(validation: PluginValidationResult): void;
106
+ onShutdown(callback: () => void | Promise<void>): void;
107
+ }
108
+ export interface Plugin {
109
+ manifest: PluginManifest;
110
+ setup(host: PluginHost): void;
111
+ validate?(host: PluginHost): PluginValidationResult[] | Promise<PluginValidationResult[]>;
112
+ shutdown?(): void | Promise<void>;
113
+ }
114
+ export declare class PluginHostError extends Error {
115
+ readonly code: string;
116
+ readonly pluginId?: string | undefined;
117
+ readonly resourceId?: string | undefined;
118
+ constructor(code: string, message: string, pluginId?: string | undefined, resourceId?: string | undefined);
119
+ }
120
+ interface RuntimePluginHostOptions {
121
+ basePath: string;
122
+ title: string;
123
+ version: string;
124
+ }
125
+ export declare class RuntimePluginHost implements PluginHost {
126
+ private readonly metadataValue;
127
+ private readonly routes;
128
+ private readonly middlewares;
129
+ private readonly capabilitiesMap;
130
+ private readonly extensionPoints;
131
+ private readonly extensionValues;
132
+ private readonly startupValidations;
133
+ private readonly shutdownCallbacks;
134
+ private readonly routeKeys;
135
+ private middlewareSequence;
136
+ private activePluginId?;
137
+ private frozen;
138
+ constructor(options: RuntimePluginHostOptions);
139
+ metadata(): HostMetadata;
140
+ modules(): RegisteredModuleView[];
141
+ useCases(): RegisteredUseCaseView[];
142
+ registerRoute(route: PluginRoute): void;
143
+ registerMiddleware(middleware: PluginMiddleware): void;
144
+ beginPluginSetup(pluginId: string): void;
145
+ endPluginSetup(): void;
146
+ exposeCapability(capability: Capability): void;
147
+ resolveCapability(id: string): CapabilityHandle | null;
148
+ requireCapability(id: string): CapabilityHandle;
149
+ declareModuleExtensionPoint(point: ModuleExtensionPoint): void;
150
+ contributeModuleExtension(contribution: ModuleExtensionContribution): void;
151
+ addStartupValidation(validation: PluginValidationResult): void;
152
+ onShutdown(callback: () => void | Promise<void>): void;
153
+ freeze(): void;
154
+ assertValid(additionalValidations?: PluginValidationResult[]): void;
155
+ applyRoutes(router: Router): void;
156
+ applyMiddlewares(slot: MiddlewareSlot, app: {
157
+ use(handler: RequestHandler): void;
158
+ }): void;
159
+ shutdown(): Promise<void>;
160
+ private assertMutable;
161
+ }
162
+ export declare function orderPlugins(plugins: readonly Plugin[]): Plugin[];
163
+ export {};
@@ -0,0 +1,304 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RuntimePluginHost = exports.PluginHostError = exports.HOST_API_VERSION = void 0;
4
+ exports.orderPlugins = orderPlugins;
5
+ const logging_middleware_1 = require("./logger/logging_middleware");
6
+ const request_pipeline_audit_1 = require("./request_pipeline_audit");
7
+ const registry_1 = require("./registry");
8
+ exports.HOST_API_VERSION = '0.1.0';
9
+ const ALLOWED_MIDDLEWARE_SLOTS = new Set(['preRouting', 'preHandler', 'postHandler']);
10
+ class PluginHostError extends Error {
11
+ code;
12
+ pluginId;
13
+ resourceId;
14
+ constructor(code, message, pluginId, resourceId) {
15
+ super(message);
16
+ this.code = code;
17
+ this.pluginId = pluginId;
18
+ this.resourceId = resourceId;
19
+ this.name = 'PluginHostError';
20
+ }
21
+ }
22
+ exports.PluginHostError = PluginHostError;
23
+ class RuntimePluginHost {
24
+ metadataValue;
25
+ routes = [];
26
+ middlewares = [];
27
+ capabilitiesMap = new Map();
28
+ extensionPoints = new Map();
29
+ extensionValues = new Map();
30
+ startupValidations = [];
31
+ shutdownCallbacks = [];
32
+ routeKeys = new Set();
33
+ middlewareSequence = 0;
34
+ activePluginId;
35
+ frozen = false;
36
+ constructor(options) {
37
+ this.metadataValue = {
38
+ basePath: normalizeBasePath(options.basePath),
39
+ title: options.title,
40
+ version: options.version,
41
+ hostApiVersion: exports.HOST_API_VERSION,
42
+ };
43
+ }
44
+ metadata() {
45
+ return { ...this.metadataValue };
46
+ }
47
+ modules() {
48
+ return [...new Set(registry_1.apiRegistry.routes.map((route) => route.module))].map((name) => ({ name }));
49
+ }
50
+ useCases() {
51
+ return registry_1.apiRegistry.routes.map((route) => ({
52
+ module: route.module,
53
+ command: route.command,
54
+ method: route.method,
55
+ path: route.path,
56
+ }));
57
+ }
58
+ registerRoute(route) {
59
+ this.assertMutable();
60
+ const finalPath = joinPath(this.metadataValue.basePath, route.path);
61
+ const key = `${route.method.toUpperCase()} ${finalPath}`;
62
+ if (this.routeKeys.has(key)) {
63
+ throw new PluginHostError('ROUTE_CONFLICT', `Route conflict for ${key}`, undefined, key);
64
+ }
65
+ this.routeKeys.add(key);
66
+ this.routes.push({ finalPath, route });
67
+ }
68
+ registerMiddleware(middleware) {
69
+ this.assertMutable();
70
+ if (!ALLOWED_MIDDLEWARE_SLOTS.has(middleware.slot)) {
71
+ throw new PluginHostError('PLUGIN_VALIDATION_FAILED', `Unknown middleware slot: ${middleware.slot}`, undefined, middleware.id);
72
+ }
73
+ this.middlewares.push({
74
+ definition: {
75
+ ...middleware,
76
+ order: middleware.order ?? 0,
77
+ handler: instrumentPluginMiddleware({ ...middleware, order: middleware.order ?? 0 }, this.activePluginId),
78
+ },
79
+ sequence: this.middlewareSequence++,
80
+ });
81
+ }
82
+ beginPluginSetup(pluginId) {
83
+ this.assertMutable();
84
+ this.activePluginId = pluginId;
85
+ }
86
+ endPluginSetup() {
87
+ this.activePluginId = undefined;
88
+ }
89
+ exposeCapability(capability) {
90
+ this.assertMutable();
91
+ if (this.capabilitiesMap.has(capability.id)) {
92
+ throw new PluginHostError('CAPABILITY_CONFLICT', `Capability already exposed: ${capability.id}`, undefined, capability.id);
93
+ }
94
+ this.capabilitiesMap.set(capability.id, { ...capability });
95
+ }
96
+ resolveCapability(id) {
97
+ return this.capabilitiesMap.get(id) ?? null;
98
+ }
99
+ requireCapability(id) {
100
+ const capability = this.resolveCapability(id);
101
+ if (!capability) {
102
+ throw new PluginHostError('CAPABILITY_REQUIRED_MISSING', `Missing capability: ${id}`, undefined, id);
103
+ }
104
+ return capability;
105
+ }
106
+ declareModuleExtensionPoint(point) {
107
+ this.assertMutable();
108
+ if (this.extensionPoints.has(point.id)) {
109
+ throw new PluginHostError('MODULE_EXTENSION_POINT_CONFLICT', `Duplicate extension point: ${point.id}`, undefined, point.id);
110
+ }
111
+ this.extensionPoints.set(point.id, point);
112
+ }
113
+ contributeModuleExtension(contribution) {
114
+ this.assertMutable();
115
+ const point = this.extensionPoints.get(contribution.extensionPointId);
116
+ if (!point) {
117
+ throw new PluginHostError('MODULE_EXTENSION_CONFLICT', `Unknown extension point: ${contribution.extensionPointId}`, undefined, contribution.extensionPointId);
118
+ }
119
+ const key = `${contribution.extensionPointId}:${contribution.moduleName}`;
120
+ const values = this.extensionValues.get(key) ?? [];
121
+ if (point.mode === 'single' && values.length > 0) {
122
+ throw new PluginHostError('MODULE_EXTENSION_CONFLICT', `Duplicate contribution for single extension point ${key}`, undefined, key);
123
+ }
124
+ values.push(contribution.value);
125
+ this.extensionValues.set(key, values);
126
+ }
127
+ addStartupValidation(validation) {
128
+ this.assertMutable();
129
+ this.startupValidations.push(validation);
130
+ }
131
+ onShutdown(callback) {
132
+ this.assertMutable();
133
+ this.shutdownCallbacks.push(callback);
134
+ }
135
+ freeze() {
136
+ this.frozen = true;
137
+ }
138
+ assertValid(additionalValidations = []) {
139
+ const blocking = [...this.startupValidations, ...additionalValidations].find((validation) => validation.blocking !== false);
140
+ if (blocking) {
141
+ throw new PluginHostError(blocking.code, blocking.message, blocking.pluginId, blocking.resourceId);
142
+ }
143
+ }
144
+ applyRoutes(router) {
145
+ for (const registration of this.routes) {
146
+ const method = registration.route.method.toLowerCase();
147
+ router[method](registration.finalPath, buildPluginRouteHandler(registration.route, this.capabilitiesMap));
148
+ }
149
+ }
150
+ applyMiddlewares(slot, app) {
151
+ for (const middleware of this.middlewares
152
+ .filter((candidate) => candidate.definition.slot === slot)
153
+ .sort((left, right) => {
154
+ const orderDelta = (left.definition.order ?? 0) - (right.definition.order ?? 0);
155
+ return orderDelta !== 0 ? orderDelta : left.sequence - right.sequence;
156
+ })) {
157
+ app.use(middleware.definition.handler);
158
+ }
159
+ }
160
+ async shutdown() {
161
+ for (const callback of [...this.shutdownCallbacks].reverse()) {
162
+ await callback();
163
+ }
164
+ }
165
+ assertMutable() {
166
+ if (this.frozen) {
167
+ throw new PluginHostError('PLUGIN_VALIDATION_FAILED', 'Plugin host registration is frozen');
168
+ }
169
+ }
170
+ }
171
+ exports.RuntimePluginHost = RuntimePluginHost;
172
+ function orderPlugins(plugins) {
173
+ const pluginsById = new Map();
174
+ for (const plugin of plugins) {
175
+ pluginsById.set(plugin.manifest.id, plugin);
176
+ }
177
+ const visitState = new Map();
178
+ const ordered = [];
179
+ const visit = (plugin) => {
180
+ const pluginId = plugin.manifest.id;
181
+ const state = visitState.get(pluginId);
182
+ if (state === 'visited') {
183
+ return;
184
+ }
185
+ if (state === 'visiting') {
186
+ throw new PluginHostError('PLUGIN_DEPENDENCY_CYCLE', `Plugin dependency cycle detected at ${pluginId}`, pluginId, pluginId);
187
+ }
188
+ visitState.set(pluginId, 'visiting');
189
+ for (const requirement of plugin.manifest.requires ?? []) {
190
+ if (requirement.type !== 'plugin') {
191
+ continue;
192
+ }
193
+ const dependency = pluginsById.get(requirement.id);
194
+ if (!dependency) {
195
+ throw new PluginHostError('PLUGIN_DEPENDENCY_MISSING', `Missing required plugin dependency ${requirement.id} for ${pluginId}`, pluginId, requirement.id);
196
+ }
197
+ visit(dependency);
198
+ }
199
+ visitState.set(pluginId, 'visited');
200
+ ordered.push(plugin);
201
+ };
202
+ for (const plugin of plugins) {
203
+ visit(plugin);
204
+ }
205
+ return ordered;
206
+ }
207
+ function buildPluginRouteHandler(route, capabilities) {
208
+ return async (req, res, next) => {
209
+ try {
210
+ const logger = res.locals[logging_middleware_1.LOGGER_LOCALS_KEY];
211
+ const response = await route.handler({
212
+ requestId: readRequestId(req, res),
213
+ logger,
214
+ method: req.method,
215
+ path: req.path,
216
+ headers: req.headers,
217
+ query: req.query,
218
+ body: req.body,
219
+ pathParams: Object.fromEntries(Object.entries(req.params).map(([key, value]) => [
220
+ key,
221
+ Array.isArray(value) ? (value[0] ?? '') : value,
222
+ ])),
223
+ capabilities: () => capabilities,
224
+ });
225
+ if (response.headers) {
226
+ for (const [name, value] of Object.entries(response.headers)) {
227
+ res.setHeader(name, value);
228
+ }
229
+ }
230
+ if (response.contentType) {
231
+ res.setHeader('Content-Type', response.contentType);
232
+ }
233
+ const status = response.status ?? 200;
234
+ const body = response.body;
235
+ if (body === undefined) {
236
+ res.sendStatus(status);
237
+ return;
238
+ }
239
+ if (typeof body === 'string' || Buffer.isBuffer(body)) {
240
+ res.status(status).send(body);
241
+ return;
242
+ }
243
+ res.status(status).json(body);
244
+ }
245
+ catch (error) {
246
+ next(error);
247
+ }
248
+ };
249
+ }
250
+ function readRequestId(req, res) {
251
+ const fromHeader = req.header('X-Request-ID');
252
+ if (fromHeader) {
253
+ return fromHeader;
254
+ }
255
+ const fromLogger = res.locals[logging_middleware_1.LOGGER_LOCALS_KEY];
256
+ return fromLogger?.traceId ?? 'unknown';
257
+ }
258
+ function normalizeBasePath(basePath) {
259
+ if (!basePath || basePath === '/') {
260
+ return '/';
261
+ }
262
+ return `/${basePath.trim().replace(/^\/+|\/+$/g, '')}`;
263
+ }
264
+ function normalizeRelativePath(path) {
265
+ const trimmed = path.trim();
266
+ if (!trimmed) {
267
+ throw new PluginHostError('PLUGIN_VALIDATION_FAILED', 'Plugin route path cannot be empty');
268
+ }
269
+ return `/${trimmed.replace(/^\/+|\/+$/g, '')}`;
270
+ }
271
+ function joinPath(basePath, relativePath) {
272
+ const normalizedBasePath = normalizeBasePath(basePath);
273
+ const normalizedRelativePath = normalizeRelativePath(relativePath);
274
+ if (normalizedBasePath === '/') {
275
+ return normalizedRelativePath;
276
+ }
277
+ return `${normalizedBasePath}${normalizedRelativePath}`.replace(/\/+/g, '/');
278
+ }
279
+ function instrumentPluginMiddleware(middleware, pluginId) {
280
+ return (req, res, next) => {
281
+ (0, request_pipeline_audit_1.setShortCircuitCandidate)(res, {
282
+ pluginId: pluginId ?? 'unknown',
283
+ middlewareId: middleware.id,
284
+ slot: middleware.slot,
285
+ });
286
+ const observedNext = (error) => {
287
+ (0, request_pipeline_audit_1.clearShortCircuitCandidate)(res, middleware.id);
288
+ next(error);
289
+ };
290
+ try {
291
+ const result = middleware.handler(req, res, observedNext);
292
+ if (result && typeof result.then === 'function') {
293
+ void Promise.resolve(result).catch((error) => {
294
+ (0, request_pipeline_audit_1.clearShortCircuitCandidate)(res, middleware.id);
295
+ next(error);
296
+ });
297
+ }
298
+ }
299
+ catch (error) {
300
+ (0, request_pipeline_audit_1.clearShortCircuitCandidate)(res, middleware.id);
301
+ next(error);
302
+ }
303
+ };
304
+ }
@@ -0,0 +1,15 @@
1
+ import type { Response } from 'express';
2
+ export interface ShortCircuitAuditEntry {
3
+ pluginId: string;
4
+ middlewareId: string;
5
+ slot: string;
6
+ }
7
+ interface RequestPipelineAuditState {
8
+ shortCircuit?: ShortCircuitAuditEntry;
9
+ }
10
+ export declare const REQUEST_PIPELINE_AUDIT_LOCALS_KEY = "requestPipelineAudit";
11
+ export declare function ensureRequestPipelineAudit(res: Response): RequestPipelineAuditState;
12
+ export declare function setShortCircuitCandidate(res: Response, candidate: ShortCircuitAuditEntry): void;
13
+ export declare function clearShortCircuitCandidate(res: Response, middlewareId: string): void;
14
+ export declare function readShortCircuitCandidate(res: Response): ShortCircuitAuditEntry | undefined;
15
+ export {};