deserved 0.5.1 → 0.6.1

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.
@@ -0,0 +1,1098 @@
1
+ import { readdirSync, realpathSync, statSync } from "node:fs";
2
+ import { extname, isAbsolute, join, resolve, sep } from "node:path";
3
+
4
+ import { escapeHTML } from "bun";
5
+
6
+ import {
7
+ EVENTS_PATH,
8
+ type Hub,
9
+ injectLiveReload,
10
+ LIVE_PATH,
11
+ LIVE_SCRIPT,
12
+ SSE_HEADERS,
13
+ } from "./live";
14
+ import { logRequest } from "./log";
15
+ import { DEFAULT_OPTIONS, type Options } from "./options";
16
+
17
+ type ResolvedFile = {
18
+ path: string;
19
+ file: Bun.BunFile;
20
+ size: number;
21
+ mtimeMs: number;
22
+ kind: "file" | "html-ext" | "dir-index";
23
+ };
24
+
25
+ type Handler = {
26
+ (req: Request): Promise<Response>;
27
+ invalidateResolutionCache(): void;
28
+ invalidateCompressedCache(): void;
29
+ resolutionCacheSize(): number;
30
+ compressedCacheBytes(): number;
31
+ };
32
+
33
+ const encoder = new TextEncoder();
34
+ const FALLBACK = "application/octet-stream";
35
+
36
+ const EXT_MAP: Record<string, string> = {
37
+ ".html": "text/html;charset=utf-8",
38
+ ".htm": "text/html;charset=utf-8",
39
+ ".css": "text/css;charset=utf-8",
40
+ ".js": "text/javascript;charset=utf-8",
41
+ ".mjs": "text/javascript;charset=utf-8",
42
+ ".json": "application/json;charset=utf-8",
43
+ ".svg": "image/svg+xml",
44
+ ".txt": "text/plain;charset=utf-8",
45
+ ".xml": "application/xml",
46
+ ".wasm": "application/wasm",
47
+ ".woff": "font/woff",
48
+ ".woff2": "font/woff2",
49
+ ".map": "application/json",
50
+ };
51
+
52
+ export function contentType(file: Bun.BunFile, path: string): string {
53
+ const type = file.type;
54
+ if (type && type !== FALLBACK && type !== "") return type;
55
+
56
+ const ext = extname(path).toLowerCase();
57
+ return EXT_MAP[ext] ?? FALLBACK;
58
+ }
59
+
60
+ export function isCompressible(type: string): boolean {
61
+ const semi = type.indexOf(";");
62
+ const base = (semi === -1 ? type : type.slice(0, semi)).trim().toLowerCase();
63
+ return (
64
+ base.startsWith("text/") ||
65
+ base === "application/javascript" ||
66
+ base === "text/javascript" ||
67
+ base === "application/json" ||
68
+ base === "application/xml" ||
69
+ base === "image/svg+xml" ||
70
+ base.endsWith("+json") ||
71
+ base.endsWith("+xml")
72
+ );
73
+ }
74
+
75
+ export function isHtml(type: string): boolean {
76
+ return type.startsWith("text/html");
77
+ }
78
+
79
+ export function makeEtag(size: number, mtimeMs: number, tag = ""): string {
80
+ return `"${size}-${Math.trunc(mtimeMs)}${tag}"`;
81
+ }
82
+
83
+ // A strong ETag promises byte-identical bodies, which a compressed and an
84
+ // identity response for the same file aren't. Weak comparison (used for
85
+ // If-None-Match) still matches, so 304s keep working; If-Range, which
86
+ // needs a strong match, falls back to a full response.
87
+ function weaken(tag: string): string {
88
+ return `W/${tag}`;
89
+ }
90
+
91
+ function stripWeak(tag: string): string {
92
+ return tag.startsWith("W/") ? tag.slice(2) : tag;
93
+ }
94
+
95
+ function etagMatches(inm: string, etag: string): boolean {
96
+ // Common case is a single value with no comma -- skip the split() array
97
+ // allocation entirely when there's nothing to split.
98
+ if (inm.indexOf(",") === -1) return stripWeak(inm.trim()) === etag;
99
+ return inm.split(",").some((t) => stripWeak(t.trim()) === etag);
100
+ }
101
+
102
+ export function notModifiedSince(req: Request, mtimeMs: number): boolean {
103
+ const ims = req.headers.get("If-Modified-Since");
104
+ if (!ims) return false;
105
+ const since = Date.parse(ims);
106
+ if (Number.isNaN(since)) return false;
107
+ return Math.trunc(mtimeMs / 1000) * 1000 <= since;
108
+ }
109
+
110
+ export function isNotModified(
111
+ req: Request,
112
+ etag: string,
113
+ mtimeMs: number,
114
+ ): boolean {
115
+ const inm = req.headers.get("If-None-Match");
116
+ return inm ? etagMatches(inm, etag) : notModifiedSince(req, mtimeMs);
117
+ }
118
+
119
+ export function ifRangeSatisfied(
120
+ req: Request,
121
+ etag: string,
122
+ mtimeMs: number,
123
+ ): boolean {
124
+ const ifRange = req.headers.get("If-Range");
125
+ if (!ifRange) return true;
126
+
127
+ if (ifRange.startsWith('"') || ifRange.startsWith("W/")) {
128
+ return ifRange === etag;
129
+ }
130
+
131
+ const date = Date.parse(ifRange);
132
+ if (Number.isNaN(date)) return false;
133
+ return date === Math.trunc(mtimeMs / 1000) * 1000;
134
+ }
135
+
136
+ export function acceptsHtml(req: Request): boolean {
137
+ const accept = req.headers.get("Accept");
138
+ if (!accept || accept === "*/*") return true;
139
+ return accept.includes("text/html") || accept.includes("application/xhtml");
140
+ }
141
+
142
+ export type CompressionEncoding = "zstd" | "gzip";
143
+
144
+ // zstd compresses faster and smaller than gzip, but not every client
145
+ // speaks it yet (e.g. Safari), so negotiate rather than replacing gzip
146
+ // outright.
147
+ export function pickEncoding(req: Request): CompressionEncoding | null {
148
+ const accept = req.headers.get("Accept-Encoding");
149
+ if (!accept) return null;
150
+ // Browsers never send q=0, so only parse when an encoding might be
151
+ // explicitly refused (e.g. `gzip;q=0`).
152
+ if (!accept.includes("q=0")) {
153
+ if (accept.includes("zstd")) return "zstd";
154
+ if (accept.includes("gzip")) return "gzip";
155
+ return null;
156
+ }
157
+ const accepted = new Set<string>();
158
+ for (const part of accept.split(",")) {
159
+ const [name = "", ...params] = part.split(";");
160
+ const q = params.map((p) => p.trim()).find((p) => p.startsWith("q="));
161
+ if (q !== undefined && Number(q.slice(2)) === 0) continue;
162
+ accepted.add(name.trim().toLowerCase());
163
+ }
164
+ if (accepted.has("zstd")) return "zstd";
165
+ if (accepted.has("gzip")) return "gzip";
166
+ return null;
167
+ }
168
+
169
+ export function shouldSpaFallback(pathname: string): boolean {
170
+ if (pathname.startsWith("/__")) return false;
171
+ const slashIdx = pathname.lastIndexOf("/");
172
+ if (slashIdx === pathname.length - 1) return true;
173
+ return pathname.indexOf(".", slashIdx + 1) === -1;
174
+ }
175
+
176
+ const WELL_KNOWN = "/.well-known";
177
+
178
+ // Dotfiles (.env, .git/) stay private even when serving a project root;
179
+ // /.well-known/ is the one dot-directory that's meant to be public.
180
+ export function isHiddenPath(pathname: string): boolean {
181
+ const from =
182
+ pathname.startsWith(WELL_KNOWN) &&
183
+ (pathname.length === WELL_KNOWN.length ||
184
+ pathname[WELL_KNOWN.length] === "/")
185
+ ? WELL_KNOWN.length
186
+ : 0;
187
+ return pathname.indexOf("/.", from) !== -1;
188
+ }
189
+
190
+ export function resolveFileWithRoot(
191
+ rootAbs: string,
192
+ realRoot: string | null,
193
+ pathname: string,
194
+ ): ResolvedFile | null {
195
+ if (!realRoot) return null;
196
+ const relative = pathname.replace(/^\/+/, "");
197
+ const candidates = buildCandidates(relative);
198
+
199
+ for (const candidate of candidates) {
200
+ const full = safeJoin(rootAbs, candidate);
201
+ if (!full) continue;
202
+ const real = containedPath(realRoot, full);
203
+ if (!real) continue;
204
+ const resolved = statFile(real, candidateKind(candidate));
205
+ if (resolved) return resolved;
206
+ }
207
+
208
+ return null;
209
+ }
210
+
211
+ function statFile(
212
+ real: string,
213
+ kind: ResolvedFile["kind"],
214
+ ): ResolvedFile | null {
215
+ try {
216
+ const st = statSync(real);
217
+ if (st.isFile()) {
218
+ return {
219
+ path: real,
220
+ file: Bun.file(real),
221
+ size: st.size,
222
+ mtimeMs: st.mtimeMs,
223
+ kind,
224
+ };
225
+ }
226
+ } catch {}
227
+ return null;
228
+ }
229
+
230
+ // Cap on distinct pathnames tracked per handler (file and dir maps each).
231
+ // Evicted LRU-style past this limit -- Map iteration order is insertion
232
+ // order, and every reused hit re-inserts its key, so the front of the map
233
+ // is always the least-recently-used entry, the same trick
234
+ // createCompressionCache.touch uses.
235
+ export const RESOLUTION_CACHE_LIMIT = 4096;
236
+
237
+ function evictOldest<T>(map: Map<string, T>, limit: number): void {
238
+ if (map.size < limit) return;
239
+ const oldestKey = map.keys().next().value;
240
+ if (oldestKey !== undefined) map.delete(oldestKey);
241
+ }
242
+
243
+ function markRecent<T>(map: Map<string, T>, key: string, entry: T): void {
244
+ map.delete(key);
245
+ map.set(key, entry);
246
+ }
247
+
248
+ // Bounds staleness in non-watch mode: a newly created or deleted candidate
249
+ // (e.g. adding about.html for a pathname previously cached as a 404)
250
+ // becomes visible within this window.
251
+ export const RESOLUTION_TTL_MS = 500;
252
+
253
+ type Cached<T> = { value: T | null; at: number };
254
+
255
+ // Remembers which candidate (if any) a pathname resolves to, so a repeat
256
+ // request skips the safeJoin + realpath containment walk across up to 3
257
+ // candidates -- the dominant cost of a 404 probe.
258
+ //
259
+ // Two freshness contracts, chosen by `watch`:
260
+ // - Non-watch: a hit re-stats the winning candidate every time, so content
261
+ // edits are visible on the very next request. Only *which file wins* (or
262
+ // whether one exists at all) can go stale, bounded by RESOLUTION_TTL_MS.
263
+ // - --watch: startServer's fs watcher already calls
264
+ // invalidateResolutionCache() on every change, clearing this map, so a hit within that window is
265
+ // already known-fresh -- re-stating it would only reconfirm what the
266
+ // watcher guarantees. A hit returns the cached ResolvedFile (including
267
+ // size/mtimeMs) directly, no statSync. This is the dominant cost on the
268
+ // handler hot path (~45%), so skipping it matters more here than the TTL
269
+ // does in non-watch mode. staleness is instead bounded by the watcher's
270
+ // event delivery (tens of ms), exactly as file existence already is.
271
+ //
272
+ // If the cached candidate no longer stats as a file (deleted, replaced by
273
+ // a dir, symlink now escapes root), resolution falls through and re-probes
274
+ // for real instead of trusting the stale entry -- this only applies to the
275
+ // non-watch re-stat path; a watch-mode hit is trusted outright.
276
+ //
277
+ // The directory-resolution side (resolveDirCached) mirrors the non-watch
278
+ // contract in both modes: it always re-confirms isDirectory() on a fresh
279
+ // hit, since a stale directory listing is comparatively cheap to redo.
280
+ function createResolutionCache(
281
+ rootAbs: string,
282
+ realRoot: string | null,
283
+ watch: boolean,
284
+ ) {
285
+ const files = new Map<string, Cached<ResolvedFile>>();
286
+ const dirs = new Map<string, Cached<string>>();
287
+
288
+ // `revalidate` returns the value to serve for a fresh cached winner, or
289
+ // null if it no longer holds (deleted or changed kind), forcing a
290
+ // re-probe.
291
+ function lookup<T>(
292
+ map: Map<string, Cached<T>>,
293
+ pathname: string,
294
+ probe: (pathname: string) => T | null,
295
+ revalidate: (value: T) => T | null,
296
+ ): T | null {
297
+ const cached = map.get(pathname);
298
+ if (cached && (watch || Date.now() - cached.at < RESOLUTION_TTL_MS)) {
299
+ const hit = cached.value === null ? null : revalidate(cached.value);
300
+ if (cached.value === null || hit !== null) {
301
+ markRecent(map, pathname, cached);
302
+ return hit;
303
+ }
304
+ }
305
+
306
+ const value = probe(pathname);
307
+ evictOldest(map, RESOLUTION_CACHE_LIMIT);
308
+ map.set(pathname, { value, at: Date.now() });
309
+ return value;
310
+ }
311
+
312
+ const probeFile = (pathname: string) =>
313
+ resolveFileWithRoot(rootAbs, realRoot, pathname);
314
+ const probeDir = (pathname: string) =>
315
+ resolveDirWithRoot(rootAbs, realRoot, pathname);
316
+ const revalidateFile = watch
317
+ ? (file: ResolvedFile) => file
318
+ : (file: ResolvedFile) => statFile(file.path, file.kind);
319
+ const revalidateDir = (dir: string) => (isDirectory(dir) ? dir : null);
320
+
321
+ return {
322
+ resolveCached: (pathname: string) =>
323
+ lookup(files, pathname, probeFile, revalidateFile),
324
+ resolveDirCached: (pathname: string) =>
325
+ lookup(dirs, pathname, probeDir, revalidateDir),
326
+ invalidate: () => {
327
+ files.clear();
328
+ dirs.clear();
329
+ },
330
+ size: () => files.size,
331
+ };
332
+ }
333
+
334
+ function isDirectory(path: string): boolean {
335
+ try {
336
+ return statSync(path).isDirectory();
337
+ } catch {
338
+ return false;
339
+ }
340
+ }
341
+
342
+ function candidateKind(candidate: string): ResolvedFile["kind"] {
343
+ if (candidate.endsWith("/index.html")) return "dir-index";
344
+ if (candidate.endsWith(".html")) return "html-ext";
345
+ return "file";
346
+ }
347
+
348
+ export function buildCandidates(relative: string): string[] {
349
+ if (!relative || relative === ".") {
350
+ return ["index.html"];
351
+ }
352
+
353
+ const trailingSlash = relative.endsWith("/");
354
+ const base = trailingSlash ? relative.slice(0, -1) : relative;
355
+ if (!base) return ["index.html"];
356
+
357
+ if (trailingSlash) {
358
+ return [`${base}/index.html`];
359
+ }
360
+
361
+ return [base, `${base}.html`, `${base}/index.html`];
362
+ }
363
+
364
+ export function safeJoin(root: string, relative: string): string | null {
365
+ // join() already normalizes its result, and every caller here already
366
+ // passes an absolute root -- resolve() only matters for the rare caller
367
+ // that doesn't, so skip it (and the cwd lookup it implies) when we can.
368
+ const rootAbs = isAbsolute(root) ? root : resolve(root);
369
+ const full = join(rootAbs, relative);
370
+ if (full !== rootAbs && !full.startsWith(rootAbs + sep)) {
371
+ return null;
372
+ }
373
+ return full;
374
+ }
375
+
376
+ function containedPath(realRoot: string, full: string): string | null {
377
+ try {
378
+ const real = realpathSync(full);
379
+ if (real !== realRoot && !real.startsWith(realRoot + sep)) return null;
380
+ return real;
381
+ } catch {
382
+ return null;
383
+ }
384
+ }
385
+
386
+ function realpathRoot(rootAbs: string): string | null {
387
+ try {
388
+ return realpathSync(rootAbs);
389
+ } catch {
390
+ return null;
391
+ }
392
+ }
393
+
394
+ export function resolveDirWithRoot(
395
+ rootAbs: string,
396
+ realRoot: string | null,
397
+ pathname: string,
398
+ ): string | null {
399
+ if (!realRoot) return null;
400
+ const relative = pathname.replace(/^\/+/, "").replace(/\/+$/, "");
401
+ const full = safeJoin(rootAbs, relative || ".");
402
+ if (!full) return null;
403
+ const real = containedPath(realRoot, full);
404
+ return real && isDirectory(real) ? real : null;
405
+ }
406
+
407
+ type DirEntry = {
408
+ name: string;
409
+ dir: boolean;
410
+ size: number | null;
411
+ mtimeMs: number | null;
412
+ };
413
+
414
+ function formatSize(bytes: number | null): string {
415
+ if (bytes === null) return "-";
416
+ if (bytes < 1024) return `${bytes} B`;
417
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
418
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
419
+ }
420
+
421
+ function formatDate(mtimeMs: number | null): string {
422
+ if (mtimeMs === null) return "-";
423
+ const d = new Date(mtimeMs);
424
+ const year = d.getFullYear();
425
+ const month = String(d.getMonth() + 1).padStart(2, "0");
426
+ const date = String(d.getDate()).padStart(2, "0");
427
+ const hours = String(d.getHours()).padStart(2, "0");
428
+ const minutes = String(d.getMinutes()).padStart(2, "0");
429
+ return `${year}-${month}-${date} ${hours}:${minutes}`;
430
+ }
431
+
432
+ export function listDir(dir: string): DirEntry[] {
433
+ const dirents = readdirSync(dir, { withFileTypes: true });
434
+ const entries: DirEntry[] = [];
435
+
436
+ for (const e of dirents) {
437
+ if (e.name.startsWith(".")) continue;
438
+ const isDir = e.isDirectory();
439
+ let size: number | null = null;
440
+ let mtimeMs: number | null = null;
441
+ if (!isDir) {
442
+ try {
443
+ const st = statSync(join(dir, e.name));
444
+ size = st.size;
445
+ mtimeMs = st.mtimeMs;
446
+ } catch {}
447
+ }
448
+ entries.push({ name: e.name, dir: isDir, size, mtimeMs });
449
+ }
450
+
451
+ return entries.sort((a, b) => {
452
+ if (a.dir !== b.dir) return a.dir ? -1 : 1;
453
+ return a.name.localeCompare(b.name);
454
+ });
455
+ }
456
+
457
+ export function directoryListing(
458
+ pathname: string,
459
+ entries: DirEntry[],
460
+ ): string {
461
+ const base = pathname.endsWith("/") ? pathname : `${pathname}/`;
462
+ const encodedBase = encodeUrlPath(base);
463
+ const parent = parentPath(pathname);
464
+ const escapedPathname = escapeHTML(pathname);
465
+
466
+ const rows = entries
467
+ .map((e) => {
468
+ const href =
469
+ joinUrl(encodedBase, encodeURIComponent(e.name)) + (e.dir ? "/" : "");
470
+ const label = e.dir ? `${e.name}/` : e.name;
471
+ const size = formatSize(e.size);
472
+ const date = formatDate(e.mtimeMs);
473
+ return ` <li><a href="${escapeHTML(href)}">${escapeHTML(label)}</a> <span class="meta">${escapeHTML(size)}</span> <span class="meta">${escapeHTML(date)}</span></li>`;
474
+ })
475
+ .join("\n");
476
+
477
+ const up =
478
+ parent !== null
479
+ ? ` <li><a href="${escapeHTML(encodeUrlPath(parent))}">../</a> <span class="meta">-</span> <span class="meta">-</span></li>\n`
480
+ : "";
481
+
482
+ return `<!DOCTYPE html>
483
+ <html lang="en">
484
+ <head>
485
+ <meta charset="utf-8">
486
+ <meta name="viewport" content="width=device-width, initial-scale=1">
487
+ <title>Index of ${escapedPathname}</title>
488
+ <style>
489
+ :root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
490
+ body { max-width: 60rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
491
+ h1 { font-size: 1.1rem; font-weight: 600; }
492
+ ul { list-style: none; padding: 0; }
493
+ li { padding: 0.2rem 0; display: flex; gap: 2rem; }
494
+ li a { color: inherit; text-decoration: none; flex: 1; }
495
+ li a:hover { text-decoration: underline; }
496
+ .meta { text-align: right; min-width: 5rem; opacity: 0.6; }
497
+ </style>
498
+ </head>
499
+ <body>
500
+ <h1>Index of ${escapedPathname || "/"}</h1>
501
+ <ul>
502
+ ${up}${rows}
503
+ </ul>
504
+ </body>
505
+ </html>
506
+ `;
507
+ }
508
+
509
+ function parentPath(pathname: string): string | null {
510
+ if (pathname === "/" || pathname === "") return null;
511
+ const trimmed = pathname.replace(/\/+$/, "");
512
+ const idx = trimmed.lastIndexOf("/");
513
+ if (idx <= 0) return "/";
514
+ return trimmed.slice(0, idx + 1);
515
+ }
516
+
517
+ function encodeUrlPath(path: string): string {
518
+ return path.split("/").map(encodeURIComponent).join("/");
519
+ }
520
+
521
+ function joinUrl(base: string, name: string): string {
522
+ if (base === "/") return `/${name}`;
523
+ return `${base.replace(/\/+$/, "")}/${name}`;
524
+ }
525
+
526
+ type NotFoundCache = { size: number; mtimeMs: number; html: string };
527
+
528
+ type HandlerContext = {
529
+ opts: Options;
530
+ hub: Hub | undefined;
531
+ resolveCached: (pathname: string) => ResolvedFile | null;
532
+ resolveDirCached: (pathname: string) => string | null;
533
+ getCompressed: GetCompressed;
534
+ notFound: NotFoundCache | null;
535
+ };
536
+
537
+ // Cheaper than `new URL(req.url).pathname` (~74ns vs ~4ns) on the hot
538
+ // path; only the pathname is needed there, and Bun's req.url is always an
539
+ // absolute URL (http://host:port/path?query#hash).
540
+ function extractPathname(url: string): string {
541
+ const schemeEnd = url.indexOf("//");
542
+ const start = url.indexOf("/", schemeEnd === -1 ? 0 : schemeEnd + 2);
543
+ if (start === -1) return "/";
544
+ let end = url.length;
545
+ const q = url.indexOf("?", start);
546
+ if (q !== -1 && q < end) end = q;
547
+ const h = url.indexOf("#", start);
548
+ if (h !== -1 && h < end) end = h;
549
+ const path = url.slice(start, end);
550
+ return path === "" ? "/" : path;
551
+ }
552
+
553
+ export function createHandler(
554
+ options: Partial<Options> = {},
555
+ hub?: Hub,
556
+ ): Handler {
557
+ const opts: Options = { ...DEFAULT_OPTIONS, ...options };
558
+ const rootAbs = resolve(opts.root);
559
+ const realRoot = realpathRoot(rootAbs);
560
+ const resolution = createResolutionCache(rootAbs, realRoot, opts.watch);
561
+ const compression = createCompressionCache();
562
+ const ctx: HandlerContext = {
563
+ opts,
564
+ hub,
565
+ resolveCached: resolution.resolveCached,
566
+ resolveDirCached: resolution.resolveDirCached,
567
+ getCompressed: compression.getCompressed,
568
+ notFound: null,
569
+ };
570
+
571
+ const handle = async function handle(req: Request): Promise<Response> {
572
+ const rawPathname = extractPathname(req.url);
573
+ const method = req.method.toUpperCase();
574
+
575
+ let pathname: string;
576
+ if (rawPathname.includes("%")) {
577
+ try {
578
+ pathname = decodeURIComponent(rawPathname);
579
+ } catch {
580
+ const res = new Response("Bad Request", { status: 400 });
581
+ return finish(method, rawPathname, opts, res);
582
+ }
583
+ } else {
584
+ pathname = rawPathname;
585
+ }
586
+
587
+ try {
588
+ return await handleDecoded(req, method, pathname, rawPathname, ctx);
589
+ } catch (err) {
590
+ console.error(err);
591
+ const res = new Response("Internal Server Error", { status: 500 });
592
+ return finish(method, rawPathname, opts, res);
593
+ }
594
+ } as Handler;
595
+
596
+ handle.invalidateResolutionCache = () => {
597
+ resolution.invalidate();
598
+ ctx.notFound = null;
599
+ };
600
+ handle.invalidateCompressedCache = compression.invalidate;
601
+ handle.resolutionCacheSize = resolution.size;
602
+ handle.compressedCacheBytes = compression.bytes;
603
+ return handle;
604
+ }
605
+
606
+ function finish(
607
+ method: string,
608
+ pathname: string,
609
+ opts: Options,
610
+ res: Response,
611
+ ): Response {
612
+ logRequest(method, res.status, pathname, opts.quiet);
613
+ return headify(method, withCors(res, opts));
614
+ }
615
+
616
+ // rawPathname (not the decoded `pathname`) so a percent-encoded request
617
+ // like /my%20docs redirects to /my%20docs/, not an unencoded literal
618
+ // space. reqUrl is only parsed here, lazily, for the query string.
619
+ // Leading slashes collapse to one: `//evil.com/` in a Location header is
620
+ // protocol-relative, i.e. an open redirect to another host.
621
+ function directoryRedirect(rawPathname: string, reqUrl: string): Response {
622
+ const path = rawPathname.replace(/^\/+/, "/");
623
+ return new Response(null, {
624
+ status: 301,
625
+ headers: { Location: `${path}/${new URL(reqUrl).search}` },
626
+ });
627
+ }
628
+
629
+ function htmlPage(html: string, opts: Options, status = 200): Response {
630
+ return new Response(opts.watch ? injectLiveReload(html) : html, {
631
+ status,
632
+ headers: {
633
+ "Content-Type": "text/html;charset=utf-8",
634
+ "Cache-Control": "no-cache",
635
+ },
636
+ });
637
+ }
638
+
639
+ async function handleDecoded(
640
+ req: Request,
641
+ method: string,
642
+ pathname: string,
643
+ rawPathname: string,
644
+ ctx: HandlerContext,
645
+ ): Promise<Response> {
646
+ const { opts, hub, resolveCached, resolveDirCached, getCompressed } = ctx;
647
+ const send = (res: Response) => finish(method, pathname, opts, res);
648
+
649
+ if (opts.cors && method === "OPTIONS") {
650
+ return send(new Response(null, { status: 204 }));
651
+ }
652
+
653
+ if (method !== "GET" && method !== "HEAD") {
654
+ const res = new Response("Method Not Allowed", {
655
+ status: 405,
656
+ headers: { Allow: "GET, HEAD" },
657
+ });
658
+ return send(res);
659
+ }
660
+
661
+ if (opts.watch && pathname === LIVE_PATH) {
662
+ const res = new Response(LIVE_SCRIPT, {
663
+ headers: {
664
+ "Content-Type": "text/javascript;charset=utf-8",
665
+ "Cache-Control": "no-store",
666
+ },
667
+ });
668
+ return send(res);
669
+ }
670
+
671
+ if (opts.watch && pathname === EVENTS_PATH && hub) {
672
+ // HEAD gets the stream's headers without subscribing a client.
673
+ if (method === "HEAD") {
674
+ return send(new Response(null, { headers: SSE_HEADERS }));
675
+ }
676
+ // An open-ended stream skips send(): headify() would drop its body.
677
+ const res = hub.subscribe();
678
+ logRequest(method, 200, pathname, opts.quiet);
679
+ return withCors(res, opts);
680
+ }
681
+
682
+ // Stale tabs may still ask after --watch was used; stay quiet.
683
+ if (pathname === LIVE_PATH || pathname === EVENTS_PATH) {
684
+ return headify(
685
+ method,
686
+ withCors(new Response("Not Found", { status: 404 }), opts),
687
+ );
688
+ }
689
+
690
+ const hidden = isHiddenPath(pathname);
691
+ const resolved = hidden ? null : resolveCached(pathname);
692
+
693
+ if (resolved) {
694
+ if (resolved.kind === "dir-index" && !pathname.endsWith("/")) {
695
+ return send(directoryRedirect(rawPathname, req.url));
696
+ }
697
+ return send(await serveFile(getCompressed, req, resolved, opts));
698
+ }
699
+
700
+ const wantsHtml = acceptsHtml(req);
701
+
702
+ if (opts.spa && wantsHtml && shouldSpaFallback(pathname)) {
703
+ const index = resolveCached("/");
704
+ if (index) {
705
+ return send(await serveFile(getCompressed, req, index, opts, true));
706
+ }
707
+ }
708
+
709
+ if (opts.dir && !hidden) {
710
+ const dir = resolveDirCached(pathname);
711
+ if (dir) {
712
+ if (!pathname.endsWith("/"))
713
+ return send(directoryRedirect(rawPathname, req.url));
714
+ const html = directoryListing(pathname, listDir(dir));
715
+ return send(htmlPage(html, opts));
716
+ }
717
+ }
718
+
719
+ if (wantsHtml) {
720
+ const notFoundPage = resolveCached("/404.html");
721
+ if (notFoundPage) {
722
+ // Error pages are small; skip compression to keep this path simple.
723
+ // resolveCached above always re-stats the winner, so the cache below
724
+ // only needs to compare against that fresh (size, mtimeMs).
725
+ const cached = ctx.notFound;
726
+ const html =
727
+ cached &&
728
+ cached.size === notFoundPage.size &&
729
+ cached.mtimeMs === notFoundPage.mtimeMs
730
+ ? cached.html
731
+ : await (async () => {
732
+ const text = await notFoundPage.file.text();
733
+ ctx.notFound = {
734
+ size: notFoundPage.size,
735
+ mtimeMs: notFoundPage.mtimeMs,
736
+ html: text,
737
+ };
738
+ return text;
739
+ })();
740
+ return send(htmlPage(html, opts, 404));
741
+ }
742
+ }
743
+
744
+ return send(new Response("Not Found", { status: 404 }));
745
+ }
746
+
747
+ type CompressedEntry = {
748
+ size: number;
749
+ mtimeMs: number;
750
+ // Blob, not Uint8Array: `new Response(Blob)` is ~95ns regardless of size
751
+ // while `new Response(Uint8Array)` copies the buffer on every hit.
752
+ data: Blob;
753
+ };
754
+
755
+ // Bounded by total retained bytes, not entry count -- payload sizes vary
756
+ // too widely (a few KB of CSS vs a near-2MB image) for a count cap to
757
+ // bound memory in any useful way. Map iteration order is insertion order,
758
+ // and every touch (read or write) re-inserts its key, so the front of the
759
+ // map is always the least-recently-used entry -- evicting from there
760
+ // gives LRU behavior without a separate linked list.
761
+ export const COMPRESSED_CACHE_BYTE_BUDGET = 64 * 1024 * 1024;
762
+
763
+ // Bun 1.4's CompressionStream is native, so gzip runs off the main thread
764
+ // the same way Bun.zstdCompress does.
765
+ async function gzipCompress(
766
+ raw: Uint8Array<ArrayBuffer>,
767
+ ): Promise<Uint8Array<ArrayBuffer>> {
768
+ const cs = new CompressionStream("gzip");
769
+ const writer = cs.writable.getWriter();
770
+ writer.write(raw);
771
+ writer.close();
772
+ return new Uint8Array(await new Response(cs.readable).arrayBuffer());
773
+ }
774
+
775
+ export async function compress(
776
+ encoding: CompressionEncoding,
777
+ raw: Uint8Array<ArrayBuffer>,
778
+ ): Promise<Uint8Array<ArrayBuffer>> {
779
+ if (encoding === "zstd") {
780
+ return new Uint8Array(await Bun.zstdCompress(raw));
781
+ }
782
+ return gzipCompress(raw);
783
+ }
784
+
785
+ type GetCompressed = (
786
+ resolved: { key: string; size: number; mtimeMs: number },
787
+ encoding: CompressionEncoding,
788
+ loadRaw: () => Promise<Uint8Array<ArrayBuffer>>,
789
+ ) => Promise<Blob | null>;
790
+
791
+ type PendingCompression = {
792
+ size: number;
793
+ mtimeMs: number;
794
+ promise: Promise<Blob | null>;
795
+ };
796
+
797
+ /**
798
+ * Compressed-output cache scoped to one handler instance -- like
799
+ * createResolutionCache above, this keeps the (potentially large)
800
+ * compressed byte buffers it retains reclaimable as soon as the handler
801
+ * itself is no longer referenced, instead of pinning them for the life of
802
+ * the process the way a module-level cache would.
803
+ */
804
+ function createCompressionCache() {
805
+ const cache = new Map<string, CompressedEntry>();
806
+ let bytes = 0;
807
+
808
+ // In-flight compressions, keyed the same as cache plus the file version
809
+ // being compressed, so concurrent requests for a stale version in-flight
810
+ // don't get handed a promise for an even-older result.
811
+ const pending = new Map<string, PendingCompression>();
812
+
813
+ function touch(cacheKey: string, entry: CompressedEntry): void {
814
+ const prev = cache.get(cacheKey);
815
+ if (prev) bytes -= prev.data.size;
816
+ markRecent(cache, cacheKey, entry);
817
+ bytes += entry.data.size;
818
+
819
+ while (bytes > COMPRESSED_CACHE_BYTE_BUDGET && cache.size > 1) {
820
+ const oldestKey = cache.keys().next().value;
821
+ if (oldestKey === undefined) break;
822
+ const oldest = cache.get(oldestKey);
823
+ cache.delete(oldestKey);
824
+ if (oldest) bytes -= oldest.data.size;
825
+ }
826
+ }
827
+
828
+ /**
829
+ * Compressed-output cache keyed by (key, encoding, size, mtimeMs). Pick a
830
+ * distinct key when the same path can yield different bytes, like
831
+ * watch-injected HTML. loadRaw runs on miss. Concurrent misses for the
832
+ * same (key, encoding, version) single-flight onto one in-flight
833
+ * compression.
834
+ */
835
+ const getCompressed: GetCompressed = async (resolved, encoding, loadRaw) => {
836
+ const cacheKey = `${resolved.key}:${encoding}`;
837
+ const cached = cache.get(cacheKey);
838
+ if (
839
+ cached &&
840
+ cached.size === resolved.size &&
841
+ cached.mtimeMs === resolved.mtimeMs
842
+ ) {
843
+ touch(cacheKey, cached);
844
+ return cached.data;
845
+ }
846
+
847
+ const inFlight = pending.get(cacheKey);
848
+ if (
849
+ inFlight &&
850
+ inFlight.size === resolved.size &&
851
+ inFlight.mtimeMs === resolved.mtimeMs
852
+ ) {
853
+ return inFlight.promise;
854
+ }
855
+
856
+ const promise = (async () => {
857
+ try {
858
+ const raw = await loadRaw();
859
+ const data = new Blob([await compress(encoding, raw)]);
860
+ touch(cacheKey, {
861
+ size: resolved.size,
862
+ mtimeMs: resolved.mtimeMs,
863
+ data,
864
+ });
865
+ return data;
866
+ } catch {
867
+ return null;
868
+ }
869
+ })();
870
+
871
+ const entry: PendingCompression = {
872
+ size: resolved.size,
873
+ mtimeMs: resolved.mtimeMs,
874
+ promise,
875
+ };
876
+ pending.set(cacheKey, entry);
877
+ // Only drop our own entry: a newer version may have replaced it.
878
+ promise.finally(() => {
879
+ if (pending.get(cacheKey) === entry) pending.delete(cacheKey);
880
+ });
881
+ return promise;
882
+ };
883
+
884
+ // The byte budget above only bounds *how much* a stale entry can cost,
885
+ // not *whether* one lingers -- a path that's deleted (e.g. a bundler's
886
+ // content-hashed output on rebuild) is never requested again, so its
887
+ // entry is never naturally replaced or evicted. Watch mode already knows
888
+ // a change happened; the caller wires this into that same signal so
889
+ // deleted paths' compressed bytes don't outlive the file.
890
+ function invalidate(): void {
891
+ cache.clear();
892
+ bytes = 0;
893
+ pending.clear();
894
+ }
895
+
896
+ return { getCompressed, invalidate, bytes: () => bytes };
897
+ }
898
+
899
+ async function tryCompress(
900
+ getCompressed: GetCompressed,
901
+ encoding: CompressionEncoding,
902
+ headers: Record<string, string>,
903
+ cacheKey: { key: string; size: number; mtimeMs: number },
904
+ loadRaw: () => Promise<Uint8Array<ArrayBuffer>>,
905
+ ): Promise<Response | null> {
906
+ const compressed = await getCompressed(cacheKey, encoding, loadRaw);
907
+ if (!compressed) return null;
908
+ headers["Content-Encoding"] = encoding;
909
+ headers["Content-Length"] = String(compressed.size);
910
+ headers.ETag = weaken(headers.ETag ?? "");
911
+ delete headers["Accept-Ranges"];
912
+ headers.Vary = "Accept-Encoding";
913
+ return new Response(compressed, { status: 200, headers });
914
+ }
915
+
916
+ async function serveFile(
917
+ getCompressed: GetCompressed,
918
+ req: Request,
919
+ resolved: ResolvedFile,
920
+ opts: Options,
921
+ forceHtmlCache = false,
922
+ ): Promise<Response> {
923
+ const { path, file, size, mtimeMs } = resolved;
924
+ const type = contentType(file, path);
925
+ const htmlish = forceHtmlCache || isHtml(type);
926
+ // Injected HTML must not share the raw-file ETag or a later non-watch
927
+ // run will 304 the old body (still requesting /__live.js).
928
+ const etag = makeEtag(size, mtimeMs, opts.watch && htmlish ? "-live" : "");
929
+ const compressible = opts.compress && isCompressible(type);
930
+ const liveHtml = opts.watch && htmlish;
931
+ const encoding =
932
+ compressible && (liveHtml || size < 2_000_000) ? pickEncoding(req) : null;
933
+
934
+ if (isNotModified(req, etag, mtimeMs)) {
935
+ const notModifiedHeaders = baseHeaders(etag, opts, htmlish, mtimeMs);
936
+ if (compressible) notModifiedHeaders.Vary = "Accept-Encoding";
937
+ if (encoding) notModifiedHeaders.ETag = weaken(etag);
938
+ return new Response(null, {
939
+ status: 304,
940
+ headers: notModifiedHeaders,
941
+ });
942
+ }
943
+
944
+ const headers = baseHeaders(etag, opts, htmlish, mtimeMs);
945
+ headers["Content-Type"] = type;
946
+ headers["Accept-Ranges"] = "bytes";
947
+ if (compressible) headers.Vary = "Accept-Encoding";
948
+
949
+ const rangeHeader = req.headers.get("Range");
950
+ const range =
951
+ rangeHeader && ifRangeSatisfied(req, etag, mtimeMs) ? rangeHeader : null;
952
+ if (range && req.method === "GET") {
953
+ const parsed = parseRange(range, size);
954
+ if (parsed === "invalid") {
955
+ headers["Content-Range"] = `bytes */${size}`;
956
+ return new Response(null, {
957
+ status: 416,
958
+ headers,
959
+ });
960
+ }
961
+ if (parsed) {
962
+ const { start, end } = parsed;
963
+ const length = end - start + 1;
964
+ headers["Content-Range"] = `bytes ${start}-${end}/${size}`;
965
+ headers["Content-Length"] = String(length);
966
+ return new Response(file.slice(start, end + 1), {
967
+ status: 206,
968
+ headers,
969
+ });
970
+ }
971
+ }
972
+
973
+ // HEAD takes the same path as GET (finish() drops the body) so it
974
+ // reports the same Content-Encoding and Content-Length a GET would.
975
+ // Compressed output is cached, so a HEAD costs at most one compression.
976
+
977
+ if (liveHtml) {
978
+ if (encoding) {
979
+ // NUL can't appear in a real path, so it safely namespaces the
980
+ // live-injected variant from the raw-file cache entry below.
981
+ const res = await tryCompress(
982
+ getCompressed,
983
+ encoding,
984
+ headers,
985
+ { key: `${path}\0live`, size, mtimeMs },
986
+ async () => encoder.encode(injectLiveReload(await file.text())),
987
+ );
988
+ if (res) return res;
989
+ }
990
+
991
+ const html = injectLiveReload(await file.text());
992
+ headers["Content-Length"] = String(Buffer.byteLength(html));
993
+ return new Response(html, { status: 200, headers });
994
+ }
995
+
996
+ if (encoding) {
997
+ const res = await tryCompress(
998
+ getCompressed,
999
+ encoding,
1000
+ headers,
1001
+ { key: path, size, mtimeMs },
1002
+ () => file.bytes(),
1003
+ );
1004
+ if (res) return res;
1005
+ }
1006
+
1007
+ headers["Content-Length"] = String(size);
1008
+ return new Response(file, { status: 200, headers });
1009
+ }
1010
+
1011
+ // Requests under load repeatedly hit the same handful of files, so the
1012
+ // same mtimeMs recurs far more often than it changes; skip reformatting
1013
+ // the date string when it hasn't.
1014
+ let lastMtimeMs = Number.NaN;
1015
+ let lastHttpDate = "";
1016
+
1017
+ function httpDate(mtimeMs: number): string {
1018
+ if (mtimeMs !== lastMtimeMs) {
1019
+ lastMtimeMs = mtimeMs;
1020
+ lastHttpDate = new Date(mtimeMs).toUTCString();
1021
+ }
1022
+ return lastHttpDate;
1023
+ }
1024
+
1025
+ // Plain object, not Headers: `new Headers()` + 5 `set()` calls costs
1026
+ // ~205ns vs ~5ns for an object literal, and `new Response(..., {headers})`
1027
+ // accepts either. Response still builds a real Headers instance from it.
1028
+ export function baseHeaders(
1029
+ etag: string,
1030
+ opts: Options,
1031
+ isHtmlFile: boolean,
1032
+ mtimeMs: number,
1033
+ ): Record<string, string> {
1034
+ return {
1035
+ ETag: etag,
1036
+ "Last-Modified": httpDate(mtimeMs),
1037
+ "Cache-Control":
1038
+ opts.watch || !opts.cache || isHtmlFile
1039
+ ? "no-cache"
1040
+ : "public, max-age=31536000, immutable",
1041
+ };
1042
+ }
1043
+
1044
+ export function parseRange(
1045
+ header: string,
1046
+ size: number,
1047
+ ): { start: number; end: number } | null | "invalid" {
1048
+ const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
1049
+ if (!m) return null;
1050
+
1051
+ const startStr = m[1];
1052
+ const endStr = m[2];
1053
+
1054
+ let start: number;
1055
+ let end: number;
1056
+
1057
+ if (startStr === "" && endStr === "") return "invalid";
1058
+
1059
+ if (startStr === "") {
1060
+ const suffix = Number(endStr);
1061
+ if (!Number.isFinite(suffix) || suffix <= 0) return "invalid";
1062
+ start = Math.max(0, size - suffix);
1063
+ end = size - 1;
1064
+ } else {
1065
+ start = Number(startStr);
1066
+ end = endStr === "" ? size - 1 : Number(endStr);
1067
+ }
1068
+
1069
+ if (
1070
+ !Number.isFinite(start) ||
1071
+ !Number.isFinite(end) ||
1072
+ start < 0 ||
1073
+ end < start ||
1074
+ start >= size
1075
+ ) {
1076
+ return "invalid";
1077
+ }
1078
+
1079
+ end = Math.min(end, size - 1);
1080
+ return { start, end };
1081
+ }
1082
+
1083
+ function withCors(res: Response, opts: Options): Response {
1084
+ if (!opts.cors) return res;
1085
+ res.headers.set("Access-Control-Allow-Origin", "*");
1086
+ res.headers.set("Access-Control-Allow-Headers", "*");
1087
+ res.headers.set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
1088
+ return res;
1089
+ }
1090
+
1091
+ function headify(method: string, res: Response): Response {
1092
+ if (method !== "HEAD") return res;
1093
+ return new Response(null, {
1094
+ status: res.status,
1095
+ statusText: res.statusText,
1096
+ headers: res.headers,
1097
+ });
1098
+ }