@forinda/kickjs 5.3.0 → 5.4.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/dist/application-mir5CSWO.mjs +12 -0
- package/dist/{application-Cna_2gex.mjs.map → application-mir5CSWO.mjs.map} +1 -1
- package/dist/bootstrap-B7j_-dOg.mjs +12 -0
- package/dist/{bootstrap-kPcmbbWe.mjs.map → bootstrap-B7j_-dOg.mjs.map} +1 -1
- package/dist/config/index.mjs +2 -4
- package/dist/config-Dk5RVTnD.mjs +12 -0
- package/dist/{config-DxEREQmR.mjs.map → config-Dk5RVTnD.mjs.map} +1 -1
- package/dist/container-DArhTDQQ.mjs +12 -0
- package/dist/{container-SMnB5yeT.mjs.map → container-DArhTDQQ.mjs.map} +1 -1
- package/dist/{context-Ymvv-85x.d.mts → context-BAdAV-zO.d.mts} +48 -11
- package/dist/context-BAdAV-zO.d.mts.map +1 -0
- package/dist/context-CIoXqpAX.mjs +12 -0
- package/dist/context-CIoXqpAX.mjs.map +1 -0
- package/dist/core/adapter.mjs +2 -2
- package/dist/core/app-module.mjs +2 -2
- package/dist/core/cache.mjs +2 -103
- package/dist/core/cache.mjs.map +1 -1
- package/dist/core/container.mjs +2 -3
- package/dist/core/cron.mjs +2 -32
- package/dist/core/cron.mjs.map +1 -1
- package/dist/core/decorators.mjs +2 -285
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.mjs +2 -110
- package/dist/core/errors.mjs.map +1 -1
- package/dist/core/interfaces.mjs +2 -53
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.mjs +2 -207
- package/dist/core/logger.mjs.map +1 -1
- package/dist/core/path.mjs +2 -35
- package/dist/core/path.mjs.map +1 -1
- package/dist/core/plugin.mjs +2 -2
- package/dist/core/reactivity.mjs +2 -179
- package/dist/core/reactivity.mjs.map +1 -1
- package/dist/core-BQZyB8Wv.mjs +12 -0
- package/dist/{core--a4XflX7.mjs.map → core-BQZyB8Wv.mjs.map} +1 -1
- package/dist/env-BL0xOTyi.mjs +12 -0
- package/dist/{env-C4Yr6nN8.mjs.map → env-BL0xOTyi.mjs.map} +1 -1
- package/dist/http/application.mjs +2 -3
- package/dist/http/bootstrap.mjs +2 -3
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -3
- package/dist/http/middleware/cors.mjs +2 -73
- package/dist/http/middleware/cors.mjs.map +1 -1
- package/dist/http/middleware/csrf.mjs +2 -62
- package/dist/http/middleware/csrf.mjs.map +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -54
- package/dist/http/middleware/error-handler.mjs.map +1 -1
- package/dist/http/middleware/helmet.mjs +2 -41
- package/dist/http/middleware/helmet.mjs.map +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -91
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.mjs +2 -25
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -39
- package/dist/http/middleware/request-logger.mjs.map +1 -1
- package/dist/http/middleware/session.mjs +2 -167
- package/dist/http/middleware/session.mjs.map +1 -1
- package/dist/http/middleware/spa.mjs +2 -98
- package/dist/http/middleware/spa.mjs.map +1 -1
- package/dist/http/middleware/upload.mjs +2 -181
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.mjs +2 -68
- package/dist/http/middleware/validate.mjs.map +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -56
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.mjs +2 -3
- package/dist/http/router-builder.mjs +2 -105
- package/dist/http/router-builder.mjs.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +2 -171
- package/dist/index.mjs.map +1 -1
- package/dist/metadata-Dn6kNT82.mjs +12 -0
- package/dist/{metadata-CdYaU-XM.mjs.map → metadata-Dn6kNT82.mjs.map} +1 -1
- package/dist/query-B7n5isk_.mjs +12 -0
- package/dist/{query-nAYUgagU.mjs.map → query-B7n5isk_.mjs.map} +1 -1
- package/dist/{views-DkNp9JJs.d.mts → views-oKRSw0Op.d.mts} +2 -2
- package/dist/{views-DkNp9JJs.d.mts.map → views-oKRSw0Op.d.mts.map} +1 -1
- package/package.json +1 -1
- package/dist/application-Cna_2gex.mjs +0 -574
- package/dist/bootstrap-kPcmbbWe.mjs +0 -195
- package/dist/config-DxEREQmR.mjs +0 -135
- package/dist/container-SMnB5yeT.mjs +0 -897
- package/dist/context-B0B3WQft.mjs +0 -348
- package/dist/context-B0B3WQft.mjs.map +0 -1
- package/dist/context-Ymvv-85x.d.mts.map +0 -1
- package/dist/core--a4XflX7.mjs +0 -820
- package/dist/env-C4Yr6nN8.mjs +0 -137
- package/dist/metadata-CdYaU-XM.mjs +0 -76
- package/dist/query-nAYUgagU.mjs +0 -164
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,71 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import
|
|
12
|
-
import "../../core--a4XflX7.mjs";
|
|
13
|
-
//#region src/http/middleware/validate.ts
|
|
14
|
-
function toValidationException(error, message, useFirstIssueMessage) {
|
|
15
|
-
const issues = error.issues || [];
|
|
16
|
-
const details = issues.map((i) => ({
|
|
17
|
-
field: i.path?.join(".") ?? "",
|
|
18
|
-
message: i.message
|
|
19
|
-
}));
|
|
20
|
-
const finalMessage = useFirstIssueMessage ? issues[0]?.message ?? message : message;
|
|
21
|
-
return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, finalMessage, details);
|
|
22
|
-
}
|
|
23
|
-
/**
|
|
24
|
-
* Express 5 installs `req.query` as a getter-only property (so pluggable
|
|
25
|
-
* `query parser` functions can run lazily). Direct assignment throws in
|
|
26
|
-
* strict mode: `Cannot set property query of #<IncomingMessage> which
|
|
27
|
-
* has only a getter`. `Object.defineProperty` replaces the getter with
|
|
28
|
-
* a plain value slot and sidesteps the throw. Used for `query` and
|
|
29
|
-
* defensively for `params` too — Express 5 currently leaves `params`
|
|
30
|
-
* writable, but swapping the descriptor costs the same and future-proofs
|
|
31
|
-
* against upstream changes.
|
|
32
|
-
*/
|
|
33
|
-
function assignReqProperty(req, key, value) {
|
|
34
|
-
Object.defineProperty(req, key, {
|
|
35
|
-
value,
|
|
36
|
-
writable: true,
|
|
37
|
-
configurable: true,
|
|
38
|
-
enumerable: true
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Express middleware that validates request body/query/params against schemas.
|
|
43
|
-
* Works with any validation library that exposes `.safeParse(data)` returning
|
|
44
|
-
* `{ success: true, data }` or `{ success: false, error: { issues } }`.
|
|
45
|
-
*
|
|
46
|
-
* Validation failures are forwarded via `next(err)` as an `HttpException`, so
|
|
47
|
-
* they flow through the application's global error handler (`onError`) and
|
|
48
|
-
* produce a uniform response envelope. Apps that keep the built-in handler
|
|
49
|
-
* continue to see the same `{ message, errors: [{ field, message }] }` body.
|
|
50
|
-
*/
|
|
51
|
-
function validate(schema) {
|
|
52
|
-
return (req, _res, next) => {
|
|
53
|
-
try {
|
|
54
|
-
if (schema.body) {
|
|
55
|
-
const result = schema.body.safeParse(req.body);
|
|
56
|
-
if (!result.success) return next(toValidationException(result.error, "Validation failed", true));
|
|
57
|
-
req.body = result.data;
|
|
58
|
-
}
|
|
59
|
-
if (schema.query) {
|
|
60
|
-
const result = schema.query.safeParse(req.query);
|
|
61
|
-
if (!result.success) return next(toValidationException(result.error, "Invalid query parameters", false));
|
|
62
|
-
assignReqProperty(req, "query", result.data);
|
|
63
|
-
}
|
|
64
|
-
if (schema.params) {
|
|
65
|
-
const result = schema.params.safeParse(req.params);
|
|
66
|
-
if (!result.success) return next(toValidationException(result.error, "Invalid path parameters", false));
|
|
67
|
-
assignReqProperty(req, "params", result.data);
|
|
68
|
-
}
|
|
69
|
-
next();
|
|
70
|
-
} catch (err) {
|
|
71
|
-
next(err);
|
|
72
|
-
}
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
//#endregion
|
|
76
|
-
export { validate };
|
|
77
|
-
|
|
11
|
+
import{HttpException,HttpStatus}from"../../core/errors.mjs";import"../../core-BQZyB8Wv.mjs";function toValidationException(error,message,useFirstIssueMessage){let issues=error.issues||[],details=issues.map(i=>({field:i.path?.join(`.`)??``,message:i.message})),finalMessage=useFirstIssueMessage?issues[0]?.message??message:message;return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY,finalMessage,details)}function assignReqProperty(req,key,value){Object.defineProperty(req,key,{value,writable:!0,configurable:!0,enumerable:!0})}function validate(schema){return(req,_res,next)=>{try{if(schema.body){let result=schema.body.safeParse(req.body);if(!result.success)return next(toValidationException(result.error,`Validation failed`,!0));req.body=result.data}if(schema.query){let result=schema.query.safeParse(req.query);if(!result.success)return next(toValidationException(result.error,`Invalid query parameters`,!1));assignReqProperty(req,`query`,result.data)}if(schema.params){let result=schema.params.safeParse(req.params);if(!result.success)return next(toValidationException(result.error,`Invalid path parameters`,!1));assignReqProperty(req,`params`,result.data)}next()}catch(err){next(err)}}}export{validate};
|
|
78
12
|
//# sourceMappingURL=validate.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate.mjs","names":[],"sources":["../../../src/http/middleware/validate.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\nimport { HttpException, HttpStatus } from '../../core'\n\nexport interface ValidationSchema {\n body?: any\n query?: any\n params?: any\n}\n\nfunction toValidationException(\n error: any,\n message: string,\n useFirstIssueMessage: boolean,\n): HttpException {\n const issues = error.issues || []\n const details = issues.map((i: any) => ({\n field: i.path?.join('.') ?? '',\n message: i.message,\n }))\n const finalMessage = useFirstIssueMessage ? (issues[0]?.message ?? message) : message\n return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, finalMessage, details)\n}\n\n/**\n * Express 5 installs `req.query` as a getter-only property (so pluggable\n * `query parser` functions can run lazily). Direct assignment throws in\n * strict mode: `Cannot set property query of #<IncomingMessage> which\n * has only a getter`. `Object.defineProperty` replaces the getter with\n * a plain value slot and sidesteps the throw. Used for `query` and\n * defensively for `params` too — Express 5 currently leaves `params`\n * writable, but swapping the descriptor costs the same and future-proofs\n * against upstream changes.\n */\nfunction assignReqProperty(req: Request, key: 'query' | 'params', value: unknown): void {\n Object.defineProperty(req, key, {\n value,\n writable: true,\n configurable: true,\n enumerable: true,\n })\n}\n\n/**\n * Express middleware that validates request body/query/params against schemas.\n * Works with any validation library that exposes `.safeParse(data)` returning\n * `{ success: true, data }` or `{ success: false, error: { issues } }`.\n *\n * Validation failures are forwarded via `next(err)` as an `HttpException`, so\n * they flow through the application's global error handler (`onError`) and\n * produce a uniform response envelope. Apps that keep the built-in handler\n * continue to see the same `{ message, errors: [{ field, message }] }` body.\n */\nexport function validate(schema: ValidationSchema) {\n return (req: Request, _res: Response, next: NextFunction) => {\n try {\n if (schema.body) {\n const result = schema.body.safeParse(req.body)\n if (!result.success) {\n return next(toValidationException(result.error, 'Validation failed', true))\n }\n req.body = result.data\n }\n\n if (schema.query) {\n const result = schema.query.safeParse(req.query)\n if (!result.success) {\n return next(toValidationException(result.error, 'Invalid query parameters', false))\n }\n assignReqProperty(req, 'query', result.data)\n }\n\n if (schema.params) {\n const result = schema.params.safeParse(req.params)\n if (!result.success) {\n return next(toValidationException(result.error, 'Invalid path parameters', false))\n }\n assignReqProperty(req, 'params', result.data)\n }\n\n next()\n } catch (err) {\n next(err)\n }\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"validate.mjs","names":[],"sources":["../../../src/http/middleware/validate.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\nimport { HttpException, HttpStatus } from '../../core'\n\nexport interface ValidationSchema {\n body?: any\n query?: any\n params?: any\n}\n\nfunction toValidationException(\n error: any,\n message: string,\n useFirstIssueMessage: boolean,\n): HttpException {\n const issues = error.issues || []\n const details = issues.map((i: any) => ({\n field: i.path?.join('.') ?? '',\n message: i.message,\n }))\n const finalMessage = useFirstIssueMessage ? (issues[0]?.message ?? message) : message\n return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, finalMessage, details)\n}\n\n/**\n * Express 5 installs `req.query` as a getter-only property (so pluggable\n * `query parser` functions can run lazily). Direct assignment throws in\n * strict mode: `Cannot set property query of #<IncomingMessage> which\n * has only a getter`. `Object.defineProperty` replaces the getter with\n * a plain value slot and sidesteps the throw. Used for `query` and\n * defensively for `params` too — Express 5 currently leaves `params`\n * writable, but swapping the descriptor costs the same and future-proofs\n * against upstream changes.\n */\nfunction assignReqProperty(req: Request, key: 'query' | 'params', value: unknown): void {\n Object.defineProperty(req, key, {\n value,\n writable: true,\n configurable: true,\n enumerable: true,\n })\n}\n\n/**\n * Express middleware that validates request body/query/params against schemas.\n * Works with any validation library that exposes `.safeParse(data)` returning\n * `{ success: true, data }` or `{ success: false, error: { issues } }`.\n *\n * Validation failures are forwarded via `next(err)` as an `HttpException`, so\n * they flow through the application's global error handler (`onError`) and\n * produce a uniform response envelope. Apps that keep the built-in handler\n * continue to see the same `{ message, errors: [{ field, message }] }` body.\n */\nexport function validate(schema: ValidationSchema) {\n return (req: Request, _res: Response, next: NextFunction) => {\n try {\n if (schema.body) {\n const result = schema.body.safeParse(req.body)\n if (!result.success) {\n return next(toValidationException(result.error, 'Validation failed', true))\n }\n req.body = result.data\n }\n\n if (schema.query) {\n const result = schema.query.safeParse(req.query)\n if (!result.success) {\n return next(toValidationException(result.error, 'Invalid query parameters', false))\n }\n assignReqProperty(req, 'query', result.data)\n }\n\n if (schema.params) {\n const result = schema.params.safeParse(req.params)\n if (!result.success) {\n return next(toValidationException(result.error, 'Invalid path parameters', false))\n }\n assignReqProperty(req, 'params', result.data)\n }\n\n next()\n } catch (err) {\n next(err)\n }\n }\n}\n"],"mappings":";;;;;;;;;;4FASA,SAAS,sBACP,MACA,QACA,qBACe,CACf,IAAM,OAAS,MAAM,QAAU,EAAE,CAC3B,QAAU,OAAO,IAAK,IAAY,CACtC,MAAO,EAAE,MAAM,KAAK,IAAI,EAAI,GAC5B,QAAS,EAAE,QACZ,EAAE,CACG,aAAe,qBAAwB,OAAO,IAAI,SAAW,QAAW,QAC9E,OAAO,IAAI,cAAc,WAAW,qBAAsB,aAAc,QAAQ,CAalF,SAAS,kBAAkB,IAAc,IAAyB,MAAsB,CACtF,OAAO,eAAe,IAAK,IAAK,CAC9B,MACA,SAAU,GACV,aAAc,GACd,WAAY,GACb,CAAC,CAaJ,SAAgB,SAAS,OAA0B,CACjD,OAAQ,IAAc,KAAgB,OAAuB,CAC3D,GAAI,CACF,GAAI,OAAO,KAAM,CACf,IAAM,OAAS,OAAO,KAAK,UAAU,IAAI,KAAK,CAC9C,GAAI,CAAC,OAAO,QACV,OAAO,KAAK,sBAAsB,OAAO,MAAO,oBAAqB,GAAK,CAAC,CAE7E,IAAI,KAAO,OAAO,KAGpB,GAAI,OAAO,MAAO,CAChB,IAAM,OAAS,OAAO,MAAM,UAAU,IAAI,MAAM,CAChD,GAAI,CAAC,OAAO,QACV,OAAO,KAAK,sBAAsB,OAAO,MAAO,2BAA4B,GAAM,CAAC,CAErF,kBAAkB,IAAK,QAAS,OAAO,KAAK,CAG9C,GAAI,OAAO,OAAQ,CACjB,IAAM,OAAS,OAAO,OAAO,UAAU,IAAI,OAAO,CAClD,GAAI,CAAC,OAAO,QACV,OAAO,KAAK,sBAAsB,OAAO,MAAO,0BAA2B,GAAM,CAAC,CAEpF,kBAAkB,IAAK,SAAU,OAAO,KAAK,CAG/C,MAAM,OACC,IAAK,CACZ,KAAK,IAAI"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,59 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import
|
|
12
|
-
import { n as defineAdapter } from "../../core--a4XflX7.mjs";
|
|
13
|
-
import { resolve } from "node:path";
|
|
14
|
-
//#region src/http/middleware/views.ts
|
|
15
|
-
const log = Logger.for("ViewEngine");
|
|
16
|
-
/**
|
|
17
|
-
* View/template adapter — pluggable template engine support for KickJS.
|
|
18
|
-
*
|
|
19
|
-
* Registers an Express view engine and sets the views directory.
|
|
20
|
-
* Use `ctx.render()` in controllers to render templates.
|
|
21
|
-
*
|
|
22
|
-
* Migrated to the `defineAdapter()` factory in v4 — call without `new`.
|
|
23
|
-
* The pre-v4 `new ViewAdapter({...})` form is gone; see
|
|
24
|
-
* `docs/guide/migration-v3-to-v4.md` for the rename.
|
|
25
|
-
*
|
|
26
|
-
* @example
|
|
27
|
-
* ```ts
|
|
28
|
-
* import ejs from 'ejs'
|
|
29
|
-
* import { ViewAdapter } from '@forinda/kickjs'
|
|
30
|
-
*
|
|
31
|
-
* bootstrap({
|
|
32
|
-
* modules,
|
|
33
|
-
* adapters: [
|
|
34
|
-
* ViewAdapter({ engine: ejs, ext: 'ejs', viewsDir: 'src/views' }),
|
|
35
|
-
* ],
|
|
36
|
-
* })
|
|
37
|
-
*
|
|
38
|
-
* // In a controller:
|
|
39
|
-
* @Get('/dashboard')
|
|
40
|
-
* async dashboard(ctx: RequestContext) {
|
|
41
|
-
* ctx.render('dashboard', { user: currentUser, title: 'Dashboard' })
|
|
42
|
-
* }
|
|
43
|
-
* ```
|
|
44
|
-
*/
|
|
45
|
-
const ViewAdapter = defineAdapter({
|
|
46
|
-
name: "ViewAdapter",
|
|
47
|
-
build: (options) => ({ beforeMount({ app }) {
|
|
48
|
-
const { engine, ext, viewsDir = "src/views" } = options;
|
|
49
|
-
if (engine.__express) app.engine(ext, engine.__express);
|
|
50
|
-
else if (typeof engine.renderFile === "function") app.engine(ext, (path, opts, callback) => {
|
|
51
|
-
engine.renderFile(path, opts, callback);
|
|
52
|
-
});
|
|
53
|
-
else if (typeof engine === "function") app.engine(ext, engine);
|
|
54
|
-
else {
|
|
55
|
-
log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`);
|
|
56
|
-
app.engine(ext, engine);
|
|
57
|
-
}
|
|
58
|
-
app.set("view engine", ext);
|
|
59
|
-
app.set("views", resolve(viewsDir));
|
|
60
|
-
log.debug(`View engine: ${ext} (${resolve(viewsDir)})`);
|
|
61
|
-
} })
|
|
62
|
-
});
|
|
63
|
-
//#endregion
|
|
64
|
-
export { ViewAdapter };
|
|
65
|
-
|
|
11
|
+
import{Logger}from"../../core/logger.mjs";import{n as defineAdapter}from"../../core-BQZyB8Wv.mjs";import{resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app}){let{engine,ext,viewsDir=`src/views`}=options;engine.__express?app.engine(ext,engine.__express):typeof engine.renderFile==`function`?app.engine(ext,(path,opts,callback)=>{engine.renderFile(path,opts,callback)}):(typeof engine==`function`||log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`),app.engine(ext,engine)),app.set(`view engine`,ext),app.set(`views`,resolve(viewsDir)),log.debug(`View engine: ${ext} (${resolve(viewsDir)})`)}})});export{ViewAdapter};
|
|
66
12
|
//# sourceMappingURL=views.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"views.mjs","names":[],"sources":["../../../src/http/middleware/views.ts"],"sourcesContent":["import { resolve } from 'node:path'\nimport { Logger, defineAdapter } from '../../core'\n\nconst log = Logger.for('ViewEngine')\n\nexport interface ViewAdapterOptions {\n /**\n * Template engine — pass the engine module or a render function.\n * Supported engines: ejs, pug, handlebars, nunjucks, or any\n * Express-compatible engine with a __express property.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * ViewAdapter({ engine: ejs, ext: 'ejs' })\n *\n * import pug from 'pug'\n * ViewAdapter({ engine: pug, ext: 'pug' })\n * ```\n */\n engine: any\n\n /** File extension for templates (e.g., 'ejs', 'pug', 'hbs') */\n ext: string\n\n /** Directory containing template files (default: 'src/views') */\n viewsDir?: string\n\n /** Default layout template (optional — depends on engine) */\n layout?: string\n}\n\n/**\n * View/template adapter — pluggable template engine support for KickJS.\n *\n * Registers an Express view engine and sets the views directory.\n * Use `ctx.render()` in controllers to render templates.\n *\n * Migrated to the `defineAdapter()` factory in v4 — call without `new`.\n * The pre-v4 `new ViewAdapter({...})` form is gone; see\n * `docs/guide/migration-v3-to-v4.md` for the rename.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * import { ViewAdapter } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * ViewAdapter({ engine: ejs, ext: 'ejs', viewsDir: 'src/views' }),\n * ],\n * })\n *\n * // In a controller:\n * @Get('/dashboard')\n * async dashboard(ctx: RequestContext) {\n * ctx.render('dashboard', { user: currentUser, title: 'Dashboard' })\n * }\n * ```\n */\nexport const ViewAdapter = defineAdapter<ViewAdapterOptions>({\n name: 'ViewAdapter',\n build: (options) => ({\n beforeMount({ app }) {\n const { engine, ext, viewsDir = 'src/views' } = options\n\n // Register the engine. Three resolution paths cover every\n // mainstream template engine + a fall-through for custom ones.\n if (engine.__express) {\n // EJS, Pug — have __express method\n app.engine(ext, engine.__express)\n } else if (typeof engine.renderFile === 'function') {\n // Engines with renderFile (nunjucks-style)\n app.engine(\n ext,\n (path: string, opts: any, callback: (err: Error | null, html?: string) => void) => {\n engine.renderFile(path, opts, callback)\n },\n )\n } else if (typeof engine === 'function') {\n // Custom render function: (path, options, callback) => void\n app.engine(ext, engine)\n } else {\n log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`)\n app.engine(ext, engine)\n }\n\n app.set('view engine', ext)\n app.set('views', resolve(viewsDir))\n\n log.debug(`View engine: ${ext} (${resolve(viewsDir)})`)\n },\n }),\n})\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"views.mjs","names":[],"sources":["../../../src/http/middleware/views.ts"],"sourcesContent":["import { resolve } from 'node:path'\nimport { Logger, defineAdapter } from '../../core'\n\nconst log = Logger.for('ViewEngine')\n\nexport interface ViewAdapterOptions {\n /**\n * Template engine — pass the engine module or a render function.\n * Supported engines: ejs, pug, handlebars, nunjucks, or any\n * Express-compatible engine with a __express property.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * ViewAdapter({ engine: ejs, ext: 'ejs' })\n *\n * import pug from 'pug'\n * ViewAdapter({ engine: pug, ext: 'pug' })\n * ```\n */\n engine: any\n\n /** File extension for templates (e.g., 'ejs', 'pug', 'hbs') */\n ext: string\n\n /** Directory containing template files (default: 'src/views') */\n viewsDir?: string\n\n /** Default layout template (optional — depends on engine) */\n layout?: string\n}\n\n/**\n * View/template adapter — pluggable template engine support for KickJS.\n *\n * Registers an Express view engine and sets the views directory.\n * Use `ctx.render()` in controllers to render templates.\n *\n * Migrated to the `defineAdapter()` factory in v4 — call without `new`.\n * The pre-v4 `new ViewAdapter({...})` form is gone; see\n * `docs/guide/migration-v3-to-v4.md` for the rename.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * import { ViewAdapter } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * ViewAdapter({ engine: ejs, ext: 'ejs', viewsDir: 'src/views' }),\n * ],\n * })\n *\n * // In a controller:\n * @Get('/dashboard')\n * async dashboard(ctx: RequestContext) {\n * ctx.render('dashboard', { user: currentUser, title: 'Dashboard' })\n * }\n * ```\n */\nexport const ViewAdapter = defineAdapter<ViewAdapterOptions>({\n name: 'ViewAdapter',\n build: (options) => ({\n beforeMount({ app }) {\n const { engine, ext, viewsDir = 'src/views' } = options\n\n // Register the engine. Three resolution paths cover every\n // mainstream template engine + a fall-through for custom ones.\n if (engine.__express) {\n // EJS, Pug — have __express method\n app.engine(ext, engine.__express)\n } else if (typeof engine.renderFile === 'function') {\n // Engines with renderFile (nunjucks-style)\n app.engine(\n ext,\n (path: string, opts: any, callback: (err: Error | null, html?: string) => void) => {\n engine.renderFile(path, opts, callback)\n },\n )\n } else if (typeof engine === 'function') {\n // Custom render function: (path, options, callback) => void\n app.engine(ext, engine)\n } else {\n log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`)\n app.engine(ext, engine)\n }\n\n app.set('view engine', ext)\n app.set('views', resolve(viewsDir))\n\n log.debug(`View engine: ${ext} (${resolve(viewsDir)})`)\n },\n }),\n})\n"],"mappings":";;;;;;;;;;iIAGA,MAAM,IAAM,OAAO,IAAI,aAAa,CA0DvB,YAAc,cAAkC,CAC3D,KAAM,cACN,MAAQ,UAAa,CACnB,YAAY,CAAE,KAAO,CACnB,GAAM,CAAE,OAAQ,IAAK,SAAW,aAAgB,QAI5C,OAAO,UAET,IAAI,OAAO,IAAK,OAAO,UAAU,CACxB,OAAO,OAAO,YAAe,WAEtC,IAAI,OACF,KACC,KAAc,KAAW,WAAyD,CACjF,OAAO,WAAW,KAAM,KAAM,SAAS,EAE1C,EACQ,OAAO,QAAW,YAI3B,IAAI,KAAK,eAAe,IAAI,uDAAuD,CAFnF,IAAI,OAAO,IAAK,OAAO,EAMzB,IAAI,IAAI,cAAe,IAAI,CAC3B,IAAI,IAAI,QAAS,QAAQ,SAAS,CAAC,CAEnC,IAAI,MAAM,gBAAgB,IAAI,IAAI,QAAQ,SAAS,CAAC,GAAG,EAE1D,EACF,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import
|
|
12
|
-
export { FILTER_OPERATORS, buildQueryParams, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort };
|
|
11
|
+
import{a as parseSearchQuery,i as parseQuery,n as parseFilters,o as parseSort,r as parsePagination,s as FILTER_OPERATORS,t as buildQueryParams}from"../../query-B7n5isk_.mjs";export{FILTER_OPERATORS,buildQueryParams,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,108 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import { t as
|
|
12
|
-
import { METADATA } from "../core/interfaces.mjs";
|
|
13
|
-
import { a as getMethodMeta, o as getMethodMetaOrUndefined, t as getClassMeta } from "../metadata-CdYaU-XM.mjs";
|
|
14
|
-
import { c as runContributors, l as buildPipeline } from "../core--a4XflX7.mjs";
|
|
15
|
-
import { t as RequestContext } from "../context-B0B3WQft.mjs";
|
|
16
|
-
import { validate } from "./middleware/validate.mjs";
|
|
17
|
-
import { buildUploadMiddleware } from "./middleware/upload.mjs";
|
|
18
|
-
import { Router } from "express";
|
|
19
|
-
//#region src/http/router-builder.ts
|
|
20
|
-
/**
|
|
21
|
-
* Per-module SourcedRegistration[] threaded through the route-mount loop by
|
|
22
|
-
* Application.setup(). Carries module + adapter + global contributors so
|
|
23
|
-
* buildRoutes() can merge them with class + method ones into a single pipeline.
|
|
24
|
-
*
|
|
25
|
-
* Module setup is sequential, so this slot is race-free. Cleared in a finally
|
|
26
|
-
* block after each module mounts. Outside of Application setup the slot is
|
|
27
|
-
* empty — direct buildRoutes() callers (mostly tests) see only class + method
|
|
28
|
-
* contributors unless they pass `externalSources` explicitly.
|
|
29
|
-
*
|
|
30
|
-
* Same idiom as `Container._requestStoreProvider` and `Logger._contextProvider`:
|
|
31
|
-
* an internal escape hatch for cross-module wiring without inversion-of-control
|
|
32
|
-
* gymnastics.
|
|
33
|
-
*
|
|
34
|
-
* @internal
|
|
35
|
-
*/
|
|
36
|
-
let _externalContributorSources = [];
|
|
37
|
-
/** @internal — set by Application.setup() before each `mod.routes()` call. */
|
|
38
|
-
function _setExternalContributorSources(sources) {
|
|
39
|
-
_externalContributorSources = sources;
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Build an Express Router from a controller class decorated with @Get, @Post, etc.
|
|
43
|
-
* Resolves the controller from the DI container, wraps handlers in RequestContext,
|
|
44
|
-
* and applies class-level and method-level middleware.
|
|
45
|
-
*
|
|
46
|
-
* Routes are registered using only the method-level decorator paths (e.g. @Get('/me') → '/me').
|
|
47
|
-
* The @Controller path is NOT baked into the router — it serves as metadata only
|
|
48
|
-
* (used by Swagger and other adapters for introspection).
|
|
49
|
-
* The module's routes().path is the single source of truth for the mount prefix,
|
|
50
|
-
* which avoids path doubling when both the module and controller specify the same path.
|
|
51
|
-
*/
|
|
52
|
-
function buildRoutes(controllerClass, options = {}) {
|
|
53
|
-
const router = Router();
|
|
54
|
-
const container = Container.getInstance();
|
|
55
|
-
const externalSources = options.externalSources ?? _externalContributorSources;
|
|
56
|
-
const routes = getClassMeta(METADATA.ROUTES, controllerClass, []);
|
|
57
|
-
const classMiddlewares = getClassMeta(METADATA.CLASS_MIDDLEWARES, controllerClass, []);
|
|
58
|
-
const classContributors = getClassMeta(METADATA.CLASS_CONTRIBUTORS, controllerClass, []);
|
|
59
|
-
for (const route of routes) {
|
|
60
|
-
const method = route.method.toLowerCase();
|
|
61
|
-
const fullPath = route.path || "/";
|
|
62
|
-
const methodMiddlewares = getMethodMeta(METADATA.METHOD_MIDDLEWARES, controllerClass, route.handlerName, []);
|
|
63
|
-
const handlers = [];
|
|
64
|
-
if (route.validation) handlers.push(validate(route.validation));
|
|
65
|
-
const fileUploadConfig = getMethodMetaOrUndefined(METADATA.FILE_UPLOAD, controllerClass, route.handlerName);
|
|
66
|
-
if (fileUploadConfig) handlers.push(buildUploadMiddleware(fileUploadConfig));
|
|
67
|
-
for (const mw of [...classMiddlewares, ...methodMiddlewares]) handlers.push((req, res, next) => {
|
|
68
|
-
const ctx = new RequestContext(req, res, next);
|
|
69
|
-
Promise.resolve(mw(ctx, next)).catch(next);
|
|
70
|
-
});
|
|
71
|
-
const methodContributors = getMethodMeta(METADATA.METHOD_CONTRIBUTORS, controllerClass, route.handlerName, []);
|
|
72
|
-
if (classContributors.length > 0 || methodContributors.length > 0 || externalSources.length > 0) {
|
|
73
|
-
const pipeline = buildPipeline([
|
|
74
|
-
...methodContributors.map((registration, i) => ({
|
|
75
|
-
source: "method",
|
|
76
|
-
registration,
|
|
77
|
-
label: `${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`
|
|
78
|
-
})),
|
|
79
|
-
...classContributors.map((registration, i) => ({
|
|
80
|
-
source: "class",
|
|
81
|
-
registration,
|
|
82
|
-
label: `${controllerClass.name}.@class#${i}(${registration.key})`
|
|
83
|
-
})),
|
|
84
|
-
...externalSources
|
|
85
|
-
], { route: `${route.method.toUpperCase()} ${fullPath}` });
|
|
86
|
-
handlers.push(async (req, res, next) => {
|
|
87
|
-
const ctx = new RequestContext(req, res, next);
|
|
88
|
-
try {
|
|
89
|
-
await runContributors({
|
|
90
|
-
pipeline,
|
|
91
|
-
ctx,
|
|
92
|
-
container
|
|
93
|
-
});
|
|
94
|
-
next();
|
|
95
|
-
} catch (err) {
|
|
96
|
-
next(err);
|
|
97
|
-
}
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
handlers.push(async (req, res, next) => {
|
|
101
|
-
const ctx = new RequestContext(req, res, next);
|
|
102
|
-
try {
|
|
103
|
-
await container.resolve(controllerClass)[route.handlerName](ctx);
|
|
104
|
-
} catch (err) {
|
|
105
|
-
next(err);
|
|
106
|
-
}
|
|
107
|
-
});
|
|
108
|
-
router[method](fullPath, ...handlers);
|
|
109
|
-
}
|
|
110
|
-
return router;
|
|
111
|
-
}
|
|
112
|
-
//#endregion
|
|
113
|
-
export { _setExternalContributorSources, buildRoutes };
|
|
114
|
-
|
|
11
|
+
import{t as Container}from"../container-DArhTDQQ.mjs";import{METADATA}from"../core/interfaces.mjs";import{a as getMethodMeta,o as getMethodMetaOrUndefined,t as getClassMeta}from"../metadata-Dn6kNT82.mjs";import{c as runContributors,l as buildPipeline}from"../core-BQZyB8Wv.mjs";import{t as RequestContext}from"../context-CIoXqpAX.mjs";import{validate}from"./middleware/validate.mjs";import{buildUploadMiddleware}from"./middleware/upload.mjs";import{Router}from"express";let _externalContributorSources=[];function _setExternalContributorSources(sources){_externalContributorSources=sources}function buildRoutes(controllerClass,options={}){let router=Router(),container=Container.getInstance(),externalSources=options.externalSources??_externalContributorSources,routes=getClassMeta(METADATA.ROUTES,controllerClass,[]),classMiddlewares=getClassMeta(METADATA.CLASS_MIDDLEWARES,controllerClass,[]),classContributors=getClassMeta(METADATA.CLASS_CONTRIBUTORS,controllerClass,[]);for(let route of routes){let method=route.method.toLowerCase(),fullPath=route.path||`/`,methodMiddlewares=getMethodMeta(METADATA.METHOD_MIDDLEWARES,controllerClass,route.handlerName,[]),handlers=[];route.validation&&handlers.push(validate(route.validation));let fileUploadConfig=getMethodMetaOrUndefined(METADATA.FILE_UPLOAD,controllerClass,route.handlerName);fileUploadConfig&&handlers.push(buildUploadMiddleware(fileUploadConfig));for(let mw of[...classMiddlewares,...methodMiddlewares])handlers.push((req,res,next)=>{let ctx=new RequestContext(req,res,next);Promise.resolve(mw(ctx,next)).catch(next)});let methodContributors=getMethodMeta(METADATA.METHOD_CONTRIBUTORS,controllerClass,route.handlerName,[]);if(classContributors.length>0||methodContributors.length>0||externalSources.length>0){let pipeline=buildPipeline([...methodContributors.map((registration,i)=>({source:`method`,registration,label:`${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`})),...classContributors.map((registration,i)=>({source:`class`,registration,label:`${controllerClass.name}.@class#${i}(${registration.key})`})),...externalSources],{route:`${route.method.toUpperCase()} ${fullPath}`});handlers.push(async(req,res,next)=>{let ctx=new RequestContext(req,res,next);try{await runContributors({pipeline,ctx,container}),next()}catch(err){next(err)}})}handlers.push(async(req,res,next)=>{let ctx=new RequestContext(req,res,next);try{await container.resolve(controllerClass)[route.handlerName](ctx)}catch(err){next(err)}}),router[method](fullPath,...handlers)}return router}export{_setExternalContributorSources,buildRoutes};
|
|
115
12
|
//# sourceMappingURL=router-builder.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-builder.mjs","names":[],"sources":["../../src/http/router-builder.ts"],"sourcesContent":["import { Router, type Request, type Response, type NextFunction } from 'express'\nimport {\n buildPipeline,\n Container,\n METADATA,\n runContributors,\n type ContributorRegistration,\n type FileUploadConfig,\n type MiddlewareHandler,\n type RouteDefinition,\n type SourcedRegistration,\n} from '../core'\nimport { getClassMeta, getMethodMeta, getMethodMetaOrUndefined } from '../core/metadata'\nimport { RequestContext } from './context'\nimport { validate } from './middleware/validate'\nimport { buildUploadMiddleware } from './middleware/upload'\n\n/**\n * Per-module SourcedRegistration[] threaded through the route-mount loop by\n * Application.setup(). Carries module + adapter + global contributors so\n * buildRoutes() can merge them with class + method ones into a single pipeline.\n *\n * Module setup is sequential, so this slot is race-free. Cleared in a finally\n * block after each module mounts. Outside of Application setup the slot is\n * empty — direct buildRoutes() callers (mostly tests) see only class + method\n * contributors unless they pass `externalSources` explicitly.\n *\n * Same idiom as `Container._requestStoreProvider` and `Logger._contextProvider`:\n * an internal escape hatch for cross-module wiring without inversion-of-control\n * gymnastics.\n *\n * @internal\n */\nlet _externalContributorSources: readonly SourcedRegistration[] = []\n\n/** @internal — set by Application.setup() before each `mod.routes()` call. */\nexport function _setExternalContributorSources(sources: readonly SourcedRegistration[]): void {\n _externalContributorSources = sources\n}\n\nexport interface BuildRoutesOptions {\n /**\n * Extra contributors to merge into the per-route pipeline at their declared\n * precedence levels. Pass explicitly when calling buildRoutes outside the\n * Application route-mount loop (typically in tests). When omitted, falls\n * back to the slot set by Application.setup().\n */\n externalSources?: readonly SourcedRegistration[]\n}\n\n/**\n * Build an Express Router from a controller class decorated with @Get, @Post, etc.\n * Resolves the controller from the DI container, wraps handlers in RequestContext,\n * and applies class-level and method-level middleware.\n *\n * Routes are registered using only the method-level decorator paths (e.g. @Get('/me') → '/me').\n * The @Controller path is NOT baked into the router — it serves as metadata only\n * (used by Swagger and other adapters for introspection).\n * The module's routes().path is the single source of truth for the mount prefix,\n * which avoids path doubling when both the module and controller specify the same path.\n */\nexport function buildRoutes(controllerClass: any, options: BuildRoutesOptions = {}): Router {\n const router = Router()\n const container = Container.getInstance()\n const externalSources = options.externalSources ?? _externalContributorSources\n const routes: RouteDefinition[] = getClassMeta<RouteDefinition[]>(\n METADATA.ROUTES,\n controllerClass,\n [],\n )\n\n // Class-level middleware\n const classMiddlewares: MiddlewareHandler[] = getClassMeta<MiddlewareHandler[]>(\n METADATA.CLASS_MIDDLEWARES,\n controllerClass,\n [],\n )\n\n // Class-level Context Contributors (#107) — applied to every method on the\n // controller. Method-level contributors are added per-route below.\n const classContributors: ContributorRegistration[] = getClassMeta<ContributorRegistration[]>(\n METADATA.CLASS_CONTRIBUTORS,\n controllerClass,\n [],\n )\n\n for (const route of routes) {\n const method = route.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch'\n const fullPath = route.path || '/'\n\n // Method-level middleware\n const methodMiddlewares: MiddlewareHandler[] = getMethodMeta<MiddlewareHandler[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // Build handler chain\n const handlers: any[] = []\n\n // Validation middleware (shared with standalone validate() export)\n if (route.validation) {\n handlers.push(validate(route.validation))\n }\n\n // @FileUpload decorator — auto-attach upload middleware from metadata\n const fileUploadConfig = getMethodMetaOrUndefined<FileUploadConfig>(\n METADATA.FILE_UPLOAD,\n controllerClass,\n route.handlerName,\n )\n if (fileUploadConfig) {\n handlers.push(buildUploadMiddleware(fileUploadConfig))\n }\n\n // Class + method middleware (wrapped as Express middleware with error catching)\n for (const mw of [...classMiddlewares, ...methodMiddlewares]) {\n handlers.push((req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n Promise.resolve(mw(ctx, next)).catch(next)\n })\n }\n\n // Context Contributor pipeline (#107) — class + method contributors,\n // built once at mount time so cycle/missing-dep failures abort boot.\n const methodContributors: ContributorRegistration[] = getMethodMeta<ContributorRegistration[]>(\n METADATA.METHOD_CONTRIBUTORS,\n controllerClass,\n route.handlerName,\n [],\n )\n\n if (\n classContributors.length > 0 ||\n methodContributors.length > 0 ||\n externalSources.length > 0\n ) {\n // Labels are surfaced in DuplicateContributorError messages — include\n // the registration's key + the original index so a same-key collision\n // at one precedence level points at the conflicting decorator slot,\n // not just the host method/class.\n const sources: SourcedRegistration[] = [\n ...methodContributors.map(\n (registration, i): SourcedRegistration => ({\n source: 'method',\n registration,\n label: `${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`,\n }),\n ),\n ...classContributors.map(\n (registration, i): SourcedRegistration => ({\n source: 'class',\n registration,\n label: `${controllerClass.name}.@class#${i}(${registration.key})`,\n }),\n ),\n ...externalSources,\n ]\n const pipeline = buildPipeline(sources, {\n route: `${route.method.toUpperCase()} ${fullPath}`,\n })\n\n handlers.push(async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n await runContributors({ pipeline, ctx, container })\n next()\n } catch (err) {\n next(err)\n }\n })\n }\n\n // Main handler — resolve controller per-request to respect DI scoping\n handlers.push(async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n const controller = container.resolve(controllerClass)\n await controller[route.handlerName](ctx)\n } catch (err: any) {\n next(err)\n }\n })\n ;(router as any)[method](fullPath, ...handlers)\n }\n\n return router\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"router-builder.mjs","names":[],"sources":["../../src/http/router-builder.ts"],"sourcesContent":["import { Router, type Request, type Response, type NextFunction } from 'express'\nimport {\n buildPipeline,\n Container,\n METADATA,\n runContributors,\n type ContributorRegistration,\n type FileUploadConfig,\n type MiddlewareHandler,\n type RouteDefinition,\n type SourcedRegistration,\n} from '../core'\nimport { getClassMeta, getMethodMeta, getMethodMetaOrUndefined } from '../core/metadata'\nimport { RequestContext } from './context'\nimport { validate } from './middleware/validate'\nimport { buildUploadMiddleware } from './middleware/upload'\n\n/**\n * Per-module SourcedRegistration[] threaded through the route-mount loop by\n * Application.setup(). Carries module + adapter + global contributors so\n * buildRoutes() can merge them with class + method ones into a single pipeline.\n *\n * Module setup is sequential, so this slot is race-free. Cleared in a finally\n * block after each module mounts. Outside of Application setup the slot is\n * empty — direct buildRoutes() callers (mostly tests) see only class + method\n * contributors unless they pass `externalSources` explicitly.\n *\n * Same idiom as `Container._requestStoreProvider` and `Logger._contextProvider`:\n * an internal escape hatch for cross-module wiring without inversion-of-control\n * gymnastics.\n *\n * @internal\n */\nlet _externalContributorSources: readonly SourcedRegistration[] = []\n\n/** @internal — set by Application.setup() before each `mod.routes()` call. */\nexport function _setExternalContributorSources(sources: readonly SourcedRegistration[]): void {\n _externalContributorSources = sources\n}\n\nexport interface BuildRoutesOptions {\n /**\n * Extra contributors to merge into the per-route pipeline at their declared\n * precedence levels. Pass explicitly when calling buildRoutes outside the\n * Application route-mount loop (typically in tests). When omitted, falls\n * back to the slot set by Application.setup().\n */\n externalSources?: readonly SourcedRegistration[]\n}\n\n/**\n * Build an Express Router from a controller class decorated with @Get, @Post, etc.\n * Resolves the controller from the DI container, wraps handlers in RequestContext,\n * and applies class-level and method-level middleware.\n *\n * Routes are registered using only the method-level decorator paths (e.g. @Get('/me') → '/me').\n * The @Controller path is NOT baked into the router — it serves as metadata only\n * (used by Swagger and other adapters for introspection).\n * The module's routes().path is the single source of truth for the mount prefix,\n * which avoids path doubling when both the module and controller specify the same path.\n */\nexport function buildRoutes(controllerClass: any, options: BuildRoutesOptions = {}): Router {\n const router = Router()\n const container = Container.getInstance()\n const externalSources = options.externalSources ?? _externalContributorSources\n const routes: RouteDefinition[] = getClassMeta<RouteDefinition[]>(\n METADATA.ROUTES,\n controllerClass,\n [],\n )\n\n // Class-level middleware\n const classMiddlewares: MiddlewareHandler[] = getClassMeta<MiddlewareHandler[]>(\n METADATA.CLASS_MIDDLEWARES,\n controllerClass,\n [],\n )\n\n // Class-level Context Contributors (#107) — applied to every method on the\n // controller. Method-level contributors are added per-route below.\n const classContributors: ContributorRegistration[] = getClassMeta<ContributorRegistration[]>(\n METADATA.CLASS_CONTRIBUTORS,\n controllerClass,\n [],\n )\n\n for (const route of routes) {\n const method = route.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch'\n const fullPath = route.path || '/'\n\n // Method-level middleware\n const methodMiddlewares: MiddlewareHandler[] = getMethodMeta<MiddlewareHandler[]>(\n METADATA.METHOD_MIDDLEWARES,\n controllerClass,\n route.handlerName,\n [],\n )\n\n // Build handler chain\n const handlers: any[] = []\n\n // Validation middleware (shared with standalone validate() export)\n if (route.validation) {\n handlers.push(validate(route.validation))\n }\n\n // @FileUpload decorator — auto-attach upload middleware from metadata\n const fileUploadConfig = getMethodMetaOrUndefined<FileUploadConfig>(\n METADATA.FILE_UPLOAD,\n controllerClass,\n route.handlerName,\n )\n if (fileUploadConfig) {\n handlers.push(buildUploadMiddleware(fileUploadConfig))\n }\n\n // Class + method middleware (wrapped as Express middleware with error catching)\n for (const mw of [...classMiddlewares, ...methodMiddlewares]) {\n handlers.push((req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n Promise.resolve(mw(ctx, next)).catch(next)\n })\n }\n\n // Context Contributor pipeline (#107) — class + method contributors,\n // built once at mount time so cycle/missing-dep failures abort boot.\n const methodContributors: ContributorRegistration[] = getMethodMeta<ContributorRegistration[]>(\n METADATA.METHOD_CONTRIBUTORS,\n controllerClass,\n route.handlerName,\n [],\n )\n\n if (\n classContributors.length > 0 ||\n methodContributors.length > 0 ||\n externalSources.length > 0\n ) {\n // Labels are surfaced in DuplicateContributorError messages — include\n // the registration's key + the original index so a same-key collision\n // at one precedence level points at the conflicting decorator slot,\n // not just the host method/class.\n const sources: SourcedRegistration[] = [\n ...methodContributors.map(\n (registration, i): SourcedRegistration => ({\n source: 'method',\n registration,\n label: `${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`,\n }),\n ),\n ...classContributors.map(\n (registration, i): SourcedRegistration => ({\n source: 'class',\n registration,\n label: `${controllerClass.name}.@class#${i}(${registration.key})`,\n }),\n ),\n ...externalSources,\n ]\n const pipeline = buildPipeline(sources, {\n route: `${route.method.toUpperCase()} ${fullPath}`,\n })\n\n handlers.push(async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n await runContributors({ pipeline, ctx, container })\n next()\n } catch (err) {\n next(err)\n }\n })\n }\n\n // Main handler — resolve controller per-request to respect DI scoping\n handlers.push(async (req: Request, res: Response, next: NextFunction) => {\n const ctx = new RequestContext(req, res, next)\n try {\n const controller = container.resolve(controllerClass)\n await controller[route.handlerName](ctx)\n } catch (err: any) {\n next(err)\n }\n })\n ;(router as any)[method](fullPath, ...handlers)\n }\n\n return router\n}\n"],"mappings":";;;;;;;;;;sdAiCA,IAAI,4BAA8D,EAAE,CAGpE,SAAgB,+BAA+B,QAA+C,CAC5F,4BAA8B,QAwBhC,SAAgB,YAAY,gBAAsB,QAA8B,EAAE,CAAU,CAC1F,IAAM,OAAS,QAAQ,CACjB,UAAY,UAAU,aAAa,CACnC,gBAAkB,QAAQ,iBAAmB,4BAC7C,OAA4B,aAChC,SAAS,OACT,gBACA,EAAE,CACH,CAGK,iBAAwC,aAC5C,SAAS,kBACT,gBACA,EAAE,CACH,CAIK,kBAA+C,aACnD,SAAS,mBACT,gBACA,EAAE,CACH,CAED,IAAK,IAAM,SAAS,OAAQ,CAC1B,IAAM,OAAS,MAAM,OAAO,aAAa,CACnC,SAAW,MAAM,MAAQ,IAGzB,kBAAyC,cAC7C,SAAS,mBACT,gBACA,MAAM,YACN,EAAE,CACH,CAGK,SAAkB,EAAE,CAGtB,MAAM,YACR,SAAS,KAAK,SAAS,MAAM,WAAW,CAAC,CAI3C,IAAM,iBAAmB,yBACvB,SAAS,YACT,gBACA,MAAM,YACP,CACG,kBACF,SAAS,KAAK,sBAAsB,iBAAiB,CAAC,CAIxD,IAAK,IAAM,KAAM,CAAC,GAAG,iBAAkB,GAAG,kBAAkB,CAC1D,SAAS,MAAM,IAAc,IAAe,OAAuB,CACjE,IAAM,IAAM,IAAI,eAAe,IAAK,IAAK,KAAK,CAC9C,QAAQ,QAAQ,GAAG,IAAK,KAAK,CAAC,CAAC,MAAM,KAAK,EAC1C,CAKJ,IAAM,mBAAgD,cACpD,SAAS,oBACT,gBACA,MAAM,YACN,EAAE,CACH,CAED,GACE,kBAAkB,OAAS,GAC3B,mBAAmB,OAAS,GAC5B,gBAAgB,OAAS,EACzB,CAsBA,IAAM,SAAW,cAjBsB,CACrC,GAAG,mBAAmB,KACnB,aAAc,KAA4B,CACzC,OAAQ,SACR,aACA,MAAO,GAAG,gBAAgB,KAAK,GAAG,OAAO,MAAM,YAAY,CAAC,GAAG,EAAE,GAAG,aAAa,IAAI,GACtF,EACF,CACD,GAAG,kBAAkB,KAClB,aAAc,KAA4B,CACzC,OAAQ,QACR,aACA,MAAO,GAAG,gBAAgB,KAAK,UAAU,EAAE,GAAG,aAAa,IAAI,GAChE,EACF,CACD,GAAG,gBACJ,CACuC,CACtC,MAAO,GAAG,MAAM,OAAO,aAAa,CAAC,GAAG,WACzC,CAAC,CAEF,SAAS,KAAK,MAAO,IAAc,IAAe,OAAuB,CACvE,IAAM,IAAM,IAAI,eAAe,IAAK,IAAK,KAAK,CAC9C,GAAI,CACF,MAAM,gBAAgB,CAAE,SAAU,IAAK,UAAW,CAAC,CACnD,MAAM,OACC,IAAK,CACZ,KAAK,IAAI,GAEX,CAIJ,SAAS,KAAK,MAAO,IAAc,IAAe,OAAuB,CACvE,IAAM,IAAM,IAAI,eAAe,IAAK,IAAK,KAAK,CAC9C,GAAI,CAEF,MADmB,UAAU,QAAQ,gBAAgB,CACpC,MAAM,aAAa,IAAI,OACjC,IAAU,CACjB,KAAK,IAAI,GAEX,CACA,OAAe,QAAQ,SAAU,GAAG,SAAS,CAGjD,OAAO"}
|
package/dist/index.d.mts
CHANGED
|
@@ -18,7 +18,7 @@ import { A as DuplicateContributorError, B as getMetaRecord, C as runContributor
|
|
|
18
18
|
import { n as ApplicationOptions, r as MiddlewareEntry, t as Application } from "./application-BTRI4aBd.mjs";
|
|
19
19
|
import { t as bootstrap } from "./bootstrap-B4YrBipl.mjs";
|
|
20
20
|
import { _ as SortItem, a as parseSearchQuery, c as FILTER_OPERATORS, d as FilterOperator, f as PaginatedResponse, g as QueryFieldConfig, h as QueryBuilderAdapter, i as parseQuery, l as FieldsOf, m as ParsedQuery, n as parseFilters, o as parseSort, p as PaginationParams, r as parsePagination, t as buildQueryParams, u as FilterItem, y as TypedParsedQuery } from "./index-B9cyOQAe.mjs";
|
|
21
|
-
import { n as
|
|
21
|
+
import { i as RouteShape, n as DeepReadonly, r as RequestContext, t as Ctx } from "./context-BAdAV-zO.mjs";
|
|
22
22
|
import { n as cors, t as CorsOptions } from "./cors-BfgqfLPd.mjs";
|
|
23
23
|
import { n as csrf, t as CsrfOptions } from "./csrf-DiK9zept.mjs";
|
|
24
24
|
import { n as notFoundHandler, t as errorHandler } from "./error-handler-Xud_3Lah.mjs";
|
|
@@ -30,6 +30,6 @@ import { a as session, i as SessionStore, n as SessionData, r as SessionOptions,
|
|
|
30
30
|
import { n as SpaAdapterOptions, t as SpaAdapter } from "./spa-e4FIS2RB.mjs";
|
|
31
31
|
import { a as upload, i as resolveMimeTypes, n as buildUploadMiddleware, r as cleanupFiles, t as UploadOptions } from "./upload-tGMrlhEB.mjs";
|
|
32
32
|
import { n as validate } from "./validate-HwAyWTwH.mjs";
|
|
33
|
-
import { a as TraceContextOptions, c as requestScopeMiddleware, d as getRequestValue, f as requestStore, h as isClusterPrimary, i as TraceContext, l as RequestStore, m as ClusterOptions, n as ViewAdapterOptions, o as parseTraceparent, p as defineHttpContextDecorator, r as TRACEPARENT_HEADER, s as traceContext, t as ViewAdapter, u as getRequestStore } from "./views-
|
|
33
|
+
import { a as TraceContextOptions, c as requestScopeMiddleware, d as getRequestValue, f as requestStore, h as isClusterPrimary, i as TraceContext, l as RequestStore, m as ClusterOptions, n as ViewAdapterOptions, o as parseTraceparent, p as defineHttpContextDecorator, r as TRACEPARENT_HEADER, s as traceContext, t as ViewAdapter, u as getRequestStore } from "./views-oKRSw0Op.mjs";
|
|
34
34
|
import { r as buildRoutes } from "./router-builder-C7sXk_FG.mjs";
|
|
35
|
-
export { ASSETS, ASSET_MANIFEST_VERSION, AdapterAsyncOptions, AdapterContext, AdapterFactory, AdapterMiddleware, AnyContributorRegistration, ApiQueryParams, ApiQueryParamsConfig, ApiQueryParamsConfig as QueryParamsConfig, AppAdapter, AppAdapterClass, AppModule, AppModuleClass, Application, ApplicationOptions, Asset, AssetKey, AssetKeyPair, AssetKeyStrategy, AugmentationMeta, Autowired, BaseUploadOptions, BuildContext, BuildPipelineOptions, Buildable, Builder, BuilderOf, CRON_META, CacheEvict, CacheOptions, CacheProvider, Cacheable, CircuitBreaker, CircuitBreakerOptions, CircuitBreakerState, CircuitBreakerStats, CircuitOpenError, ClassKind, ClusterOptions, ColumnApiQueryParamsConfig, Component, ComputedRef, ConfigService, ConsoleLoggerProvider, Constructor, Container, ContainerChangeEvent, ContainerChangeListener, ContextDecorator, ContextDecoratorSpec, ContextMeta, ContextMetaKey, ContributorCycleError, ContributorPipeline, ContributorRegistration, ContributorRegistrations, ContributorSource, Controller, CorsOptions, Cron, CronJobMeta, CsrfOptions, Ctx, DefineAdapterOptions, DefinePluginOptions, Delete, DepValue, DuplicateContributorError, DuplicateMountNameError, Env, EnvKey, ExecutionContext, FILTER_OPERATORS, FieldsOf, FileTypeFilter, FileUpload, FileUploadConfig, FilterItem, FilterOperator, Get, GroupAssetKeysOptions, GroupAssetKeysResult, HelmetOptions, HttpException, HttpStatus, HttpStatusCode, INJECTION_TOKEN, Inject, Injectable, InjectionToken, KickAssets, KickJsPluginName, KickJsPluginRegistry, KickJsRegistry, KickPlugin, Logger, LoggerProvider, METADATA, MaybePromise, MemoryCacheProvider, MetaValue, Middleware, MiddlewareEntry, MiddlewareHandler, MiddlewarePhase, MissingContributorError, MissingMountDepError, ModuleRoutes, MountCycleError, MountKind, MountSortItem, PaginatedResponse, PaginationParams, ParsedQuery, Patch, PluginAsyncOptions, PluginFactory, Post, PostConstruct, PostConstructStatus, Put, QueryBuilderAdapter, QueryFieldConfig, REQUEST_ID_HEADER, RateLimitOptions, RateLimitStore, Ref, Repository, RequestContext, RequestLoggerOptions, RequestStore, ResolvedDeps, RouteDefinition, RouteShape, RunContributorsOptions, Scope, Service, ServiceOptions, Session, SessionData, SessionOptions, SessionStore, SortItem, SourcedRegistration, SpaAdapter, SpaAdapterOptions, TRACEPARENT_HEADER, TraceContext, TraceContextOptions, TypedConfigService, TypedParsedQuery, UnknownAssetError, UploadOptions, ValidationError, Value, ViewAdapter, ViewAdapterOptions, WatchOptions, assets, baseEnvSchema, bootstrap, buildPipeline, buildQueryParams, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createLogger, createToken, csrf, defineAdapter, defineAugmentation, defineContextDecorator, defineEnv, defineHttpContextDecorator, definePlugin, errorHandler, getCacheProvider, getClassMeta, getClassMetaOrUndefined, getCronJobs, getEnv, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, getRequestStore, getRequestValue, groupAssetKeys, hasClassMeta, helmet, isClusterPrimary, isInjectionToken, isRef, joinPaths, loadEnv, mountSort, normalizeApiQueryParamsConfig, normalizePath, notFoundHandler, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, parseTraceparent, pushClassMeta, pushMethodMeta, rateLimit, reactive, ref, reloadEnv, requestId, requestLogger, requestScopeMiddleware, requestStore, resetEnvCache, resolveAsset, resolveMimeTypes, rootLogger, runContributors, session, setCacheProvider, setClassMeta, setInMetaMap, setInMetaRecord, setMethodMeta, stripExt, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, watch, withBuilder };
|
|
35
|
+
export { ASSETS, ASSET_MANIFEST_VERSION, AdapterAsyncOptions, AdapterContext, AdapterFactory, AdapterMiddleware, AnyContributorRegistration, ApiQueryParams, ApiQueryParamsConfig, ApiQueryParamsConfig as QueryParamsConfig, AppAdapter, AppAdapterClass, AppModule, AppModuleClass, Application, ApplicationOptions, Asset, AssetKey, AssetKeyPair, AssetKeyStrategy, AugmentationMeta, Autowired, BaseUploadOptions, BuildContext, BuildPipelineOptions, Buildable, Builder, BuilderOf, CRON_META, CacheEvict, CacheOptions, CacheProvider, Cacheable, CircuitBreaker, CircuitBreakerOptions, CircuitBreakerState, CircuitBreakerStats, CircuitOpenError, ClassKind, ClusterOptions, ColumnApiQueryParamsConfig, Component, ComputedRef, ConfigService, ConsoleLoggerProvider, Constructor, Container, ContainerChangeEvent, ContainerChangeListener, ContextDecorator, ContextDecoratorSpec, ContextMeta, ContextMetaKey, ContributorCycleError, ContributorPipeline, ContributorRegistration, ContributorRegistrations, ContributorSource, Controller, CorsOptions, Cron, CronJobMeta, CsrfOptions, Ctx, DeepReadonly, DefineAdapterOptions, DefinePluginOptions, Delete, DepValue, DuplicateContributorError, DuplicateMountNameError, Env, EnvKey, ExecutionContext, FILTER_OPERATORS, FieldsOf, FileTypeFilter, FileUpload, FileUploadConfig, FilterItem, FilterOperator, Get, GroupAssetKeysOptions, GroupAssetKeysResult, HelmetOptions, HttpException, HttpStatus, HttpStatusCode, INJECTION_TOKEN, Inject, Injectable, InjectionToken, KickAssets, KickJsPluginName, KickJsPluginRegistry, KickJsRegistry, KickPlugin, Logger, LoggerProvider, METADATA, MaybePromise, MemoryCacheProvider, MetaValue, Middleware, MiddlewareEntry, MiddlewareHandler, MiddlewarePhase, MissingContributorError, MissingMountDepError, ModuleRoutes, MountCycleError, MountKind, MountSortItem, PaginatedResponse, PaginationParams, ParsedQuery, Patch, PluginAsyncOptions, PluginFactory, Post, PostConstruct, PostConstructStatus, Put, QueryBuilderAdapter, QueryFieldConfig, REQUEST_ID_HEADER, RateLimitOptions, RateLimitStore, Ref, Repository, RequestContext, RequestLoggerOptions, RequestStore, ResolvedDeps, RouteDefinition, RouteShape, RunContributorsOptions, Scope, Service, ServiceOptions, Session, SessionData, SessionOptions, SessionStore, SortItem, SourcedRegistration, SpaAdapter, SpaAdapterOptions, TRACEPARENT_HEADER, TraceContext, TraceContextOptions, TypedConfigService, TypedParsedQuery, UnknownAssetError, UploadOptions, ValidationError, Value, ViewAdapter, ViewAdapterOptions, WatchOptions, assets, baseEnvSchema, bootstrap, buildPipeline, buildQueryParams, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createLogger, createToken, csrf, defineAdapter, defineAugmentation, defineContextDecorator, defineEnv, defineHttpContextDecorator, definePlugin, errorHandler, getCacheProvider, getClassMeta, getClassMetaOrUndefined, getCronJobs, getEnv, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, getRequestStore, getRequestValue, groupAssetKeys, hasClassMeta, helmet, isClusterPrimary, isInjectionToken, isRef, joinPaths, loadEnv, mountSort, normalizeApiQueryParamsConfig, normalizePath, notFoundHandler, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, parseTraceparent, pushClassMeta, pushMethodMeta, rateLimit, reactive, ref, reloadEnv, requestId, requestLogger, requestScopeMiddleware, requestStore, resetEnvCache, resolveAsset, resolveMimeTypes, rootLogger, runContributors, session, setCacheProvider, setClassMeta, setInMetaMap, setInMetaRecord, setMethodMeta, stripExt, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, watch, withBuilder };
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,174 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import
|
|
12
|
-
import { METADATA, Scope } from "./core/interfaces.mjs";
|
|
13
|
-
import { ConsoleLoggerProvider, Logger, createLogger, rootLogger } from "./core/logger.mjs";
|
|
14
|
-
import { a as getMethodMeta, c as pushClassMeta, d as setInMetaMap, f as setInMetaRecord, i as getMetaRecord, l as pushMethodMeta, n as getClassMetaOrUndefined, o as getMethodMetaOrUndefined, p as setMethodMeta, r as getMetaMap, s as hasClassMeta, t as getClassMeta, u as setClassMeta } from "./metadata-CdYaU-XM.mjs";
|
|
15
|
-
import { ApiQueryParams, Asset, Autowired, Builder, Component, Controller, Delete, FileUpload, Get, Inject, Injectable, Middleware, Patch, Post, PostConstruct, Put, Repository, Service, Value, normalizeApiQueryParamsConfig, withBuilder } from "./core/decorators.mjs";
|
|
16
|
-
import { CRON_META, Cron, getCronJobs } from "./core/cron.mjs";
|
|
17
|
-
import { CacheEvict, Cacheable, MemoryCacheProvider, getCacheProvider, setCacheProvider } from "./core/cache.mjs";
|
|
18
|
-
import { HttpException, HttpStatus } from "./core/errors.mjs";
|
|
19
|
-
import { joinPaths, normalizePath } from "./core/path.mjs";
|
|
20
|
-
import { a as MissingMountDepError, c as runContributors, d as DuplicateContributorError, f as MissingContributorError, h as CircuitOpenError, i as DuplicateMountNameError, l as buildPipeline, m as CircuitBreaker, n as defineAdapter, o as MountCycleError, p as defineContextDecorator, r as definePlugin, s as mountSort, t as defineAugmentation, u as ContributorCycleError } from "./core--a4XflX7.mjs";
|
|
21
|
-
import { computed, isRef, reactive, ref, toRefs, unref, watch } from "./core/reactivity.mjs";
|
|
22
|
-
import { REQUEST_ID_HEADER, requestId } from "./http/middleware/request-id.mjs";
|
|
23
|
-
import { errorHandler, notFoundHandler } from "./http/middleware/error-handler.mjs";
|
|
24
|
-
import { i as requestStore, n as getRequestStore, r as getRequestValue, t as RequestContext } from "./context-B0B3WQft.mjs";
|
|
25
|
-
import { n as requestScopeMiddleware, t as Application } from "./application-Cna_2gex.mjs";
|
|
26
|
-
import { a as parseSearchQuery, i as parseQuery, n as parseFilters, o as parseSort, r as parsePagination, s as FILTER_OPERATORS, t as buildQueryParams } from "./query-nAYUgagU.mjs";
|
|
27
|
-
import { validate } from "./http/middleware/validate.mjs";
|
|
28
|
-
import { buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload } from "./http/middleware/upload.mjs";
|
|
29
|
-
import { buildRoutes } from "./http/router-builder.mjs";
|
|
30
|
-
import { a as reloadEnv, i as loadEnv, n as defineEnv, o as resetEnvCache, r as getEnv, t as baseEnvSchema } from "./env-C4Yr6nN8.mjs";
|
|
31
|
-
import { n as isClusterPrimary, t as bootstrap } from "./bootstrap-kPcmbbWe.mjs";
|
|
32
|
-
import { csrf } from "./http/middleware/csrf.mjs";
|
|
33
|
-
import { requestLogger } from "./http/middleware/request-logger.mjs";
|
|
34
|
-
import { helmet } from "./http/middleware/helmet.mjs";
|
|
35
|
-
import { cors } from "./http/middleware/cors.mjs";
|
|
36
|
-
import { rateLimit } from "./http/middleware/rate-limit.mjs";
|
|
37
|
-
import { session } from "./http/middleware/session.mjs";
|
|
38
|
-
import { ViewAdapter } from "./http/middleware/views.mjs";
|
|
39
|
-
import { SpaAdapter } from "./http/middleware/spa.mjs";
|
|
40
|
-
import { n as createConfigService, t as ConfigService } from "./config-DxEREQmR.mjs";
|
|
41
|
-
import crypto from "node:crypto";
|
|
42
|
-
//#region src/http/define-http-context-decorator.ts
|
|
43
|
-
/**
|
|
44
|
-
* HTTP-flavoured wrapper around {@link defineContextDecorator}.
|
|
45
|
-
*
|
|
46
|
-
* The core factory leaves `Ctx` defaulted to {@link ExecutionContext} so the
|
|
47
|
-
* Context Contributor pipeline stays transport-agnostic — future WebSocket,
|
|
48
|
-
* queue, and cron contexts share the same primitive. The cost is that the
|
|
49
|
-
* vast majority of contributors (which are HTTP) have to spell the fourth
|
|
50
|
-
* generic by hand to get `ctx.req` / `ctx.headers` typing:
|
|
51
|
-
*
|
|
52
|
-
* ```ts
|
|
53
|
-
* // Verbose: spell every generic, including the params shape `P`.
|
|
54
|
-
* defineContextDecorator<'tenant', Record<string, never>, Record<string, never>, RequestContext>({
|
|
55
|
-
* key: 'tenant',
|
|
56
|
-
* resolve: (ctx) => ({ id: ctx.req.headers['x-tenant-id'] as string }),
|
|
57
|
-
* })
|
|
58
|
-
* ```
|
|
59
|
-
*
|
|
60
|
-
* `defineHttpContextDecorator` removes that ceremony — the spec is typed
|
|
61
|
-
* against `RequestContext` from the start, so resolvers can read `ctx.req`,
|
|
62
|
-
* `ctx.headers`, `ctx.params`, etc. without a cast or generic dance:
|
|
63
|
-
*
|
|
64
|
-
* ```ts
|
|
65
|
-
* import { defineHttpContextDecorator } from '@forinda/kickjs'
|
|
66
|
-
*
|
|
67
|
-
* const LoadTenant = defineHttpContextDecorator({
|
|
68
|
-
* key: 'tenant',
|
|
69
|
-
* resolve: (ctx) => ({ id: ctx.req.headers['x-tenant-id'] as string }),
|
|
70
|
-
* })
|
|
71
|
-
*
|
|
72
|
-
* // Parameterised: the third generic carries the per-call params shape.
|
|
73
|
-
* const LoadTenantParameterised = defineHttpContextDecorator<
|
|
74
|
-
* 'tenant',
|
|
75
|
-
* Record<string, never>,
|
|
76
|
-
* { source: 'header' | 'subdomain' }
|
|
77
|
-
* >({
|
|
78
|
-
* key: 'tenant',
|
|
79
|
-
* paramDefaults: { source: 'header' },
|
|
80
|
-
* resolve: (ctx, _deps, params) => {
|
|
81
|
-
* // params.source narrows inside `if` branches.
|
|
82
|
-
* },
|
|
83
|
-
* })
|
|
84
|
-
* ```
|
|
85
|
-
*
|
|
86
|
-
* Use {@link defineContextDecorator} directly when authoring contributors
|
|
87
|
-
* for non-HTTP transports or when you want to share one contributor across
|
|
88
|
-
* HTTP + WS + queue (the resolver then has to stick to the
|
|
89
|
-
* `ExecutionContext` surface — `ctx.get` / `ctx.set` / `ctx.requestId`).
|
|
90
|
-
*/
|
|
91
|
-
function defineHttpContextDecorator(spec) {
|
|
92
|
-
return defineContextDecorator(spec);
|
|
93
|
-
}
|
|
94
|
-
//#endregion
|
|
95
|
-
//#region src/http/middleware/trace-context.ts
|
|
96
|
-
/**
|
|
97
|
-
* W3C Trace Context header name.
|
|
98
|
-
* @see https://www.w3.org/TR/trace-context/#traceparent-header
|
|
99
|
-
*/
|
|
100
|
-
const TRACEPARENT_HEADER = "traceparent";
|
|
101
|
-
/** Regex for a valid W3C traceparent: {version}-{trace-id}-{parent-id}-{flags} */
|
|
102
|
-
const TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
|
|
103
|
-
/**
|
|
104
|
-
* Generate a random 32-hex-character trace ID.
|
|
105
|
-
*/
|
|
106
|
-
function generateTraceId() {
|
|
107
|
-
return crypto.randomBytes(16).toString("hex");
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* Generate a random 16-hex-character span ID.
|
|
111
|
-
*/
|
|
112
|
-
function generateSpanId() {
|
|
113
|
-
return crypto.randomBytes(8).toString("hex");
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Parse a W3C traceparent header value.
|
|
117
|
-
* Returns null if the format is invalid.
|
|
118
|
-
*/
|
|
119
|
-
function parseTraceparent(header) {
|
|
120
|
-
const match = TRACEPARENT_RE.exec(header.trim().toLowerCase());
|
|
121
|
-
if (!match) return null;
|
|
122
|
-
const version = match[1];
|
|
123
|
-
const traceId = match[2];
|
|
124
|
-
const parentSpanId = match[3];
|
|
125
|
-
const flags = match[4];
|
|
126
|
-
if (version === "ff" || traceId === "00000000000000000000000000000000" || parentSpanId === "0000000000000000") return null;
|
|
127
|
-
return {
|
|
128
|
-
version,
|
|
129
|
-
traceId,
|
|
130
|
-
parentSpanId,
|
|
131
|
-
flags
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
/**
|
|
135
|
-
* Middleware that extracts W3C `traceparent` header and stores trace context
|
|
136
|
-
* in the request's AsyncLocalStorage store.
|
|
137
|
-
*
|
|
138
|
-
* If no valid `traceparent` header is present, a new traceId is generated
|
|
139
|
-
* so that every request always has a trace ID available for correlation.
|
|
140
|
-
*
|
|
141
|
-
* Must be mounted **after** `requestScopeMiddleware()` (which creates the store).
|
|
142
|
-
*
|
|
143
|
-
* @example
|
|
144
|
-
* ```ts
|
|
145
|
-
* bootstrap({
|
|
146
|
-
* middleware: [
|
|
147
|
-
* requestScopeMiddleware(),
|
|
148
|
-
* traceContext(), // extracts or generates traceId
|
|
149
|
-
* requestLogger(),
|
|
150
|
-
* express.json(),
|
|
151
|
-
* ],
|
|
152
|
-
* })
|
|
153
|
-
* ```
|
|
154
|
-
*/
|
|
155
|
-
function traceContext(options = {}) {
|
|
156
|
-
return (req, res, next) => {
|
|
157
|
-
const store = requestStore.getStore();
|
|
158
|
-
const traceparentHeader = req.headers[TRACEPARENT_HEADER];
|
|
159
|
-
const raw = Array.isArray(traceparentHeader) ? traceparentHeader[0] : traceparentHeader;
|
|
160
|
-
const parsed = raw ? parseTraceparent(raw) : null;
|
|
161
|
-
const traceId = parsed?.traceId ?? generateTraceId();
|
|
162
|
-
const spanId = generateSpanId();
|
|
163
|
-
if (store) {
|
|
164
|
-
store.values.set("traceId", traceId);
|
|
165
|
-
store.values.set("spanId", spanId);
|
|
166
|
-
if (parsed) {
|
|
167
|
-
store.values.set("parentSpanId", parsed.parentSpanId);
|
|
168
|
-
store.values.set("traceFlags", parsed.flags);
|
|
169
|
-
store.values.set("traceVersion", parsed.version);
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
req.traceId = traceId;
|
|
173
|
-
req.spanId = spanId;
|
|
174
|
-
if (options.propagateResponse) res.setHeader("traceresponse", traceId);
|
|
175
|
-
next();
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
//#endregion
|
|
179
|
-
export { ASSETS, ASSET_MANIFEST_VERSION, ApiQueryParams, Application, Asset, Autowired, Builder, CRON_META, CacheEvict, Cacheable, CircuitBreaker, CircuitOpenError, Component, ConfigService, ConsoleLoggerProvider, Container, ContributorCycleError, Controller, Cron, Delete, DuplicateContributorError, DuplicateMountNameError, FILTER_OPERATORS, FileUpload, Get, HttpException, HttpStatus, INJECTION_TOKEN, Inject, Injectable, Logger, METADATA, MemoryCacheProvider, Middleware, MissingContributorError, MissingMountDepError, MountCycleError, Patch, Post, PostConstruct, Put, REQUEST_ID_HEADER, Repository, RequestContext, Scope, Service, SpaAdapter, TRACEPARENT_HEADER, UnknownAssetError, Value, ViewAdapter, assets, baseEnvSchema, bootstrap, buildPipeline, buildQueryParams, buildRoutes, buildUploadMiddleware, cleanupFiles, clearAssetCache, computed, cors, createConfigService, createLogger, createToken, csrf, defineAdapter, defineAugmentation, defineContextDecorator, defineEnv, defineHttpContextDecorator, definePlugin, errorHandler, getCacheProvider, getClassMeta, getClassMetaOrUndefined, getCronJobs, getEnv, getMetaMap, getMetaRecord, getMethodMeta, getMethodMetaOrUndefined, getRequestStore, getRequestValue, groupAssetKeys, hasClassMeta, helmet, isClusterPrimary, isInjectionToken, isRef, joinPaths, loadEnv, mountSort, normalizeApiQueryParamsConfig, normalizePath, notFoundHandler, parseFilters, parsePagination, parseQuery, parseSearchQuery, parseSort, parseTraceparent, pushClassMeta, pushMethodMeta, rateLimit, reactive, ref, reloadEnv, requestId, requestLogger, requestScopeMiddleware, requestStore, resetEnvCache, resolveAsset, resolveMimeTypes, rootLogger, runContributors, session, setCacheProvider, setClassMeta, setInMetaMap, setInMetaRecord, setMethodMeta, stripExt, toRefs, tokenName, traceContext, unref, upload, useAssets, validate, watch, withBuilder };
|
|
180
|
-
|
|
11
|
+
import{a as UnknownAssetError,c as resolveAsset,d as stripExt,f as INJECTION_TOKEN,i as ASSET_MANIFEST_VERSION,l as useAssets,m as isInjectionToken,n as tokenName,o as assets,p as createToken,r as ASSETS,s as clearAssetCache,t as Container,u as groupAssetKeys}from"./container-DArhTDQQ.mjs";import{METADATA,Scope}from"./core/interfaces.mjs";import{ConsoleLoggerProvider,Logger,createLogger,rootLogger}from"./core/logger.mjs";import{a as getMethodMeta,c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,i as getMetaRecord,l as pushMethodMeta,n as getClassMetaOrUndefined,o as getMethodMetaOrUndefined,p as setMethodMeta,r as getMetaMap,s as hasClassMeta,t as getClassMeta,u as setClassMeta}from"./metadata-Dn6kNT82.mjs";import{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder}from"./core/decorators.mjs";import{CRON_META,Cron,getCronJobs}from"./core/cron.mjs";import{CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider}from"./core/cache.mjs";import{HttpException,HttpStatus}from"./core/errors.mjs";import{joinPaths,normalizePath}from"./core/path.mjs";import{a as MissingMountDepError,c as runContributors,d as DuplicateContributorError,f as MissingContributorError,h as CircuitOpenError,i as DuplicateMountNameError,l as buildPipeline,m as CircuitBreaker,n as defineAdapter,o as MountCycleError,p as defineContextDecorator,r as definePlugin,s as mountSort,t as defineAugmentation,u as ContributorCycleError}from"./core-BQZyB8Wv.mjs";import{computed,isRef,reactive,ref,toRefs,unref,watch}from"./core/reactivity.mjs";import{REQUEST_ID_HEADER,requestId}from"./http/middleware/request-id.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as requestStore,n as getRequestStore,r as getRequestValue,t as RequestContext}from"./context-CIoXqpAX.mjs";import{n as requestScopeMiddleware,t as Application}from"./application-mir5CSWO.mjs";import{a as parseSearchQuery,i as parseQuery,n as parseFilters,o as parseSort,r as parsePagination,s as FILTER_OPERATORS,t as buildQueryParams}from"./query-B7n5isk_.mjs";import{validate}from"./http/middleware/validate.mjs";import{buildUploadMiddleware,cleanupFiles,resolveMimeTypes,upload}from"./http/middleware/upload.mjs";import{buildRoutes}from"./http/router-builder.mjs";import{a as reloadEnv,i as loadEnv,n as defineEnv,o as resetEnvCache,r as getEnv,t as baseEnvSchema}from"./env-BL0xOTyi.mjs";import{n as isClusterPrimary,t as bootstrap}from"./bootstrap-B7j_-dOg.mjs";import{csrf}from"./http/middleware/csrf.mjs";import{requestLogger}from"./http/middleware/request-logger.mjs";import{helmet}from"./http/middleware/helmet.mjs";import{cors}from"./http/middleware/cors.mjs";import{rateLimit}from"./http/middleware/rate-limit.mjs";import{session}from"./http/middleware/session.mjs";import{ViewAdapter}from"./http/middleware/views.mjs";import{SpaAdapter}from"./http/middleware/spa.mjs";import{n as createConfigService,t as ConfigService}from"./config-Dk5RVTnD.mjs";import crypto from"node:crypto";function defineHttpContextDecorator(spec){return defineContextDecorator(spec)}const TRACEPARENT_HEADER=`traceparent`,TRACEPARENT_RE=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function generateTraceId(){return crypto.randomBytes(16).toString(`hex`)}function generateSpanId(){return crypto.randomBytes(8).toString(`hex`)}function parseTraceparent(header){let match=TRACEPARENT_RE.exec(header.trim().toLowerCase());if(!match)return null;let version=match[1],traceId=match[2],parentSpanId=match[3],flags=match[4];return version===`ff`||traceId===`00000000000000000000000000000000`||parentSpanId===`0000000000000000`?null:{version,traceId,parentSpanId,flags}}function traceContext(options={}){return(req,res,next)=>{let store=requestStore.getStore(),traceparentHeader=req.headers[TRACEPARENT_HEADER],raw=Array.isArray(traceparentHeader)?traceparentHeader[0]:traceparentHeader,parsed=raw?parseTraceparent(raw):null,traceId=parsed?.traceId??generateTraceId(),spanId=generateSpanId();store&&(store.values.set(`traceId`,traceId),store.values.set(`spanId`,spanId),parsed&&(store.values.set(`parentSpanId`,parsed.parentSpanId),store.values.set(`traceFlags`,parsed.flags),store.values.set(`traceVersion`,parsed.version))),req.traceId=traceId,req.spanId=spanId,options.propagateResponse&&res.setHeader(`traceresponse`,traceId),next()}}export{ASSETS,ASSET_MANIFEST_VERSION,ApiQueryParams,Application,Asset,Autowired,Builder,CRON_META,CacheEvict,Cacheable,CircuitBreaker,CircuitOpenError,Component,ConfigService,ConsoleLoggerProvider,Container,ContributorCycleError,Controller,Cron,Delete,DuplicateContributorError,DuplicateMountNameError,FILTER_OPERATORS,FileUpload,Get,HttpException,HttpStatus,INJECTION_TOKEN,Inject,Injectable,Logger,METADATA,MemoryCacheProvider,Middleware,MissingContributorError,MissingMountDepError,MountCycleError,Patch,Post,PostConstruct,Put,REQUEST_ID_HEADER,Repository,RequestContext,Scope,Service,SpaAdapter,TRACEPARENT_HEADER,UnknownAssetError,Value,ViewAdapter,assets,baseEnvSchema,bootstrap,buildPipeline,buildQueryParams,buildRoutes,buildUploadMiddleware,cleanupFiles,clearAssetCache,computed,cors,createConfigService,createLogger,createToken,csrf,defineAdapter,defineAugmentation,defineContextDecorator,defineEnv,defineHttpContextDecorator,definePlugin,errorHandler,getCacheProvider,getClassMeta,getClassMetaOrUndefined,getCronJobs,getEnv,getMetaMap,getMetaRecord,getMethodMeta,getMethodMetaOrUndefined,getRequestStore,getRequestValue,groupAssetKeys,hasClassMeta,helmet,isClusterPrimary,isInjectionToken,isRef,joinPaths,loadEnv,mountSort,normalizeApiQueryParamsConfig,normalizePath,notFoundHandler,parseFilters,parsePagination,parseQuery,parseSearchQuery,parseSort,parseTraceparent,pushClassMeta,pushMethodMeta,rateLimit,reactive,ref,reloadEnv,requestId,requestLogger,requestScopeMiddleware,requestStore,resetEnvCache,resolveAsset,resolveMimeTypes,rootLogger,runContributors,session,setCacheProvider,setClassMeta,setInMetaMap,setInMetaRecord,setMethodMeta,stripExt,toRefs,tokenName,traceContext,unref,upload,useAssets,validate,watch,withBuilder};
|
|
181
12
|
//# sourceMappingURL=index.mjs.map
|