barejs 0.1.57 → 0.1.59
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 +66 -37
- package/dist/index.js +208 -186
- package/dist/node.js +362 -0
- package/dist/types/core/bare.d.ts +19 -7
- package/dist/types/core/context.d.ts +24 -0
- package/dist/types/core/router.d.ts +1 -0
- package/dist/types/core/ws-match.d.ts +15 -0
- package/dist/types/index.d.ts +2 -2
- package/dist/types/node.d.ts +1 -0
- package/dist/types/runtime/bun.d.ts +2 -0
- package/dist/types/runtime/index.d.ts +10 -0
- package/dist/types/runtime/node.d.ts +2 -0
- package/dist/types/runtime/types.d.ts +44 -0
- package/llms.txt +7 -4
- package/package.json +43 -7
- package/src/core/bare.ts +227 -114
- package/src/core/context.ts +293 -1
- package/src/core/loader.ts +5 -3
- package/src/core/router.ts +6 -0
- package/src/core/ws-match.ts +60 -0
- package/src/index.ts +4 -2
- package/src/node.ts +6 -0
- package/src/runtime/bun.ts +87 -0
- package/src/runtime/index.ts +24 -0
- package/src/runtime/node.ts +333 -0
- package/src/runtime/types.ts +49 -0
- package/src/security/hash.ts +3 -6
- package/src/security/idempotency.ts +3 -1
- package/src/utils/compress.ts +4 -3
- package/src/utils/static.ts +3 -2
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
|
|
2
|
+
import { createReadStream } from 'node:fs';
|
|
3
|
+
import { extname } from 'node:path';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
5
|
+
import { gzipSync } from 'node:zlib';
|
|
6
|
+
import type { RuntimeDriver, RuntimeFileHandle, RuntimePasswordConfig, ServeOptions, ServerHandle } from './types';
|
|
7
|
+
import { matchWsRoute } from '../core/ws-match';
|
|
8
|
+
|
|
9
|
+
const MIME_MAP: Record<string, string> = {
|
|
10
|
+
'.html': 'text/html; charset=utf-8',
|
|
11
|
+
'.htm': 'text/html; charset=utf-8',
|
|
12
|
+
'.js': 'application/javascript; charset=utf-8',
|
|
13
|
+
'.mjs': 'application/javascript; charset=utf-8',
|
|
14
|
+
'.css': 'text/css; charset=utf-8',
|
|
15
|
+
'.json': 'application/json; charset=utf-8',
|
|
16
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
17
|
+
'.xml': 'application/xml; charset=utf-8',
|
|
18
|
+
'.svg': 'image/svg+xml',
|
|
19
|
+
'.png': 'image/png',
|
|
20
|
+
'.jpg': 'image/jpeg',
|
|
21
|
+
'.jpeg': 'image/jpeg',
|
|
22
|
+
'.gif': 'image/gif',
|
|
23
|
+
'.webp': 'image/webp',
|
|
24
|
+
'.ico': 'image/x-icon',
|
|
25
|
+
'.woff': 'font/woff',
|
|
26
|
+
'.woff2': 'font/woff2',
|
|
27
|
+
'.wasm': 'application/wasm',
|
|
28
|
+
'.pdf': 'application/pdf',
|
|
29
|
+
'.mp4': 'video/mp4',
|
|
30
|
+
'.mp3': 'audio/mpeg',
|
|
31
|
+
'.csv': 'text/csv; charset=utf-8',
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
function toWebRequest(req: IncomingMessage, maxBodySize: number): { request?: Request; errorStatus?: number } {
|
|
35
|
+
const host = req.headers.host || 'localhost';
|
|
36
|
+
const url = `http://${host}${req.url || '/'}`;
|
|
37
|
+
const method = req.method || 'GET';
|
|
38
|
+
|
|
39
|
+
const clRaw = req.headers['content-length'];
|
|
40
|
+
if (clRaw !== undefined) {
|
|
41
|
+
const cl = Number(Array.isArray(clRaw) ? clRaw[0] : clRaw);
|
|
42
|
+
if (Number.isFinite(cl) && cl > maxBodySize) {
|
|
43
|
+
return { errorStatus: 413 };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const headers = new Headers();
|
|
48
|
+
const raw = req.rawHeaders;
|
|
49
|
+
if (raw && raw.length > 0) {
|
|
50
|
+
for (let i = 0; i < raw.length; i += 2) {
|
|
51
|
+
headers.append(raw[i]!, raw[i + 1]!);
|
|
52
|
+
}
|
|
53
|
+
} else {
|
|
54
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
55
|
+
if (v === undefined) continue;
|
|
56
|
+
if (Array.isArray(v)) {
|
|
57
|
+
for (const item of v) headers.append(k, item);
|
|
58
|
+
} else {
|
|
59
|
+
headers.set(k, v);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const hasBody = method !== 'GET' && method !== 'HEAD';
|
|
65
|
+
let body: ReadableStream<Uint8Array> | undefined;
|
|
66
|
+
if (hasBody) {
|
|
67
|
+
let total = 0;
|
|
68
|
+
const nodeStream = req;
|
|
69
|
+
body = new ReadableStream<Uint8Array>({
|
|
70
|
+
start(controller) {
|
|
71
|
+
nodeStream.on('data', (chunk: Buffer) => {
|
|
72
|
+
total += chunk.byteLength;
|
|
73
|
+
if (total > maxBodySize) {
|
|
74
|
+
const err: any = new Error('Payload Too Large');
|
|
75
|
+
err.status = 413;
|
|
76
|
+
controller.error(err);
|
|
77
|
+
nodeStream.destroy();
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
|
|
81
|
+
});
|
|
82
|
+
nodeStream.on('end', () => {
|
|
83
|
+
try { controller.close(); } catch {}
|
|
84
|
+
});
|
|
85
|
+
nodeStream.on('error', (err) => {
|
|
86
|
+
try { controller.error(err); } catch {}
|
|
87
|
+
});
|
|
88
|
+
},
|
|
89
|
+
cancel() {
|
|
90
|
+
nodeStream.destroy();
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const init: RequestInit & { duplex?: 'half' } = { method, headers };
|
|
96
|
+
if (body) {
|
|
97
|
+
init.body = body;
|
|
98
|
+
init.duplex = 'half';
|
|
99
|
+
}
|
|
100
|
+
return { request: new Request(url, init) };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function writeWebResponse(webRes: Response, res: ServerResponse): Promise<void> {
|
|
104
|
+
if (res.writableEnded || res.destroyed) return;
|
|
105
|
+
|
|
106
|
+
const headersObj: Record<string, string | string[]> = {};
|
|
107
|
+
webRes.headers.forEach((value, key) => {
|
|
108
|
+
if (key.toLowerCase() === 'set-cookie') return;
|
|
109
|
+
headersObj[key] = value;
|
|
110
|
+
});
|
|
111
|
+
const cookies = typeof (webRes.headers as any).getSetCookie === 'function'
|
|
112
|
+
? (webRes.headers as any).getSetCookie()
|
|
113
|
+
: [];
|
|
114
|
+
if (cookies.length > 0) {
|
|
115
|
+
headersObj['set-cookie'] = cookies;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
res.writeHead(webRes.status, headersObj);
|
|
119
|
+
if (typeof res.flushHeaders === 'function') res.flushHeaders();
|
|
120
|
+
|
|
121
|
+
if (!webRes.body) {
|
|
122
|
+
res.end();
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const reader = webRes.body.getReader();
|
|
127
|
+
try {
|
|
128
|
+
while (true) {
|
|
129
|
+
const { done, value } = await reader.read();
|
|
130
|
+
if (done) break;
|
|
131
|
+
if (res.destroyed || res.writableEnded) {
|
|
132
|
+
await reader.cancel().catch(() => {});
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
if (value && value.byteLength > 0) {
|
|
136
|
+
const ok = res.write(value);
|
|
137
|
+
if (!ok) {
|
|
138
|
+
await new Promise<void>((resolve) => {
|
|
139
|
+
const onDrain = () => { res.off('close', onClose); resolve(); };
|
|
140
|
+
const onClose = () => { res.off('drain', onDrain); resolve(); };
|
|
141
|
+
res.once('drain', onDrain);
|
|
142
|
+
res.once('close', onClose);
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
} finally {
|
|
148
|
+
try { reader.releaseLock(); } catch {}
|
|
149
|
+
if (!res.writableEnded && !res.destroyed) {
|
|
150
|
+
res.end();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export const nodeDriver: RuntimeDriver = {
|
|
156
|
+
name: 'node',
|
|
157
|
+
|
|
158
|
+
serve(opts: ServeOptions): ServerHandle {
|
|
159
|
+
const server = createServer(async (req, res) => {
|
|
160
|
+
const parsed = toWebRequest(req, opts.maxRequestBodySize);
|
|
161
|
+
if (parsed.errorStatus === 413 || !parsed.request) {
|
|
162
|
+
res.writeHead(413, { 'content-type': 'application/json' });
|
|
163
|
+
res.end(JSON.stringify({ status: 'error', message: 'Payload Too Large' }));
|
|
164
|
+
req.resume();
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const peerIp = req.socket?.remoteAddress;
|
|
169
|
+
try {
|
|
170
|
+
const webRes = await opts.fetch(parsed.request, peerIp);
|
|
171
|
+
await writeWebResponse(webRes, res);
|
|
172
|
+
} catch (err: any) {
|
|
173
|
+
if (!res.headersSent) {
|
|
174
|
+
const status = err?.status === 413 ? 413 : 500;
|
|
175
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
176
|
+
res.end(JSON.stringify({ status: 'error', message: err?.message || 'Internal Server Error' }));
|
|
177
|
+
} else if (!res.writableEnded) {
|
|
178
|
+
res.end();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
if (opts.ws) {
|
|
184
|
+
const wsCfg = opts.ws;
|
|
185
|
+
let wssPromise: Promise<any> | null = null;
|
|
186
|
+
const getWss = () => {
|
|
187
|
+
if (!wssPromise) {
|
|
188
|
+
const wsPkg = 'ws';
|
|
189
|
+
wssPromise = import(wsPkg).then(
|
|
190
|
+
(m: any) => new m.WebSocketServer({ noServer: true }),
|
|
191
|
+
() => {
|
|
192
|
+
throw new Error(
|
|
193
|
+
'[BareJS] WebSocket on Node.js requires the optional peer dependency "ws". Install it with: npm install ws'
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
return wssPromise;
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
server.on('upgrade', async (req, socket, head) => {
|
|
202
|
+
const matched = matchWsRoute(wsCfg.routes, req.url || '/');
|
|
203
|
+
if (!matched) {
|
|
204
|
+
socket.destroy();
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
const wss = await getWss();
|
|
209
|
+
wss.handleUpgrade(req, socket, head, (rawWs: any) => {
|
|
210
|
+
const data = matched.params ? { ...matched.handler, params: matched.params } : matched.handler;
|
|
211
|
+
rawWs.data = data;
|
|
212
|
+
wsCfg.adapter.open(rawWs);
|
|
213
|
+
rawWs.on('message', (msg: any, isBinary: boolean) => {
|
|
214
|
+
const payload = isBinary ? (Buffer.isBuffer(msg) ? msg : Buffer.from(msg)) : msg.toString();
|
|
215
|
+
wsCfg.adapter.message(rawWs, payload);
|
|
216
|
+
});
|
|
217
|
+
rawWs.on('close', (code: number, reason: Buffer) => {
|
|
218
|
+
wsCfg.adapter.close(rawWs, code, reason?.toString?.() ?? '');
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
} catch (err) {
|
|
222
|
+
console.error(err);
|
|
223
|
+
socket.destroy();
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const listenOpts: any = { port: opts.port, host: opts.hostname };
|
|
229
|
+
if (opts.reusePort) {
|
|
230
|
+
// Node >= 22.12 supports reusePort; older Node ignores or throws EINVAL on unsupported platforms
|
|
231
|
+
const parts = process.versions?.node?.split('.').map(Number) || [];
|
|
232
|
+
if ((parts[0] ?? 0) > 22 || ((parts[0] ?? 0) === 22 && (parts[1] ?? 0) >= 12)) {
|
|
233
|
+
listenOpts.reusePort = true;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
server.listen(listenOpts);
|
|
237
|
+
|
|
238
|
+
const addr = server.address();
|
|
239
|
+
const boundPort = typeof addr === 'object' && addr ? addr.port : opts.port;
|
|
240
|
+
|
|
241
|
+
return {
|
|
242
|
+
stop(closeActiveConnections = false) {
|
|
243
|
+
return new Promise<void>((resolve) => {
|
|
244
|
+
if (closeActiveConnections && typeof (server as any).closeAllConnections === 'function') {
|
|
245
|
+
(server as any).closeAllConnections();
|
|
246
|
+
}
|
|
247
|
+
server.close(() => resolve());
|
|
248
|
+
});
|
|
249
|
+
},
|
|
250
|
+
port: boundPort,
|
|
251
|
+
raw: server
|
|
252
|
+
};
|
|
253
|
+
},
|
|
254
|
+
|
|
255
|
+
gzip(data: Uint8Array, level: number): Uint8Array {
|
|
256
|
+
return new Uint8Array(gzipSync(data, { level }));
|
|
257
|
+
},
|
|
258
|
+
|
|
259
|
+
openFile(path: string): RuntimeFileHandle {
|
|
260
|
+
const ext = extname(path).toLowerCase();
|
|
261
|
+
const mime = MIME_MAP[ext] || 'application/octet-stream';
|
|
262
|
+
return {
|
|
263
|
+
type: mime,
|
|
264
|
+
full() {
|
|
265
|
+
return Readable.toWeb(createReadStream(path));
|
|
266
|
+
},
|
|
267
|
+
slice(start: number, endExclusive: number) {
|
|
268
|
+
const endInclusive = Math.max(start, endExclusive - 1);
|
|
269
|
+
return Readable.toWeb(createReadStream(path, { start, end: endInclusive }));
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
},
|
|
273
|
+
|
|
274
|
+
password: {
|
|
275
|
+
async hash(data: string, cfg: RuntimePasswordConfig): Promise<string> {
|
|
276
|
+
if (cfg.algorithm === 'bcrypt') {
|
|
277
|
+
let bcrypt: any;
|
|
278
|
+
try {
|
|
279
|
+
const pkg = 'bcryptjs';
|
|
280
|
+
bcrypt = await import(pkg);
|
|
281
|
+
} catch {
|
|
282
|
+
throw new Error(
|
|
283
|
+
'[BareJS] bcrypt hashing on Node.js requires optional peer dependency "bcryptjs". Install it with: npm install bcryptjs'
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
const cost = Math.max(4, Math.min(31, cfg.timeCost));
|
|
287
|
+
return bcrypt.default ? bcrypt.default.hash(data, cost) : bcrypt.hash(data, cost);
|
|
288
|
+
}
|
|
289
|
+
let argon2: any;
|
|
290
|
+
try {
|
|
291
|
+
const pkg = '@node-rs/argon2';
|
|
292
|
+
argon2 = await import(pkg);
|
|
293
|
+
} catch {
|
|
294
|
+
throw new Error(
|
|
295
|
+
'[BareJS] Argon2id hashing on Node.js requires optional peer dependency "@node-rs/argon2". Install it with: npm install @node-rs/argon2'
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
const fn = argon2.hash ?? argon2.default?.hash;
|
|
299
|
+
return fn(data, {
|
|
300
|
+
algorithm: argon2.Algorithm?.Argon2id ?? 2,
|
|
301
|
+
memoryCost: cfg.memoryCost,
|
|
302
|
+
timeCost: cfg.timeCost
|
|
303
|
+
});
|
|
304
|
+
},
|
|
305
|
+
|
|
306
|
+
async verify(data: string, hash: string): Promise<boolean> {
|
|
307
|
+
if (!hash || typeof hash !== 'string') return false;
|
|
308
|
+
if (/^\$2[aby]\$/.test(hash)) {
|
|
309
|
+
let bcrypt: any;
|
|
310
|
+
try {
|
|
311
|
+
const pkg = 'bcryptjs';
|
|
312
|
+
bcrypt = await import(pkg);
|
|
313
|
+
} catch {
|
|
314
|
+
throw new Error(
|
|
315
|
+
'[BareJS] bcrypt verification on Node.js requires optional peer dependency "bcryptjs".'
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
return bcrypt.default ? bcrypt.default.compare(data, hash) : bcrypt.compare(data, hash);
|
|
319
|
+
}
|
|
320
|
+
let argon2: any;
|
|
321
|
+
try {
|
|
322
|
+
const pkg = '@node-rs/argon2';
|
|
323
|
+
argon2 = await import(pkg);
|
|
324
|
+
} catch {
|
|
325
|
+
throw new Error(
|
|
326
|
+
'[BareJS] Argon2id verification on Node.js requires optional peer dependency "@node-rs/argon2".'
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
const fn = argon2.verify ?? argon2.default?.verify;
|
|
330
|
+
return fn(hash, data);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { WebSocketRouteHandler } from '../core/ws-match';
|
|
2
|
+
|
|
3
|
+
export interface ServeOptions {
|
|
4
|
+
port: number;
|
|
5
|
+
hostname: string;
|
|
6
|
+
reusePort: boolean;
|
|
7
|
+
maxRequestBodySize: number;
|
|
8
|
+
fetch: (req: Request, peerIp?: string) => Response | Promise<Response>;
|
|
9
|
+
ws?: {
|
|
10
|
+
routes: Map<string, WebSocketRouteHandler>;
|
|
11
|
+
adapter: {
|
|
12
|
+
open(ws: any): void;
|
|
13
|
+
message(ws: any, msg: any): void;
|
|
14
|
+
close(ws: any, code: any, reason: any): void;
|
|
15
|
+
drain(ws: any): void;
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ServerHandle {
|
|
21
|
+
stop(closeActiveConnections?: boolean): void | Promise<void>;
|
|
22
|
+
port: number;
|
|
23
|
+
/** Underlying runtime server instance (e.g. Bun Server or node:http Server) */
|
|
24
|
+
raw: any;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface RuntimeFileHandle {
|
|
28
|
+
readonly type: string;
|
|
29
|
+
full(): any;
|
|
30
|
+
slice(start: number, endExclusive: number): any;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface RuntimePasswordConfig {
|
|
34
|
+
algorithm: 'argon2id' | 'bcrypt';
|
|
35
|
+
memoryCost: number;
|
|
36
|
+
timeCost: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface RuntimeDriver {
|
|
40
|
+
readonly name: 'bun' | 'node';
|
|
41
|
+
serve(opts: ServeOptions): ServerHandle;
|
|
42
|
+
gzip(data: Uint8Array, level: number): Uint8Array;
|
|
43
|
+
zstd?: (data: Uint8Array) => Uint8Array;
|
|
44
|
+
openFile(path: string): RuntimeFileHandle;
|
|
45
|
+
password: {
|
|
46
|
+
hash(data: string, cfg: RuntimePasswordConfig): Promise<string>;
|
|
47
|
+
verify(data: string, hash: string): Promise<boolean>;
|
|
48
|
+
};
|
|
49
|
+
}
|
package/src/security/hash.ts
CHANGED
|
@@ -1,19 +1,16 @@
|
|
|
1
1
|
// src/security/hash.ts
|
|
2
2
|
import { BARE_CONFIG } from '../core/config';
|
|
3
|
+
import { runtime } from '../runtime';
|
|
3
4
|
|
|
4
5
|
export const Hash = {
|
|
5
6
|
make: (data: string): Promise<string> => {
|
|
6
|
-
|
|
7
|
-
const cost = Math.max(4, Math.min(31, BARE_CONFIG.hash.timeCost));
|
|
8
|
-
return Bun.password.hash(data, { algorithm: 'bcrypt', cost });
|
|
9
|
-
}
|
|
10
|
-
return Bun.password.hash(data, BARE_CONFIG.hash);
|
|
7
|
+
return runtime.password.hash(data, BARE_CONFIG.hash);
|
|
11
8
|
},
|
|
12
9
|
|
|
13
10
|
verify: async (data: string, hash: string): Promise<boolean> => {
|
|
14
11
|
if (!hash || typeof hash !== 'string') return false;
|
|
15
12
|
try {
|
|
16
|
-
return await
|
|
13
|
+
return await runtime.password.verify(data, hash);
|
|
17
14
|
} catch {
|
|
18
15
|
return false;
|
|
19
16
|
}
|
|
@@ -274,7 +274,9 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
|
|
|
274
274
|
if (!(ctx as any)._detached && !isStream && status >= 200 && status < 300) {
|
|
275
275
|
if (isResp) {
|
|
276
276
|
let cloned: any = null;
|
|
277
|
-
|
|
277
|
+
if (!resVal.bodyUsed) {
|
|
278
|
+
try { cloned = resVal.clone(); } catch { cloned = null; }
|
|
279
|
+
}
|
|
278
280
|
if (cloned) {
|
|
279
281
|
const ct = cloned.headers.get('content-type') || 'application/json';
|
|
280
282
|
return cloned.arrayBuffer().then((buf: ArrayBuffer) => {
|
package/src/utils/compress.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Context, Middleware, Next } from '../core/context';
|
|
2
2
|
import { brotliCompressSync, constants as zlibConstants } from 'node:zlib';
|
|
3
|
+
import { runtime } from '../runtime';
|
|
3
4
|
|
|
4
5
|
export type CompressionEncoding = 'zstd' | 'br' | 'gzip';
|
|
5
6
|
|
|
@@ -20,7 +21,7 @@ export const compress = (options: CompressOptions = {}): Middleware => {
|
|
|
20
21
|
const minSize = options.minSize ?? 1024;
|
|
21
22
|
const level = options.level ?? 6;
|
|
22
23
|
const encodings: CompressionEncoding[] = options.encodings ?? ['zstd', 'br', 'gzip'];
|
|
23
|
-
const hasZstd = typeof
|
|
24
|
+
const hasZstd = typeof runtime.zstd === 'function';
|
|
24
25
|
|
|
25
26
|
const negotiate = (accept: string): CompressionEncoding | null => {
|
|
26
27
|
const lower = accept.toLowerCase();
|
|
@@ -78,13 +79,13 @@ export const compress = (options: CompressOptions = {}): Middleware => {
|
|
|
78
79
|
const raw = new Uint8Array(buf);
|
|
79
80
|
let compressed: Uint8Array;
|
|
80
81
|
if (chosen === 'zstd') {
|
|
81
|
-
compressed =
|
|
82
|
+
compressed = runtime.zstd!(raw);
|
|
82
83
|
} else if (chosen === 'br') {
|
|
83
84
|
compressed = brotliCompressSync(raw, {
|
|
84
85
|
params: { [zlibConstants.BROTLI_PARAM_QUALITY]: Math.min(11, Math.max(1, level)) }
|
|
85
86
|
});
|
|
86
87
|
} else {
|
|
87
|
-
compressed =
|
|
88
|
+
compressed = runtime.gzip(raw, level);
|
|
88
89
|
}
|
|
89
90
|
|
|
90
91
|
const headers = new Headers(res.headers);
|
package/src/utils/static.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { resolve, sep } from 'node:path';
|
|
2
2
|
import { stat, realpath } from 'node:fs/promises';
|
|
3
|
+
import { runtime } from '../runtime';
|
|
3
4
|
|
|
4
5
|
export interface StaticMetadataCacheOptions {
|
|
5
6
|
/** Maximum cached file metadata entries (default: 1000) */
|
|
@@ -115,7 +116,7 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
|
|
|
115
116
|
}
|
|
116
117
|
}
|
|
117
118
|
|
|
118
|
-
const file =
|
|
119
|
+
const file = runtime.openFile(realFile);
|
|
119
120
|
|
|
120
121
|
const headers: Record<string, string> = {
|
|
121
122
|
'Cache-Control': `public, max-age=${maxAge}`,
|
|
@@ -181,7 +182,7 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
|
|
|
181
182
|
|
|
182
183
|
if (file.type) headers['Content-Type'] = file.type;
|
|
183
184
|
headers['Content-Length'] = String(fileSize);
|
|
184
|
-
return new Response(method === 'HEAD' ? null : file, { status: 200, headers });
|
|
185
|
+
return new Response(method === 'HEAD' ? null : file.full(), { status: 200, headers });
|
|
185
186
|
};
|
|
186
187
|
(mw as any).__isStatic = true;
|
|
187
188
|
return mw;
|