@forinda/kickjs 2.0.0 → 2.1.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/README.md +85 -584
- package/dist/adapter-BqGjZCSm.d.mts +122 -0
- package/dist/adapter-BqGjZCSm.d.mts.map +1 -0
- package/dist/app-module-CcEbAVtB.d.mts +33 -0
- package/dist/app-module-CcEbAVtB.d.mts.map +1 -0
- package/dist/application-DNHj-_UL.mjs +449 -0
- package/dist/application-DNHj-_UL.mjs.map +1 -0
- package/dist/bootstrap-DLEZaJ3b.mjs +205 -0
- package/dist/bootstrap-DLEZaJ3b.mjs.map +1 -0
- package/dist/{core/cache.d.ts → cache-DJeMaGqb.d.mts} +33 -31
- package/dist/cache-DJeMaGqb.d.mts.map +1 -0
- package/dist/chunk-C5Qp-JxE.mjs +15 -0
- package/dist/container-nBSIhyqV.d.mts +141 -0
- package/dist/container-nBSIhyqV.d.mts.map +1 -0
- package/dist/core/adapter.d.mts +3 -0
- package/dist/core/adapter.mjs +11 -0
- package/dist/core/app-module.d.mts +3 -0
- package/dist/core/app-module.mjs +11 -0
- package/dist/core/cache.d.mts +3 -0
- package/dist/core/cache.mjs +113 -0
- package/dist/core/cache.mjs.map +1 -0
- package/dist/core/container.d.mts +3 -0
- package/dist/core/container.mjs +426 -0
- package/dist/core/container.mjs.map +1 -0
- package/dist/core/cron.d.mts +3 -0
- package/dist/core/cron.mjs +42 -0
- package/dist/core/cron.mjs.map +1 -0
- package/dist/core/decorators.d.mts +3 -0
- package/dist/core/decorators.mjs +213 -0
- package/dist/core/decorators.mjs.map +1 -0
- package/dist/core/errors.d.mts +3 -0
- package/dist/core/errors.mjs +97 -0
- package/dist/core/errors.mjs.map +1 -0
- package/dist/core/interfaces.d.mts +3 -0
- package/dist/core/interfaces.mjs +44 -0
- package/dist/core/interfaces.mjs.map +1 -0
- package/dist/core/logger.d.mts +3 -0
- package/dist/core/logger.mjs +217 -0
- package/dist/core/logger.mjs.map +1 -0
- package/dist/core/path.d.mts +3 -0
- package/dist/core/path.mjs +45 -0
- package/dist/core/path.mjs.map +1 -0
- package/dist/core/plugin.d.mts +3 -0
- package/dist/core/plugin.mjs +11 -0
- package/dist/core/reactivity.d.mts +3 -0
- package/dist/core/reactivity.mjs +189 -0
- package/dist/core/reactivity.mjs.map +1 -0
- package/dist/core-BL_H8fEZ.mjs +121 -0
- package/dist/core-BL_H8fEZ.mjs.map +1 -0
- package/dist/{core/cron.d.ts → cron-RKhH5TOd.d.mts} +16 -14
- package/dist/cron-RKhH5TOd.d.mts.map +1 -0
- package/dist/decorators-CQ93ak6Z.d.mts +154 -0
- package/dist/decorators-CQ93ak6Z.d.mts.map +1 -0
- package/dist/errors-te5Km00o.d.mts +68 -0
- package/dist/errors-te5Km00o.d.mts.map +1 -0
- package/dist/http/application.d.mts +220 -0
- package/dist/http/application.d.mts.map +1 -0
- package/dist/http/application.mjs +12 -0
- package/dist/http/bootstrap.d.mts +43 -0
- package/dist/http/bootstrap.d.mts.map +1 -0
- package/dist/http/bootstrap.mjs +12 -0
- package/dist/http/context.d.mts +131 -0
- package/dist/http/context.d.mts.map +1 -0
- package/dist/http/context.mjs +220 -0
- package/dist/http/context.mjs.map +1 -0
- package/dist/http/middleware/cors.d.mts +48 -0
- package/dist/http/middleware/cors.d.mts.map +1 -0
- package/dist/http/middleware/cors.mjs +83 -0
- package/dist/http/middleware/cors.mjs.map +1 -0
- package/dist/http/middleware/csrf.d.mts +52 -0
- package/dist/http/middleware/csrf.d.mts.map +1 -0
- package/dist/http/middleware/csrf.mjs +72 -0
- package/dist/http/middleware/csrf.mjs.map +1 -0
- package/dist/http/middleware/error-handler.d.mts +11 -0
- package/dist/http/middleware/error-handler.d.mts.map +1 -0
- package/dist/http/middleware/error-handler.mjs +52 -0
- package/dist/http/middleware/error-handler.mjs.map +1 -0
- package/dist/http/middleware/helmet.d.mts +41 -0
- package/dist/http/middleware/helmet.d.mts.map +1 -0
- package/dist/http/middleware/helmet.mjs +51 -0
- package/dist/http/middleware/helmet.mjs.map +1 -0
- package/dist/http/middleware/rate-limit.d.mts +56 -0
- package/dist/http/middleware/rate-limit.d.mts.map +1 -0
- package/dist/http/middleware/rate-limit.mjs +101 -0
- package/dist/http/middleware/rate-limit.mjs.map +1 -0
- package/dist/http/middleware/request-id.d.mts +10 -0
- package/dist/http/middleware/request-id.d.mts.map +1 -0
- package/dist/http/middleware/request-id.mjs +26 -0
- package/dist/http/middleware/request-id.mjs.map +1 -0
- package/dist/http/middleware/request-logger.d.mts +32 -0
- package/dist/http/middleware/request-logger.d.mts.map +1 -0
- package/dist/http/middleware/request-logger.mjs +49 -0
- package/dist/http/middleware/request-logger.mjs.map +1 -0
- package/dist/http/middleware/session.d.mts +67 -0
- package/dist/http/middleware/session.d.mts.map +1 -0
- package/dist/http/middleware/session.mjs +152 -0
- package/dist/http/middleware/session.mjs.map +1 -0
- package/dist/http/middleware/spa.d.mts +101 -0
- package/dist/http/middleware/spa.d.mts.map +1 -0
- package/dist/http/middleware/spa.mjs +108 -0
- package/dist/http/middleware/spa.mjs.map +1 -0
- package/dist/http/middleware/{upload.d.ts → upload.d.mts} +21 -17
- package/dist/http/middleware/upload.d.mts.map +1 -0
- package/dist/http/middleware/upload.mjs +191 -0
- package/dist/http/middleware/upload.mjs.map +1 -0
- package/dist/http/middleware/validate.d.mts +18 -0
- package/dist/http/middleware/validate.d.mts.map +1 -0
- package/dist/http/middleware/validate.mjs +62 -0
- package/dist/http/middleware/validate.mjs.map +1 -0
- package/dist/http/middleware/views.d.mts +62 -0
- package/dist/http/middleware/views.d.mts.map +1 -0
- package/dist/http/middleware/views.mjs +65 -0
- package/dist/http/middleware/views.mjs.map +1 -0
- package/dist/http/query/index.d.mts +3 -0
- package/dist/http/query/index.mjs +12 -0
- package/dist/http/{router-builder.d.ts → router-builder.d.mts} +9 -5
- package/dist/http/router-builder.d.mts.map +1 -0
- package/dist/http/router-builder.mjs +67 -0
- package/dist/http/router-builder.mjs.map +1 -0
- package/dist/index-C0gbnpSg.d.mts +107 -0
- package/dist/index-C0gbnpSg.d.mts.map +1 -0
- package/dist/index-Cls52etj.d.mts +148 -0
- package/dist/index-Cls52etj.d.mts.map +1 -0
- package/dist/index.d.mts +133 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +126 -0
- package/dist/index.mjs.map +1 -0
- package/dist/interfaces-D-48zotH.d.mts +52 -0
- package/dist/interfaces-D-48zotH.d.mts.map +1 -0
- package/dist/logger-Dzj-TF0t.d.mts +119 -0
- package/dist/logger-Dzj-TF0t.d.mts.map +1 -0
- package/dist/metadata-fmvikBA0.mjs +76 -0
- package/dist/metadata-fmvikBA0.mjs.map +1 -0
- package/dist/{core/path.d.ts → path-LmwfhfyH.d.mts} +7 -3
- package/dist/path-LmwfhfyH.d.mts.map +1 -0
- package/dist/plugin-DIoPIpSm.d.mts +95 -0
- package/dist/plugin-DIoPIpSm.d.mts.map +1 -0
- package/dist/query-7cdHF6ry.mjs +164 -0
- package/dist/query-7cdHF6ry.mjs.map +1 -0
- package/dist/{core/reactivity.d.ts → reactivity-BbS-99ow.d.mts} +21 -20
- package/dist/reactivity-BbS-99ow.d.mts.map +1 -0
- package/package.json +73 -43
- package/dist/chunk-DVVP7zzD.js +0 -7
- package/dist/core/adapter.d.ts +0 -109
- package/dist/core/adapter.d.ts.map +0 -1
- package/dist/core/adapter.js +0 -0
- package/dist/core/app-module.d.ts +0 -28
- package/dist/core/app-module.d.ts.map +0 -1
- package/dist/core/app-module.js +0 -0
- package/dist/core/cache.d.ts.map +0 -1
- package/dist/core/cache.js +0 -57
- package/dist/core/container.d.ts +0 -63
- package/dist/core/container.d.ts.map +0 -1
- package/dist/core/container.js +0 -117
- package/dist/core/cron.d.ts.map +0 -1
- package/dist/core/cron.js +0 -22
- package/dist/core/decorators.d.ts +0 -153
- package/dist/core/decorators.d.ts.map +0 -1
- package/dist/core/decorators.js +0 -141
- package/dist/core/errors.d.ts +0 -64
- package/dist/core/errors.d.ts.map +0 -1
- package/dist/core/errors.js +0 -67
- package/dist/core/index.d.ts +0 -14
- package/dist/core/index.d.ts.map +0 -1
- package/dist/core/interfaces.d.ts +0 -44
- package/dist/core/interfaces.d.ts.map +0 -1
- package/dist/core/interfaces.js +0 -25
- package/dist/core/logger.d.ts +0 -43
- package/dist/core/logger.d.ts.map +0 -1
- package/dist/core/logger.js +0 -54
- package/dist/core/path.d.ts.map +0 -1
- package/dist/core/path.js +0 -12
- package/dist/core/plugin.d.ts +0 -90
- package/dist/core/plugin.d.ts.map +0 -1
- package/dist/core/plugin.js +0 -0
- package/dist/core/reactivity.d.ts.map +0 -1
- package/dist/core/reactivity.js +0 -101
- package/dist/core-B6Okew3W.js +0 -7
- package/dist/http/application.d.ts +0 -103
- package/dist/http/application.d.ts.map +0 -1
- package/dist/http/application.js +0 -167
- package/dist/http/bootstrap.d.ts +0 -22
- package/dist/http/bootstrap.d.ts.map +0 -1
- package/dist/http/bootstrap.js +0 -40
- package/dist/http/context.d.ts +0 -129
- package/dist/http/context.d.ts.map +0 -1
- package/dist/http/context.js +0 -115
- package/dist/http/index.d.ts +0 -16
- package/dist/http/index.d.ts.map +0 -1
- package/dist/http/middleware/cors.d.ts +0 -43
- package/dist/http/middleware/cors.d.ts.map +0 -1
- package/dist/http/middleware/cors.js +0 -31
- package/dist/http/middleware/csrf.d.ts +0 -47
- package/dist/http/middleware/csrf.d.ts.map +0 -1
- package/dist/http/middleware/csrf.js +0 -25
- package/dist/http/middleware/error-handler.d.ts +0 -6
- package/dist/http/middleware/error-handler.d.ts.map +0 -1
- package/dist/http/middleware/error-handler.js +0 -37
- package/dist/http/middleware/helmet.d.ts +0 -36
- package/dist/http/middleware/helmet.d.ts.map +0 -1
- package/dist/http/middleware/helmet.js +0 -20
- package/dist/http/middleware/rate-limit.d.ts +0 -51
- package/dist/http/middleware/rate-limit.d.ts.map +0 -1
- package/dist/http/middleware/rate-limit.js +0 -46
- package/dist/http/middleware/request-id.d.ts +0 -5
- package/dist/http/middleware/request-id.d.ts.map +0 -1
- package/dist/http/middleware/request-id.js +0 -12
- package/dist/http/middleware/request-logger.d.ts +0 -27
- package/dist/http/middleware/request-logger.d.ts.map +0 -1
- package/dist/http/middleware/request-logger.js +0 -16
- package/dist/http/middleware/session.d.ts +0 -62
- package/dist/http/middleware/session.d.ts.map +0 -1
- package/dist/http/middleware/session.js +0 -76
- package/dist/http/middleware/spa.d.ts +0 -93
- package/dist/http/middleware/spa.d.ts.map +0 -1
- package/dist/http/middleware/spa.js +0 -52
- package/dist/http/middleware/upload.d.ts.map +0 -1
- package/dist/http/middleware/upload.js +0 -119
- package/dist/http/middleware/validate.d.ts +0 -13
- package/dist/http/middleware/validate.d.ts.map +0 -1
- package/dist/http/middleware/validate.js +0 -45
- package/dist/http/middleware/views.d.ts +0 -56
- package/dist/http/middleware/views.d.ts.map +0 -1
- package/dist/http/middleware/views.js +0 -18
- package/dist/http/query/index.d.ts +0 -4
- package/dist/http/query/index.d.ts.map +0 -1
- package/dist/http/query/index.js +0 -10
- package/dist/http/query/parse-query.d.ts +0 -44
- package/dist/http/query/parse-query.d.ts.map +0 -1
- package/dist/http/query/types.d.ts +0 -100
- package/dist/http/query/types.d.ts.map +0 -1
- package/dist/http/router-builder.d.ts.map +0 -1
- package/dist/http/router-builder.js +0 -37
- package/dist/index.d.ts +0 -25
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -103
- package/dist/query-Bym31XRp.js +0 -88
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
|
|
2
|
+
import { h as QueryFieldConfig, p as ParsedQuery } from "../index-Cls52etj.mjs";
|
|
3
|
+
import * as _$node_http0 from "node:http";
|
|
4
|
+
import { NextFunction, Request, Response } from "express";
|
|
5
|
+
|
|
6
|
+
//#region src/http/context.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* Unified request/response abstraction passed to every controller method.
|
|
9
|
+
* Shields handlers from raw Express objects and provides convenience methods.
|
|
10
|
+
*/
|
|
11
|
+
declare class RequestContext<TBody = any, TParams = any, TQuery = any> {
|
|
12
|
+
readonly req: Request;
|
|
13
|
+
readonly res: Response;
|
|
14
|
+
readonly next: NextFunction;
|
|
15
|
+
constructor(req: Request, res: Response, next: NextFunction);
|
|
16
|
+
/**
|
|
17
|
+
* Per-request metadata map shared across all RequestContext instances
|
|
18
|
+
* for the same request. Stored on `req` so middleware can pass data
|
|
19
|
+
* to handlers via `ctx.set()` / `ctx.get()`.
|
|
20
|
+
*/
|
|
21
|
+
private get metadata();
|
|
22
|
+
get body(): TBody;
|
|
23
|
+
get params(): TParams;
|
|
24
|
+
get query(): TQuery;
|
|
25
|
+
get headers(): _$node_http0.IncomingHttpHeaders;
|
|
26
|
+
get requestId(): string | undefined;
|
|
27
|
+
/** Session data (requires session middleware) */
|
|
28
|
+
get session(): any;
|
|
29
|
+
/**
|
|
30
|
+
* Parse the request query string into structured filters, sort, pagination, and search.
|
|
31
|
+
* Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).
|
|
32
|
+
*
|
|
33
|
+
* @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* ```ts
|
|
37
|
+
* @Get('/')
|
|
38
|
+
* async list(ctx: RequestContext) {
|
|
39
|
+
* const parsed = ctx.qs({
|
|
40
|
+
* filterable: ['status', 'priority'],
|
|
41
|
+
* sortable: ['createdAt', 'title'],
|
|
42
|
+
* })
|
|
43
|
+
* const q = drizzleAdapter.build(parsed, { columns })
|
|
44
|
+
* // ... use q.where, q.orderBy, q.limit, q.offset
|
|
45
|
+
* }
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
qs(fieldConfig?: QueryFieldConfig): ParsedQuery;
|
|
49
|
+
/** Single uploaded file (requires @FileUpload({ mode: 'single' })) */
|
|
50
|
+
get file(): any;
|
|
51
|
+
/** Array of uploaded files (requires @FileUpload({ mode: 'array' })) */
|
|
52
|
+
get files(): any[] | undefined;
|
|
53
|
+
get<T = any>(key: string): T | undefined;
|
|
54
|
+
set(key: string, value: any): void;
|
|
55
|
+
json(data: any, status?: number): Response<any, Record<string, any>>;
|
|
56
|
+
created(data: any): Response<any, Record<string, any>>;
|
|
57
|
+
noContent(): Response<any, Record<string, any>>;
|
|
58
|
+
notFound(message?: string): Response<any, Record<string, any>>;
|
|
59
|
+
badRequest(message: string): Response<any, Record<string, any>>;
|
|
60
|
+
html(content: string, status?: number): Response<any, Record<string, any>>;
|
|
61
|
+
download(buffer: Buffer, filename: string, contentType?: string): Response<any, Record<string, any>>;
|
|
62
|
+
/**
|
|
63
|
+
* Render a template using the registered view engine (EJS, Pug, Handlebars, etc.).
|
|
64
|
+
* Requires a ViewAdapter to be configured in bootstrap().
|
|
65
|
+
*
|
|
66
|
+
* @param template - Template name (without extension, relative to viewsDir)
|
|
67
|
+
* @param data - Data to pass to the template
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```ts
|
|
71
|
+
* ctx.render('dashboard', { user, title: 'Dashboard' })
|
|
72
|
+
* ctx.render('emails/welcome', { name: 'Alice' })
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
render(template: string, data?: Record<string, any>): void;
|
|
76
|
+
/**
|
|
77
|
+
* Parse query params and return a standardized paginated response.
|
|
78
|
+
* Calls `ctx.qs()` internally, then wraps your data with pagination meta.
|
|
79
|
+
*
|
|
80
|
+
* @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`
|
|
81
|
+
* @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* ```ts
|
|
85
|
+
* @Get('/')
|
|
86
|
+
* async list(ctx: RequestContext) {
|
|
87
|
+
* return ctx.paginate(
|
|
88
|
+
* async (parsed) => {
|
|
89
|
+
* const data = await db.select().from(users)
|
|
90
|
+
* .where(query.where).limit(parsed.pagination.limit)
|
|
91
|
+
* .offset(parsed.pagination.offset).all()
|
|
92
|
+
* const total = await db.select({ count: count() }).from(users).get()
|
|
93
|
+
* return { data, total: total?.count ?? 0 }
|
|
94
|
+
* },
|
|
95
|
+
* { filterable: ['name', 'role'], sortable: ['createdAt'] },
|
|
96
|
+
* )
|
|
97
|
+
* }
|
|
98
|
+
* ```
|
|
99
|
+
*/
|
|
100
|
+
paginate<T>(fetcher: (parsed: ParsedQuery) => Promise<{
|
|
101
|
+
data: T[];
|
|
102
|
+
total: number;
|
|
103
|
+
}>, fieldConfig?: QueryFieldConfig): Promise<Response<any, Record<string, any>>>;
|
|
104
|
+
/**
|
|
105
|
+
* Start an SSE (Server-Sent Events) stream.
|
|
106
|
+
* Sets the correct headers and returns helpers to send events.
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* ```ts
|
|
110
|
+
* @Get('/events')
|
|
111
|
+
* async stream(ctx: RequestContext) {
|
|
112
|
+
* const sse = ctx.sse()
|
|
113
|
+
*
|
|
114
|
+
* const interval = setInterval(() => {
|
|
115
|
+
* sse.send({ time: new Date().toISOString() }, 'tick')
|
|
116
|
+
* }, 1000)
|
|
117
|
+
*
|
|
118
|
+
* sse.onClose(() => clearInterval(interval))
|
|
119
|
+
* }
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
sse(): {
|
|
123
|
+
/** Send an SSE event with optional event name and id */send: (data: any, event?: string, id?: string) => void; /** Send a comment (keeps connection alive) */
|
|
124
|
+
comment: (text: string) => void; /** Register a callback when the client disconnects */
|
|
125
|
+
onClose: (fn: () => void) => void; /** End the SSE stream */
|
|
126
|
+
close: () => void;
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
//#endregion
|
|
130
|
+
export { RequestContext };
|
|
131
|
+
//# sourceMappingURL=context.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.mts","names":[],"sources":["../../src/http/context.ts"],"mappings":";;;;;;;;;AAYA;cAAa,cAAA;EAAA,SAEO,GAAA,EAAK,OAAA;EAAA,SACL,GAAA,EAAK,QAAA;EAAA,SACL,IAAA,EAAM,YAAA;cAFN,GAAA,EAAK,OAAA,EACL,GAAA,EAAK,QAAA,EACL,IAAA,EAAM,YAAA;EAFD;;;;;EAAA,YAUX,QAAA,CAAA;EAAA,IAQR,IAAA,CAAA,GAAQ,KAAA;EAAA,IAIR,MAAA,CAAA,GAAU,OAAA;EAAA,IAIV,KAAA,CAAA,GAAS,MAAA;EAAA,IAIT,OAAA,CAAA,GAJe,YAAA,CAIR,mBAAA;EAAA,IAIP,SAAA,CAAA;EA0DwB;EAAA,IArDxB,OAAA,CAAA;EAyDa;;;;;;;;;;;;;;;;;;;EAhCjB,EAAA,CAAG,WAAA,GAAc,gBAAA,GAAmB,WAAA;EAqGJ;EAAA,IA9F5B,IAAA,CAAA;EAzEsB;EAAA,IA8EtB,KAAA,CAAA;EAMJ,GAAA,SAAA,CAAa,GAAA,WAAc,CAAA;EAI3B,GAAA,CAAI,GAAA,UAAa,KAAA;EAMjB,IAAA,CAAK,IAAA,OAAW,MAAA,YAAY,QAAA,MAAA,MAAA;EAI5B,OAAA,CAAQ,IAAA,QAAS,QAAA,MAAA,MAAA;EAIjB,SAAA,CAAA,GAAS,QAAA,MAAA,MAAA;EAIT,QAAA,CAAS,OAAA,YAAqB,QAAA,MAAA,MAAA;EAI9B,UAAA,CAAW,OAAA,WAAe,QAAA,MAAA,MAAA;EAI1B,IAAA,CAAK,OAAA,UAAiB,MAAA,YAAY,QAAA,MAAA,MAAA;EAIlC,QAAA,CAAS,MAAA,EAAQ,MAAA,EAAQ,QAAA,UAAkB,WAAA,YAAwC,QAAA,MAAA,MAAA;EApHjE;;;;;;;;;;;;;EAuIlB,MAAA,CAAO,QAAA,UAAkB,IAAA,GAAM,MAAA;EArG3B;;;;;;;;;;;;;;;;;;;;;;;;EAiIE,QAAA,GAAA,CACJ,OAAA,GAAU,MAAA,EAAQ,WAAA,KAAgB,OAAA;IAAU,IAAA,EAAM,CAAA;IAAK,KAAA;EAAA,IACvD,WAAA,GAAc,gBAAA,GAAgB,OAAA,CAAA,QAAA,MAAA,MAAA;EA7DvB;;;;;;;;;;;;;;;;;;EAuGT,GAAA,CAAA;IAxEA,0EAyFoB,KAAA,WAAgB,EAAA,oBAzFL;qCA4BzB;uCACc"}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v2.1.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import { i as parseQuery } from "../query-7cdHF6ry.mjs";
|
|
12
|
+
//#region src/http/context.ts
|
|
13
|
+
/**
|
|
14
|
+
* Unified request/response abstraction passed to every controller method.
|
|
15
|
+
* Shields handlers from raw Express objects and provides convenience methods.
|
|
16
|
+
*/
|
|
17
|
+
var RequestContext = class {
|
|
18
|
+
constructor(req, res, next) {
|
|
19
|
+
this.req = req;
|
|
20
|
+
this.res = res;
|
|
21
|
+
this.next = next;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Per-request metadata map shared across all RequestContext instances
|
|
25
|
+
* for the same request. Stored on `req` so middleware can pass data
|
|
26
|
+
* to handlers via `ctx.set()` / `ctx.get()`.
|
|
27
|
+
*/
|
|
28
|
+
get metadata() {
|
|
29
|
+
const r = this.req;
|
|
30
|
+
if (!r.__ctxMeta) r.__ctxMeta = /* @__PURE__ */ new Map();
|
|
31
|
+
return r.__ctxMeta;
|
|
32
|
+
}
|
|
33
|
+
get body() {
|
|
34
|
+
return this.req.body;
|
|
35
|
+
}
|
|
36
|
+
get params() {
|
|
37
|
+
return this.req.params;
|
|
38
|
+
}
|
|
39
|
+
get query() {
|
|
40
|
+
return this.req.query;
|
|
41
|
+
}
|
|
42
|
+
get headers() {
|
|
43
|
+
return this.req.headers;
|
|
44
|
+
}
|
|
45
|
+
get requestId() {
|
|
46
|
+
return this.req.requestId ?? this.req.headers["x-request-id"];
|
|
47
|
+
}
|
|
48
|
+
/** Session data (requires session middleware) */
|
|
49
|
+
get session() {
|
|
50
|
+
return this.req.session;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Parse the request query string into structured filters, sort, pagination, and search.
|
|
54
|
+
* Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).
|
|
55
|
+
*
|
|
56
|
+
* @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```ts
|
|
60
|
+
* @Get('/')
|
|
61
|
+
* async list(ctx: RequestContext) {
|
|
62
|
+
* const parsed = ctx.qs({
|
|
63
|
+
* filterable: ['status', 'priority'],
|
|
64
|
+
* sortable: ['createdAt', 'title'],
|
|
65
|
+
* })
|
|
66
|
+
* const q = drizzleAdapter.build(parsed, { columns })
|
|
67
|
+
* // ... use q.where, q.orderBy, q.limit, q.offset
|
|
68
|
+
* }
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
qs(fieldConfig) {
|
|
72
|
+
return parseQuery(this.req.query, fieldConfig);
|
|
73
|
+
}
|
|
74
|
+
/** Single uploaded file (requires @FileUpload({ mode: 'single' })) */
|
|
75
|
+
get file() {
|
|
76
|
+
return this.req.file;
|
|
77
|
+
}
|
|
78
|
+
/** Array of uploaded files (requires @FileUpload({ mode: 'array' })) */
|
|
79
|
+
get files() {
|
|
80
|
+
return this.req.files;
|
|
81
|
+
}
|
|
82
|
+
get(key) {
|
|
83
|
+
return this.metadata.get(key);
|
|
84
|
+
}
|
|
85
|
+
set(key, value) {
|
|
86
|
+
this.metadata.set(key, value);
|
|
87
|
+
}
|
|
88
|
+
json(data, status = 200) {
|
|
89
|
+
return this.res.status(status).json(data);
|
|
90
|
+
}
|
|
91
|
+
created(data) {
|
|
92
|
+
return this.res.status(201).json(data);
|
|
93
|
+
}
|
|
94
|
+
noContent() {
|
|
95
|
+
return this.res.status(204).end();
|
|
96
|
+
}
|
|
97
|
+
notFound(message = "Not Found") {
|
|
98
|
+
return this.res.status(404).json({ message });
|
|
99
|
+
}
|
|
100
|
+
badRequest(message) {
|
|
101
|
+
return this.res.status(400).json({ message });
|
|
102
|
+
}
|
|
103
|
+
html(content, status = 200) {
|
|
104
|
+
return this.res.status(status).type("html").send(content);
|
|
105
|
+
}
|
|
106
|
+
download(buffer, filename, contentType = "application/octet-stream") {
|
|
107
|
+
this.res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
|
|
108
|
+
this.res.setHeader("Content-Type", contentType);
|
|
109
|
+
return this.res.send(buffer);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Render a template using the registered view engine (EJS, Pug, Handlebars, etc.).
|
|
113
|
+
* Requires a ViewAdapter to be configured in bootstrap().
|
|
114
|
+
*
|
|
115
|
+
* @param template - Template name (without extension, relative to viewsDir)
|
|
116
|
+
* @param data - Data to pass to the template
|
|
117
|
+
*
|
|
118
|
+
* @example
|
|
119
|
+
* ```ts
|
|
120
|
+
* ctx.render('dashboard', { user, title: 'Dashboard' })
|
|
121
|
+
* ctx.render('emails/welcome', { name: 'Alice' })
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
render(template, data = {}) {
|
|
125
|
+
return this.res.render(template, data);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Parse query params and return a standardized paginated response.
|
|
129
|
+
* Calls `ctx.qs()` internally, then wraps your data with pagination meta.
|
|
130
|
+
*
|
|
131
|
+
* @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`
|
|
132
|
+
* @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields
|
|
133
|
+
*
|
|
134
|
+
* @example
|
|
135
|
+
* ```ts
|
|
136
|
+
* @Get('/')
|
|
137
|
+
* async list(ctx: RequestContext) {
|
|
138
|
+
* return ctx.paginate(
|
|
139
|
+
* async (parsed) => {
|
|
140
|
+
* const data = await db.select().from(users)
|
|
141
|
+
* .where(query.where).limit(parsed.pagination.limit)
|
|
142
|
+
* .offset(parsed.pagination.offset).all()
|
|
143
|
+
* const total = await db.select({ count: count() }).from(users).get()
|
|
144
|
+
* return { data, total: total?.count ?? 0 }
|
|
145
|
+
* },
|
|
146
|
+
* { filterable: ['name', 'role'], sortable: ['createdAt'] },
|
|
147
|
+
* )
|
|
148
|
+
* }
|
|
149
|
+
* ```
|
|
150
|
+
*/
|
|
151
|
+
async paginate(fetcher, fieldConfig) {
|
|
152
|
+
const parsed = this.qs(fieldConfig);
|
|
153
|
+
const { data, total } = await fetcher(parsed);
|
|
154
|
+
const { page, limit } = parsed.pagination;
|
|
155
|
+
const totalPages = Math.ceil(total / limit) || 1;
|
|
156
|
+
const response = {
|
|
157
|
+
data,
|
|
158
|
+
meta: {
|
|
159
|
+
page,
|
|
160
|
+
limit,
|
|
161
|
+
total,
|
|
162
|
+
totalPages,
|
|
163
|
+
hasNext: page < totalPages,
|
|
164
|
+
hasPrev: page > 1
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
return this.json(response);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Start an SSE (Server-Sent Events) stream.
|
|
171
|
+
* Sets the correct headers and returns helpers to send events.
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* ```ts
|
|
175
|
+
* @Get('/events')
|
|
176
|
+
* async stream(ctx: RequestContext) {
|
|
177
|
+
* const sse = ctx.sse()
|
|
178
|
+
*
|
|
179
|
+
* const interval = setInterval(() => {
|
|
180
|
+
* sse.send({ time: new Date().toISOString() }, 'tick')
|
|
181
|
+
* }, 1000)
|
|
182
|
+
*
|
|
183
|
+
* sse.onClose(() => clearInterval(interval))
|
|
184
|
+
* }
|
|
185
|
+
* ```
|
|
186
|
+
*/
|
|
187
|
+
sse() {
|
|
188
|
+
this.res.writeHead(200, {
|
|
189
|
+
"Content-Type": "text/event-stream",
|
|
190
|
+
"Cache-Control": "no-cache",
|
|
191
|
+
Connection: "keep-alive",
|
|
192
|
+
"X-Accel-Buffering": "no"
|
|
193
|
+
});
|
|
194
|
+
this.res.flushHeaders();
|
|
195
|
+
const closeCallbacks = [];
|
|
196
|
+
this.req.on("close", () => {
|
|
197
|
+
for (const cb of closeCallbacks) cb();
|
|
198
|
+
});
|
|
199
|
+
return {
|
|
200
|
+
send: (data, event, id) => {
|
|
201
|
+
if (id) this.res.write(`id: ${id}\n`);
|
|
202
|
+
if (event) this.res.write(`event: ${event}\n`);
|
|
203
|
+
this.res.write(`data: ${JSON.stringify(data)}\n\n`);
|
|
204
|
+
},
|
|
205
|
+
comment: (text) => {
|
|
206
|
+
this.res.write(`: ${text}\n\n`);
|
|
207
|
+
},
|
|
208
|
+
onClose: (fn) => {
|
|
209
|
+
closeCallbacks.push(fn);
|
|
210
|
+
},
|
|
211
|
+
close: () => {
|
|
212
|
+
this.res.end();
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
//#endregion
|
|
218
|
+
export { RequestContext };
|
|
219
|
+
|
|
220
|
+
//# sourceMappingURL=context.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.mjs","names":[],"sources":["../../src/http/context.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\nimport {\n parseQuery,\n type ParsedQuery,\n type QueryFieldConfig,\n type PaginatedResponse,\n} from './query'\n\n/**\n * Unified request/response abstraction passed to every controller method.\n * Shields handlers from raw Express objects and provides convenience methods.\n */\nexport class RequestContext<TBody = any, TParams = any, TQuery = any> {\n constructor(\n public readonly req: Request,\n public readonly res: Response,\n public readonly next: NextFunction,\n ) {}\n\n /**\n * Per-request metadata map shared across all RequestContext instances\n * for the same request. Stored on `req` so middleware can pass data\n * to handlers via `ctx.set()` / `ctx.get()`.\n */\n private get metadata(): Map<string, any> {\n const r = this.req as any\n if (!r.__ctxMeta) r.__ctxMeta = new Map<string, any>()\n return r.__ctxMeta\n }\n\n // ── Request Data ────────────────────────────────────────────────────\n\n get body(): TBody {\n return this.req.body as TBody\n }\n\n get params(): TParams {\n return this.req.params as TParams\n }\n\n get query(): TQuery {\n return this.req.query as TQuery\n }\n\n get headers() {\n return this.req.headers\n }\n\n get requestId(): string | undefined {\n return (this.req as any).requestId ?? (this.req.headers['x-request-id'] as string | undefined)\n }\n\n /** Session data (requires session middleware) */\n get session(): any {\n return (this.req as any).session\n }\n\n // ── Query String Parsing ───────────────────────────────────────────\n\n /**\n * Parse the request query string into structured filters, sort, pagination, and search.\n * Pass the result to an ORM query builder adapter (Drizzle, Prisma, Sequelize, etc.).\n *\n * @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields\n *\n * @example\n * ```ts\n * @Get('/')\n * async list(ctx: RequestContext) {\n * const parsed = ctx.qs({\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt', 'title'],\n * })\n * const q = drizzleAdapter.build(parsed, { columns })\n * // ... use q.where, q.orderBy, q.limit, q.offset\n * }\n * ```\n */\n qs(fieldConfig?: QueryFieldConfig): ParsedQuery {\n return parseQuery(this.req.query as Record<string, any>, fieldConfig)\n }\n\n // ── File Uploads ────────────────────────────────────────────────────\n\n /** Single uploaded file (requires @FileUpload({ mode: 'single' })) */\n get file(): any {\n return (this.req as any).file\n }\n\n /** Array of uploaded files (requires @FileUpload({ mode: 'array' })) */\n get files(): any[] | undefined {\n return (this.req as any).files\n }\n\n // ── Metadata Store ──────────────────────────────────────────────────\n\n get<T = any>(key: string): T | undefined {\n return this.metadata.get(key) as T | undefined\n }\n\n set(key: string, value: any): void {\n this.metadata.set(key, value)\n }\n\n // ── Response Helpers ────────────────────────────────────────────────\n\n json(data: any, status = 200) {\n return this.res.status(status).json(data)\n }\n\n created(data: any) {\n return this.res.status(201).json(data)\n }\n\n noContent() {\n return this.res.status(204).end()\n }\n\n notFound(message = 'Not Found') {\n return this.res.status(404).json({ message })\n }\n\n badRequest(message: string) {\n return this.res.status(400).json({ message })\n }\n\n html(content: string, status = 200) {\n return this.res.status(status).type('html').send(content)\n }\n\n download(buffer: Buffer, filename: string, contentType = 'application/octet-stream') {\n this.res.setHeader('Content-Disposition', `attachment; filename=\"${filename}\"`)\n this.res.setHeader('Content-Type', contentType)\n return this.res.send(buffer)\n }\n\n /**\n * Render a template using the registered view engine (EJS, Pug, Handlebars, etc.).\n * Requires a ViewAdapter to be configured in bootstrap().\n *\n * @param template - Template name (without extension, relative to viewsDir)\n * @param data - Data to pass to the template\n *\n * @example\n * ```ts\n * ctx.render('dashboard', { user, title: 'Dashboard' })\n * ctx.render('emails/welcome', { name: 'Alice' })\n * ```\n */\n render(template: string, data: Record<string, any> = {}) {\n return this.res.render(template, data)\n }\n\n /**\n * Parse query params and return a standardized paginated response.\n * Calls `ctx.qs()` internally, then wraps your data with pagination meta.\n *\n * @param fetcher - Async function that receives ParsedQuery and returns `{ data, total }`\n * @param fieldConfig - Optional whitelist for filterable, sortable, searchable fields\n *\n * @example\n * ```ts\n * @Get('/')\n * async list(ctx: RequestContext) {\n * return ctx.paginate(\n * async (parsed) => {\n * const data = await db.select().from(users)\n * .where(query.where).limit(parsed.pagination.limit)\n * .offset(parsed.pagination.offset).all()\n * const total = await db.select({ count: count() }).from(users).get()\n * return { data, total: total?.count ?? 0 }\n * },\n * { filterable: ['name', 'role'], sortable: ['createdAt'] },\n * )\n * }\n * ```\n */\n async paginate<T>(\n fetcher: (parsed: ParsedQuery) => Promise<{ data: T[]; total: number }>,\n fieldConfig?: QueryFieldConfig,\n ) {\n const parsed = this.qs(fieldConfig)\n const { data, total } = await fetcher(parsed)\n const { page, limit } = parsed.pagination\n const totalPages = Math.ceil(total / limit) || 1\n\n const response: PaginatedResponse<T> = {\n data,\n meta: {\n page,\n limit,\n total,\n totalPages,\n hasNext: page < totalPages,\n hasPrev: page > 1,\n },\n }\n\n return this.json(response)\n }\n\n // ── Server-Sent Events ──────────────────────────────────────────────\n\n /**\n * Start an SSE (Server-Sent Events) stream.\n * Sets the correct headers and returns helpers to send events.\n *\n * @example\n * ```ts\n * @Get('/events')\n * async stream(ctx: RequestContext) {\n * const sse = ctx.sse()\n *\n * const interval = setInterval(() => {\n * sse.send({ time: new Date().toISOString() }, 'tick')\n * }, 1000)\n *\n * sse.onClose(() => clearInterval(interval))\n * }\n * ```\n */\n sse() {\n this.res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n })\n this.res.flushHeaders()\n\n const closeCallbacks: Array<() => void> = []\n\n this.req.on('close', () => {\n for (const cb of closeCallbacks) cb()\n })\n\n return {\n /** Send an SSE event with optional event name and id */\n send: (data: any, event?: string, id?: string) => {\n if (id) this.res.write(`id: ${id}\\n`)\n if (event) this.res.write(`event: ${event}\\n`)\n this.res.write(`data: ${JSON.stringify(data)}\\n\\n`)\n },\n /** Send a comment (keeps connection alive) */\n comment: (text: string) => {\n this.res.write(`: ${text}\\n\\n`)\n },\n /** Register a callback when the client disconnects */\n onClose: (fn: () => void) => {\n closeCallbacks.push(fn)\n },\n /** End the SSE stream */\n close: () => {\n this.res.end()\n },\n }\n }\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
|
|
2
|
+
import { NextFunction, Request, Response } from "express";
|
|
3
|
+
|
|
4
|
+
//#region src/http/middleware/cors.d.ts
|
|
5
|
+
interface CorsOptions {
|
|
6
|
+
/** Allowed origin(s). `true` reflects request origin, `'*'` allows all, `false` rejects all. Default: `false` (restrictive) */
|
|
7
|
+
origin?: boolean | string | RegExp | (string | RegExp)[];
|
|
8
|
+
/** Allowed HTTP methods. Default: `['GET','HEAD','PUT','PATCH','POST','DELETE']` */
|
|
9
|
+
methods?: string[];
|
|
10
|
+
/** Allowed request headers. Default: reflects `Access-Control-Request-Headers` */
|
|
11
|
+
allowedHeaders?: string[];
|
|
12
|
+
/** Headers exposed to the browser. Default: none */
|
|
13
|
+
exposedHeaders?: string[];
|
|
14
|
+
/** Allow credentials (cookies, authorization). Default: false */
|
|
15
|
+
credentials?: boolean;
|
|
16
|
+
/** Preflight cache duration in seconds. Default: 86400 (24h) */
|
|
17
|
+
maxAge?: number;
|
|
18
|
+
/** Handle preflight OPTIONS requests. Default: true */
|
|
19
|
+
preflight?: boolean;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* CORS middleware with correct spec behavior.
|
|
23
|
+
*
|
|
24
|
+
* - Reflects origin from allowlist (sets `Vary: Origin`)
|
|
25
|
+
* - Handles preflight `OPTIONS` with `204 No Content`
|
|
26
|
+
* - Supports string, regex, and array origin matching
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```ts
|
|
30
|
+
* // Allow all origins
|
|
31
|
+
* bootstrap({ middleware: [cors(), express.json()] })
|
|
32
|
+
*
|
|
33
|
+
* // Allowlist specific origins
|
|
34
|
+
* bootstrap({
|
|
35
|
+
* middleware: [
|
|
36
|
+
* cors({
|
|
37
|
+
* origin: ['https://app.example.com', /\.example\.com$/],
|
|
38
|
+
* credentials: true,
|
|
39
|
+
* }),
|
|
40
|
+
* express.json(),
|
|
41
|
+
* ],
|
|
42
|
+
* })
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
declare function cors(options?: CorsOptions): (req: Request, res: Response, next: NextFunction) => void;
|
|
46
|
+
//#endregion
|
|
47
|
+
export { CorsOptions, cors };
|
|
48
|
+
//# sourceMappingURL=cors.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cors.d.mts","names":[],"sources":["../../../src/http/middleware/cors.ts"],"mappings":";;;;UAEiB,WAAA;;EAEf,MAAA,sBAA4B,MAAA,aAAmB,MAAA;EAFrB;EAI1B,OAAA;EAFqD;EAIrD,cAAA;EAJ4B;EAM5B,cAAA;EAJA;EAMA,WAAA;EAFA;EAIA,MAAA;EAAA;EAEA,SAAA;AAAA;;AAyCF;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,IAAA,CAAK,OAAA,GAAS,WAAA,IAWpB,GAAA,EAAK,OAAA,EAAS,GAAA,EAAK,QAAA,EAAU,IAAA,EAAM,YAAA"}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v2.1.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
//#region src/http/middleware/cors.ts
|
|
12
|
+
const DEFAULT_METHODS = [
|
|
13
|
+
"GET",
|
|
14
|
+
"HEAD",
|
|
15
|
+
"PUT",
|
|
16
|
+
"PATCH",
|
|
17
|
+
"POST",
|
|
18
|
+
"DELETE"
|
|
19
|
+
];
|
|
20
|
+
function isOriginAllowed(requestOrigin, allowed) {
|
|
21
|
+
if (allowed === true || allowed === "*") return true;
|
|
22
|
+
if (typeof allowed === "string") return requestOrigin === allowed;
|
|
23
|
+
if (allowed instanceof RegExp) return allowed.test(requestOrigin);
|
|
24
|
+
if (Array.isArray(allowed)) return allowed.some((pattern) => typeof pattern === "string" ? requestOrigin === pattern : pattern.test(requestOrigin));
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* CORS middleware with correct spec behavior.
|
|
29
|
+
*
|
|
30
|
+
* - Reflects origin from allowlist (sets `Vary: Origin`)
|
|
31
|
+
* - Handles preflight `OPTIONS` with `204 No Content`
|
|
32
|
+
* - Supports string, regex, and array origin matching
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```ts
|
|
36
|
+
* // Allow all origins
|
|
37
|
+
* bootstrap({ middleware: [cors(), express.json()] })
|
|
38
|
+
*
|
|
39
|
+
* // Allowlist specific origins
|
|
40
|
+
* bootstrap({
|
|
41
|
+
* middleware: [
|
|
42
|
+
* cors({
|
|
43
|
+
* origin: ['https://app.example.com', /\.example\.com$/],
|
|
44
|
+
* credentials: true,
|
|
45
|
+
* }),
|
|
46
|
+
* express.json(),
|
|
47
|
+
* ],
|
|
48
|
+
* })
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
function cors(options = {}) {
|
|
52
|
+
const { origin = false, methods = DEFAULT_METHODS, allowedHeaders, exposedHeaders, credentials = false, maxAge = 86400, preflight = true } = options;
|
|
53
|
+
return (req, res, next) => {
|
|
54
|
+
const requestOrigin = req.headers.origin;
|
|
55
|
+
if (origin === "*" && !credentials) res.setHeader("Access-Control-Allow-Origin", "*");
|
|
56
|
+
else if (requestOrigin) {
|
|
57
|
+
if (isOriginAllowed(requestOrigin, origin)) {
|
|
58
|
+
res.setHeader("Access-Control-Allow-Origin", requestOrigin);
|
|
59
|
+
res.setHeader("Vary", "Origin");
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (credentials) res.setHeader("Access-Control-Allow-Credentials", "true");
|
|
63
|
+
if (exposedHeaders?.length) res.setHeader("Access-Control-Expose-Headers", exposedHeaders.join(", "));
|
|
64
|
+
if (preflight && req.method === "OPTIONS") {
|
|
65
|
+
res.setHeader("Access-Control-Allow-Methods", methods.join(", "));
|
|
66
|
+
const reqHeaders = allowedHeaders ?? req.headers["access-control-request-headers"];
|
|
67
|
+
if (reqHeaders) {
|
|
68
|
+
const value = Array.isArray(reqHeaders) ? reqHeaders.join(", ") : reqHeaders;
|
|
69
|
+
res.setHeader("Access-Control-Allow-Headers", value);
|
|
70
|
+
}
|
|
71
|
+
if (maxAge) res.setHeader("Access-Control-Max-Age", String(maxAge));
|
|
72
|
+
res.statusCode = 204;
|
|
73
|
+
res.setHeader("Content-Length", "0");
|
|
74
|
+
res.end();
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
next();
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
//#endregion
|
|
81
|
+
export { cors };
|
|
82
|
+
|
|
83
|
+
//# sourceMappingURL=cors.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cors.mjs","names":[],"sources":["../../../src/http/middleware/cors.ts"],"sourcesContent":["import type { Request, Response, NextFunction } from 'express'\n\nexport interface CorsOptions {\n /** Allowed origin(s). `true` reflects request origin, `'*'` allows all, `false` rejects all. Default: `false` (restrictive) */\n origin?: boolean | string | RegExp | (string | RegExp)[]\n /** Allowed HTTP methods. Default: `['GET','HEAD','PUT','PATCH','POST','DELETE']` */\n methods?: string[]\n /** Allowed request headers. Default: reflects `Access-Control-Request-Headers` */\n allowedHeaders?: string[]\n /** Headers exposed to the browser. Default: none */\n exposedHeaders?: string[]\n /** Allow credentials (cookies, authorization). Default: false */\n credentials?: boolean\n /** Preflight cache duration in seconds. Default: 86400 (24h) */\n maxAge?: number\n /** Handle preflight OPTIONS requests. Default: true */\n preflight?: boolean\n}\n\nconst DEFAULT_METHODS = ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE']\n\nfunction isOriginAllowed(requestOrigin: string, allowed: CorsOptions['origin']): boolean {\n if (allowed === true || allowed === '*') return true\n if (typeof allowed === 'string') return requestOrigin === allowed\n if (allowed instanceof RegExp) return allowed.test(requestOrigin)\n if (Array.isArray(allowed)) {\n return allowed.some((pattern) =>\n typeof pattern === 'string' ? requestOrigin === pattern : pattern.test(requestOrigin),\n )\n }\n return false\n}\n\n/**\n * CORS middleware with correct spec behavior.\n *\n * - Reflects origin from allowlist (sets `Vary: Origin`)\n * - Handles preflight `OPTIONS` with `204 No Content`\n * - Supports string, regex, and array origin matching\n *\n * @example\n * ```ts\n * // Allow all origins\n * bootstrap({ middleware: [cors(), express.json()] })\n *\n * // Allowlist specific origins\n * bootstrap({\n * middleware: [\n * cors({\n * origin: ['https://app.example.com', /\\.example\\.com$/],\n * credentials: true,\n * }),\n * express.json(),\n * ],\n * })\n * ```\n */\nexport function cors(options: CorsOptions = {}) {\n const {\n origin = false,\n methods = DEFAULT_METHODS,\n allowedHeaders,\n exposedHeaders,\n credentials = false,\n maxAge = 86400,\n preflight = true,\n } = options\n\n return (req: Request, res: Response, next: NextFunction) => {\n const requestOrigin = req.headers.origin\n\n // Determine the Access-Control-Allow-Origin value\n if (origin === '*' && !credentials) {\n res.setHeader('Access-Control-Allow-Origin', '*')\n } else if (requestOrigin) {\n if (isOriginAllowed(requestOrigin, origin)) {\n res.setHeader('Access-Control-Allow-Origin', requestOrigin)\n // Must vary by Origin when reflecting — CDN/proxy correctness\n res.setHeader('Vary', 'Origin')\n }\n }\n\n if (credentials) {\n res.setHeader('Access-Control-Allow-Credentials', 'true')\n }\n\n if (exposedHeaders?.length) {\n res.setHeader('Access-Control-Expose-Headers', exposedHeaders.join(', '))\n }\n\n // Preflight handling\n if (preflight && req.method === 'OPTIONS') {\n res.setHeader('Access-Control-Allow-Methods', methods.join(', '))\n\n const reqHeaders = allowedHeaders ?? req.headers['access-control-request-headers']\n if (reqHeaders) {\n const value = Array.isArray(reqHeaders) ? reqHeaders.join(', ') : reqHeaders\n res.setHeader('Access-Control-Allow-Headers', value)\n }\n\n if (maxAge) {\n res.setHeader('Access-Control-Max-Age', String(maxAge))\n }\n\n res.statusCode = 204\n res.setHeader('Content-Length', '0')\n res.end()\n return\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAM,kBAAkB;CAAC;CAAO;CAAQ;CAAO;CAAS;CAAQ;CAAS;AAEzE,SAAS,gBAAgB,eAAuB,SAAyC;AACvF,KAAI,YAAY,QAAQ,YAAY,IAAK,QAAO;AAChD,KAAI,OAAO,YAAY,SAAU,QAAO,kBAAkB;AAC1D,KAAI,mBAAmB,OAAQ,QAAO,QAAQ,KAAK,cAAc;AACjE,KAAI,MAAM,QAAQ,QAAQ,CACxB,QAAO,QAAQ,MAAM,YACnB,OAAO,YAAY,WAAW,kBAAkB,UAAU,QAAQ,KAAK,cAAc,CACtF;AAEH,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BT,SAAgB,KAAK,UAAuB,EAAE,EAAE;CAC9C,MAAM,EACJ,SAAS,OACT,UAAU,iBACV,gBACA,gBACA,cAAc,OACd,SAAS,OACT,YAAY,SACV;AAEJ,SAAQ,KAAc,KAAe,SAAuB;EAC1D,MAAM,gBAAgB,IAAI,QAAQ;AAGlC,MAAI,WAAW,OAAO,CAAC,YACrB,KAAI,UAAU,+BAA+B,IAAI;WACxC;OACL,gBAAgB,eAAe,OAAO,EAAE;AAC1C,QAAI,UAAU,+BAA+B,cAAc;AAE3D,QAAI,UAAU,QAAQ,SAAS;;;AAInC,MAAI,YACF,KAAI,UAAU,oCAAoC,OAAO;AAG3D,MAAI,gBAAgB,OAClB,KAAI,UAAU,iCAAiC,eAAe,KAAK,KAAK,CAAC;AAI3E,MAAI,aAAa,IAAI,WAAW,WAAW;AACzC,OAAI,UAAU,gCAAgC,QAAQ,KAAK,KAAK,CAAC;GAEjE,MAAM,aAAa,kBAAkB,IAAI,QAAQ;AACjD,OAAI,YAAY;IACd,MAAM,QAAQ,MAAM,QAAQ,WAAW,GAAG,WAAW,KAAK,KAAK,GAAG;AAClE,QAAI,UAAU,gCAAgC,MAAM;;AAGtD,OAAI,OACF,KAAI,UAAU,0BAA0B,OAAO,OAAO,CAAC;AAGzD,OAAI,aAAa;AACjB,OAAI,UAAU,kBAAkB,IAAI;AACpC,OAAI,KAAK;AACT;;AAGF,QAAM"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
|
|
2
|
+
import { NextFunction, Request, Response } from "express";
|
|
3
|
+
|
|
4
|
+
//#region src/http/middleware/csrf.d.ts
|
|
5
|
+
interface CsrfOptions {
|
|
6
|
+
/** Cookie name for the CSRF token (default: '_csrf') */
|
|
7
|
+
cookie?: string;
|
|
8
|
+
/** Header name to check for the token (default: 'x-csrf-token') */
|
|
9
|
+
header?: string;
|
|
10
|
+
/** HTTP methods that require CSRF validation (default: POST, PUT, PATCH, DELETE) */
|
|
11
|
+
methods?: string[];
|
|
12
|
+
/** Paths to exclude from CSRF checks (e.g. webhooks) */
|
|
13
|
+
ignorePaths?: string[];
|
|
14
|
+
/** Token byte length before hex encoding (default: 32 = 64 hex chars) */
|
|
15
|
+
tokenLength?: number;
|
|
16
|
+
/** Cookie options */
|
|
17
|
+
cookieOptions?: {
|
|
18
|
+
httpOnly?: boolean;
|
|
19
|
+
sameSite?: 'strict' | 'lax' | 'none';
|
|
20
|
+
secure?: boolean;
|
|
21
|
+
path?: string;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Double-submit cookie CSRF protection middleware.
|
|
26
|
+
*
|
|
27
|
+
* On every request, sets a CSRF token cookie. For state-changing methods
|
|
28
|
+
* (POST, PUT, PATCH, DELETE), validates that the request header matches
|
|
29
|
+
* the cookie value.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* import { csrf } from '@forinda/kickjs-http'
|
|
34
|
+
*
|
|
35
|
+
* bootstrap({
|
|
36
|
+
* modules,
|
|
37
|
+
* middleware: [
|
|
38
|
+
* cookieParser(),
|
|
39
|
+
* csrf(),
|
|
40
|
+
* // ... other middleware
|
|
41
|
+
* ],
|
|
42
|
+
* })
|
|
43
|
+
* ```
|
|
44
|
+
*
|
|
45
|
+
* Client usage:
|
|
46
|
+
* 1. Read the `_csrf` cookie value
|
|
47
|
+
* 2. Send it in the `x-csrf-token` header on every mutating request
|
|
48
|
+
*/
|
|
49
|
+
declare function csrf(options?: CsrfOptions): (req: Request, res: Response, next: NextFunction) => void | Response<any, Record<string, any>>;
|
|
50
|
+
//#endregion
|
|
51
|
+
export { CsrfOptions, csrf };
|
|
52
|
+
//# sourceMappingURL=csrf.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"csrf.d.mts","names":[],"sources":["../../../src/http/middleware/csrf.ts"],"mappings":";;;;UAGiB,WAAA;;EAEf,MAAA;EAF0B;EAI1B,MAAA;EAJ0B;EAM1B,OAAA;EAFA;EAIA,WAAA;EAAA;EAEA,WAAA;EAEA;EAAA,aAAA;IACE,QAAA;IACA,QAAA;IACA,MAAA;IACA,IAAA;EAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6BY,IAAA,CAAK,OAAA,GAAS,WAAA,IAgBpB,GAAA,EAAK,OAAA,EAAS,GAAA,EAAK,QAAA,EAAU,IAAA,EAAM,YAAA,YAAY,QAAA,MAAA,MAAA"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v2.1.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import { randomBytes } from "node:crypto";
|
|
12
|
+
//#region src/http/middleware/csrf.ts
|
|
13
|
+
/**
|
|
14
|
+
* Double-submit cookie CSRF protection middleware.
|
|
15
|
+
*
|
|
16
|
+
* On every request, sets a CSRF token cookie. For state-changing methods
|
|
17
|
+
* (POST, PUT, PATCH, DELETE), validates that the request header matches
|
|
18
|
+
* the cookie value.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* import { csrf } from '@forinda/kickjs-http'
|
|
23
|
+
*
|
|
24
|
+
* bootstrap({
|
|
25
|
+
* modules,
|
|
26
|
+
* middleware: [
|
|
27
|
+
* cookieParser(),
|
|
28
|
+
* csrf(),
|
|
29
|
+
* // ... other middleware
|
|
30
|
+
* ],
|
|
31
|
+
* })
|
|
32
|
+
* ```
|
|
33
|
+
*
|
|
34
|
+
* Client usage:
|
|
35
|
+
* 1. Read the `_csrf` cookie value
|
|
36
|
+
* 2. Send it in the `x-csrf-token` header on every mutating request
|
|
37
|
+
*/
|
|
38
|
+
function csrf(options = {}) {
|
|
39
|
+
const cookieName = options.cookie ?? "_csrf";
|
|
40
|
+
const headerName = options.header ?? "x-csrf-token";
|
|
41
|
+
const protectedMethods = new Set((options.methods ?? [
|
|
42
|
+
"POST",
|
|
43
|
+
"PUT",
|
|
44
|
+
"PATCH",
|
|
45
|
+
"DELETE"
|
|
46
|
+
]).map((m) => m.toUpperCase()));
|
|
47
|
+
const ignorePaths = new Set(options.ignorePaths ?? []);
|
|
48
|
+
const tokenLength = options.tokenLength ?? 32;
|
|
49
|
+
const cookieOpts = {
|
|
50
|
+
httpOnly: true,
|
|
51
|
+
sameSite: "strict",
|
|
52
|
+
secure: process.env.NODE_ENV === "production",
|
|
53
|
+
path: "/",
|
|
54
|
+
...options.cookieOptions
|
|
55
|
+
};
|
|
56
|
+
return (req, res, next) => {
|
|
57
|
+
let token = (req.cookies || {})[cookieName];
|
|
58
|
+
if (!token) {
|
|
59
|
+
token = randomBytes(tokenLength).toString("hex");
|
|
60
|
+
res.cookie(cookieName, token, cookieOpts);
|
|
61
|
+
}
|
|
62
|
+
if (!protectedMethods.has(req.method.toUpperCase())) return next();
|
|
63
|
+
if (ignorePaths.has(req.path)) return next();
|
|
64
|
+
const headerToken = req.headers[headerName];
|
|
65
|
+
if (!headerToken || headerToken !== token) return res.status(403).json({ message: "CSRF token mismatch" });
|
|
66
|
+
next();
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
70
|
+
export { csrf };
|
|
71
|
+
|
|
72
|
+
//# sourceMappingURL=csrf.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"csrf.mjs","names":[],"sources":["../../../src/http/middleware/csrf.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport type { Request, Response, NextFunction } from 'express'\n\nexport interface CsrfOptions {\n /** Cookie name for the CSRF token (default: '_csrf') */\n cookie?: string\n /** Header name to check for the token (default: 'x-csrf-token') */\n header?: string\n /** HTTP methods that require CSRF validation (default: POST, PUT, PATCH, DELETE) */\n methods?: string[]\n /** Paths to exclude from CSRF checks (e.g. webhooks) */\n ignorePaths?: string[]\n /** Token byte length before hex encoding (default: 32 = 64 hex chars) */\n tokenLength?: number\n /** Cookie options */\n cookieOptions?: {\n httpOnly?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n secure?: boolean\n path?: string\n }\n}\n\n/**\n * Double-submit cookie CSRF protection middleware.\n *\n * On every request, sets a CSRF token cookie. For state-changing methods\n * (POST, PUT, PATCH, DELETE), validates that the request header matches\n * the cookie value.\n *\n * @example\n * ```ts\n * import { csrf } from '@forinda/kickjs-http'\n *\n * bootstrap({\n * modules,\n * middleware: [\n * cookieParser(),\n * csrf(),\n * // ... other middleware\n * ],\n * })\n * ```\n *\n * Client usage:\n * 1. Read the `_csrf` cookie value\n * 2. Send it in the `x-csrf-token` header on every mutating request\n */\nexport function csrf(options: CsrfOptions = {}) {\n const cookieName = options.cookie ?? '_csrf'\n const headerName = options.header ?? 'x-csrf-token'\n const protectedMethods = new Set(\n (options.methods ?? ['POST', 'PUT', 'PATCH', 'DELETE']).map((m) => m.toUpperCase()),\n )\n const ignorePaths = new Set(options.ignorePaths ?? [])\n const tokenLength = options.tokenLength ?? 32\n const cookieOpts = {\n httpOnly: true,\n sameSite: 'strict' as const,\n secure: process.env.NODE_ENV === 'production',\n path: '/',\n ...options.cookieOptions,\n }\n\n return (req: Request, res: Response, next: NextFunction) => {\n // Generate or reuse CSRF token\n const cookies = (req as any).cookies || {}\n let token = cookies[cookieName]\n\n if (!token) {\n token = randomBytes(tokenLength).toString('hex')\n res.cookie(cookieName, token, cookieOpts)\n }\n\n // Skip validation for safe methods and ignored paths\n if (!protectedMethods.has(req.method.toUpperCase())) {\n return next()\n }\n\n if (ignorePaths.has(req.path)) {\n return next()\n }\n\n // Validate: header token must match cookie token\n const headerToken = req.headers[headerName] as string | undefined\n\n if (!headerToken || headerToken !== token) {\n return res.status(403).json({\n message: 'CSRF token mismatch',\n })\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,KAAK,UAAuB,EAAE,EAAE;CAC9C,MAAM,aAAa,QAAQ,UAAU;CACrC,MAAM,aAAa,QAAQ,UAAU;CACrC,MAAM,mBAAmB,IAAI,KAC1B,QAAQ,WAAW;EAAC;EAAQ;EAAO;EAAS;EAAS,EAAE,KAAK,MAAM,EAAE,aAAa,CAAC,CACpF;CACD,MAAM,cAAc,IAAI,IAAI,QAAQ,eAAe,EAAE,CAAC;CACtD,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,aAAa;EACjB,UAAU;EACV,UAAU;EACV,QAAQ,QAAQ,IAAI,aAAa;EACjC,MAAM;EACN,GAAG,QAAQ;EACZ;AAED,SAAQ,KAAc,KAAe,SAAuB;EAG1D,IAAI,SADa,IAAY,WAAW,EAAE,EACtB;AAEpB,MAAI,CAAC,OAAO;AACV,WAAQ,YAAY,YAAY,CAAC,SAAS,MAAM;AAChD,OAAI,OAAO,YAAY,OAAO,WAAW;;AAI3C,MAAI,CAAC,iBAAiB,IAAI,IAAI,OAAO,aAAa,CAAC,CACjD,QAAO,MAAM;AAGf,MAAI,YAAY,IAAI,IAAI,KAAK,CAC3B,QAAO,MAAM;EAIf,MAAM,cAAc,IAAI,QAAQ;AAEhC,MAAI,CAAC,eAAe,gBAAgB,MAClC,QAAO,IAAI,OAAO,IAAI,CAAC,KAAK,EAC1B,SAAS,uBACV,CAAC;AAGJ,QAAM"}
|