@macss/modular-api 0.7.2 → 0.8.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.8.0](https://github.com/ccisnedev/modular_api/compare/modular_api-v0.7.3...modular_api-v0.8.0) (2026-11-27)
4
+
5
+
6
+ ### ⚠ BREAKING CHANGES
7
+
8
+ * **routing:** in the TypeScript SDK a client that sends a trailing slash, a double slash or a different case now receives 404. Call the exact path from the OpenAPI document. `strictRouting: false` restores the 0.7.x routing temporarily and logs a deprecation warning at startup.
9
+
10
+ ### Features
11
+
12
+ * expose the resolved use case to middlewares in the three SDKs ([#68](https://github.com/ccisnedev/modular_api/issues/68)) ([283c168](https://github.com/ccisnedev/modular_api/commit/283c16828fbddbe6e939cbfaababccba15448a1e)), closes [#47](https://github.com/ccisnedev/modular_api/issues/47)
13
+ * **routing:** route TypeScript use cases only through their canonical path ([#66](https://github.com/ccisnedev/modular_api/issues/66)) ([0b3f03b](https://github.com/ccisnedev/modular_api/commit/0b3f03b6cb587647c064315f3b54c23b31370dfc))
14
+
15
+
16
+ ### Bug Fixes
17
+
18
+ * **routing:** count non-canonical paths in metrics, as logging and tracing do ([#69](https://github.com/ccisnedev/modular_api/issues/69)) ([c5bd49b](https://github.com/ccisnedev/modular_api/commit/c5bd49b88a2ce8b7d060811ea343b6c424cf936d)), closes [#47](https://github.com/ccisnedev/modular_api/issues/47)
19
+
20
+ ## [0.7.3](https://github.com/ccisnedev/modular_api/compare/modular_api-v0.7.2...modular_api-v0.7.3) (2026-11-27)
21
+
22
+
23
+ ### Bug Fixes
24
+
25
+ * **handler:** answer 400, not 500, to a body that cannot become the input ([#64](https://github.com/ccisnedev/modular_api/issues/64)) ([fc4c1a9](https://github.com/ccisnedev/modular_api/commit/fc4c1a9e5c8f6b732617ffe67b0632b3a6bb5578)), closes [#44](https://github.com/ccisnedev/modular_api/issues/44)
26
+ * **metrics:** serialize the root value of an unlabeled counter ([#61](https://github.com/ccisnedev/modular_api/issues/61)) ([559a39e](https://github.com/ccisnedev/modular_api/commit/559a39e9c24e58a4a1d22b48180c357911f79b21)), closes [#46](https://github.com/ccisnedev/modular_api/issues/46)
27
+ * **openapi:** carry the ModularApi version into info.version in Dart ([#62](https://github.com/ccisnedev/modular_api/issues/62)) ([b73c8e8](https://github.com/ccisnedev/modular_api/commit/b73c8e871eaaf8de1f0cb65a1aae16271901b833)), closes [#38](https://github.com/ccisnedev/modular_api/issues/38)
28
+ * **schema:** fail at class definition when @Field is a legacy decorator ([#65](https://github.com/ccisnedev/modular_api/issues/65)) ([87015b8](https://github.com/ccisnedev/modular_api/commit/87015b851f28cf46607c75c14a64e2be9068c021)), closes [#19](https://github.com/ccisnedev/modular_api/issues/19)
29
+
3
30
  ## [0.7.2](https://github.com/ccisnedev/modular_api/compare/modular_api-v0.7.1...modular_api-v0.7.2) (2026-11-26)
4
31
 
5
32
 
package/README.md CHANGED
@@ -61,6 +61,26 @@ bytes). The limit measures UTF-8 body bytes, applies only to bodies handled by t
61
61
  JSON parser, and is independent for each `ModularApi` instance. Oversized bodies
62
62
  keep the existing error response.
63
63
 
64
+ ### Strict routing (since 0.8.0)
65
+
66
+ A use case is reachable only through its canonical path, as in the Dart and Python
67
+ SDKs:
68
+
69
+ - A different case (`/API/Payments/Execute`) does not resolve: 404.
70
+ - Repeated slashes (`/api/payments//execute`) and a trailing slash
71
+ (`/api/payments/execute/`, except `/`) are answered `404 {"error":"Not found"}`
72
+ right after the `preRouting` plugin slot, before any middleware registered with
73
+ `use()`, the `preHandler` slot and the routes. Like logging and tracing,
74
+ `preRouting` sees every request, so metrics count those 404s.
75
+
76
+ Before 0.8.0 Express resolved those variants to the use case, so a middleware that
77
+ compared `req.path` exactly (an auth check, for example) could be bypassed (issue #47).
78
+
79
+ **Migration:** clients must call the exact path shown in the OpenAPI document. If you
80
+ need time to fix them, `new ModularApi({ strictRouting: false })` restores the 0.7.x
81
+ behaviour and logs a deprecation warning at startup; the option will be removed in a
82
+ future minor.
83
+
64
84
  ---
65
85
 
66
86
  ## Features
@@ -0,0 +1,18 @@
1
+ import type { RequestHandler } from 'express';
2
+ /**
3
+ * Options for every router ModularApi creates when strict routing is on: a path that differs in
4
+ * case or by a trailing slash does not resolve to a route.
5
+ */
6
+ export declare const STRICT_ROUTER_OPTIONS: {
7
+ readonly caseSensitive: true;
8
+ readonly strict: true;
9
+ };
10
+ /**
11
+ * Answers 404 to a path with repeated slashes or a trailing slash (except `/`), the same way Dart
12
+ * does. Express would otherwise resolve some of those variants to a route while a middleware that
13
+ * compares `req.path` exactly does not recognize them.
14
+ */
15
+ export declare const canonicalPathMiddleware: RequestHandler;
16
+ /** True when the path has no empty segment: no `//` and no trailing slash, except the root. */
17
+ export declare function isCanonicalPath(path: string): boolean;
18
+ export declare const STRICT_ROUTING_DEPRECATION: string;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ // ============================================================
3
+ // core/canonical_path.ts
4
+ // Rejects non-canonical paths before the middlewares registered with use() run (issue #47).
5
+ // ============================================================
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.STRICT_ROUTING_DEPRECATION = exports.canonicalPathMiddleware = exports.STRICT_ROUTER_OPTIONS = void 0;
8
+ exports.isCanonicalPath = isCanonicalPath;
9
+ /**
10
+ * Options for every router ModularApi creates when strict routing is on: a path that differs in
11
+ * case or by a trailing slash does not resolve to a route.
12
+ */
13
+ exports.STRICT_ROUTER_OPTIONS = { caseSensitive: true, strict: true };
14
+ /**
15
+ * Answers 404 to a path with repeated slashes or a trailing slash (except `/`), the same way Dart
16
+ * does. Express would otherwise resolve some of those variants to a route while a middleware that
17
+ * compares `req.path` exactly does not recognize them.
18
+ */
19
+ const canonicalPathMiddleware = (req, res, next) => {
20
+ if (isCanonicalPath(req.path)) {
21
+ next();
22
+ return;
23
+ }
24
+ res.status(404).json({ error: 'Not found' });
25
+ };
26
+ exports.canonicalPathMiddleware = canonicalPathMiddleware;
27
+ /** True when the path has no empty segment: no `//` and no trailing slash, except the root. */
28
+ function isCanonicalPath(path) {
29
+ if (path === '/')
30
+ return true;
31
+ return !path.includes('//') && !path.endsWith('/');
32
+ }
33
+ exports.STRICT_ROUTING_DEPRECATION = '[modular_api] strictRouting: false is deprecated and will be removed in a future minor. ' +
34
+ 'It lets case, trailing-slash and double-slash variants of a path reach a use case, so a ' +
35
+ 'middleware that compares req.path exactly can be bypassed (issue #47).';
@@ -83,8 +83,12 @@ class MetricRegistry {
83
83
  }
84
84
  serializeCounter(lines, counter) {
85
85
  const samples = counter.collect();
86
- if (samples.length === 0)
86
+ if (samples.length === 0) {
87
+ // Root counter with no labeled children — emit the root value, like a gauge.
88
+ // Once a labeled child exists, the root value is not serialized.
89
+ lines.push(`${counter.name} ${formatValue(counter.value)}`);
87
90
  return;
91
+ }
88
92
  for (const s of samples) {
89
93
  lines.push(`${counter.name}${formatLabels(s.labels)} ${formatValue(s.value)}`);
90
94
  }
@@ -50,6 +50,17 @@ export interface ModularApiOptions {
50
50
  }>;
51
51
  /** GraphQL runtime integration. Disabled by default. */
52
52
  graphql?: GraphqlOptions;
53
+ /**
54
+ * Strict routing. Default: true.
55
+ *
56
+ * A use case is reachable only through its canonical path: a different case does not resolve,
57
+ * and repeated slashes or a trailing slash (except `/`) are answered 404 before any middleware
58
+ * registered with `use()` or a plugin runs.
59
+ *
60
+ * `false` restores the permissive routing of 0.7.x and logs a deprecation warning at startup.
61
+ * It lets path variants bypass a middleware that compares `req.path` exactly (issue #47).
62
+ */
63
+ strictRouting?: boolean;
53
64
  }
54
65
  /**
55
66
  * Main entry point for modular_api.
@@ -80,6 +91,7 @@ export declare class ModularApi {
80
91
  private readonly title;
81
92
  private readonly version;
82
93
  private readonly middlewares;
94
+ private readonly resolvedRoutes;
83
95
  private readonly healthService;
84
96
  private readonly plugins;
85
97
  private readonly metricsEnabled;
@@ -95,6 +107,7 @@ export declare class ModularApi {
95
107
  private readonly tracing?;
96
108
  private readonly servers?;
97
109
  private readonly graphql?;
110
+ private readonly strictRouting;
98
111
  /** Public accessor for custom-metric registration. Undefined when metrics are disabled. */
99
112
  get metrics(): MetricsRegistrar | undefined;
100
113
  constructor(options?: ModularApiOptions);
@@ -21,6 +21,8 @@ const logger_1 = require("./logger/logger");
21
21
  const body_parser_error_handler_1 = require("./body_parser_error_handler");
22
22
  const unhandled_request_error_handler_1 = require("./unhandled_request_error_handler");
23
23
  const official_plugins_1 = require("./official_plugins");
24
+ const resolved_route_1 = require("./resolved_route");
25
+ const canonical_path_1 = require("./canonical_path");
24
26
  const plugin_1 = require("./plugin");
25
27
  /**
26
28
  * Main entry point for modular_api.
@@ -51,6 +53,7 @@ class ModularApi {
51
53
  title;
52
54
  version;
53
55
  middlewares = [];
56
+ resolvedRoutes = [];
54
57
  healthService;
55
58
  plugins = [];
56
59
  // Metrics
@@ -69,6 +72,8 @@ class ModularApi {
69
72
  // OpenAPI
70
73
  servers;
71
74
  graphql;
75
+ // Routing
76
+ strictRouting;
72
77
  /** Public accessor for custom-metric registration. Undefined when metrics are disabled. */
73
78
  get metrics() {
74
79
  return this._metricsRegistrar;
@@ -92,6 +97,7 @@ class ModularApi {
92
97
  // OpenAPI servers
93
98
  this.servers = options.servers;
94
99
  this.graphql = options.graphql;
100
+ this.strictRouting = options.strictRouting ?? true;
95
101
  if (this.metricsEnabled) {
96
102
  this.metricRegistry = new metric_registry_1.MetricRegistry();
97
103
  this._metricsRegistrar = new metric_registry_1.MetricsRegistrar(this.metricRegistry);
@@ -111,7 +117,7 @@ class ModularApi {
111
117
  });
112
118
  }
113
119
  this.app = (0, express_1.default)();
114
- this.rootRouter = express_1.default.Router();
120
+ this.rootRouter = this.strictRouting ? express_1.default.Router(canonical_path_1.STRICT_ROUTER_OPTIONS) : express_1.default.Router();
115
121
  }
116
122
  /**
117
123
  * Register a {@link HealthCheck} to be evaluated on `GET /health`.
@@ -139,9 +145,10 @@ class ModularApi {
139
145
  * ```
140
146
  */
141
147
  module(name, build) {
142
- const builder = new module_builder_1.ModuleBuilder(this.basePath, name, this.rootRouter);
148
+ const builder = new module_builder_1.ModuleBuilder(this.basePath, name, this.rootRouter, this.strictRouting);
143
149
  build(builder);
144
150
  builder._mount();
151
+ this.resolvedRoutes.push(...builder._resolvedRoutes);
145
152
  return this;
146
153
  }
147
154
  /**
@@ -283,7 +290,19 @@ class ModularApi {
283
290
  // Body parsing AFTER loggingMiddleware — SyntaxErrors now have trace_id.
284
291
  this.app.use(express_1.default.json({ limit: this.jsonBodyLimit }));
285
292
  this.app.use(body_parser_error_handler_1.bodyParserErrorHandler);
293
+ // Route resolution: every plugin and user middleware can read the use case that will run,
294
+ // so access control does not have to compare the raw path (issue #47).
295
+ this.app.use((0, resolved_route_1.routeResolverMiddleware)(this.resolvedRoutes));
286
296
  pluginHost.applyMiddlewares('preRouting', this.app);
297
+ // Non-canonical paths end here (issue #47): after the preRouting slot, which sees every
298
+ // request like logging and tracing do, so metrics count them; before any middleware
299
+ // registered with use(), the preHandler slot and the routes.
300
+ if (this.strictRouting) {
301
+ this.app.use(canonical_path_1.canonicalPathMiddleware);
302
+ }
303
+ else {
304
+ console.warn(canonical_path_1.STRICT_ROUTING_DEPRECATION);
305
+ }
287
306
  // Register middlewares before routes
288
307
  for (const mw of this.middlewares) {
289
308
  this.app.use(mw);
@@ -1,5 +1,6 @@
1
1
  import { Router } from 'express';
2
2
  import type { Input, Output, UseCaseFactory } from './usecase';
3
+ import type { ResolvedRoute } from './resolved_route';
3
4
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
4
5
  export interface UseCaseOptions {
5
6
  /** HTTP method. Defaults to POST (same as Dart version). */
@@ -34,7 +35,9 @@ export declare class ModuleBuilder {
34
35
  private readonly moduleName;
35
36
  private readonly rootRouter;
36
37
  private readonly router;
37
- constructor(basePath: string, moduleName: string, rootRouter: Router);
38
+ /** @internal — the use cases registered here, read by ModularApi's route resolver. */
39
+ readonly _resolvedRoutes: ResolvedRoute[];
40
+ constructor(basePath: string, moduleName: string, rootRouter: Router, strictRouting?: boolean);
38
41
  /**
39
42
  * Registers a use case as an HTTP endpoint.
40
43
  *
@@ -10,6 +10,7 @@ const express_1 = require("express");
10
10
  const usecase_handler_1 = require("./usecase_handler");
11
11
  const registry_1 = require("./registry");
12
12
  const field_1 = require("./schema/field");
13
+ const canonical_path_1 = require("./canonical_path");
13
14
  /**
14
15
  * Fluent builder that registers use cases on a module-scoped Express Router.
15
16
  * Returned and used inside the callback of `ModularApi.module()`.
@@ -29,11 +30,13 @@ class ModuleBuilder {
29
30
  moduleName;
30
31
  rootRouter;
31
32
  router;
32
- constructor(basePath, moduleName, rootRouter) {
33
+ /** @internal — the use cases registered here, read by ModularApi's route resolver. */
34
+ _resolvedRoutes = [];
35
+ constructor(basePath, moduleName, rootRouter, strictRouting = true) {
33
36
  this.basePath = basePath;
34
37
  this.moduleName = moduleName;
35
38
  this.rootRouter = rootRouter;
36
- this.router = (0, express_1.Router)();
39
+ this.router = strictRouting ? (0, express_1.Router)(canonical_path_1.STRICT_ROUTER_OPTIONS) : (0, express_1.Router)();
37
40
  }
38
41
  /**
39
42
  * Registers a use case as an HTTP endpoint.
@@ -56,12 +59,14 @@ class ModuleBuilder {
56
59
  input: inputSchema ?? extracted.input,
57
60
  output: outputSchema ?? extracted.output,
58
61
  };
62
+ const path = `${this._normalizeBase(this.basePath)}/${this.moduleName}/${cleanCommand}`;
63
+ this._resolvedRoutes.push({ module: this.moduleName, useCase: cleanCommand, method, path });
59
64
  // Register in the global registry for OpenAPI generation
60
65
  registry_1.apiRegistry.routes.push({
61
66
  module: this.moduleName,
62
67
  command: cleanCommand,
63
68
  method: method,
64
- path: `${this._normalizeBase(this.basePath)}/${this.moduleName}/${cleanCommand}`,
69
+ path,
65
70
  factory: factory,
66
71
  schemas,
67
72
  doc: {
@@ -0,0 +1,24 @@
1
+ import type { RequestHandler, Response } from 'express';
2
+ /** `res.locals` key under which the resolved use case is stored. */
3
+ export declare const RESOLVED_ROUTE_LOCALS_KEY = "modularRoute";
4
+ /** A registered use case: its module, command, HTTP method and canonical path. */
5
+ export interface ResolvedRoute {
6
+ readonly module: string;
7
+ readonly useCase: string;
8
+ readonly method: string;
9
+ readonly path: string;
10
+ }
11
+ /**
12
+ * The use case this request will run, or `undefined`.
13
+ *
14
+ * `undefined` means no use case matches the method and path: a 404, a 405, or an operational
15
+ * endpoint such as `/health`. Deny by default: treat `undefined` as "not a public use case".
16
+ */
17
+ export declare function resolvedRoute(res: Response): ResolvedRoute | undefined;
18
+ /**
19
+ * Stores the resolved use case under {@link RESOLVED_ROUTE_LOCALS_KEY}.
20
+ *
21
+ * Matching is exact on method and path, whatever `strictRouting` says, so a path variant never
22
+ * resolves. HEAD resolves to the GET use case, because Express runs the GET handler for it.
23
+ */
24
+ export declare function routeResolverMiddleware(routes: readonly ResolvedRoute[]): RequestHandler;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ // ============================================================
3
+ // core/resolved_route.ts
4
+ // The use case a request resolves to, readable by every middleware (issue #47).
5
+ //
6
+ // A middleware that protects use cases should decide by what will run, not by
7
+ // comparing the raw path. The framework resolves the request against its own
8
+ // route table before any plugin or custom middleware runs and stores the result
9
+ // in res.locals.
10
+ //
11
+ // Mirrors `resolved_route` in Python and `resolvedRoute` in Dart.
12
+ // ============================================================
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.RESOLVED_ROUTE_LOCALS_KEY = void 0;
15
+ exports.resolvedRoute = resolvedRoute;
16
+ exports.routeResolverMiddleware = routeResolverMiddleware;
17
+ /** `res.locals` key under which the resolved use case is stored. */
18
+ exports.RESOLVED_ROUTE_LOCALS_KEY = 'modularRoute';
19
+ /**
20
+ * The use case this request will run, or `undefined`.
21
+ *
22
+ * `undefined` means no use case matches the method and path: a 404, a 405, or an operational
23
+ * endpoint such as `/health`. Deny by default: treat `undefined` as "not a public use case".
24
+ */
25
+ function resolvedRoute(res) {
26
+ return res.locals[exports.RESOLVED_ROUTE_LOCALS_KEY];
27
+ }
28
+ /**
29
+ * Stores the resolved use case under {@link RESOLVED_ROUTE_LOCALS_KEY}.
30
+ *
31
+ * Matching is exact on method and path, whatever `strictRouting` says, so a path variant never
32
+ * resolves. HEAD resolves to the GET use case, because Express runs the GET handler for it.
33
+ */
34
+ function routeResolverMiddleware(routes) {
35
+ const table = new Map();
36
+ for (const route of routes)
37
+ table.set(`${route.method} ${route.path}`, route);
38
+ return (req, res, next) => {
39
+ const method = req.method.toUpperCase();
40
+ const route = table.get(`${method} ${req.path}`) ??
41
+ (method === 'HEAD' ? table.get(`GET ${req.path}`) : undefined);
42
+ if (route !== undefined) {
43
+ res.locals[exports.RESOLVED_ROUTE_LOCALS_KEY] = route;
44
+ }
45
+ next();
46
+ };
47
+ }
@@ -24,6 +24,7 @@ Symbol.metadata ??= Symbol('Symbol.metadata');
24
24
  const FIELD_KEY = Symbol('FieldMeta');
25
25
  function makeFieldDecorator(type, options = {}, extra = {}) {
26
26
  return function (_value, context) {
27
+ assertStage3Context(context);
27
28
  const meta = {
28
29
  name: String(context.name),
29
30
  type,
@@ -42,6 +43,26 @@ function makeFieldDecorator(type, options = {}, extra = {}) {
42
43
  metadata[FIELD_KEY].push(meta);
43
44
  };
44
45
  }
46
+ /**
47
+ * Fails at class definition when `@Field` is not called as a Stage 3 decorator.
48
+ *
49
+ * With `experimentalDecorators: true` the compiler calls `decorator(prototype, propertyKey)`, so
50
+ * `context` is the property name, and a transformer without Stage 3 metadata passes a context
51
+ * without `metadata`. Either way the field would never be registered and the DTO would break
52
+ * later, far from the cause (`toJson() not implemented`).
53
+ */
54
+ function assertStage3Context(context) {
55
+ const ctx = context;
56
+ if (typeof ctx === 'object' && ctx !== null && typeof ctx.metadata === 'object' && ctx.metadata) {
57
+ return;
58
+ }
59
+ const property = typeof context === 'string' || typeof context === 'symbol' ? String(context) : ctx?.name;
60
+ throw new TypeError(`@Field${property !== undefined ? ` on '${String(property)}'` : ''} was not called as a ` +
61
+ 'TC39 Stage 3 decorator, so its metadata cannot be registered. Remove ' +
62
+ '`experimentalDecorators` from every tsconfig of the project (including the ones it ' +
63
+ 'extends) and use a transformer with Stage 3 decorator support (tsc 5, esbuild). ' +
64
+ 'See docs/pitfalls.md.');
65
+ }
45
66
  // ── Public API ───────────────────────────────────────────────
46
67
  exports.Field = {
47
68
  string(options = {}) {
@@ -18,6 +18,8 @@ export interface UseCaseHandlerOptions {
18
18
  * 7. Return output.toJson() with output.statusCode
19
19
  *
20
20
  * Errors:
21
+ * - Body that is not a JSON object, or a TypeError/SyntaxError/RangeError thrown by fromJson
22
+ * → 400 (the cause is logged at warning level, not returned)
21
23
  * - InputValidationError → 400 with structured error message
22
24
  * - UseCaseException → statusCode from exception, structured JSON body
23
25
  * - Any other Error → 500 Internal Server Error
@@ -24,6 +24,8 @@ const JSON_HEADERS = { 'Content-Type': 'application/json; charset=utf-8' };
24
24
  * 7. Return output.toJson() with output.statusCode
25
25
  *
26
26
  * Errors:
27
+ * - Body that is not a JSON object, or a TypeError/SyntaxError/RangeError thrown by fromJson
28
+ * → 400 (the cause is logged at warning level, not returned)
27
29
  * - InputValidationError → 400 with structured error message
28
30
  * - UseCaseException → statusCode from exception, structured JSON body
29
31
  * - Any other Error → 500 Internal Server Error
@@ -37,15 +39,34 @@ function useCaseHandler(factory, options = {}) {
37
39
  return async (req, res) => {
38
40
  try {
39
41
  // 1. Extract payload
40
- const data = req.method.toUpperCase() === 'GET' || req.method.toUpperCase() === 'DELETE'
42
+ const isQuery = req.method.toUpperCase() === 'GET' || req.method.toUpperCase() === 'DELETE';
43
+ const body = isQuery ? undefined : req.body;
44
+ // express.json() accepts objects and arrays; only an object can be the use case input.
45
+ if (!isQuery && (Array.isArray(body) || (body !== undefined && typeof body !== 'object'))) {
46
+ badRequest(res, 'Request body must be a JSON object');
47
+ return;
48
+ }
49
+ const data = isQuery
41
50
  ? { ...req.query, ...req.params }
42
- : (req.body ?? {});
51
+ : (body ?? {});
43
52
  // 2. Pre-validate BEFORE fromJson (when inputClass provided)
44
53
  if (options.inputClass) {
45
54
  usecase_1.Input.validateJson(data, options.inputClass);
46
55
  }
47
- // 3. Build use case
48
- const useCase = factory(data);
56
+ // 3. Build use case. fromJson only maps untrusted input into the use case input, so a
57
+ // TypeError, SyntaxError or RangeError thrown there means the body has the wrong shape:
58
+ // a client error. UseCaseException and InputValidationError keep their own handling.
59
+ let useCase;
60
+ try {
61
+ useCase = factory(data);
62
+ }
63
+ catch (err) {
64
+ if (err instanceof TypeError || err instanceof SyntaxError || err instanceof RangeError) {
65
+ badRequest(res, 'Invalid request body', err);
66
+ return;
67
+ }
68
+ throw err;
69
+ }
49
70
  // 3a. Post-validate for legacy path (no inputClass)
50
71
  if (!options.inputClass) {
51
72
  usecase_1.Input.validateJson(data, useCase.input.constructor);
@@ -82,3 +103,12 @@ function useCaseHandler(factory, options = {}) {
82
103
  }
83
104
  };
84
105
  }
106
+ /** A 400 for a body that cannot become the use case input; the cause is logged, never returned. */
107
+ function badRequest(res, message, cause) {
108
+ const logger = res.locals[logging_middleware_1.LOGGER_LOCALS_KEY];
109
+ logger?.warning(message, {
110
+ status: 400,
111
+ ...(cause ? { error: `${cause.name}: ${cause.message}` } : {}),
112
+ });
113
+ res.status(400).set(JSON_HEADERS).json({ error: message });
114
+ }
package/dist/index.d.ts CHANGED
@@ -6,6 +6,8 @@ export { UseCaseException } from './core/use_case_exception';
6
6
  export { InputValidationError } from './core/input_validation_error';
7
7
  export { ModularApi } from './core/modular_api';
8
8
  export type { ModularApiOptions } from './core/modular_api';
9
+ export { resolvedRoute, RESOLVED_ROUTE_LOCALS_KEY } from './core/resolved_route';
10
+ export type { ResolvedRoute } from './core/resolved_route';
9
11
  export { HOST_API_VERSION, PluginHostError } from './core/plugin';
10
12
  export type { Capability, CapabilityHandle, HostMetadata, HttpMethod, MiddlewareSlot, ModuleExtensionContribution, ModuleExtensionPoint, Plugin, PluginHost, PluginManifest, PluginMiddleware, PluginRequestContext, PluginRequirement, PluginResponse, PluginRoute, PluginRouteVisibility, PluginValidationResult, RegisteredModuleView, RegisteredPluginRouteView, RegisteredUseCaseView, } from './core/plugin';
11
13
  export { ModuleBuilder } from './core/module_builder';
package/dist/index.js CHANGED
@@ -5,8 +5,8 @@
5
5
  // import { ModularApi, UseCase, Input, Output } from 'modular_api'
6
6
  // ============================================================
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.GraphqlCatalogBuildMode = exports.GraphqlMetadataSeverity = exports.GraphqlMetadataParser = exports.SqlServerMetadataReader = exports.SqlServerConnectionSettings = exports.PhysicalObjectKind = exports.swaggerDocsHandler = exports.openApiYamlHandler = exports.openApiJsonHandler = exports.jsonToYaml = exports.buildOpenApiSpec = exports.completeServerSpan = exports.startServerSpan = exports.PROPAGATION_RESULT_LOCAL = exports.TRACING_SPAN_LOCAL = exports.TRACESTATE_HEADER = exports.TRACEPARENT_HEADER = exports.W3CTraceContextPropagator = exports.REQUEST_ID_HEADER = exports.PropagationPolicy = exports.TracingOptions = exports.LOGGER_LOCALS_KEY = exports.loggingMiddleware = exports.RequestScopedLogger = exports.LogLevel = exports.metricsHandler = exports.metricsMiddleware = exports.MetricsRegistrar = exports.MetricRegistry = exports.DEFAULT_BUCKETS = exports.Histogram = exports.Gauge = exports.Counter = exports.healthHandler = exports.HealthResponse = exports.HealthService = exports.HealthCheckResult = exports.HealthCheck = exports.cors = exports.ModuleBuilder = exports.PluginHostError = exports.HOST_API_VERSION = exports.ModularApi = exports.InputValidationError = exports.UseCaseException = exports.getFieldMetadata = exports.Field = exports.UseCase = exports.Output = exports.Input = void 0;
9
- exports.SqlServerReadCompiler = exports.SqlCatalogReadDispatcher = exports.SqlSortDirection = exports.SqlRelationBatchSelection = exports.SqlReadCommandPurpose = exports.SqlReadCommand = exports.SqlParameter = exports.SqlPage = exports.SqlOrderByClause = exports.SqlItemSelection = exports.SqlFilterOperator = exports.SqlFilterGroupKind = exports.SqlFilterGroup = exports.SqlFilterCondition = exports.SqlCountSelection = exports.SqlCollectionSelection = exports.RowSet = exports.ReadExecutionContext = exports.tryLoadGraphqlCatalogArtifacts = exports.GraphqlArtifactLoadError = exports.GraphqlArtifactCompiler = exports.GraphqlArtifactCompileError = exports.GraphqlArtifactBundle = exports.graphqlDefaultReadExecutorCapabilityId = exports.GraphqlRequestPhase = exports.GraphqlRequestEvent = exports.GraphqlOptions = exports.GraphqlSchemaSdlGenerator = exports.GraphqlCatalogRelationCardinality = exports.GraphqlCatalogPaginationMode = exports.GraphqlCatalogOrigin = exports.GraphqlCatalogNaming = exports.GraphqlCatalogIdentityMode = exports.GraphqlCatalogFieldVisibility = exports.GraphqlCatalogDiagnosticSeverity = exports.GraphqlCatalogBuilder = void 0;
8
+ exports.GraphqlMetadataParser = exports.SqlServerMetadataReader = exports.SqlServerConnectionSettings = exports.PhysicalObjectKind = exports.swaggerDocsHandler = exports.openApiYamlHandler = exports.openApiJsonHandler = exports.jsonToYaml = exports.buildOpenApiSpec = exports.completeServerSpan = exports.startServerSpan = exports.PROPAGATION_RESULT_LOCAL = exports.TRACING_SPAN_LOCAL = exports.TRACESTATE_HEADER = exports.TRACEPARENT_HEADER = exports.W3CTraceContextPropagator = exports.REQUEST_ID_HEADER = exports.PropagationPolicy = exports.TracingOptions = exports.LOGGER_LOCALS_KEY = exports.loggingMiddleware = exports.RequestScopedLogger = exports.LogLevel = exports.metricsHandler = exports.metricsMiddleware = exports.MetricsRegistrar = exports.MetricRegistry = exports.DEFAULT_BUCKETS = exports.Histogram = exports.Gauge = exports.Counter = exports.healthHandler = exports.HealthResponse = exports.HealthService = exports.HealthCheckResult = exports.HealthCheck = exports.cors = exports.ModuleBuilder = exports.PluginHostError = exports.HOST_API_VERSION = exports.RESOLVED_ROUTE_LOCALS_KEY = exports.resolvedRoute = exports.ModularApi = exports.InputValidationError = exports.UseCaseException = exports.getFieldMetadata = exports.Field = exports.UseCase = exports.Output = exports.Input = void 0;
9
+ exports.SqlServerReadCompiler = exports.SqlCatalogReadDispatcher = exports.SqlSortDirection = exports.SqlRelationBatchSelection = exports.SqlReadCommandPurpose = exports.SqlReadCommand = exports.SqlParameter = exports.SqlPage = exports.SqlOrderByClause = exports.SqlItemSelection = exports.SqlFilterOperator = exports.SqlFilterGroupKind = exports.SqlFilterGroup = exports.SqlFilterCondition = exports.SqlCountSelection = exports.SqlCollectionSelection = exports.RowSet = exports.ReadExecutionContext = exports.tryLoadGraphqlCatalogArtifacts = exports.GraphqlArtifactLoadError = exports.GraphqlArtifactCompiler = exports.GraphqlArtifactCompileError = exports.GraphqlArtifactBundle = exports.graphqlDefaultReadExecutorCapabilityId = exports.GraphqlRequestPhase = exports.GraphqlRequestEvent = exports.GraphqlOptions = exports.GraphqlSchemaSdlGenerator = exports.GraphqlCatalogRelationCardinality = exports.GraphqlCatalogPaginationMode = exports.GraphqlCatalogOrigin = exports.GraphqlCatalogNaming = exports.GraphqlCatalogIdentityMode = exports.GraphqlCatalogFieldVisibility = exports.GraphqlCatalogDiagnosticSeverity = exports.GraphqlCatalogBuilder = exports.GraphqlCatalogBuildMode = exports.GraphqlMetadataSeverity = void 0;
10
10
  // Core abstractions
11
11
  var usecase_1 = require("./core/usecase");
12
12
  Object.defineProperty(exports, "Input", { enumerable: true, get: function () { return usecase_1.Input; } });
@@ -24,6 +24,9 @@ Object.defineProperty(exports, "InputValidationError", { enumerable: true, get:
24
24
  // Main orchestrator
25
25
  var modular_api_1 = require("./core/modular_api");
26
26
  Object.defineProperty(exports, "ModularApi", { enumerable: true, get: function () { return modular_api_1.ModularApi; } });
27
+ var resolved_route_1 = require("./core/resolved_route");
28
+ Object.defineProperty(exports, "resolvedRoute", { enumerable: true, get: function () { return resolved_route_1.resolvedRoute; } });
29
+ Object.defineProperty(exports, "RESOLVED_ROUTE_LOCALS_KEY", { enumerable: true, get: function () { return resolved_route_1.RESOLVED_ROUTE_LOCALS_KEY; } });
27
30
  var plugin_1 = require("./core/plugin");
28
31
  Object.defineProperty(exports, "HOST_API_VERSION", { enumerable: true, get: function () { return plugin_1.HOST_API_VERSION; } });
29
32
  Object.defineProperty(exports, "PluginHostError", { enumerable: true, get: function () { return plugin_1.PluginHostError; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@macss/modular-api",
3
- "version": "0.7.2",
3
+ "version": "0.8.0",
4
4
  "description": "Use-case-centric toolkit for building modular APIs with Express. Define UseCase classes (input → validate → execute → output), connect them to HTTP routes, and expose Swagger/OpenAPI documentation automatically.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",