@forinda/kickjs 2.0.1 → 2.2.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 +63 -20
- package/dist/adapter-wuoBNkNs.d.mts +122 -0
- package/dist/adapter-wuoBNkNs.d.mts.map +1 -0
- package/dist/app-module-DOBmxARW.d.mts +40 -0
- package/dist/app-module-DOBmxARW.d.mts.map +1 -0
- package/dist/application-C5Q720a2.mjs +449 -0
- package/dist/application-C5Q720a2.mjs.map +1 -0
- package/dist/bootstrap-dEN6SjBl.mjs +205 -0
- package/dist/bootstrap-dEN6SjBl.mjs.map +1 -0
- package/dist/{core/cache.d.ts → cache-PufEhr0n.d.mts} +33 -31
- package/dist/cache-PufEhr0n.d.mts.map +1 -0
- package/dist/chunk-C9tIbwLT.mjs +15 -0
- package/dist/container-B7jFEbPE.mjs +496 -0
- package/dist/container-B7jFEbPE.mjs.map +1 -0
- package/dist/container-CcgV8eHL.d.mts +253 -0
- package/dist/container-CcgV8eHL.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 +12 -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 +219 -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-CMgIoRvg.mjs +121 -0
- package/dist/core-CMgIoRvg.mjs.map +1 -0
- package/dist/{core/cron.d.ts → cron-C29iHvHT.d.mts} +16 -14
- package/dist/cron-C29iHvHT.d.mts.map +1 -0
- package/dist/decorators-D3lBlmud.d.mts +204 -0
- package/dist/decorators-D3lBlmud.d.mts.map +1 -0
- package/dist/errors-BZUdxtjC.d.mts +68 -0
- package/dist/errors-BZUdxtjC.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 +190 -0
- package/dist/http/context.d.mts.map +1 -0
- package/dist/http/context.mjs +225 -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-4VM4dUJf.d.mts +107 -0
- package/dist/index-4VM4dUJf.d.mts.map +1 -0
- package/dist/index-rnK23QBD.d.mts +184 -0
- package/dist/index-rnK23QBD.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-D5ohYl6D.d.mts +52 -0
- package/dist/interfaces-D5ohYl6D.d.mts.map +1 -0
- package/dist/logger-BLdfUF5b.d.mts +119 -0
- package/dist/logger-BLdfUF5b.d.mts.map +1 -0
- package/dist/metadata-BqXgNTOf.mjs +76 -0
- package/dist/metadata-BqXgNTOf.mjs.map +1 -0
- package/dist/{core/path.d.ts → path-Dq5V-i-x.d.mts} +7 -3
- package/dist/path-Dq5V-i-x.d.mts.map +1 -0
- package/dist/plugin-D20muJwC.d.mts +95 -0
- package/dist/plugin-D20muJwC.d.mts.map +1 -0
- package/dist/query-vljPDFaZ.mjs +164 -0
- package/dist/query-vljPDFaZ.mjs.map +1 -0
- package/dist/{core/reactivity.d.ts → reactivity-CMAQh0gi.d.mts} +21 -20
- package/dist/reactivity-CMAQh0gi.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,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v2.2.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 { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
12
|
+
//#region src/http/middleware/session.ts
|
|
13
|
+
var MemoryStore = class {
|
|
14
|
+
sessions = /* @__PURE__ */ new Map();
|
|
15
|
+
cleanupInterval;
|
|
16
|
+
constructor() {
|
|
17
|
+
this.cleanupInterval = setInterval(() => this.purge(), 6e4);
|
|
18
|
+
this.cleanupInterval.unref();
|
|
19
|
+
}
|
|
20
|
+
async get(sid) {
|
|
21
|
+
const entry = this.sessions.get(sid);
|
|
22
|
+
if (!entry) return null;
|
|
23
|
+
if (Date.now() > entry.expires) {
|
|
24
|
+
this.sessions.delete(sid);
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
return entry.data;
|
|
28
|
+
}
|
|
29
|
+
async set(sid, data, maxAge) {
|
|
30
|
+
this.sessions.set(sid, {
|
|
31
|
+
data,
|
|
32
|
+
expires: Date.now() + maxAge
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
async destroy(sid) {
|
|
36
|
+
this.sessions.delete(sid);
|
|
37
|
+
}
|
|
38
|
+
async touch(sid, maxAge) {
|
|
39
|
+
const entry = this.sessions.get(sid);
|
|
40
|
+
if (entry) entry.expires = Date.now() + maxAge;
|
|
41
|
+
}
|
|
42
|
+
purge() {
|
|
43
|
+
const now = Date.now();
|
|
44
|
+
for (const [sid, entry] of this.sessions) if (now > entry.expires) this.sessions.delete(sid);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
function sign(value, secret) {
|
|
48
|
+
return `s:${value}.${createHmac("sha256", secret).update(value).digest("base64url")}`;
|
|
49
|
+
}
|
|
50
|
+
function unsign(signed, secret) {
|
|
51
|
+
if (!signed.startsWith("s:")) return false;
|
|
52
|
+
const raw = signed.slice(2);
|
|
53
|
+
const dotIndex = raw.lastIndexOf(".");
|
|
54
|
+
if (dotIndex === -1) return false;
|
|
55
|
+
const value = raw.slice(0, dotIndex);
|
|
56
|
+
const providedSig = raw.slice(dotIndex + 1);
|
|
57
|
+
const expectedSig = createHmac("sha256", secret).update(value).digest("base64url");
|
|
58
|
+
const a = Buffer.from(providedSig);
|
|
59
|
+
const b = Buffer.from(expectedSig);
|
|
60
|
+
if (a.length !== b.length || !timingSafeEqual(a, b)) return false;
|
|
61
|
+
return value;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Session management middleware.
|
|
65
|
+
*
|
|
66
|
+
* Attaches a `req.session` object with `id`, `data`, `regenerate()`,
|
|
67
|
+
* `destroy()`, and `save()` methods. Session IDs are signed with
|
|
68
|
+
* HMAC-SHA256 to prevent cookie tampering.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```ts
|
|
72
|
+
* import { session } from '@forinda/kickjs-http'
|
|
73
|
+
*
|
|
74
|
+
* bootstrap({
|
|
75
|
+
* modules,
|
|
76
|
+
* middleware: [
|
|
77
|
+
* cookieParser(),
|
|
78
|
+
* session({ secret: process.env.SESSION_SECRET! }),
|
|
79
|
+
* // ... other middleware
|
|
80
|
+
* ],
|
|
81
|
+
* })
|
|
82
|
+
* ```
|
|
83
|
+
*/
|
|
84
|
+
function session(options) {
|
|
85
|
+
const { secret, cookieName = "kick.sid", maxAge = 864e5, rolling = false, saveUninitialized = true, store = new MemoryStore(), cookie: cookieOpts = {} } = options;
|
|
86
|
+
const cookieDefaults = {
|
|
87
|
+
httpOnly: cookieOpts.httpOnly ?? true,
|
|
88
|
+
secure: cookieOpts.secure ?? process.env.NODE_ENV === "production",
|
|
89
|
+
sameSite: cookieOpts.sameSite ?? "lax",
|
|
90
|
+
path: cookieOpts.path ?? "/",
|
|
91
|
+
...cookieOpts.domain ? { domain: cookieOpts.domain } : {},
|
|
92
|
+
maxAge
|
|
93
|
+
};
|
|
94
|
+
return async (req, res, next) => {
|
|
95
|
+
const signedCookie = (req.cookies || {})[cookieName];
|
|
96
|
+
let sid = false;
|
|
97
|
+
let sessionData = null;
|
|
98
|
+
let isNew = false;
|
|
99
|
+
if (signedCookie) {
|
|
100
|
+
sid = unsign(signedCookie, secret);
|
|
101
|
+
if (sid) sessionData = await store.get(sid);
|
|
102
|
+
}
|
|
103
|
+
if (!sid || !sessionData) {
|
|
104
|
+
sid = randomUUID();
|
|
105
|
+
sessionData = {};
|
|
106
|
+
isNew = true;
|
|
107
|
+
}
|
|
108
|
+
let currentSid = sid;
|
|
109
|
+
let currentData = { ...sessionData };
|
|
110
|
+
let destroyed = false;
|
|
111
|
+
const sessionObj = {
|
|
112
|
+
get id() {
|
|
113
|
+
return currentSid;
|
|
114
|
+
},
|
|
115
|
+
data: currentData,
|
|
116
|
+
async regenerate() {
|
|
117
|
+
await store.destroy(currentSid);
|
|
118
|
+
currentSid = randomUUID();
|
|
119
|
+
currentData = {};
|
|
120
|
+
sessionObj.data = currentData;
|
|
121
|
+
await store.set(currentSid, currentData, maxAge);
|
|
122
|
+
res.cookie(cookieName, sign(currentSid, secret), cookieDefaults);
|
|
123
|
+
},
|
|
124
|
+
async destroy() {
|
|
125
|
+
await store.destroy(currentSid);
|
|
126
|
+
destroyed = true;
|
|
127
|
+
currentData = {};
|
|
128
|
+
sessionObj.data = currentData;
|
|
129
|
+
res.clearCookie(cookieName, { path: cookieDefaults.path });
|
|
130
|
+
},
|
|
131
|
+
async save() {
|
|
132
|
+
if (!destroyed) await store.set(currentSid, currentData, maxAge);
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
req.session = sessionObj;
|
|
136
|
+
if (isNew) res.cookie(cookieName, sign(currentSid, secret), cookieDefaults);
|
|
137
|
+
res.on("finish", async () => {
|
|
138
|
+
if (destroyed) return;
|
|
139
|
+
if (isNew && !saveUninitialized && Object.keys(currentData).length === 0) return;
|
|
140
|
+
await store.set(currentSid, currentData, maxAge);
|
|
141
|
+
if (rolling && !isNew) {
|
|
142
|
+
if (store.touch) await store.touch(currentSid, maxAge);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
if (rolling && !isNew) res.cookie(cookieName, sign(currentSid, secret), cookieDefaults);
|
|
146
|
+
next();
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
//#endregion
|
|
150
|
+
export { session };
|
|
151
|
+
|
|
152
|
+
//# sourceMappingURL=session.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session.mjs","names":[],"sources":["../../../src/http/middleware/session.ts"],"sourcesContent":["import { randomUUID, createHmac, timingSafeEqual } from 'node:crypto'\nimport type { Request, Response, NextFunction } from 'express'\n\nexport interface SessionData {\n [key: string]: unknown\n}\n\nexport interface SessionStore {\n get(sid: string): Promise<SessionData | null>\n set(sid: string, data: SessionData, maxAge: number): Promise<void>\n destroy(sid: string): Promise<void>\n touch?(sid: string, maxAge: number): Promise<void>\n}\n\nexport interface Session {\n id: string\n data: SessionData\n regenerate(): Promise<void>\n destroy(): Promise<void>\n save(): Promise<void>\n}\n\nexport interface SessionOptions {\n /** Secret used to sign the session cookie (required) */\n secret: string\n /** Cookie name (default: 'kick.sid') */\n cookieName?: string\n /** Session max age in milliseconds (default: 86400000 = 24h) */\n maxAge?: number\n /** Reset maxAge on every response (default: false) */\n rolling?: boolean\n /** Save new sessions that have not been modified (default: true) */\n saveUninitialized?: boolean\n /** Cookie options */\n cookie?: {\n httpOnly?: boolean\n secure?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n path?: string\n domain?: string\n }\n /** Custom session store (default: in-memory store with TTL cleanup) */\n store?: SessionStore\n}\n\n// ── In-Memory Store ───────────────────────────────────────────────────\n\nclass MemoryStore implements SessionStore {\n private sessions = new Map<string, { data: SessionData; expires: number }>()\n private cleanupInterval: ReturnType<typeof setInterval>\n\n constructor() {\n // Purge expired sessions every 60 seconds\n this.cleanupInterval = setInterval(() => this.purge(), 60_000)\n this.cleanupInterval.unref()\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const entry = this.sessions.get(sid)\n if (!entry) return null\n if (Date.now() > entry.expires) {\n this.sessions.delete(sid)\n return null\n }\n return entry.data\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n this.sessions.set(sid, { data, expires: Date.now() + maxAge })\n }\n\n async destroy(sid: string): Promise<void> {\n this.sessions.delete(sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const entry = this.sessions.get(sid)\n if (entry) {\n entry.expires = Date.now() + maxAge\n }\n }\n\n private purge() {\n const now = Date.now()\n for (const [sid, entry] of this.sessions) {\n if (now > entry.expires) {\n this.sessions.delete(sid)\n }\n }\n }\n}\n\n// ── Cookie Signing ────────────────────────────────────────────────────\n\nfunction sign(value: string, secret: string): string {\n const signature = createHmac('sha256', secret).update(value).digest('base64url')\n return `s:${value}.${signature}`\n}\n\nfunction unsign(signed: string, secret: string): string | false {\n if (!signed.startsWith('s:')) return false\n const raw = signed.slice(2)\n const dotIndex = raw.lastIndexOf('.')\n if (dotIndex === -1) return false\n\n const value = raw.slice(0, dotIndex)\n const providedSig = raw.slice(dotIndex + 1)\n const expectedSig = createHmac('sha256', secret).update(value).digest('base64url')\n\n const a = Buffer.from(providedSig)\n const b = Buffer.from(expectedSig)\n\n if (a.length !== b.length || !timingSafeEqual(a, b)) {\n return false\n }\n\n return value\n}\n\n// ── Middleware Factory ────────────────────────────────────────────────\n\n/**\n * Session management middleware.\n *\n * Attaches a `req.session` object with `id`, `data`, `regenerate()`,\n * `destroy()`, and `save()` methods. Session IDs are signed with\n * HMAC-SHA256 to prevent cookie tampering.\n *\n * @example\n * ```ts\n * import { session } from '@forinda/kickjs-http'\n *\n * bootstrap({\n * modules,\n * middleware: [\n * cookieParser(),\n * session({ secret: process.env.SESSION_SECRET! }),\n * // ... other middleware\n * ],\n * })\n * ```\n */\nexport function session(options: SessionOptions) {\n const {\n secret,\n cookieName = 'kick.sid',\n maxAge = 86_400_000,\n rolling = false,\n saveUninitialized = true,\n store = new MemoryStore(),\n cookie: cookieOpts = {},\n } = options\n\n const cookieDefaults = {\n httpOnly: cookieOpts.httpOnly ?? true,\n secure: cookieOpts.secure ?? process.env.NODE_ENV === 'production',\n sameSite: cookieOpts.sameSite ?? ('lax' as const),\n path: cookieOpts.path ?? '/',\n ...(cookieOpts.domain ? { domain: cookieOpts.domain } : {}),\n maxAge,\n }\n\n return async (req: Request, res: Response, next: NextFunction) => {\n const cookies = (req as any).cookies || {}\n const signedCookie = cookies[cookieName]\n let sid: string | false = false\n let sessionData: SessionData | null = null\n let isNew = false\n\n // Attempt to recover existing session\n if (signedCookie) {\n sid = unsign(signedCookie, secret)\n if (sid) {\n sessionData = await store.get(sid)\n }\n }\n\n // Create new session if none found\n if (!sid || !sessionData) {\n sid = randomUUID()\n sessionData = {}\n isNew = true\n }\n\n let currentSid = sid as string\n let currentData = { ...sessionData }\n let destroyed = false\n\n const sessionObj: Session = {\n get id() {\n return currentSid\n },\n data: currentData,\n\n async regenerate() {\n await store.destroy(currentSid)\n currentSid = randomUUID()\n currentData = {}\n sessionObj.data = currentData\n await store.set(currentSid, currentData, maxAge)\n res.cookie(cookieName, sign(currentSid, secret), cookieDefaults)\n },\n\n async destroy() {\n await store.destroy(currentSid)\n destroyed = true\n currentData = {}\n sessionObj.data = currentData\n res.clearCookie(cookieName, { path: cookieDefaults.path })\n },\n\n async save() {\n if (!destroyed) {\n await store.set(currentSid, currentData, maxAge)\n }\n },\n }\n\n ;(req as any).session = sessionObj\n\n // Set cookie for new sessions\n if (isNew) {\n res.cookie(cookieName, sign(currentSid, secret), cookieDefaults)\n }\n\n // Auto-save on response finish\n res.on('finish', async () => {\n if (destroyed) return\n if (isNew && !saveUninitialized && Object.keys(currentData).length === 0) return\n\n await store.set(currentSid, currentData, maxAge)\n\n if (rolling && !isNew) {\n if (store.touch) {\n await store.touch(currentSid, maxAge)\n }\n }\n })\n\n // Rolling: refresh cookie on every response\n if (rolling && !isNew) {\n res.cookie(cookieName, sign(currentSid, secret), cookieDefaults)\n }\n\n next()\n }\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
|
|
2
|
+
import { r as AppAdapter, t as AdapterContext } from "../../adapter-wuoBNkNs.mjs";
|
|
3
|
+
//#region src/http/middleware/spa.d.ts
|
|
4
|
+
interface SpaAdapterOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Directory containing the built SPA files (index.html, assets, etc.)
|
|
7
|
+
* Default: 'dist/client'
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* // Vue: 'dist'
|
|
12
|
+
* // React (Vite): 'dist'
|
|
13
|
+
* // React (CRA): 'build'
|
|
14
|
+
* // Svelte: 'build'
|
|
15
|
+
* // Angular: 'dist/my-app/browser'
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
clientDir?: string;
|
|
19
|
+
/**
|
|
20
|
+
* URL prefix for API routes. SPA fallback only applies to
|
|
21
|
+
* non-API routes (routes NOT starting with this prefix).
|
|
22
|
+
* Default: '/api'
|
|
23
|
+
*
|
|
24
|
+
* Set to an array for multiple prefixes:
|
|
25
|
+
* ```ts
|
|
26
|
+
* apiPrefix: ['/api', '/graphql', '/_debug']
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
apiPrefix?: string | string[];
|
|
30
|
+
/**
|
|
31
|
+
* Additional paths to exclude from SPA fallback.
|
|
32
|
+
* These paths will NOT serve index.html.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```ts
|
|
36
|
+
* exclude: ['/health', '/metrics', '/ws']
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
exclude?: string[];
|
|
40
|
+
/**
|
|
41
|
+
* Cache-Control header for static assets (default: 'public, max-age=31536000, immutable')
|
|
42
|
+
* Set to false to disable caching headers.
|
|
43
|
+
*/
|
|
44
|
+
cacheControl?: string | false;
|
|
45
|
+
/**
|
|
46
|
+
* Cache-Control for index.html (default: 'no-cache')
|
|
47
|
+
* index.html should not be cached to ensure clients get fresh builds.
|
|
48
|
+
*/
|
|
49
|
+
indexCacheControl?: string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* SPA adapter — serve a Vue, React, Svelte, or Angular build alongside
|
|
53
|
+
* your KickJS API. API routes are handled by controllers; everything else
|
|
54
|
+
* falls back to index.html for client-side routing.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```ts
|
|
58
|
+
* import { SpaAdapter } from '@forinda/kickjs-http/spa'
|
|
59
|
+
*
|
|
60
|
+
* bootstrap({
|
|
61
|
+
* modules,
|
|
62
|
+
* adapters: [
|
|
63
|
+
* new SpaAdapter({
|
|
64
|
+
* clientDir: 'dist/client', // or 'build', 'dist', etc.
|
|
65
|
+
* apiPrefix: '/api',
|
|
66
|
+
* }),
|
|
67
|
+
* ],
|
|
68
|
+
* })
|
|
69
|
+
* ```
|
|
70
|
+
*
|
|
71
|
+
* File structure:
|
|
72
|
+
* ```
|
|
73
|
+
* dist/
|
|
74
|
+
* client/ ← SPA build output
|
|
75
|
+
* index.html
|
|
76
|
+
* assets/
|
|
77
|
+
* app.js
|
|
78
|
+
* style.css
|
|
79
|
+
* server/ ← KickJS server
|
|
80
|
+
* ```
|
|
81
|
+
*/
|
|
82
|
+
declare class SpaAdapter implements AppAdapter {
|
|
83
|
+
private options;
|
|
84
|
+
name: string;
|
|
85
|
+
private clientDir;
|
|
86
|
+
private apiPrefixes;
|
|
87
|
+
private excludePaths;
|
|
88
|
+
private cacheControl;
|
|
89
|
+
private indexCacheControl;
|
|
90
|
+
private indexHtml;
|
|
91
|
+
constructor(options?: SpaAdapterOptions);
|
|
92
|
+
beforeMount({
|
|
93
|
+
app
|
|
94
|
+
}: AdapterContext): void;
|
|
95
|
+
beforeStart({
|
|
96
|
+
app
|
|
97
|
+
}: AdapterContext): void;
|
|
98
|
+
}
|
|
99
|
+
//#endregion
|
|
100
|
+
export { SpaAdapter, SpaAdapterOptions };
|
|
101
|
+
//# sourceMappingURL=spa.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spa.d.mts","names":[],"sources":["../../../src/http/middleware/spa.ts"],"mappings":";;;UAMiB,iBAAA;;;AAAjB;;;;;;;;;;;EAcE,SAAA;EAqEsB;;;;;;;;;;EAzDtB,SAAA;EAkEoB;;;;;;;;;EAvDpB,OAAA;EAuDoB;;;;EAjDpB,YAAA;EAoGA;;;;EA9FA,iBAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAkCW,UAAA,YAAsB,UAAA;EAAA,QASb,OAAA;EARpB,IAAA;EAAA,QACQ,SAAA;EAAA,QACA,WAAA;EAAA,QACA,YAAA;EAAA,QACA,YAAA;EAAA,QACA,iBAAA;EAAA,QACA,SAAA;cAEY,OAAA,GAAS,iBAAA;EAU7B,WAAA,CAAA;IAAc;EAAA,GAAO,cAAA;EAyCrB,WAAA,CAAA;IAAc;EAAA,GAAO,cAAA;AAAA"}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v2.2.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 { t as __require } from "../../chunk-C9tIbwLT.mjs";
|
|
12
|
+
import { Logger } from "../../core/logger.mjs";
|
|
13
|
+
import "../../core-CMgIoRvg.mjs";
|
|
14
|
+
import { join, resolve } from "node:path";
|
|
15
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
16
|
+
//#region src/http/middleware/spa.ts
|
|
17
|
+
const log = Logger.for("SpaAdapter");
|
|
18
|
+
/**
|
|
19
|
+
* SPA adapter — serve a Vue, React, Svelte, or Angular build alongside
|
|
20
|
+
* your KickJS API. API routes are handled by controllers; everything else
|
|
21
|
+
* falls back to index.html for client-side routing.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* import { SpaAdapter } from '@forinda/kickjs-http/spa'
|
|
26
|
+
*
|
|
27
|
+
* bootstrap({
|
|
28
|
+
* modules,
|
|
29
|
+
* adapters: [
|
|
30
|
+
* new SpaAdapter({
|
|
31
|
+
* clientDir: 'dist/client', // or 'build', 'dist', etc.
|
|
32
|
+
* apiPrefix: '/api',
|
|
33
|
+
* }),
|
|
34
|
+
* ],
|
|
35
|
+
* })
|
|
36
|
+
* ```
|
|
37
|
+
*
|
|
38
|
+
* File structure:
|
|
39
|
+
* ```
|
|
40
|
+
* dist/
|
|
41
|
+
* client/ ← SPA build output
|
|
42
|
+
* index.html
|
|
43
|
+
* assets/
|
|
44
|
+
* app.js
|
|
45
|
+
* style.css
|
|
46
|
+
* server/ ← KickJS server
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
var SpaAdapter = class {
|
|
50
|
+
name = "SpaAdapter";
|
|
51
|
+
clientDir;
|
|
52
|
+
apiPrefixes;
|
|
53
|
+
excludePaths;
|
|
54
|
+
cacheControl;
|
|
55
|
+
indexCacheControl;
|
|
56
|
+
indexHtml = null;
|
|
57
|
+
constructor(options = {}) {
|
|
58
|
+
this.options = options;
|
|
59
|
+
this.clientDir = resolve(options.clientDir ?? "dist/client");
|
|
60
|
+
this.excludePaths = options.exclude ?? [];
|
|
61
|
+
this.cacheControl = options.cacheControl ?? "public, max-age=31536000, immutable";
|
|
62
|
+
this.indexCacheControl = options.indexCacheControl ?? "no-cache";
|
|
63
|
+
const prefix = options.apiPrefix ?? "/api";
|
|
64
|
+
this.apiPrefixes = Array.isArray(prefix) ? prefix : [prefix];
|
|
65
|
+
}
|
|
66
|
+
beforeMount({ app }) {
|
|
67
|
+
if (!existsSync(this.clientDir)) {
|
|
68
|
+
log.warn(`SPA client directory not found: ${this.clientDir}`);
|
|
69
|
+
log.warn("Build your frontend first, or set clientDir to the correct path.");
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const indexPath = join(this.clientDir, "index.html");
|
|
73
|
+
if (existsSync(indexPath)) this.indexHtml = readFileSync(indexPath, "utf-8");
|
|
74
|
+
else {
|
|
75
|
+
log.warn(`index.html not found in ${this.clientDir}`);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
const express = __require("express");
|
|
80
|
+
const staticOpts = {};
|
|
81
|
+
if (this.cacheControl) staticOpts.setHeaders = (res, filePath) => {
|
|
82
|
+
if (filePath.endsWith(".html")) res.setHeader("Cache-Control", this.indexCacheControl);
|
|
83
|
+
else res.setHeader("Cache-Control", this.cacheControl);
|
|
84
|
+
};
|
|
85
|
+
app.use(express.static(this.clientDir, staticOpts));
|
|
86
|
+
} catch {
|
|
87
|
+
log.error("express.static not available — SPA static file serving disabled");
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
log.info(`Serving SPA from ${this.clientDir}`);
|
|
91
|
+
}
|
|
92
|
+
beforeStart({ app }) {
|
|
93
|
+
if (!this.indexHtml) return;
|
|
94
|
+
app.use((req, res, next) => {
|
|
95
|
+
for (const prefix of this.apiPrefixes) if (req.path.startsWith(prefix)) return next();
|
|
96
|
+
for (const path of this.excludePaths) if (req.path.startsWith(path)) return next();
|
|
97
|
+
if (req.path.includes(".")) return next();
|
|
98
|
+
if (req.method !== "GET") return next();
|
|
99
|
+
res.setHeader("Content-Type", "text/html");
|
|
100
|
+
res.setHeader("Cache-Control", this.indexCacheControl);
|
|
101
|
+
res.send(this.indexHtml);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
//#endregion
|
|
106
|
+
export { SpaAdapter };
|
|
107
|
+
|
|
108
|
+
//# sourceMappingURL=spa.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spa.mjs","names":[],"sources":["../../../src/http/middleware/spa.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { resolve, join } from 'node:path'\nimport { Logger, type AppAdapter, type AdapterContext } from '../../core'\n\nconst log = Logger.for('SpaAdapter')\n\nexport interface SpaAdapterOptions {\n /**\n * Directory containing the built SPA files (index.html, assets, etc.)\n * Default: 'dist/client'\n *\n * @example\n * ```ts\n * // Vue: 'dist'\n * // React (Vite): 'dist'\n * // React (CRA): 'build'\n * // Svelte: 'build'\n * // Angular: 'dist/my-app/browser'\n * ```\n */\n clientDir?: string\n\n /**\n * URL prefix for API routes. SPA fallback only applies to\n * non-API routes (routes NOT starting with this prefix).\n * Default: '/api'\n *\n * Set to an array for multiple prefixes:\n * ```ts\n * apiPrefix: ['/api', '/graphql', '/_debug']\n * ```\n */\n apiPrefix?: string | string[]\n\n /**\n * Additional paths to exclude from SPA fallback.\n * These paths will NOT serve index.html.\n *\n * @example\n * ```ts\n * exclude: ['/health', '/metrics', '/ws']\n * ```\n */\n exclude?: string[]\n\n /**\n * Cache-Control header for static assets (default: 'public, max-age=31536000, immutable')\n * Set to false to disable caching headers.\n */\n cacheControl?: string | false\n\n /**\n * Cache-Control for index.html (default: 'no-cache')\n * index.html should not be cached to ensure clients get fresh builds.\n */\n indexCacheControl?: string\n}\n\n/**\n * SPA adapter — serve a Vue, React, Svelte, or Angular build alongside\n * your KickJS API. API routes are handled by controllers; everything else\n * falls back to index.html for client-side routing.\n *\n * @example\n * ```ts\n * import { SpaAdapter } from '@forinda/kickjs-http/spa'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * new SpaAdapter({\n * clientDir: 'dist/client', // or 'build', 'dist', etc.\n * apiPrefix: '/api',\n * }),\n * ],\n * })\n * ```\n *\n * File structure:\n * ```\n * dist/\n * client/ ← SPA build output\n * index.html\n * assets/\n * app.js\n * style.css\n * server/ ← KickJS server\n * ```\n */\nexport class SpaAdapter implements AppAdapter {\n name = 'SpaAdapter'\n private clientDir: string\n private apiPrefixes: string[]\n private excludePaths: string[]\n private cacheControl: string | false\n private indexCacheControl: string\n private indexHtml: string | null = null\n\n constructor(private options: SpaAdapterOptions = {}) {\n this.clientDir = resolve(options.clientDir ?? 'dist/client')\n this.excludePaths = options.exclude ?? []\n this.cacheControl = options.cacheControl ?? 'public, max-age=31536000, immutable'\n this.indexCacheControl = options.indexCacheControl ?? 'no-cache'\n\n const prefix = options.apiPrefix ?? '/api'\n this.apiPrefixes = Array.isArray(prefix) ? prefix : [prefix]\n }\n\n beforeMount({ app }: AdapterContext): void {\n if (!existsSync(this.clientDir)) {\n log.warn(`SPA client directory not found: ${this.clientDir}`)\n log.warn('Build your frontend first, or set clientDir to the correct path.')\n return\n }\n\n // Read index.html into memory\n const indexPath = join(this.clientDir, 'index.html')\n if (existsSync(indexPath)) {\n this.indexHtml = readFileSync(indexPath, 'utf-8')\n } else {\n log.warn(`index.html not found in ${this.clientDir}`)\n return\n }\n\n // Serve static files with cache headers\n try {\n // Dynamic import to avoid hard dependency on express.static\n const express = require('express')\n const staticOpts: any = {}\n\n if (this.cacheControl) {\n staticOpts.setHeaders = (res: any, filePath: string) => {\n if (filePath.endsWith('.html')) {\n res.setHeader('Cache-Control', this.indexCacheControl)\n } else {\n res.setHeader('Cache-Control', this.cacheControl as string)\n }\n }\n }\n\n app.use(express.static(this.clientDir, staticOpts))\n } catch {\n log.error('express.static not available — SPA static file serving disabled')\n return\n }\n\n log.info(`Serving SPA from ${this.clientDir}`)\n }\n\n beforeStart({ app }: AdapterContext): void {\n if (!this.indexHtml) return\n\n // SPA fallback: serve index.html for all non-API, non-file routes\n app.use((req: any, res: any, next: any) => {\n // Skip API routes\n for (const prefix of this.apiPrefixes) {\n if (req.path.startsWith(prefix)) return next()\n }\n\n // Skip excluded paths\n for (const path of this.excludePaths) {\n if (req.path.startsWith(path)) return next()\n }\n\n // Skip requests for files (have an extension)\n if (req.path.includes('.')) return next()\n\n // Skip non-GET requests\n if (req.method !== 'GET') return next()\n\n // Serve index.html\n res.setHeader('Content-Type', 'text/html')\n res.setHeader('Cache-Control', this.indexCacheControl)\n res.send(this.indexHtml)\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAIA,MAAM,MAAM,OAAO,IAAI,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFpC,IAAa,aAAb,MAA8C;CAC5C,OAAO;CACP;CACA;CACA;CACA;CACA;CACA,YAAmC;CAEnC,YAAY,UAAqC,EAAE,EAAE;AAAjC,OAAA,UAAA;AAClB,OAAK,YAAY,QAAQ,QAAQ,aAAa,cAAc;AAC5D,OAAK,eAAe,QAAQ,WAAW,EAAE;AACzC,OAAK,eAAe,QAAQ,gBAAgB;AAC5C,OAAK,oBAAoB,QAAQ,qBAAqB;EAEtD,MAAM,SAAS,QAAQ,aAAa;AACpC,OAAK,cAAc,MAAM,QAAQ,OAAO,GAAG,SAAS,CAAC,OAAO;;CAG9D,YAAY,EAAE,OAA6B;AACzC,MAAI,CAAC,WAAW,KAAK,UAAU,EAAE;AAC/B,OAAI,KAAK,mCAAmC,KAAK,YAAY;AAC7D,OAAI,KAAK,mEAAmE;AAC5E;;EAIF,MAAM,YAAY,KAAK,KAAK,WAAW,aAAa;AACpD,MAAI,WAAW,UAAU,CACvB,MAAK,YAAY,aAAa,WAAW,QAAQ;OAC5C;AACL,OAAI,KAAK,2BAA2B,KAAK,YAAY;AACrD;;AAIF,MAAI;GAEF,MAAM,UAAA,UAAkB,UAAU;GAClC,MAAM,aAAkB,EAAE;AAE1B,OAAI,KAAK,aACP,YAAW,cAAc,KAAU,aAAqB;AACtD,QAAI,SAAS,SAAS,QAAQ,CAC5B,KAAI,UAAU,iBAAiB,KAAK,kBAAkB;QAEtD,KAAI,UAAU,iBAAiB,KAAK,aAAuB;;AAKjE,OAAI,IAAI,QAAQ,OAAO,KAAK,WAAW,WAAW,CAAC;UAC7C;AACN,OAAI,MAAM,kEAAkE;AAC5E;;AAGF,MAAI,KAAK,oBAAoB,KAAK,YAAY;;CAGhD,YAAY,EAAE,OAA6B;AACzC,MAAI,CAAC,KAAK,UAAW;AAGrB,MAAI,KAAK,KAAU,KAAU,SAAc;AAEzC,QAAK,MAAM,UAAU,KAAK,YACxB,KAAI,IAAI,KAAK,WAAW,OAAO,CAAE,QAAO,MAAM;AAIhD,QAAK,MAAM,QAAQ,KAAK,aACtB,KAAI,IAAI,KAAK,WAAW,KAAK,CAAE,QAAO,MAAM;AAI9C,OAAI,IAAI,KAAK,SAAS,IAAI,CAAE,QAAO,MAAM;AAGzC,OAAI,IAAI,WAAW,MAAO,QAAO,MAAM;AAGvC,OAAI,UAAU,gBAAgB,YAAY;AAC1C,OAAI,UAAU,iBAAiB,KAAK,kBAAkB;AACtD,OAAI,KAAK,KAAK,UAAU;IACxB"}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
1
|
+
|
|
2
|
+
import { i as BaseUploadOptions, m as FileUploadConfig } from "../../decorators-D3lBlmud.mjs";
|
|
3
|
+
import { NextFunction, Request, RequestHandler, Response } from "express";
|
|
4
|
+
import { Options } from "multer";
|
|
5
|
+
|
|
6
|
+
//#region src/http/middleware/upload.d.ts
|
|
4
7
|
/**
|
|
5
8
|
* Resolves a list of file type identifiers to MIME type strings.
|
|
6
9
|
* Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).
|
|
@@ -11,17 +14,17 @@ import type { BaseUploadOptions, FileUploadConfig } from '../../core';
|
|
|
11
14
|
* // → ['image/jpeg', 'image/png', 'application/pdf']
|
|
12
15
|
* ```
|
|
13
16
|
*/
|
|
14
|
-
|
|
17
|
+
declare function resolveMimeTypes(types: string[]): string[];
|
|
15
18
|
/**
|
|
16
19
|
* Upload options for the middleware.
|
|
17
20
|
* Extends BaseUploadOptions from core (shared with @FileUpload decorator)
|
|
18
21
|
* and adds Multer-specific storage options.
|
|
19
22
|
*/
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
23
|
+
interface UploadOptions extends BaseUploadOptions {
|
|
24
|
+
/** Multer storage config (default: memory storage) */
|
|
25
|
+
storage?: Options['storage'];
|
|
26
|
+
/** Multer dest for disk storage shorthand */
|
|
27
|
+
dest?: string;
|
|
25
28
|
}
|
|
26
29
|
/**
|
|
27
30
|
* Single file upload middleware. Attaches the file to `req.file`.
|
|
@@ -58,18 +61,19 @@ declare function none(options?: UploadOptions): RequestHandler;
|
|
|
58
61
|
* }
|
|
59
62
|
* ```
|
|
60
63
|
*/
|
|
61
|
-
|
|
64
|
+
declare function cleanupFiles(): (req: Request, res: Response, next: NextFunction) => void;
|
|
62
65
|
/**
|
|
63
66
|
* Build upload middleware from a @FileUpload decorator config.
|
|
64
67
|
* Used internally by the router builder when it detects FILE_UPLOAD metadata.
|
|
65
68
|
* Accepts the same FileUploadConfig interface used by the @FileUpload decorator.
|
|
66
69
|
*/
|
|
67
|
-
|
|
70
|
+
declare function buildUploadMiddleware(config: FileUploadConfig): RequestHandler;
|
|
68
71
|
/** Upload middleware factory with `.single()`, `.array()`, `.none()` methods */
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
72
|
+
declare const upload: {
|
|
73
|
+
single: typeof single;
|
|
74
|
+
array: typeof array;
|
|
75
|
+
none: typeof none;
|
|
73
76
|
};
|
|
74
|
-
|
|
75
|
-
|
|
77
|
+
//#endregion
|
|
78
|
+
export { UploadOptions, buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
|
|
79
|
+
//# sourceMappingURL=upload.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"upload.d.mts","names":[],"sources":["../../../src/http/middleware/upload.ts"],"mappings":";;;;;;;;;AAsEA;;;;;AAYA;;iBAZgB,gBAAA,CAAiB,KAAA;;;;;;UAYhB,aAAA,SAAsB,iBAAA;EAIjC;EAFJ,OAAA,GAAU,OAAA;EAmEG;EAjEb,IAAA;AAAA;;;;;;;AAiE6E;;;;;;iBAAtE,MAAA,CAAO,SAAA,UAAmB,OAAA,GAAS,aAAA,GAAqB,cAAA;;;;iBAQxD,KAAA,CAAM,SAAA,UAAmB,QAAA,WAAe,OAAA,GAAS,aAAA,GAAqB,cAAA;AAAc;;;AAAA,iBAQpF,IAAA,CAAK,OAAA,GAAS,aAAA,GAAqB,cAAA;;;;;;AAmB5C;;;;;;;;;iBAAgB,YAAA,CAAA,IACN,GAAA,EAAK,OAAA,EAAS,GAAA,EAAK,QAAA,EAAU,IAAA,EAAM,YAAA;;;;;;iBA+B7B,qBAAA,CAAsB,MAAA,EAAQ,gBAAA,GAAmB,cAAA;AAAjE;AAAA,cAmBa,MAAA"}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v2.2.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 { unlink } from "node:fs/promises";
|
|
12
|
+
import multer from "multer";
|
|
13
|
+
//#region src/http/middleware/upload.ts
|
|
14
|
+
/**
|
|
15
|
+
* Maps short file extensions to their MIME types.
|
|
16
|
+
* Users can pass `['jpg', 'png', 'pdf']` instead of full MIME strings.
|
|
17
|
+
*/
|
|
18
|
+
const MIME_MAP = {
|
|
19
|
+
jpg: "image/jpeg",
|
|
20
|
+
jpeg: "image/jpeg",
|
|
21
|
+
png: "image/png",
|
|
22
|
+
gif: "image/gif",
|
|
23
|
+
webp: "image/webp",
|
|
24
|
+
svg: "image/svg+xml",
|
|
25
|
+
bmp: "image/bmp",
|
|
26
|
+
ico: "image/x-icon",
|
|
27
|
+
tiff: "image/tiff",
|
|
28
|
+
tif: "image/tiff",
|
|
29
|
+
avif: "image/avif",
|
|
30
|
+
pdf: "application/pdf",
|
|
31
|
+
doc: "application/msword",
|
|
32
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
33
|
+
xls: "application/vnd.ms-excel",
|
|
34
|
+
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
35
|
+
ppt: "application/vnd.ms-powerpoint",
|
|
36
|
+
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
37
|
+
odt: "application/vnd.oasis.opendocument.text",
|
|
38
|
+
ods: "application/vnd.oasis.opendocument.spreadsheet",
|
|
39
|
+
odp: "application/vnd.oasis.opendocument.presentation",
|
|
40
|
+
rtf: "application/rtf",
|
|
41
|
+
txt: "text/plain",
|
|
42
|
+
csv: "text/csv",
|
|
43
|
+
zip: "application/zip",
|
|
44
|
+
gz: "application/gzip",
|
|
45
|
+
tar: "application/x-tar",
|
|
46
|
+
rar: "application/vnd.rar",
|
|
47
|
+
"7z": "application/x-7z-compressed",
|
|
48
|
+
mp3: "audio/mpeg",
|
|
49
|
+
wav: "audio/wav",
|
|
50
|
+
ogg: "audio/ogg",
|
|
51
|
+
flac: "audio/flac",
|
|
52
|
+
aac: "audio/aac",
|
|
53
|
+
mp4: "video/mp4",
|
|
54
|
+
webm: "video/webm",
|
|
55
|
+
avi: "video/x-msvideo",
|
|
56
|
+
mov: "video/quicktime",
|
|
57
|
+
mkv: "video/x-matroska",
|
|
58
|
+
json: "application/json",
|
|
59
|
+
xml: "application/xml",
|
|
60
|
+
html: "text/html"
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Resolves a list of file type identifiers to MIME type strings.
|
|
64
|
+
* Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```ts
|
|
68
|
+
* resolveMimeTypes(['jpg', 'png', 'application/pdf'])
|
|
69
|
+
* // → ['image/jpeg', 'image/png', 'application/pdf']
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
function resolveMimeTypes(types) {
|
|
73
|
+
return types.map((t) => {
|
|
74
|
+
return MIME_MAP[t.toLowerCase().replace(/^\./, "")] ?? t;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
function createMulter(options) {
|
|
78
|
+
const mimeMap = options.customMimeMap ? {
|
|
79
|
+
...MIME_MAP,
|
|
80
|
+
...options.customMimeMap
|
|
81
|
+
} : MIME_MAP;
|
|
82
|
+
const limits = { fileSize: options.maxSize ?? 5 * 1024 * 1024 };
|
|
83
|
+
let fileFilter;
|
|
84
|
+
if (typeof options.allowedTypes === "function") {
|
|
85
|
+
const filterFn = options.allowedTypes;
|
|
86
|
+
fileFilter = (_req, file, cb) => {
|
|
87
|
+
if (filterFn(file.mimetype, file.originalname)) cb(null, true);
|
|
88
|
+
else cb(/* @__PURE__ */ new Error(`File type ${file.mimetype} is not allowed`));
|
|
89
|
+
};
|
|
90
|
+
} else if (Array.isArray(options.allowedTypes)) {
|
|
91
|
+
const resolvedTypes = options.allowedTypes.map((t) => {
|
|
92
|
+
return mimeMap[t.toLowerCase().replace(/^\./, "")] ?? t;
|
|
93
|
+
});
|
|
94
|
+
fileFilter = (_req, file, cb) => {
|
|
95
|
+
if (resolvedTypes.some((type) => {
|
|
96
|
+
if (type.endsWith("/*")) return file.mimetype.startsWith(type.replace("/*", "/"));
|
|
97
|
+
return file.mimetype === type;
|
|
98
|
+
})) cb(null, true);
|
|
99
|
+
else cb(/* @__PURE__ */ new Error(`File type ${file.mimetype} is not allowed`));
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
return multer({
|
|
103
|
+
limits,
|
|
104
|
+
...fileFilter ? { fileFilter } : {},
|
|
105
|
+
...options.storage ? { storage: options.storage } : {},
|
|
106
|
+
...options.dest ? { dest: options.dest } : {}
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Single file upload middleware. Attaches the file to `req.file`.
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```ts
|
|
114
|
+
* @Post('/avatar')
|
|
115
|
+
* @Middleware(upload.single('avatar', { maxSize: 2 * 1024 * 1024, allowedTypes: ['jpg', 'png'] }))
|
|
116
|
+
* async uploadAvatar(ctx: RequestContext) {
|
|
117
|
+
* ctx.json({ filename: ctx.file.originalname })
|
|
118
|
+
* }
|
|
119
|
+
* ```
|
|
120
|
+
*/
|
|
121
|
+
function single(fieldName, options = {}) {
|
|
122
|
+
return createMulter(options).single(fieldName);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Multiple file upload middleware. Attaches files to `req.files`.
|
|
126
|
+
*/
|
|
127
|
+
function array(fieldName, maxCount = 10, options = {}) {
|
|
128
|
+
return createMulter(options).array(fieldName, maxCount);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* No file upload — just parse multipart form data without file fields.
|
|
132
|
+
*/
|
|
133
|
+
function none(options = {}) {
|
|
134
|
+
return createMulter(options).none();
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Removes temporary files from disk after the response is sent.
|
|
138
|
+
* Attach this as Express middleware after the upload middleware.
|
|
139
|
+
* Works with both `req.file` (single) and `req.files` (array).
|
|
140
|
+
*
|
|
141
|
+
* @example
|
|
142
|
+
* ```ts
|
|
143
|
+
* @Post('/process')
|
|
144
|
+
* @Middleware(upload.single('document', { dest: '/tmp/uploads' }), cleanupFiles())
|
|
145
|
+
* async processDocument(ctx: RequestContext) {
|
|
146
|
+
* ctx.json({ ok: true })
|
|
147
|
+
* }
|
|
148
|
+
* ```
|
|
149
|
+
*/
|
|
150
|
+
function cleanupFiles() {
|
|
151
|
+
return (req, res, next) => {
|
|
152
|
+
res.on("finish", async () => {
|
|
153
|
+
const files = [];
|
|
154
|
+
if (req.file?.path) files.push(req.file);
|
|
155
|
+
if (Array.isArray(req.files)) {
|
|
156
|
+
for (const f of req.files) if (f?.path) files.push(f);
|
|
157
|
+
}
|
|
158
|
+
for (const file of files) try {
|
|
159
|
+
await unlink(file.path);
|
|
160
|
+
} catch {}
|
|
161
|
+
});
|
|
162
|
+
next();
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Build upload middleware from a @FileUpload decorator config.
|
|
167
|
+
* Used internally by the router builder when it detects FILE_UPLOAD metadata.
|
|
168
|
+
* Accepts the same FileUploadConfig interface used by the @FileUpload decorator.
|
|
169
|
+
*/
|
|
170
|
+
function buildUploadMiddleware(config) {
|
|
171
|
+
const options = {};
|
|
172
|
+
if (config.maxSize) options.maxSize = config.maxSize;
|
|
173
|
+
if (config.allowedTypes) options.allowedTypes = config.allowedTypes;
|
|
174
|
+
if (config.customMimeMap) options.customMimeMap = config.customMimeMap;
|
|
175
|
+
const fieldName = config.fieldName ?? "file";
|
|
176
|
+
switch (config.mode) {
|
|
177
|
+
case "single": return single(fieldName, options);
|
|
178
|
+
case "array": return array(fieldName, config.maxCount ?? 10, options);
|
|
179
|
+
case "none": return none(options);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/** Upload middleware factory with `.single()`, `.array()`, `.none()` methods */
|
|
183
|
+
const upload = {
|
|
184
|
+
single,
|
|
185
|
+
array,
|
|
186
|
+
none
|
|
187
|
+
};
|
|
188
|
+
//#endregion
|
|
189
|
+
export { buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
|
|
190
|
+
|
|
191
|
+
//# sourceMappingURL=upload.mjs.map
|