deserved 0.6.1 → 0.7.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.
- package/index.d.ts +17 -20
- package/package.json +1 -1
- package/src/cli.ts +12 -9
- package/src/handlers.ts +32 -36
- package/src/index.ts +3 -2
- package/src/live.ts +12 -4
- package/src/log.ts +13 -14
- package/src/options.ts +2 -2
package/index.d.ts
CHANGED
|
@@ -13,13 +13,21 @@ export type Options = {
|
|
|
13
13
|
compress: boolean;
|
|
14
14
|
quiet: boolean;
|
|
15
15
|
};
|
|
16
|
-
|
|
16
|
+
/**
|
|
17
|
+
* The live-reload hub `serve` creates under `watch`, which a handler
|
|
18
|
+
* streams change events from.
|
|
19
|
+
*/
|
|
20
|
+
export type Hub = ReturnType<typeof createSseHub>;
|
|
17
21
|
declare function createSseHub(): {
|
|
18
22
|
subscribe: () => Response;
|
|
19
23
|
broadcast: (data?: string) => void;
|
|
20
24
|
close: () => void;
|
|
21
25
|
};
|
|
22
|
-
|
|
26
|
+
/**
|
|
27
|
+
* The request handler {@link createHandler} returns: a `fetch` for
|
|
28
|
+
* `Bun.serve`, with its caches' sizes and a way to clear each.
|
|
29
|
+
*/
|
|
30
|
+
export type Handler = {
|
|
23
31
|
(req: Request): Promise<Response>;
|
|
24
32
|
invalidateResolutionCache(): void;
|
|
25
33
|
invalidateCompressedCache(): void;
|
|
@@ -27,19 +35,7 @@ type Handler = {
|
|
|
27
35
|
compressedCacheBytes(): number;
|
|
28
36
|
};
|
|
29
37
|
/** The settings `serve()` and the CLI start from. */
|
|
30
|
-
export declare const DEFAULT_OPTIONS:
|
|
31
|
-
root: string;
|
|
32
|
-
port: number;
|
|
33
|
-
host: string;
|
|
34
|
-
spa: false;
|
|
35
|
-
watch: false;
|
|
36
|
-
open: false;
|
|
37
|
-
cors: false;
|
|
38
|
-
dir: true;
|
|
39
|
-
cache: false;
|
|
40
|
-
compress: true;
|
|
41
|
-
quiet: false;
|
|
42
|
-
};
|
|
38
|
+
export declare const DEFAULT_OPTIONS: Options;
|
|
43
39
|
/** The server couldn't listen on the host and port. */
|
|
44
40
|
export declare class BindError extends Error {
|
|
45
41
|
constructor(host: string, port: number, options?: ErrorOptions);
|
|
@@ -48,6 +44,11 @@ export declare class BindError extends Error {
|
|
|
48
44
|
export declare class RootError extends Error {
|
|
49
45
|
constructor(message: string, options?: ErrorOptions);
|
|
50
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Starts a server for `options.root`, over the defaults; a bind failure
|
|
49
|
+
* rejects instead of exiting.
|
|
50
|
+
*/
|
|
51
|
+
export declare function serve(options?: Partial<Options>): Promise<ServerHandle>;
|
|
51
52
|
/** A running server: where it listens, and `stop()` to close it. */
|
|
52
53
|
export type ServerHandle = {
|
|
53
54
|
port: number;
|
|
@@ -55,8 +56,4 @@ export type ServerHandle = {
|
|
|
55
56
|
url: string;
|
|
56
57
|
stop: () => Promise<void>;
|
|
57
58
|
};
|
|
58
|
-
|
|
59
|
-
* Starts a server for `options.root`, over the defaults; a bind failure
|
|
60
|
-
* rejects instead of exiting.
|
|
61
|
-
*/
|
|
62
|
-
export declare function serve(options?: Partial<Options>): Promise<ServerHandle>;
|
|
59
|
+
export {};
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -100,7 +100,8 @@ export function parseArgs(
|
|
|
100
100
|
continue;
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
-
//
|
|
103
|
+
// Only the long form carries its value inline (`--port=8080`);
|
|
104
|
+
// otherwise the value is the next arg (`-p 8080`).
|
|
104
105
|
const eq = a.startsWith("--") ? a.indexOf("=") : -1;
|
|
105
106
|
const flag = eq === -1 ? a : a.slice(0, eq);
|
|
106
107
|
const key = VALUE_FLAGS.get(flag);
|
|
@@ -148,7 +149,16 @@ function fail(msg: string): never {
|
|
|
148
149
|
if (import.meta.main) {
|
|
149
150
|
const opts = parseArgs(process.argv);
|
|
150
151
|
|
|
151
|
-
|
|
152
|
+
// Registered before the server starts, so a signal sent once the banner
|
|
153
|
+
// prints, while `--watch` is still setting up, still shuts it down.
|
|
154
|
+
let handle: Awaited<ReturnType<typeof startServer>> | undefined;
|
|
155
|
+
const shutdown = async () => {
|
|
156
|
+
await handle?.stop();
|
|
157
|
+
process.exit(0);
|
|
158
|
+
};
|
|
159
|
+
process.on("SIGINT", shutdown);
|
|
160
|
+
process.on("SIGTERM", shutdown);
|
|
161
|
+
|
|
152
162
|
try {
|
|
153
163
|
handle = await startServer(opts, { portExplicit: opts.portExplicit });
|
|
154
164
|
} catch (err) {
|
|
@@ -166,11 +176,4 @@ if (import.meta.main) {
|
|
|
166
176
|
}
|
|
167
177
|
throw err;
|
|
168
178
|
}
|
|
169
|
-
|
|
170
|
-
const shutdown = async () => {
|
|
171
|
-
await handle.stop();
|
|
172
|
-
process.exit(0);
|
|
173
|
-
};
|
|
174
|
-
process.on("SIGINT", shutdown);
|
|
175
|
-
process.on("SIGTERM", shutdown);
|
|
176
179
|
}
|
package/src/handlers.ts
CHANGED
|
@@ -22,7 +22,11 @@ type ResolvedFile = {
|
|
|
22
22
|
kind: "file" | "html-ext" | "dir-index";
|
|
23
23
|
};
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
/**
|
|
26
|
+
* The request handler {@link createHandler} returns: a `fetch` for
|
|
27
|
+
* `Bun.serve`, with its caches' sizes and a way to clear each.
|
|
28
|
+
*/
|
|
29
|
+
export type Handler = {
|
|
26
30
|
(req: Request): Promise<Response>;
|
|
27
31
|
invalidateResolutionCache(): void;
|
|
28
32
|
invalidateCompressedCache(): void;
|
|
@@ -175,8 +179,8 @@ export function shouldSpaFallback(pathname: string): boolean {
|
|
|
175
179
|
|
|
176
180
|
const WELL_KNOWN = "/.well-known";
|
|
177
181
|
|
|
178
|
-
//
|
|
179
|
-
// /.well-known/ is the one dot-directory
|
|
182
|
+
// security: dotfiles (.env, .git/) stay private even when serving a
|
|
183
|
+
// project root; /.well-known/ is the one dot-directory meant to be public.
|
|
180
184
|
export function isHiddenPath(pathname: string): boolean {
|
|
181
185
|
const from =
|
|
182
186
|
pathname.startsWith(WELL_KNOWN) &&
|
|
@@ -245,9 +249,9 @@ function markRecent<T>(map: Map<string, T>, key: string, entry: T): void {
|
|
|
245
249
|
map.set(key, entry);
|
|
246
250
|
}
|
|
247
251
|
|
|
248
|
-
//
|
|
249
|
-
// (e.g. adding about.html for a pathname previously cached as a 404)
|
|
250
|
-
//
|
|
252
|
+
// Without --watch nothing reports a newly created or deleted candidate
|
|
253
|
+
// (e.g. adding about.html for a pathname previously cached as a 404),
|
|
254
|
+
// so this window bounds how long it stays unseen.
|
|
251
255
|
export const RESOLUTION_TTL_MS = 500;
|
|
252
256
|
|
|
253
257
|
type Cached<T> = { value: T | null; at: number };
|
|
@@ -285,9 +289,8 @@ function createResolutionCache(
|
|
|
285
289
|
const files = new Map<string, Cached<ResolvedFile>>();
|
|
286
290
|
const dirs = new Map<string, Cached<string>>();
|
|
287
291
|
|
|
288
|
-
//
|
|
289
|
-
//
|
|
290
|
-
// re-probe.
|
|
292
|
+
// A fresh cached winner still goes through `revalidate`, since it can be
|
|
293
|
+
// deleted or change kind; its null forces a re-probe.
|
|
291
294
|
function lookup<T>(
|
|
292
295
|
map: Map<string, Cached<T>>,
|
|
293
296
|
pathname: string,
|
|
@@ -591,16 +594,17 @@ export function createHandler(
|
|
|
591
594
|
const res = new Response("Internal Server Error", { status: 500 });
|
|
592
595
|
return finish(method, rawPathname, opts, res);
|
|
593
596
|
}
|
|
594
|
-
} as Handler;
|
|
595
|
-
|
|
596
|
-
handle.invalidateResolutionCache = () => {
|
|
597
|
-
resolution.invalidate();
|
|
598
|
-
ctx.notFound = null;
|
|
599
597
|
};
|
|
600
|
-
|
|
601
|
-
handle
|
|
602
|
-
|
|
603
|
-
|
|
598
|
+
|
|
599
|
+
return Object.assign(handle, {
|
|
600
|
+
invalidateResolutionCache: () => {
|
|
601
|
+
resolution.invalidate();
|
|
602
|
+
ctx.notFound = null;
|
|
603
|
+
},
|
|
604
|
+
invalidateCompressedCache: compression.invalidate,
|
|
605
|
+
resolutionCacheSize: resolution.size,
|
|
606
|
+
compressedCacheBytes: compression.bytes,
|
|
607
|
+
});
|
|
604
608
|
}
|
|
605
609
|
|
|
606
610
|
function finish(
|
|
@@ -758,7 +762,7 @@ type CompressedEntry = {
|
|
|
758
762
|
// and every touch (read or write) re-inserts its key, so the front of the
|
|
759
763
|
// map is always the least-recently-used entry -- evicting from there
|
|
760
764
|
// gives LRU behavior without a separate linked list.
|
|
761
|
-
export const COMPRESSED_CACHE_BYTE_BUDGET = 64 * 1024 * 1024;
|
|
765
|
+
export const COMPRESSED_CACHE_BYTE_BUDGET: number = 64 * 1024 * 1024;
|
|
762
766
|
|
|
763
767
|
// Bun 1.4's CompressionStream is native, so gzip runs off the main thread
|
|
764
768
|
// the same way Bun.zstdCompress does.
|
|
@@ -794,13 +798,8 @@ type PendingCompression = {
|
|
|
794
798
|
promise: Promise<Blob | null>;
|
|
795
799
|
};
|
|
796
800
|
|
|
797
|
-
|
|
798
|
-
|
|
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
|
-
*/
|
|
801
|
+
// Scoped to one handler, so its buffers are freed with the handler, where
|
|
802
|
+
// a module-level cache would pin them for the life of the process.
|
|
804
803
|
function createCompressionCache() {
|
|
805
804
|
const cache = new Map<string, CompressedEntry>();
|
|
806
805
|
let bytes = 0;
|
|
@@ -825,13 +824,9 @@ function createCompressionCache() {
|
|
|
825
824
|
}
|
|
826
825
|
}
|
|
827
826
|
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
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
|
-
*/
|
|
827
|
+
// Keyed by (key, encoding, size, mtimeMs), so a caller must pick a
|
|
828
|
+
// distinct key when one path can yield different bytes, as watch-injected
|
|
829
|
+
// HTML does. Concurrent misses for one entry share one compression.
|
|
835
830
|
const getCompressed: GetCompressed = async (resolved, encoding, loadRaw) => {
|
|
836
831
|
const cacheKey = `${resolved.key}:${encoding}`;
|
|
837
832
|
const cached = cache.get(cacheKey);
|
|
@@ -1022,9 +1017,10 @@ function httpDate(mtimeMs: number): string {
|
|
|
1022
1017
|
return lastHttpDate;
|
|
1023
1018
|
}
|
|
1024
1019
|
|
|
1025
|
-
//
|
|
1026
|
-
// ~205ns vs ~5ns for an object literal, and
|
|
1027
|
-
// accepts either. Response still builds a
|
|
1020
|
+
// perf: a plain object, not Headers: `new Headers()` + 5 `set()` calls
|
|
1021
|
+
// costs ~205ns vs ~5ns for an object literal, and
|
|
1022
|
+
// `new Response(..., {headers})` accepts either. Response still builds a
|
|
1023
|
+
// real Headers instance from it.
|
|
1028
1024
|
export function baseHeaders(
|
|
1029
1025
|
etag: string,
|
|
1030
1026
|
opts: Options,
|
package/src/index.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
export { createHandler } from "./handlers";
|
|
1
|
+
export { createHandler, type Handler } from "./handlers";
|
|
2
|
+
export type { Hub } from "./live";
|
|
2
3
|
export { DEFAULT_OPTIONS, type Options } from "./options";
|
|
3
|
-
export { BindError, RootError, type ServerHandle
|
|
4
|
+
export { BindError, RootError, serve, type ServerHandle } from "./server";
|
package/src/live.ts
CHANGED
|
@@ -7,7 +7,7 @@ export const EVENTS_PATH = "/__events";
|
|
|
7
7
|
// the source closes for good, so reload once to pick up the new server.
|
|
8
8
|
// A source that never connected (a handler with no hub) stays put, so
|
|
9
9
|
// it can't loop.
|
|
10
|
-
export const LIVE_SCRIPT = `(()=>{let down=false;const e=new EventSource("${EVENTS_PATH}");e.onopen=()=>{if(down)location.reload()};e.onmessage=(m)=>{if(m.data==="css"){for(const l of document.querySelectorAll('link[rel="stylesheet"]')){const h=l.href.split("?")[0];l.href=h+"?t="+Date.now()}}else{location.reload()}};e.onerror=()=>{if(down&&e.readyState===2)location.reload();down=true}})()`;
|
|
10
|
+
export const LIVE_SCRIPT: string = `(()=>{let down=false;const e=new EventSource("${EVENTS_PATH}");e.onopen=()=>{if(down)location.reload()};e.onmessage=(m)=>{if(m.data==="css"){for(const l of document.querySelectorAll('link[rel="stylesheet"]')){const h=l.href.split("?")[0];l.href=h+"?t="+Date.now()}}else{location.reload()}};e.onerror=()=>{if(down&&e.readyState===2)location.reload();down=true}})()`;
|
|
11
11
|
|
|
12
12
|
const INJECT = `<script src="${LIVE_PATH}"></script>`;
|
|
13
13
|
|
|
@@ -23,7 +23,11 @@ export const SSE_HEADERS = {
|
|
|
23
23
|
Connection: "keep-alive",
|
|
24
24
|
};
|
|
25
25
|
|
|
26
|
-
export function createSseHub() {
|
|
26
|
+
export function createSseHub(): {
|
|
27
|
+
subscribe: () => Response;
|
|
28
|
+
broadcast: (data?: string) => void;
|
|
29
|
+
close: () => void;
|
|
30
|
+
} {
|
|
27
31
|
const clients = new Set<ReadableStreamDefaultController<Uint8Array>>();
|
|
28
32
|
const encoder = new TextEncoder();
|
|
29
33
|
const PING = encoder.encode(": ping\n\n");
|
|
@@ -60,7 +64,7 @@ export function createSseHub() {
|
|
|
60
64
|
return new Response(stream, { headers: SSE_HEADERS });
|
|
61
65
|
}
|
|
62
66
|
|
|
63
|
-
function broadcast(data = "reload") {
|
|
67
|
+
function broadcast(data = "reload"): void {
|
|
64
68
|
const payload = encoder.encode(`data: ${data}\n\n`);
|
|
65
69
|
for (const c of clients) {
|
|
66
70
|
try {
|
|
@@ -71,7 +75,7 @@ export function createSseHub() {
|
|
|
71
75
|
}
|
|
72
76
|
}
|
|
73
77
|
|
|
74
|
-
function close() {
|
|
78
|
+
function close(): void {
|
|
75
79
|
clearInterval(heartbeat);
|
|
76
80
|
for (const c of clients) {
|
|
77
81
|
try {
|
|
@@ -84,6 +88,10 @@ export function createSseHub() {
|
|
|
84
88
|
return { subscribe, broadcast, close };
|
|
85
89
|
}
|
|
86
90
|
|
|
91
|
+
/**
|
|
92
|
+
* The live-reload hub `serve` creates under `watch`, which a handler
|
|
93
|
+
* streams change events from.
|
|
94
|
+
*/
|
|
87
95
|
export type Hub = ReturnType<typeof createSseHub>;
|
|
88
96
|
|
|
89
97
|
export function isIgnoredWatchPath(filename: string): boolean {
|
package/src/log.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// spec: https://no-color.org (NO_COLOR); piped output (CI logs, `| tee`)
|
|
2
|
+
// is plain text too.
|
|
3
3
|
export function shouldColor(
|
|
4
4
|
isTTY: boolean | undefined,
|
|
5
5
|
env: Record<string, string | undefined>,
|
|
@@ -20,10 +20,10 @@ const c = {
|
|
|
20
20
|
bold: ansi(1),
|
|
21
21
|
} as const;
|
|
22
22
|
|
|
23
|
-
//
|
|
24
|
-
const CONTROL_CHARS = /
|
|
25
|
-
//
|
|
26
|
-
const HAS_CONTROL = /
|
|
23
|
+
// C0 and C1 controls, since either can start a terminal escape (ESC, CSI).
|
|
24
|
+
const CONTROL_CHARS = /\p{Cc}/gu;
|
|
25
|
+
// A pre-check, so a clean path, the common case, skips the replace.
|
|
26
|
+
const HAS_CONTROL = /\p{Cc}/u;
|
|
27
27
|
|
|
28
28
|
function sanitizeForLog(s: string): string {
|
|
29
29
|
return HAS_CONTROL.test(s) ? s.replace(CONTROL_CHARS, "") : s;
|
|
@@ -35,10 +35,9 @@ const ICON_ERR = `${c.red}✗${c.reset}`;
|
|
|
35
35
|
const DIM = c.dim;
|
|
36
36
|
const RESET = c.reset;
|
|
37
37
|
|
|
38
|
-
//
|
|
39
|
-
// console.log/write per request costs a syscall
|
|
40
|
-
//
|
|
41
|
-
// microtask queue.
|
|
38
|
+
// Lines queue here and flush once per tick, at the end of the current
|
|
39
|
+
// microtask queue, because a console.log/write per request costs a syscall
|
|
40
|
+
// each, which adds up under load.
|
|
42
41
|
let pendingLines: string[] = [];
|
|
43
42
|
|
|
44
43
|
function scheduleFlush(): void {
|
|
@@ -57,7 +56,7 @@ export function logRequest(
|
|
|
57
56
|
status: number,
|
|
58
57
|
path: string,
|
|
59
58
|
quiet: boolean,
|
|
60
|
-
) {
|
|
59
|
+
): void {
|
|
61
60
|
if (quiet) return;
|
|
62
61
|
const icon = status < 300 ? ICON_OK : status < 400 ? ICON_REDIRECT : ICON_ERR;
|
|
63
62
|
pendingLines.push(
|
|
@@ -66,7 +65,7 @@ export function logRequest(
|
|
|
66
65
|
scheduleFlush();
|
|
67
66
|
}
|
|
68
67
|
|
|
69
|
-
export function logInfo(msg: string, quiet = false) {
|
|
68
|
+
export function logInfo(msg: string, quiet = false): void {
|
|
70
69
|
if (quiet) return;
|
|
71
70
|
console.log(`${c.cyan}│${c.reset} ${msg}`);
|
|
72
71
|
}
|
|
@@ -76,7 +75,7 @@ export function logBanner(
|
|
|
76
75
|
root: string,
|
|
77
76
|
flags: string[],
|
|
78
77
|
networkUrl?: string,
|
|
79
|
-
) {
|
|
78
|
+
): void {
|
|
80
79
|
console.log();
|
|
81
80
|
console.log(
|
|
82
81
|
` ${c.bold}deserved${c.reset} ${c.dim}serving${c.reset} ${root}`,
|
|
@@ -91,7 +90,7 @@ export function logBanner(
|
|
|
91
90
|
console.log();
|
|
92
91
|
}
|
|
93
92
|
|
|
94
|
-
export function logReload(quiet: boolean, kind: "css" | "reload") {
|
|
93
|
+
export function logReload(quiet: boolean, kind: "css" | "reload"): void {
|
|
95
94
|
if (quiet) return;
|
|
96
95
|
console.log(`${c.yellow}*${c.reset} ${kind}`);
|
|
97
96
|
}
|
package/src/options.ts
CHANGED
|
@@ -14,7 +14,7 @@ export type Options = {
|
|
|
14
14
|
};
|
|
15
15
|
|
|
16
16
|
/** The settings `serve()` and the CLI start from. */
|
|
17
|
-
export const DEFAULT_OPTIONS = {
|
|
17
|
+
export const DEFAULT_OPTIONS: Options = {
|
|
18
18
|
root: ".",
|
|
19
19
|
port: 3000,
|
|
20
20
|
host: "localhost",
|
|
@@ -26,4 +26,4 @@ export const DEFAULT_OPTIONS = {
|
|
|
26
26
|
cache: false,
|
|
27
27
|
compress: true,
|
|
28
28
|
quiet: false,
|
|
29
|
-
}
|
|
29
|
+
};
|