@macss/modular-api 0.4.6 → 0.5.0

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 (41) hide show
  1. package/README.md +76 -8
  2. package/dist/core/logger/logger.d.ts +1 -0
  3. package/dist/core/logger/logger.js +1 -0
  4. package/dist/core/logger/logging_middleware.js +11 -0
  5. package/dist/core/modular_api.d.ts +8 -0
  6. package/dist/core/modular_api.js +99 -42
  7. package/dist/core/official_plugins.d.ts +41 -0
  8. package/dist/core/official_plugins.js +237 -0
  9. package/dist/core/plugin.d.ts +182 -0
  10. package/dist/core/plugin.js +314 -0
  11. package/dist/core/request_pipeline_audit.d.ts +15 -0
  12. package/dist/core/request_pipeline_audit.js +29 -0
  13. package/dist/core/unhandled_request_error_handler.d.ts +2 -0
  14. package/dist/core/unhandled_request_error_handler.js +17 -0
  15. package/dist/graphql/catalog/graphql_catalog_builder.d.ts +149 -0
  16. package/dist/graphql/catalog/graphql_catalog_builder.js +564 -0
  17. package/dist/graphql/metadata/graphql_metadata_parser.d.ts +53 -0
  18. package/dist/graphql/metadata/graphql_metadata_parser.js +373 -0
  19. package/dist/graphql/read/sql_read_contract.d.ts +155 -0
  20. package/dist/graphql/read/sql_read_contract.js +194 -0
  21. package/dist/graphql/read/sqlserver_read_compiler.d.ts +58 -0
  22. package/dist/graphql/read/sqlserver_read_compiler.js +279 -0
  23. package/dist/graphql/runtime/graphql_artifacts.d.ts +43 -0
  24. package/dist/graphql/runtime/graphql_artifacts.js +512 -0
  25. package/dist/graphql/runtime/graphql_runtime_options.d.ts +52 -0
  26. package/dist/graphql/runtime/graphql_runtime_options.js +60 -0
  27. package/dist/graphql/runtime/graphql_runtime_plugin.d.ts +18 -0
  28. package/dist/graphql/runtime/graphql_runtime_plugin.js +946 -0
  29. package/dist/graphql/schema/graphql_schema_sdl_generator.d.ts +17 -0
  30. package/dist/graphql/schema/graphql_schema_sdl_generator.js +221 -0
  31. package/dist/graphql/sqlserver/physical_model.d.ts +28 -0
  32. package/dist/graphql/sqlserver/physical_model.js +8 -0
  33. package/dist/graphql/sqlserver/sql_server_connection_settings.d.ts +15 -0
  34. package/dist/graphql/sqlserver/sql_server_connection_settings.js +28 -0
  35. package/dist/graphql/sqlserver/sql_server_metadata_reader.d.ts +39 -0
  36. package/dist/graphql/sqlserver/sql_server_metadata_reader.js +294 -0
  37. package/dist/index.d.ts +17 -0
  38. package/dist/index.js +58 -1
  39. package/dist/openapi/swagger_docs.d.ts +4 -0
  40. package/dist/openapi/swagger_docs.js +6 -2
  41. package/package.json +8 -6
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.operationalRoutePaths = operationalRoutePaths;
4
+ exports.mergePluginRoutesIntoSpec = mergePluginRoutesIntoSpec;
5
+ exports.buildRuntimePlugins = buildRuntimePlugins;
6
+ const openapi_1 = require("../openapi/openapi");
7
+ const swagger_docs_1 = require("../openapi/swagger_docs");
8
+ const graphql_runtime_plugin_1 = require("../graphql/runtime/graphql_runtime_plugin");
9
+ const metrics_middleware_1 = require("./metrics/metrics_middleware");
10
+ const registry_1 = require("./registry");
11
+ const OPENAPI_SPEC_CAPABILITY_ID = 'modular_api.openapi.spec';
12
+ const OFFICIAL_PLUGIN_HOST_RANGE = '>=0.1.0 <0.2.0';
13
+ function operationalRoutePaths(basePath, metricsPath) {
14
+ return {
15
+ healthPath: joinPath(basePath, '/health'),
16
+ docsPath: joinPath(basePath, '/docs'),
17
+ openApiJsonPath: joinPath(basePath, '/openapi.json'),
18
+ openApiYamlPath: joinPath(basePath, '/openapi.yaml'),
19
+ metricsPath: metricsPath ? joinPath(basePath, metricsPath) : undefined,
20
+ };
21
+ }
22
+ /**
23
+ * Merges plugin-contributed routes into the generated OpenAPI spec (ADR-0003).
24
+ * Only `custom` and `transport` routes that declare an `openapi` operation are
25
+ * documented; `operational` routes do not belong to the business contract.
26
+ */
27
+ function mergePluginRoutesIntoSpec(spec, routes) {
28
+ const paths = (spec.paths ?? {});
29
+ spec.paths = paths;
30
+ for (const route of routes) {
31
+ if (route.visibility === 'operational' || !route.openapi) {
32
+ continue;
33
+ }
34
+ const pathItem = (paths[route.path] ?? {});
35
+ pathItem[route.method.toLowerCase()] = route.openapi;
36
+ paths[route.path] = pathItem;
37
+ }
38
+ }
39
+ function buildRuntimePlugins(options) {
40
+ const plugins = [
41
+ new HealthRuntimePlugin(options.healthService),
42
+ new graphql_runtime_plugin_1.GraphqlRuntimePlugin(options.graphql, options.healthService),
43
+ ];
44
+ if (options.metrics) {
45
+ plugins.push(new MetricsRuntimePlugin(options.basePath, options.metrics));
46
+ }
47
+ plugins.push(new OpenApiRuntimePlugin({
48
+ basePath: options.basePath,
49
+ title: options.title,
50
+ version: options.version,
51
+ port: options.port,
52
+ servers: options.servers,
53
+ }), new DocsRuntimePlugin());
54
+ return plugins;
55
+ }
56
+ class HealthRuntimePlugin {
57
+ healthService;
58
+ manifest = {
59
+ id: 'modular_api.health',
60
+ displayName: 'Health Plugin',
61
+ version: '0.1.0',
62
+ hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
63
+ };
64
+ constructor(healthService) {
65
+ this.healthService = healthService;
66
+ }
67
+ setup(host) {
68
+ host.registerRoute({
69
+ id: 'health.endpoint',
70
+ method: 'GET',
71
+ path: '/health',
72
+ visibility: 'operational',
73
+ handler: async () => {
74
+ const health = await this.healthService.evaluate();
75
+ return {
76
+ status: health.httpStatusCode,
77
+ contentType: 'application/health+json; charset=utf-8',
78
+ body: health.toJson(),
79
+ };
80
+ },
81
+ });
82
+ }
83
+ }
84
+ class MetricsRuntimePlugin {
85
+ basePath;
86
+ options;
87
+ manifest = {
88
+ id: 'modular_api.metrics',
89
+ displayName: 'Metrics Plugin',
90
+ version: '0.1.0',
91
+ hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
92
+ };
93
+ constructor(basePath, options) {
94
+ this.basePath = basePath;
95
+ this.options = options;
96
+ }
97
+ setup(host) {
98
+ if (!this.options) {
99
+ return;
100
+ }
101
+ const paths = operationalRoutePaths(this.basePath, this.options.path);
102
+ const configuredExcluded = this.options.excludedRoutes.map((route) => joinPath(this.basePath, route));
103
+ const excludedRoutes = [...new Set([
104
+ ...configuredExcluded,
105
+ paths.healthPath,
106
+ paths.docsPath,
107
+ paths.openApiJsonPath,
108
+ paths.openApiYamlPath,
109
+ ...(paths.metricsPath ? [paths.metricsPath] : []),
110
+ ])];
111
+ host.registerMiddleware({
112
+ id: 'metrics.middleware',
113
+ slot: 'preRouting',
114
+ order: 0,
115
+ handler: (0, metrics_middleware_1.metricsMiddleware)({
116
+ requestsTotal: this.options.requestsTotal,
117
+ requestsInFlight: this.options.requestsInFlight,
118
+ requestDuration: this.options.requestDuration,
119
+ excludedRoutes,
120
+ // Plugin routes also get their real route label instead of UNMATCHED (ADR-0003).
121
+ // User plugins run setup() before official plugins, so their routes are visible here.
122
+ registeredPaths: [
123
+ ...registry_1.apiRegistry.routes.map((route) => route.path),
124
+ ...host.routes().map((route) => route.path),
125
+ ],
126
+ }),
127
+ });
128
+ host.registerRoute({
129
+ id: 'metrics.endpoint',
130
+ method: 'GET',
131
+ path: this.options.path,
132
+ visibility: 'operational',
133
+ handler: () => ({
134
+ status: 200,
135
+ contentType: 'text/plain; version=0.0.4; charset=utf-8',
136
+ body: this.options?.registry.serialize(),
137
+ }),
138
+ });
139
+ }
140
+ }
141
+ class OpenApiRuntimePlugin {
142
+ options;
143
+ manifest = {
144
+ id: 'modular_api.openapi',
145
+ displayName: 'OpenAPI Plugin',
146
+ version: '0.1.0',
147
+ hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
148
+ };
149
+ constructor(options) {
150
+ this.options = options;
151
+ }
152
+ setup(host) {
153
+ const spec = (0, openapi_1.buildOpenApiSpec)({
154
+ title: this.options.title,
155
+ port: this.options.port,
156
+ version: this.options.version,
157
+ servers: this.options.servers,
158
+ });
159
+ mergePluginRoutesIntoSpec(spec, host.routes());
160
+ const yaml = (0, openapi_1.jsonToYaml)(spec);
161
+ const specUrl = operationalRoutePaths(this.options.basePath).openApiJsonPath;
162
+ host.exposeCapability({
163
+ id: OPENAPI_SPEC_CAPABILITY_ID,
164
+ version: '1.0.0',
165
+ value: { spec, yaml, specUrl },
166
+ });
167
+ host.registerRoute({
168
+ id: 'openapi.json.endpoint',
169
+ method: 'GET',
170
+ path: '/openapi.json',
171
+ visibility: 'operational',
172
+ handler: () => ({
173
+ status: 200,
174
+ contentType: 'application/json; charset=utf-8',
175
+ body: spec,
176
+ }),
177
+ });
178
+ host.registerRoute({
179
+ id: 'openapi.yaml.endpoint',
180
+ method: 'GET',
181
+ path: '/openapi.yaml',
182
+ visibility: 'operational',
183
+ handler: () => ({
184
+ status: 200,
185
+ contentType: 'application/x-yaml; charset=utf-8',
186
+ body: yaml,
187
+ }),
188
+ });
189
+ }
190
+ }
191
+ class DocsRuntimePlugin {
192
+ manifest = {
193
+ id: 'modular_api.docs',
194
+ displayName: 'Docs Plugin',
195
+ version: '0.1.0',
196
+ hostApiVersion: OFFICIAL_PLUGIN_HOST_RANGE,
197
+ };
198
+ setup(host) {
199
+ const specCapability = host.requireCapability(OPENAPI_SPEC_CAPABILITY_ID);
200
+ const html = (0, swagger_docs_1.buildSwaggerDocsHtml)({
201
+ title: host.metadata().title,
202
+ specUrl: specCapability.value.specUrl,
203
+ });
204
+ host.registerRoute({
205
+ id: 'docs.endpoint',
206
+ method: 'GET',
207
+ path: '/docs',
208
+ visibility: 'operational',
209
+ handler: () => ({
210
+ status: 200,
211
+ contentType: 'text/html; charset=utf-8',
212
+ body: html,
213
+ }),
214
+ });
215
+ }
216
+ }
217
+ function normalizeBasePath(basePath) {
218
+ if (!basePath || basePath === '/') {
219
+ return '/';
220
+ }
221
+ return `/${basePath.trim().replace(/^\/+|\/+$/g, '')}`;
222
+ }
223
+ function normalizeRelativePath(path) {
224
+ const trimmed = path.trim();
225
+ if (!trimmed) {
226
+ throw new Error('Plugin route path cannot be empty');
227
+ }
228
+ return `/${trimmed.replace(/^\/+|\/+$/g, '')}`;
229
+ }
230
+ function joinPath(basePath, relativePath) {
231
+ const normalizedBasePath = normalizeBasePath(basePath);
232
+ const normalizedRelativePath = normalizeRelativePath(relativePath);
233
+ if (normalizedBasePath === '/') {
234
+ return normalizedRelativePath;
235
+ }
236
+ return `${normalizedBasePath}${normalizedRelativePath}`.replace(/\/+/g, '/');
237
+ }
@@ -0,0 +1,182 @@
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
+ /**
78
+ * Optional standard OpenAPI Operation object (summary, parameters, requestBody,
79
+ * responses — including binary content types). When present on a `custom` or
80
+ * `transport` route, the official OpenApiPlugin merges it into the generated
81
+ * spec so the route appears in /openapi.json and /docs (ADR-0003).
82
+ */
83
+ openapi?: Record<string, unknown>;
84
+ handler(context: PluginRequestContext): PluginResponse | Promise<PluginResponse>;
85
+ }
86
+ export interface PluginMiddleware {
87
+ id: string;
88
+ slot: MiddlewareSlot;
89
+ order?: number;
90
+ handler: RequestHandler;
91
+ }
92
+ export interface RegisteredModuleView {
93
+ name: string;
94
+ }
95
+ export interface RegisteredUseCaseView {
96
+ module: string;
97
+ command: string;
98
+ method: string;
99
+ path: string;
100
+ }
101
+ /** Read view of a plugin route already registered on the host (ADR-0003). */
102
+ export interface RegisteredPluginRouteView {
103
+ pluginId?: string;
104
+ id: string;
105
+ method: HttpMethod;
106
+ /** Absolute mounted path (basePath already joined). */
107
+ path: string;
108
+ visibility: PluginRouteVisibility;
109
+ openapi?: Record<string, unknown>;
110
+ }
111
+ export interface PluginHost {
112
+ metadata(): HostMetadata;
113
+ modules(): RegisteredModuleView[];
114
+ useCases(): RegisteredUseCaseView[];
115
+ routes(): RegisteredPluginRouteView[];
116
+ registerRoute(route: PluginRoute): void;
117
+ registerMiddleware(middleware: PluginMiddleware): void;
118
+ exposeCapability(capability: Capability): void;
119
+ resolveCapability(id: string): CapabilityHandle | null;
120
+ requireCapability(id: string): CapabilityHandle;
121
+ declareModuleExtensionPoint(point: ModuleExtensionPoint): void;
122
+ contributeModuleExtension(contribution: ModuleExtensionContribution): void;
123
+ addStartupValidation(validation: PluginValidationResult): void;
124
+ onShutdown(callback: () => void | Promise<void>): void;
125
+ }
126
+ export interface Plugin {
127
+ manifest: PluginManifest;
128
+ setup(host: PluginHost): void;
129
+ validate?(host: PluginHost): PluginValidationResult[] | Promise<PluginValidationResult[]>;
130
+ shutdown?(): void | Promise<void>;
131
+ }
132
+ export declare class PluginHostError extends Error {
133
+ readonly code: string;
134
+ readonly pluginId?: string | undefined;
135
+ readonly resourceId?: string | undefined;
136
+ constructor(code: string, message: string, pluginId?: string | undefined, resourceId?: string | undefined);
137
+ }
138
+ interface RuntimePluginHostOptions {
139
+ basePath: string;
140
+ title: string;
141
+ version: string;
142
+ }
143
+ export declare class RuntimePluginHost implements PluginHost {
144
+ private readonly metadataValue;
145
+ private readonly registeredRoutes;
146
+ private readonly middlewares;
147
+ private readonly capabilitiesMap;
148
+ private readonly extensionPoints;
149
+ private readonly extensionValues;
150
+ private readonly startupValidations;
151
+ private readonly shutdownCallbacks;
152
+ private readonly routeKeys;
153
+ private middlewareSequence;
154
+ private activePluginId?;
155
+ private frozen;
156
+ constructor(options: RuntimePluginHostOptions);
157
+ metadata(): HostMetadata;
158
+ modules(): RegisteredModuleView[];
159
+ useCases(): RegisteredUseCaseView[];
160
+ registerRoute(route: PluginRoute): void;
161
+ routes(): RegisteredPluginRouteView[];
162
+ registerMiddleware(middleware: PluginMiddleware): void;
163
+ beginPluginSetup(pluginId: string): void;
164
+ endPluginSetup(): void;
165
+ exposeCapability(capability: Capability): void;
166
+ resolveCapability(id: string): CapabilityHandle | null;
167
+ requireCapability(id: string): CapabilityHandle;
168
+ declareModuleExtensionPoint(point: ModuleExtensionPoint): void;
169
+ contributeModuleExtension(contribution: ModuleExtensionContribution): void;
170
+ addStartupValidation(validation: PluginValidationResult): void;
171
+ onShutdown(callback: () => void | Promise<void>): void;
172
+ freeze(): void;
173
+ assertValid(additionalValidations?: PluginValidationResult[]): void;
174
+ applyRoutes(router: Router): void;
175
+ applyMiddlewares(slot: MiddlewareSlot, app: {
176
+ use(handler: RequestHandler): void;
177
+ }): void;
178
+ shutdown(): Promise<void>;
179
+ private assertMutable;
180
+ }
181
+ export declare function orderPlugins(plugins: readonly Plugin[]): Plugin[];
182
+ export {};