@heliosjs/middlewares 10.0.5 → 10.0.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/dist/catch.d.ts CHANGED
@@ -1,29 +1,30 @@
1
1
  import type { ErrorHandler } from '@heliosjs/core/types';
2
2
  /**
3
- * Decorator to register a global or controller-level error handler.
3
+ * Registers an error handler on a controller class or a single route method. It
4
+ * fires when a guard, pipe, middleware, handler, or interceptor throws.
4
5
  *
5
- * This decorator accepts an error handling callback function which will be invoked
6
- * whenever an error occurs within the decorated target's scope (e.g., controller or service).
7
- * It attaches the handler as metadata on the target class, allowing the framework to
8
- * retrieve and execute the error handler appropriately during runtime.
6
+ * Handlers run newest-first (method-level before controller-level). The first one
7
+ * that **returns a non-Error value** stops the chain and that value becomes the
8
+ * response body; a handler that returns an `Error` or re-throws passes control to
9
+ * the next handler, and if none resolves the error it propagates to the adapter's
10
+ * default error response.
9
11
  *
10
- * @param {ErrorHandler} handler - The error callback function to handle errors.
12
+ * Declaring `@Catch` also opts the route into handling the "self-resolving" error
13
+ * codes (`FORBIDDEN`, `NOT_FOUND`, `RATE_LIMIT_EXCEEDED`, `UNAUTHORIZED`) that
14
+ * otherwise bypass error handlers.
11
15
  *
12
- * @returns {Function} A class decorator function that defines the error handler metadata.
16
+ * @param handler - `(error, req, res) => unknown`. `error` is the thrown value
17
+ * (often a `HeliosError` subclass with `.code` / `.status`). Return a value to
18
+ * answer the request, or return/throw an `Error` to defer. May be async. Why:
19
+ * map domain errors to response shapes in one place.
20
+ *
21
+ * @returns A class or method decorator.
13
22
  *
14
23
  * @example
15
- * // Register a global error handler for a controller
16
- * @Catch(async (error, context) => {
17
- * console.error('Error caught:', error);
18
- * // Custom error handling logic
24
+ * @Catch((err, req, res) => {
25
+ * if (err instanceof NotFoundError) return { error: 'not found', path: req.path };
26
+ * throw err; // let the framework handle everything else
19
27
  * })
20
- * class MyController {
21
- * // ...
22
- * }
23
- *
24
- * @remarks
25
- * The metadata key used for storing the error handler is defined by `CATCH`.
26
- * This metadata is accessible via Reflect API and used internally by the framework
27
- * to invoke the registered error handler when errors occur.
28
+ * class MyController {}
28
29
  */
29
- export declare function Catch(handler: ErrorHandler): (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => void;
30
+ export declare function Catch(handler: ErrorHandler): (target: any, propertyKey?: string, _descriptor?: PropertyDescriptor) => void;
package/dist/catch.js CHANGED
@@ -3,36 +3,37 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Catch = Catch;
4
4
  const utils_1 = require("@heliosjs/core/utils");
5
5
  /**
6
- * Decorator to register a global or controller-level error handler.
6
+ * Registers an error handler on a controller class or a single route method. It
7
+ * fires when a guard, pipe, middleware, handler, or interceptor throws.
7
8
  *
8
- * This decorator accepts an error handling callback function which will be invoked
9
- * whenever an error occurs within the decorated target's scope (e.g., controller or service).
10
- * It attaches the handler as metadata on the target class, allowing the framework to
11
- * retrieve and execute the error handler appropriately during runtime.
9
+ * Handlers run newest-first (method-level before controller-level). The first one
10
+ * that **returns a non-Error value** stops the chain and that value becomes the
11
+ * response body; a handler that returns an `Error` or re-throws passes control to
12
+ * the next handler, and if none resolves the error it propagates to the adapter's
13
+ * default error response.
12
14
  *
13
- * @param {ErrorHandler} handler - The error callback function to handle errors.
15
+ * Declaring `@Catch` also opts the route into handling the "self-resolving" error
16
+ * codes (`FORBIDDEN`, `NOT_FOUND`, `RATE_LIMIT_EXCEEDED`, `UNAUTHORIZED`) that
17
+ * otherwise bypass error handlers.
14
18
  *
15
- * @returns {Function} A class decorator function that defines the error handler metadata.
19
+ * @param handler - `(error, req, res) => unknown`. `error` is the thrown value
20
+ * (often a `HeliosError` subclass with `.code` / `.status`). Return a value to
21
+ * answer the request, or return/throw an `Error` to defer. May be async. Why:
22
+ * map domain errors to response shapes in one place.
23
+ *
24
+ * @returns A class or method decorator.
16
25
  *
17
26
  * @example
18
- * // Register a global error handler for a controller
19
- * @Catch(async (error, context) => {
20
- * console.error('Error caught:', error);
21
- * // Custom error handling logic
27
+ * @Catch((err, req, res) => {
28
+ * if (err instanceof NotFoundError) return { error: 'not found', path: req.path };
29
+ * throw err; // let the framework handle everything else
22
30
  * })
23
- * class MyController {
24
- * // ...
25
- * }
26
- *
27
- * @remarks
28
- * The metadata key used for storing the error handler is defined by `CATCH`.
29
- * This metadata is accessible via Reflect API and used internally by the framework
30
- * to invoke the registered error handler when errors occur.
31
+ * class MyController {}
31
32
  */
32
33
  function Catch(handler) {
33
- return function (target, propertyKey, descriptor) {
34
+ return function (target, propertyKey, _descriptor) {
34
35
  const data = [{ errorHandler: handler }];
35
- if (descriptor) {
36
+ if (propertyKey) {
36
37
  (0, utils_1.defineMiddlewaresMeta)(data, target, propertyKey);
37
38
  }
38
39
  else {
package/dist/catch.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"catch.js","sourceRoot":"","sources":["../src/catch.ts"],"names":[],"mappings":";;AA6BA,sBAUC;AAtCD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,SAAgB,KAAK,CAAC,OAAqB;IACzC,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,UAA+B;QACjF,MAAM,IAAI,GAAG,CAAC,EAAE,YAAY,EAAE,OAAO,EAAE,CAAC,CAAC;QAEzC,IAAI,UAAU,EAAE,CAAC;YACf,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"catch.js","sourceRoot":"","sources":["../src/catch.ts"],"names":[],"mappings":";;AA8BA,sBAUC;AAvCD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,SAAgB,KAAK,CAAC,OAAqB;IACzC,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,WAAgC;QAClF,MAAM,IAAI,GAAG,CAAC,EAAE,YAAY,EAAE,OAAO,EAAE,CAAC,CAAC;QAEzC,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
package/dist/cors.d.ts CHANGED
@@ -1,37 +1,40 @@
1
1
  import type { CORSConfig } from '@heliosjs/core/types';
2
2
  /**
3
- * Decorator to configure Cross-Origin Resource Sharing (CORS) settings for HTTP controllers or methods.
3
+ * Configures Cross-Origin Resource Sharing for a controller class or a single
4
+ * route method. On a preflight (`OPTIONS`) request the response is answered
5
+ * directly with the negotiated CORS headers and `optionsSuccessStatus`; on a
6
+ * real request a disallowed origin is rejected with HTTP 403.
4
7
  *
5
- * This decorator allows you to specify CORS policies such as allowed origins, HTTP methods, and
6
- * the status code to return for successful OPTIONS requests. It can be applied at the class level
7
- * to affect all endpoints within a controller or at the method level to customize CORS for specific endpoints.
8
+ * Unspecified keys fall back to: `origin: '*'`, `optionsSuccessStatus: 204`,
9
+ * `methods:` every HTTP method Helios knows.
8
10
  *
9
- * When applied, the decorator defines metadata on the target (class prototype or method) which can be
10
- * later retrieved by the framework to enforce CORS policies during request handling.
11
+ * @param config - CORS options (all optional):
12
+ * - `origin` `string`, `string[]`, or `(origin) => boolean`. `'*'` allows
13
+ * any origin; a list allows exact matches; a function decides per request.
14
+ * Why: the allow-list is the core of the policy.
15
+ * - `methods` — allowed methods for `Access-Control-Allow-Methods`, e.g.
16
+ * `['GET', 'POST']`. Why: advertise only what the route group supports.
17
+ * - `allowedHeaders` — value for `Access-Control-Allow-Headers` (request
18
+ * headers the browser may send). Why: without this, custom headers like
19
+ * `Authorization` are blocked on cross-origin calls.
20
+ * - `exposedHeaders` — response headers JS may read
21
+ * (`Access-Control-Expose-Headers`). Why: e.g. expose `X-Total-Count`.
22
+ * - `credentials` — when `true`, sets `Access-Control-Allow-Credentials: true`
23
+ * so cookies / `Authorization` are sent. Why: required for cookie auth;
24
+ * cannot be combined with `origin: '*'` per the spec.
25
+ * - `maxAge` — seconds a browser may cache the preflight result. Why: fewer
26
+ * `OPTIONS` round-trips.
27
+ * - `optionsSuccessStatus` — status for a successful preflight (default `204`;
28
+ * use `200` for legacy browsers that choke on 204).
11
29
  *
12
- * @param {CORSConfig} [config={}] - Configuration object for CORS settings.
13
- * @param {string|string[]} [config.origin='*'] - Specifies the allowed origin(s) for CORS requests. Defaults to '*'.
14
- * @param {number} [config.optionsSuccessStatus=204] - HTTP status code to return for successful OPTIONS requests.
15
- * @param {string[]} [config.methods=Object.keys(HTTP_METHODS)] - Array of allowed HTTP methods for CORS.
16
- *
17
- * @returns {Function} A decorator function that applies the CORS configuration metadata.
18
- *
19
- * @example
20
- * // Apply CORS with default settings to all endpoints in a controller
21
- * @Cors()
22
- * class MyController {
23
- * // ...
24
- * }
30
+ * @returns A class or method decorator.
25
31
  *
26
32
  * @example
27
- * // Apply CORS with custom settings to a specific method
28
- * @Cors({ origin: 'https://example.com', methods: ['GET', 'POST'] })
29
- * async myMethod() {
30
- * // ...
31
- * }
32
- *
33
- * @remarks
34
- * The metadata key used for storing the CORS configuration is defined by `CORS_METADATA`.
35
- * This metadata is accessible via Reflect API and used internally by the framework to enforce CORS.
33
+ * @Cors({
34
+ * origin: ['https://app.example.com'],
35
+ * methods: ['GET', 'POST'],
36
+ * credentials: true,
37
+ * })
38
+ * class ApiController {}
36
39
  */
37
- export declare function Cors(config?: CORSConfig): (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => void;
40
+ export declare function Cors(config?: CORSConfig): (target: any, propertyKey?: string, _descriptor?: PropertyDescriptor) => void;
package/dist/cors.js CHANGED
@@ -4,42 +4,45 @@ exports.Cors = Cors;
4
4
  const types_1 = require("@heliosjs/core/types");
5
5
  const utils_1 = require("@heliosjs/core/utils");
6
6
  /**
7
- * Decorator to configure Cross-Origin Resource Sharing (CORS) settings for HTTP controllers or methods.
7
+ * Configures Cross-Origin Resource Sharing for a controller class or a single
8
+ * route method. On a preflight (`OPTIONS`) request the response is answered
9
+ * directly with the negotiated CORS headers and `optionsSuccessStatus`; on a
10
+ * real request a disallowed origin is rejected with HTTP 403.
8
11
  *
9
- * This decorator allows you to specify CORS policies such as allowed origins, HTTP methods, and
10
- * the status code to return for successful OPTIONS requests. It can be applied at the class level
11
- * to affect all endpoints within a controller or at the method level to customize CORS for specific endpoints.
12
+ * Unspecified keys fall back to: `origin: '*'`, `optionsSuccessStatus: 204`,
13
+ * `methods:` every HTTP method Helios knows.
12
14
  *
13
- * When applied, the decorator defines metadata on the target (class prototype or method) which can be
14
- * later retrieved by the framework to enforce CORS policies during request handling.
15
+ * @param config - CORS options (all optional):
16
+ * - `origin` `string`, `string[]`, or `(origin) => boolean`. `'*'` allows
17
+ * any origin; a list allows exact matches; a function decides per request.
18
+ * Why: the allow-list is the core of the policy.
19
+ * - `methods` — allowed methods for `Access-Control-Allow-Methods`, e.g.
20
+ * `['GET', 'POST']`. Why: advertise only what the route group supports.
21
+ * - `allowedHeaders` — value for `Access-Control-Allow-Headers` (request
22
+ * headers the browser may send). Why: without this, custom headers like
23
+ * `Authorization` are blocked on cross-origin calls.
24
+ * - `exposedHeaders` — response headers JS may read
25
+ * (`Access-Control-Expose-Headers`). Why: e.g. expose `X-Total-Count`.
26
+ * - `credentials` — when `true`, sets `Access-Control-Allow-Credentials: true`
27
+ * so cookies / `Authorization` are sent. Why: required for cookie auth;
28
+ * cannot be combined with `origin: '*'` per the spec.
29
+ * - `maxAge` — seconds a browser may cache the preflight result. Why: fewer
30
+ * `OPTIONS` round-trips.
31
+ * - `optionsSuccessStatus` — status for a successful preflight (default `204`;
32
+ * use `200` for legacy browsers that choke on 204).
15
33
  *
16
- * @param {CORSConfig} [config={}] - Configuration object for CORS settings.
17
- * @param {string|string[]} [config.origin='*'] - Specifies the allowed origin(s) for CORS requests. Defaults to '*'.
18
- * @param {number} [config.optionsSuccessStatus=204] - HTTP status code to return for successful OPTIONS requests.
19
- * @param {string[]} [config.methods=Object.keys(HTTP_METHODS)] - Array of allowed HTTP methods for CORS.
20
- *
21
- * @returns {Function} A decorator function that applies the CORS configuration metadata.
22
- *
23
- * @example
24
- * // Apply CORS with default settings to all endpoints in a controller
25
- * @Cors()
26
- * class MyController {
27
- * // ...
28
- * }
34
+ * @returns A class or method decorator.
29
35
  *
30
36
  * @example
31
- * // Apply CORS with custom settings to a specific method
32
- * @Cors({ origin: 'https://example.com', methods: ['GET', 'POST'] })
33
- * async myMethod() {
34
- * // ...
35
- * }
36
- *
37
- * @remarks
38
- * The metadata key used for storing the CORS configuration is defined by `CORS_METADATA`.
39
- * This metadata is accessible via Reflect API and used internally by the framework to enforce CORS.
37
+ * @Cors({
38
+ * origin: ['https://app.example.com'],
39
+ * methods: ['GET', 'POST'],
40
+ * credentials: true,
41
+ * })
42
+ * class ApiController {}
40
43
  */
41
44
  function Cors(config = {}) {
42
- return function (target, propertyKey, descriptor) {
45
+ return function (target, propertyKey, _descriptor) {
43
46
  const defaultConfig = {
44
47
  origin: '*',
45
48
  optionsSuccessStatus: 204,
@@ -47,7 +50,7 @@ function Cors(config = {}) {
47
50
  };
48
51
  const finalConfig = { ...defaultConfig, ...config };
49
52
  const data = [{ cors: finalConfig }];
50
- if (descriptor) {
53
+ if (propertyKey) {
51
54
  (0, utils_1.defineMiddlewaresMeta)(data, target, propertyKey);
52
55
  }
53
56
  else {
package/dist/cors.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cors.js","sourceRoot":"","sources":["../src/cors.ts"],"names":[],"mappings":";;AAsCA,oBAkBC;AAvDD,gDAAoD;AACpD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,SAAgB,IAAI,CAAC,SAAqB,EAAE;IAC1C,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,UAA+B;QACjF,MAAM,aAAa,GAAe;YAChC,MAAM,EAAE,GAAG;YACX,oBAAoB,EAAE,GAAG;YACzB,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,oBAAY,CAAC;SACnC,CAAC;QAEF,MAAM,WAAW,GAAG,EAAE,GAAG,aAAa,EAAE,GAAG,MAAM,EAAE,CAAC;QAEpD,MAAM,IAAI,GAAG,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC;QAErC,IAAI,UAAU,EAAE,CAAC;YACf,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"cors.js","sourceRoot":"","sources":["../src/cors.ts"],"names":[],"mappings":";;AAyCA,oBAkBC;AA1DD,gDAAoD;AACpD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,SAAgB,IAAI,CAAC,SAAqB,EAAE;IAC1C,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,WAAgC;QAClF,MAAM,aAAa,GAAe;YAChC,MAAM,EAAE,GAAG;YACX,oBAAoB,EAAE,GAAG;YACzB,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,oBAAY,CAAC;SACnC,CAAC;QAEF,MAAM,WAAW,GAAG,EAAE,GAAG,aAAa,EAAE,GAAG,MAAM,EAAE,CAAC;QAEpD,MAAM,IAAI,GAAG,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC;QAErC,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
@@ -1,5 +1,7 @@
1
1
  import type { FingerprintComponent } from '@heliosjs/core/types';
2
+ /** Options for `@UseFingerprint`. */
2
3
  export interface UseFingerprintOptions {
4
+ /** Component set to hash for this scope, overriding the configured/default set. See {@link FingerprintComponent}. */
3
5
  components?: FingerprintComponent[];
4
6
  }
5
7
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"fingerprint.js","sourceRoot":"","sources":["../src/fingerprint.ts"],"names":[],"mappings":";;AAoBA,wCAeC;AA/BD,gDAAsF;AAMtF;;;;;;;;;GASG;AACH,SAAgB,cAAc,CAAC,UAAiC,EAAE;IAChE,MAAM,UAAU,GAAiB,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;QACnD,IAAA,+BAAuB,EAAC,GAAG,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;QACjD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC;IAEF,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,WAAgC;QAClF,MAAM,IAAI,GAAG,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC;QAC9B,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"fingerprint.js","sourceRoot":"","sources":["../src/fingerprint.ts"],"names":[],"mappings":";;AAsBA,wCAeC;AAjCD,gDAAsF;AAQtF;;;;;;;;;GASG;AACH,SAAgB,cAAc,CAAC,UAAiC,EAAE;IAChE,MAAM,UAAU,GAAiB,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;QACnD,IAAA,+BAAuB,EAAC,GAAG,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;QACjD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC;IAEF,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,WAAgC;QAClF,MAAM,IAAI,GAAG,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC;QAC9B,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC"}
package/dist/guard.d.ts CHANGED
@@ -1,45 +1,40 @@
1
1
  import type { GuardFunction, GuardInstance } from '@heliosjs/core/types';
2
2
  import { type GuardClass } from '@heliosjs/core/types';
3
3
  /**
4
- * Decorator to register a guard.
5
- *
6
- * Guards are used to control access to a controller by validating
7
- * incoming requests before they reach route handlers. If a guard
8
- * returns `false`, the request is blocked.
9
- *
10
- * @param guard - A guard class or function used to determine whether
11
- * the request is allowed to proceed.
12
- *
13
- * @returns A class decorator that attaches guard metadata to the target.
4
+ * Registers a guard on a controller class or a single route method. Guards run
5
+ * before pipes, middlewares, and the handler; use them for authentication and
6
+ * authorization checks.
7
+ *
8
+ * A guard grants access by returning `true` and denies by returning `false` or a
9
+ * `string`. On denial the request is rejected with `ForbiddenError` (HTTP 403);
10
+ * a returned string becomes the error message (falling back to
11
+ * `guard.message`, then `"Forbidden"`). Guards may be async.
12
+ *
13
+ * @param guard - One of:
14
+ * - a **function** `(req, res) => boolean | string | Promise<boolean | string>`;
15
+ * - a **class** with a `canActivate(req, res)` method (instantiated per request,
16
+ * may expose a `message` property for the denial text);
17
+ * - an already-constructed **instance** with `canActivate` (and optional
18
+ * `message`).
19
+ * Why: pick the lightest form — a closure for simple checks, a class when the
20
+ * guard needs its own dependencies.
21
+ *
22
+ * @returns A class or method decorator.
14
23
  *
15
24
  * @example
16
- * // Using function guard
17
- * @GuardClass((req, res) => {
18
- * return !!req.headers.authorization;
19
- * })
20
- * class MyController {}
25
+ * @Guard((req) => !!req.getHeader('authorization') || 'Missing token')
26
+ * class SecureController {}
21
27
  *
22
- * @example
23
- * // Using class-based guard
24
- * class AuthGuard {
25
- * canActivate(req: Request, res: Response) {
26
- * return !!req.headers.authorization;
28
+ * class RoleGuard {
29
+ * message = 'Admins only';
30
+ * canActivate(req: Request) {
31
+ * return req.getState('role') === 'admin';
27
32
  * }
28
33
  * }
29
34
  *
30
- * @GuardClass(AuthGuard)
31
- * class MyController {}
32
- *
33
- * @remarks
34
- * Guards are executed before controller methods.
35
- * They can be used for:
36
- * - authentication
37
- * - authorization
38
- * - request validation
39
- *
40
- * If any guard returns `false`, the request handling is stopped.
41
- *
42
- * Metadata is stored under the CONTROLLER_CONFIGURATION key and used
43
- * internally by the framework during request processing.
35
+ * class AdminController {
36
+ * @Guard(RoleGuard)
37
+ * deleteEverything() {}
38
+ * }
44
39
  */
45
- export declare function Guard(guard: GuardClass | GuardFunction | GuardInstance): (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => void;
40
+ export declare function Guard(guard: GuardClass | GuardFunction | GuardInstance): (target: any, propertyKey?: string, _descriptor?: PropertyDescriptor) => void;
package/dist/guard.js CHANGED
@@ -3,51 +3,46 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Guard = Guard;
4
4
  const utils_1 = require("@heliosjs/core/utils");
5
5
  /**
6
- * Decorator to register a guard.
7
- *
8
- * Guards are used to control access to a controller by validating
9
- * incoming requests before they reach route handlers. If a guard
10
- * returns `false`, the request is blocked.
11
- *
12
- * @param guard - A guard class or function used to determine whether
13
- * the request is allowed to proceed.
14
- *
15
- * @returns A class decorator that attaches guard metadata to the target.
6
+ * Registers a guard on a controller class or a single route method. Guards run
7
+ * before pipes, middlewares, and the handler; use them for authentication and
8
+ * authorization checks.
9
+ *
10
+ * A guard grants access by returning `true` and denies by returning `false` or a
11
+ * `string`. On denial the request is rejected with `ForbiddenError` (HTTP 403);
12
+ * a returned string becomes the error message (falling back to
13
+ * `guard.message`, then `"Forbidden"`). Guards may be async.
14
+ *
15
+ * @param guard - One of:
16
+ * - a **function** `(req, res) => boolean | string | Promise<boolean | string>`;
17
+ * - a **class** with a `canActivate(req, res)` method (instantiated per request,
18
+ * may expose a `message` property for the denial text);
19
+ * - an already-constructed **instance** with `canActivate` (and optional
20
+ * `message`).
21
+ * Why: pick the lightest form — a closure for simple checks, a class when the
22
+ * guard needs its own dependencies.
23
+ *
24
+ * @returns A class or method decorator.
16
25
  *
17
26
  * @example
18
- * // Using function guard
19
- * @GuardClass((req, res) => {
20
- * return !!req.headers.authorization;
21
- * })
22
- * class MyController {}
27
+ * @Guard((req) => !!req.getHeader('authorization') || 'Missing token')
28
+ * class SecureController {}
23
29
  *
24
- * @example
25
- * // Using class-based guard
26
- * class AuthGuard {
27
- * canActivate(req: Request, res: Response) {
28
- * return !!req.headers.authorization;
30
+ * class RoleGuard {
31
+ * message = 'Admins only';
32
+ * canActivate(req: Request) {
33
+ * return req.getState('role') === 'admin';
29
34
  * }
30
35
  * }
31
36
  *
32
- * @GuardClass(AuthGuard)
33
- * class MyController {}
34
- *
35
- * @remarks
36
- * Guards are executed before controller methods.
37
- * They can be used for:
38
- * - authentication
39
- * - authorization
40
- * - request validation
41
- *
42
- * If any guard returns `false`, the request handling is stopped.
43
- *
44
- * Metadata is stored under the CONTROLLER_CONFIGURATION key and used
45
- * internally by the framework during request processing.
37
+ * class AdminController {
38
+ * @Guard(RoleGuard)
39
+ * deleteEverything() {}
40
+ * }
46
41
  */
47
42
  function Guard(guard) {
48
- return function (target, propertyKey, descriptor) {
43
+ return function (target, propertyKey, _descriptor) {
49
44
  const data = [{ guard: guard }];
50
- if (descriptor) {
45
+ if (propertyKey) {
51
46
  (0, utils_1.defineMiddlewaresMeta)(data, target, propertyKey);
52
47
  }
53
48
  else {
package/dist/guard.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"guard.js","sourceRoot":"","sources":["../src/guard.ts"],"names":[],"mappings":";;AA6CA,sBAUC;AArDD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,SAAgB,KAAK,CAAC,KAAiD;IACrE,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,UAA+B;QACjF,MAAM,IAAI,GAAG,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QAEhC,IAAI,UAAU,EAAE,CAAC;YACf,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"guard.js","sourceRoot":"","sources":["../src/guard.ts"],"names":[],"mappings":";;AAwCA,sBAUC;AAhDD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,SAAgB,KAAK,CAAC,KAAiD;IACrE,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,WAAgC;QAClF,MAAM,IAAI,GAAG,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QAEhC,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
@@ -2,37 +2,33 @@ import type { InterceptorCB } from '@heliosjs/core/types';
2
2
  /**
3
3
  * Decorator to register an interceptor at the controller or method level.
4
4
  *
5
- * Interceptors are functions that wrap the execution of a route handler.
6
- * They can run logic before after the handler is executed, allowing
7
- * you to modify responses, or handle cross-cutting concerns.
5
+ * An interceptor runs *after* the route handler. It receives the value the
6
+ * handler returned and whatever it returns becomes the new response payload,
7
+ * so it is the place for response shaping, wrapping, or caching.
8
8
  *
9
- * @param handler - Interceptor callback function.
9
+ * Signature: `(data, req, res) => newData` (may be async). Interceptors run
10
+ * regardless of whether the handler returned a value, including `undefined`.
11
+ *
12
+ * @param interceptor - `(data, req, res) => newData` callback.
10
13
  *
11
14
  * @returns A decorator that attaches interceptor metadata to the target
12
15
  * (either a class or a method).
13
16
  *
14
17
  * @example
15
- * // Logging interceptor
16
- * @Intercept(async (ctx, next) => {
17
- * console.log('Before');
18
- * const result = await next();
19
- * console.log('After');
20
- * return result;
21
- * })
18
+ * // Wrap every response body
19
+ * @Intercept((data) => ({ data, timestamp: Date.now() }))
22
20
  * class MyController {}
23
21
  *
24
22
  * @example
25
23
  * // Method-level interceptor
26
24
  * class MyController {
27
- * @Intercept(async (ctx, next) => {
28
- * return next();
29
- * })
25
+ * @Intercept(async (data, req) => ({ ...data, path: req.path }))
30
26
  * getData() {}
31
27
  * }
32
28
  *
33
29
  * @remarks
34
- * - Interceptors can modify the result returned by the handler.
35
- * - They are executed in the order they are applied.
30
+ * - Interceptors replace the result returned by the handler.
31
+ * - Multiple interceptors run in reverse order (the one nearest the handler first).
36
32
  * - Can be used for:
37
33
  * - logging
38
34
  * - response transformation
@@ -42,4 +38,4 @@ import type { InterceptorCB } from '@heliosjs/core/types';
42
38
  * Metadata is stored using the MIDDLEWARES_CONFIG key and
43
39
  * used internally by the framework during request processing.
44
40
  */
45
- export declare function Intercept(interceptor: InterceptorCB): (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => void;
41
+ export declare function Intercept(interceptor: InterceptorCB): (target: any, propertyKey?: string, _descriptor?: PropertyDescriptor) => void;
@@ -5,37 +5,33 @@ const utils_1 = require("@heliosjs/core/utils");
5
5
  /**
6
6
  * Decorator to register an interceptor at the controller or method level.
7
7
  *
8
- * Interceptors are functions that wrap the execution of a route handler.
9
- * They can run logic before after the handler is executed, allowing
10
- * you to modify responses, or handle cross-cutting concerns.
8
+ * An interceptor runs *after* the route handler. It receives the value the
9
+ * handler returned and whatever it returns becomes the new response payload,
10
+ * so it is the place for response shaping, wrapping, or caching.
11
11
  *
12
- * @param handler - Interceptor callback function.
12
+ * Signature: `(data, req, res) => newData` (may be async). Interceptors run
13
+ * regardless of whether the handler returned a value, including `undefined`.
14
+ *
15
+ * @param interceptor - `(data, req, res) => newData` callback.
13
16
  *
14
17
  * @returns A decorator that attaches interceptor metadata to the target
15
18
  * (either a class or a method).
16
19
  *
17
20
  * @example
18
- * // Logging interceptor
19
- * @Intercept(async (ctx, next) => {
20
- * console.log('Before');
21
- * const result = await next();
22
- * console.log('After');
23
- * return result;
24
- * })
21
+ * // Wrap every response body
22
+ * @Intercept((data) => ({ data, timestamp: Date.now() }))
25
23
  * class MyController {}
26
24
  *
27
25
  * @example
28
26
  * // Method-level interceptor
29
27
  * class MyController {
30
- * @Intercept(async (ctx, next) => {
31
- * return next();
32
- * })
28
+ * @Intercept(async (data, req) => ({ ...data, path: req.path }))
33
29
  * getData() {}
34
30
  * }
35
31
  *
36
32
  * @remarks
37
- * - Interceptors can modify the result returned by the handler.
38
- * - They are executed in the order they are applied.
33
+ * - Interceptors replace the result returned by the handler.
34
+ * - Multiple interceptors run in reverse order (the one nearest the handler first).
39
35
  * - Can be used for:
40
36
  * - logging
41
37
  * - response transformation
@@ -46,9 +42,9 @@ const utils_1 = require("@heliosjs/core/utils");
46
42
  * used internally by the framework during request processing.
47
43
  */
48
44
  function Intercept(interceptor) {
49
- return function (target, propertyKey, descriptor) {
45
+ return function (target, propertyKey, _descriptor) {
50
46
  const data = [{ interceptor }];
51
- if (descriptor) {
47
+ if (propertyKey) {
52
48
  (0, utils_1.defineMiddlewaresMeta)(data, target, propertyKey);
53
49
  }
54
50
  else {
@@ -1 +1 @@
1
- {"version":3,"file":"interceptor.js","sourceRoot":"","sources":["../src/interceptor.ts"],"names":[],"mappings":";;AA6CA,8BAUC;AAtDD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,SAAgB,SAAS,CAAC,WAA0B;IAClD,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,UAA+B;QACjF,MAAM,IAAI,GAAG,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;QAE/B,IAAI,UAAU,EAAE,CAAC;YACf,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"interceptor.js","sourceRoot":"","sources":["../src/interceptor.ts"],"names":[],"mappings":";;AAyCA,8BAUC;AAlDD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,SAAgB,SAAS,CAAC,WAA0B;IAClD,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,WAAgC;QAClF,MAAM,IAAI,GAAG,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;QAE/B,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}