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.
- package/README.md +42 -18
- package/index.d.ts +62 -2
- package/package.json +17 -13
- package/src/cli.ts +176 -0
- package/src/handlers.ts +1098 -0
- package/src/index.ts +3 -0
- package/src/live.ts +98 -0
- package/src/log.ts +97 -0
- package/src/options.ts +29 -0
- package/src/server.ts +202 -0
- package/cli.js +0 -67
- package/handlers.d.ts +0 -53
- package/index.js +0 -36
- package/server.d.ts +0 -56
package/src/index.ts
ADDED
package/src/live.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
export const LIVE_PATH = "/__live.js";
|
|
2
|
+
export const EVENTS_PATH = "/__events";
|
|
3
|
+
|
|
4
|
+
// Once the stream drops (server stopped or restarting), the browser's
|
|
5
|
+
// EventSource retries on its own; the first successful reconnect reloads
|
|
6
|
+
// the page. If the server comes back without --watch, /__events 404s and
|
|
7
|
+
// the source closes for good, so reload once to pick up the new server.
|
|
8
|
+
// A source that never connected (a handler with no hub) stays put, so
|
|
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}})()`;
|
|
11
|
+
|
|
12
|
+
const INJECT = `<script src="${LIVE_PATH}"></script>`;
|
|
13
|
+
|
|
14
|
+
export function injectLiveReload(html: string): string {
|
|
15
|
+
const idx = html.toLowerCase().lastIndexOf("</body>");
|
|
16
|
+
if (idx === -1) return html + INJECT;
|
|
17
|
+
return html.slice(0, idx) + INJECT + html.slice(idx);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const SSE_HEADERS = {
|
|
21
|
+
"Content-Type": "text/event-stream",
|
|
22
|
+
"Cache-Control": "no-cache",
|
|
23
|
+
Connection: "keep-alive",
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export function createSseHub() {
|
|
27
|
+
const clients = new Set<ReadableStreamDefaultController<Uint8Array>>();
|
|
28
|
+
const encoder = new TextEncoder();
|
|
29
|
+
const PING = encoder.encode(": ping\n\n");
|
|
30
|
+
|
|
31
|
+
// Bun force-closes a connection after ~10s of no traffic, which would
|
|
32
|
+
// otherwise drop an idle browser tab's SSE stream and make it reload on
|
|
33
|
+
// reconnect. Keep it warm so it only ever closes on shutdown.
|
|
34
|
+
const heartbeat = setInterval(() => {
|
|
35
|
+
for (const c of clients) {
|
|
36
|
+
try {
|
|
37
|
+
c.enqueue(PING);
|
|
38
|
+
} catch {
|
|
39
|
+
clients.delete(c);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}, 8000);
|
|
43
|
+
heartbeat.unref();
|
|
44
|
+
|
|
45
|
+
function subscribe(): Response {
|
|
46
|
+
let controller: ReadableStreamDefaultController<Uint8Array>;
|
|
47
|
+
|
|
48
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
49
|
+
start(c) {
|
|
50
|
+
controller = c;
|
|
51
|
+
clients.add(c);
|
|
52
|
+
// retry: how soon the browser reconnects after a restart.
|
|
53
|
+
c.enqueue(encoder.encode("retry: 500\n: connected\n\n"));
|
|
54
|
+
},
|
|
55
|
+
cancel() {
|
|
56
|
+
clients.delete(controller);
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
return new Response(stream, { headers: SSE_HEADERS });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function broadcast(data = "reload") {
|
|
64
|
+
const payload = encoder.encode(`data: ${data}\n\n`);
|
|
65
|
+
for (const c of clients) {
|
|
66
|
+
try {
|
|
67
|
+
c.enqueue(payload);
|
|
68
|
+
} catch {
|
|
69
|
+
clients.delete(c);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function close() {
|
|
75
|
+
clearInterval(heartbeat);
|
|
76
|
+
for (const c of clients) {
|
|
77
|
+
try {
|
|
78
|
+
c.close();
|
|
79
|
+
} catch {}
|
|
80
|
+
}
|
|
81
|
+
clients.clear();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return { subscribe, broadcast, close };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export type Hub = ReturnType<typeof createSseHub>;
|
|
88
|
+
|
|
89
|
+
export function isIgnoredWatchPath(filename: string): boolean {
|
|
90
|
+
return filename
|
|
91
|
+
.split(/[/\\]/)
|
|
92
|
+
.some((segment) => segment.startsWith(".") || segment === "node_modules");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function classifyBatch(files: (string | null)[]): "css" | "reload" {
|
|
96
|
+
if (files.length === 0) return "reload";
|
|
97
|
+
return files.every((f) => f?.endsWith(".css")) ? "css" : "reload";
|
|
98
|
+
}
|
package/src/log.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Plain text when piped (CI logs, `| tee`) or when NO_COLOR is set
|
|
2
|
+
// (https://no-color.org).
|
|
3
|
+
export function shouldColor(
|
|
4
|
+
isTTY: boolean | undefined,
|
|
5
|
+
env: Record<string, string | undefined>,
|
|
6
|
+
): boolean {
|
|
7
|
+
return isTTY === true && !env.NO_COLOR;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const useColor = shouldColor(process.stdout.isTTY, process.env);
|
|
11
|
+
const ansi = (code: number) => (useColor ? `\x1b[${code}m` : "");
|
|
12
|
+
|
|
13
|
+
const c = {
|
|
14
|
+
reset: ansi(0),
|
|
15
|
+
dim: ansi(2),
|
|
16
|
+
green: ansi(32),
|
|
17
|
+
yellow: ansi(33),
|
|
18
|
+
red: ansi(31),
|
|
19
|
+
cyan: ansi(36),
|
|
20
|
+
bold: ansi(1),
|
|
21
|
+
} as const;
|
|
22
|
+
|
|
23
|
+
// eslint-disable-next-line no-control-regex -- strip control chars from logs
|
|
24
|
+
const CONTROL_CHARS = /[\x00-\x1f\x7f]/g;
|
|
25
|
+
// eslint-disable-next-line no-control-regex -- cheap pre-check so the common clean-path case skips replace()
|
|
26
|
+
const HAS_CONTROL = /[\x00-\x1f\x7f]/;
|
|
27
|
+
|
|
28
|
+
function sanitizeForLog(s: string): string {
|
|
29
|
+
return HAS_CONTROL.test(s) ? s.replace(CONTROL_CHARS, "") : s;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const ICON_OK = `${c.green}✓${c.reset}`;
|
|
33
|
+
const ICON_REDIRECT = `${c.yellow}○${c.reset}`;
|
|
34
|
+
const ICON_ERR = `${c.red}✗${c.reset}`;
|
|
35
|
+
const DIM = c.dim;
|
|
36
|
+
const RESET = c.reset;
|
|
37
|
+
|
|
38
|
+
// Collapses many synchronous per-request writes into one per tick: a
|
|
39
|
+
// console.log/write per request costs a syscall each, which adds up under
|
|
40
|
+
// load. Lines queue here and flush once, at the end of the current
|
|
41
|
+
// microtask queue.
|
|
42
|
+
let pendingLines: string[] = [];
|
|
43
|
+
|
|
44
|
+
function scheduleFlush(): void {
|
|
45
|
+
if (pendingLines.length === 1) queueMicrotask(flushLogs);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function flushLogs(): void {
|
|
49
|
+
if (pendingLines.length === 0) return;
|
|
50
|
+
const out = pendingLines.join("\n");
|
|
51
|
+
pendingLines = [];
|
|
52
|
+
process.stdout.write(`${out}\n`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function logRequest(
|
|
56
|
+
method: string,
|
|
57
|
+
status: number,
|
|
58
|
+
path: string,
|
|
59
|
+
quiet: boolean,
|
|
60
|
+
) {
|
|
61
|
+
if (quiet) return;
|
|
62
|
+
const icon = status < 300 ? ICON_OK : status < 400 ? ICON_REDIRECT : ICON_ERR;
|
|
63
|
+
pendingLines.push(
|
|
64
|
+
`${icon} ${DIM}${method}${RESET} ${status} ${sanitizeForLog(path)}`,
|
|
65
|
+
);
|
|
66
|
+
scheduleFlush();
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function logInfo(msg: string, quiet = false) {
|
|
70
|
+
if (quiet) return;
|
|
71
|
+
console.log(`${c.cyan}│${c.reset} ${msg}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function logBanner(
|
|
75
|
+
url: string,
|
|
76
|
+
root: string,
|
|
77
|
+
flags: string[],
|
|
78
|
+
networkUrl?: string,
|
|
79
|
+
) {
|
|
80
|
+
console.log();
|
|
81
|
+
console.log(
|
|
82
|
+
` ${c.bold}deserved${c.reset} ${c.dim}serving${c.reset} ${root}`,
|
|
83
|
+
);
|
|
84
|
+
console.log(` ${c.green}->${c.reset} ${c.cyan}${url}${c.reset}`);
|
|
85
|
+
if (networkUrl) {
|
|
86
|
+
console.log(` ${c.green}->${c.reset} ${c.cyan}${networkUrl}${c.reset}`);
|
|
87
|
+
}
|
|
88
|
+
if (flags.length) {
|
|
89
|
+
console.log(` ${c.dim}${flags.join(" ")}${c.reset}`);
|
|
90
|
+
}
|
|
91
|
+
console.log();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function logReload(quiet: boolean, kind: "css" | "reload") {
|
|
95
|
+
if (quiet) return;
|
|
96
|
+
console.log(`${c.yellow}*${c.reset} ${kind}`);
|
|
97
|
+
}
|
package/src/options.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** The server's settings; the CLI's flags set the same keys. */
|
|
2
|
+
export type Options = {
|
|
3
|
+
root: string;
|
|
4
|
+
port: number;
|
|
5
|
+
host: string;
|
|
6
|
+
spa: boolean;
|
|
7
|
+
watch: boolean;
|
|
8
|
+
open: boolean;
|
|
9
|
+
cors: boolean;
|
|
10
|
+
dir: boolean;
|
|
11
|
+
cache: boolean;
|
|
12
|
+
compress: boolean;
|
|
13
|
+
quiet: boolean;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** The settings `serve()` and the CLI start from. */
|
|
17
|
+
export const DEFAULT_OPTIONS = {
|
|
18
|
+
root: ".",
|
|
19
|
+
port: 3000,
|
|
20
|
+
host: "localhost",
|
|
21
|
+
spa: false,
|
|
22
|
+
watch: false,
|
|
23
|
+
open: false,
|
|
24
|
+
cors: false,
|
|
25
|
+
dir: true,
|
|
26
|
+
cache: false,
|
|
27
|
+
compress: true,
|
|
28
|
+
quiet: false,
|
|
29
|
+
} satisfies Options;
|
package/src/server.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { statSync, watch } from "node:fs";
|
|
2
|
+
import { networkInterfaces } from "node:os";
|
|
3
|
+
import { relative, resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
import { createHandler } from "./handlers";
|
|
6
|
+
import { classifyBatch, createSseHub, isIgnoredWatchPath } from "./live";
|
|
7
|
+
import { flushLogs, logBanner, logInfo, logReload } from "./log";
|
|
8
|
+
import { DEFAULT_OPTIONS, type Options } from "./options";
|
|
9
|
+
|
|
10
|
+
/** A running server: where it listens, and `stop()` to close it. */
|
|
11
|
+
export type ServerHandle = {
|
|
12
|
+
port: number;
|
|
13
|
+
hostname: string;
|
|
14
|
+
url: string;
|
|
15
|
+
stop: () => Promise<void>;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** The root to serve doesn't exist or isn't a directory. */
|
|
19
|
+
export class RootError extends Error {
|
|
20
|
+
constructor(message: string, options?: ErrorOptions) {
|
|
21
|
+
super(message, options);
|
|
22
|
+
this.name = "RootError";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The server couldn't listen on the host and port. */
|
|
27
|
+
export class BindError extends Error {
|
|
28
|
+
constructor(host: string, port: number, options?: ErrorOptions) {
|
|
29
|
+
super(`could not bind to ${host}:${port}`, options);
|
|
30
|
+
this.name = "BindError";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const MAX_PORT_FALLBACK_ATTEMPTS = 10;
|
|
35
|
+
|
|
36
|
+
function isAddrInUseError(err: unknown): boolean {
|
|
37
|
+
if (
|
|
38
|
+
err &&
|
|
39
|
+
typeof err === "object" &&
|
|
40
|
+
"code" in err &&
|
|
41
|
+
err.code === "EADDRINUSE"
|
|
42
|
+
)
|
|
43
|
+
return true;
|
|
44
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
45
|
+
return /EADDRINUSE|address already in use/i.test(message);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function formatUrl(host: string, port: number): string {
|
|
49
|
+
const bracketed = host.includes(":") ? `[${host}]` : host;
|
|
50
|
+
return `http://${bracketed}:${port}`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function lanAddress(): string | null {
|
|
54
|
+
const nets = networkInterfaces();
|
|
55
|
+
for (const iface of Object.values(nets)) {
|
|
56
|
+
for (const net of iface ?? []) {
|
|
57
|
+
if (net.family === "IPv4" && !net.internal) return net.address;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function openCommand(url: string): string[] {
|
|
64
|
+
if (process.platform === "darwin") return ["open", url];
|
|
65
|
+
if (process.platform === "win32") return ["cmd", "/c", "start", "", url];
|
|
66
|
+
return ["xdg-open", url];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Fire and forget: some xdg-open setups block until the browser exits,
|
|
70
|
+
// which would otherwise hold up startServer() for the whole session.
|
|
71
|
+
function openBrowser(url: string): void {
|
|
72
|
+
try {
|
|
73
|
+
Bun.spawn(openCommand(url), { stdout: "ignore", stderr: "ignore" }).unref();
|
|
74
|
+
} catch {
|
|
75
|
+
console.error(`Could not open browser for ${url}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function validateRoot(rootPath: string): void {
|
|
80
|
+
try {
|
|
81
|
+
const st = statSync(rootPath);
|
|
82
|
+
if (!st.isDirectory()) {
|
|
83
|
+
throw new RootError(`not a directory: ${rootPath}`);
|
|
84
|
+
}
|
|
85
|
+
} catch (err) {
|
|
86
|
+
if (err instanceof RootError) throw err;
|
|
87
|
+
if (err instanceof Error && "code" in err && err.code === "ENOENT") {
|
|
88
|
+
throw new RootError(`directory not found: ${rootPath}`);
|
|
89
|
+
}
|
|
90
|
+
throw new RootError(`not a directory: ${rootPath}`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
type StartOptions = {
|
|
95
|
+
// The default port hops to the next free one when taken; an explicit
|
|
96
|
+
// one (the CLI's --port, or any port passed to serve()) never does.
|
|
97
|
+
portExplicit?: boolean;
|
|
98
|
+
// The CLI always prints the banner (-q only silences request logs);
|
|
99
|
+
// serve() skips it when quiet so embedding stays silent.
|
|
100
|
+
banner?: boolean;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
export async function startServer(
|
|
104
|
+
opts: Options,
|
|
105
|
+
{ portExplicit = false, banner = true }: StartOptions = {},
|
|
106
|
+
): Promise<ServerHandle> {
|
|
107
|
+
const root = resolve(opts.root);
|
|
108
|
+
validateRoot(root);
|
|
109
|
+
|
|
110
|
+
const hub = opts.watch ? createSseHub() : undefined;
|
|
111
|
+
const fetch = createHandler({ ...opts, root }, hub);
|
|
112
|
+
|
|
113
|
+
// Bun.serve misses bind conflicts when hostname is the string "localhost".
|
|
114
|
+
// A literal loopback IP throws. Bind to 127.0.0.1 so a second instance
|
|
115
|
+
// fails cleanly.
|
|
116
|
+
const bindHost = opts.host === "localhost" ? "127.0.0.1" : opts.host;
|
|
117
|
+
|
|
118
|
+
// Port 0 already means "any free port", so there's nothing to hop from.
|
|
119
|
+
const maxHops =
|
|
120
|
+
!portExplicit && opts.port !== 0 ? MAX_PORT_FALLBACK_ATTEMPTS : 0;
|
|
121
|
+
|
|
122
|
+
let server: ReturnType<typeof Bun.serve> | undefined;
|
|
123
|
+
for (let hop = 0; !server; hop++) {
|
|
124
|
+
const port = opts.port + hop;
|
|
125
|
+
try {
|
|
126
|
+
server = Bun.serve({ port, hostname: bindHost, fetch });
|
|
127
|
+
} catch (err) {
|
|
128
|
+
if (hop >= maxHops || !isAddrInUseError(err)) {
|
|
129
|
+
throw new BindError(opts.host, port, { cause: err });
|
|
130
|
+
}
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (hop > 0) logInfo(`port ${opts.port} in use, using ${port}`, opts.quiet);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const isWildcardHost = opts.host === "0.0.0.0" || opts.host === "::";
|
|
137
|
+
const displayHost = isWildcardHost ? "localhost" : opts.host;
|
|
138
|
+
const url = formatUrl(displayHost, server.port ?? opts.port);
|
|
139
|
+
const lanIp = isWildcardHost ? lanAddress() : null;
|
|
140
|
+
const networkUrl = lanIp ? `http://${lanIp}:${server.port}` : undefined;
|
|
141
|
+
|
|
142
|
+
const flags: string[] = [];
|
|
143
|
+
if (opts.spa) flags.push("--spa");
|
|
144
|
+
if (opts.watch) flags.push("--watch");
|
|
145
|
+
if (opts.cors) flags.push("--cors");
|
|
146
|
+
if (!opts.dir) flags.push("--no-dir");
|
|
147
|
+
if (!opts.compress) flags.push("--no-compress");
|
|
148
|
+
if (opts.cache) flags.push("--cache");
|
|
149
|
+
|
|
150
|
+
if (banner) {
|
|
151
|
+
logBanner(url, relative(process.cwd(), root) || ".", flags, networkUrl);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let watcher: ReturnType<typeof watch> | undefined;
|
|
155
|
+
if (opts.watch && hub) {
|
|
156
|
+
let timer: Timer | null = null;
|
|
157
|
+
const batch = new Set<string | null>();
|
|
158
|
+
watcher = watch(root, { recursive: true }, (_event, filename) => {
|
|
159
|
+
if (filename && isIgnoredWatchPath(filename)) return;
|
|
160
|
+
// Clear before debouncing the reload broadcast, so a request racing
|
|
161
|
+
// the debounce window still sees the post-change state.
|
|
162
|
+
fetch.invalidateResolutionCache();
|
|
163
|
+
fetch.invalidateCompressedCache();
|
|
164
|
+
batch.add(filename);
|
|
165
|
+
if (timer) clearTimeout(timer);
|
|
166
|
+
timer = setTimeout(() => {
|
|
167
|
+
const kind = classifyBatch([...batch]);
|
|
168
|
+
batch.clear();
|
|
169
|
+
logReload(opts.quiet, kind);
|
|
170
|
+
hub.broadcast(kind);
|
|
171
|
+
}, 80);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
logInfo("watching for changes", opts.quiet);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const stop = async () => {
|
|
178
|
+
watcher?.close();
|
|
179
|
+
hub?.close();
|
|
180
|
+
await server.stop();
|
|
181
|
+
flushLogs();
|
|
182
|
+
logInfo("server stopped", opts.quiet);
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
if (opts.open) openBrowser(url);
|
|
186
|
+
|
|
187
|
+
return { port: server.port ?? opts.port, hostname: displayHost, url, stop };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Starts a server for `options.root`, over the defaults; a bind failure
|
|
192
|
+
* rejects instead of exiting.
|
|
193
|
+
*/
|
|
194
|
+
export async function serve(
|
|
195
|
+
options: Partial<Options> = {},
|
|
196
|
+
): Promise<ServerHandle> {
|
|
197
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
198
|
+
return startServer(opts, {
|
|
199
|
+
portExplicit: options.port !== undefined,
|
|
200
|
+
banner: !opts.quiet,
|
|
201
|
+
});
|
|
202
|
+
}
|
package/cli.js
DELETED
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bun
|
|
2
|
-
// @bun
|
|
3
|
-
import{resolve as $t}from"path";var U="0.5.1";import{statSync as Ze,watch as et}from"fs";import{networkInterfaces as tt}from"os";import{relative as nt,resolve as rt}from"path";import{readdirSync as be,realpathSync as re,statSync as z}from"fs";import{extname as ye,isAbsolute as xe,join as se,resolve as oe,sep as ie}from"path";var{escapeHTML:S}=globalThis.Bun;var we=new TextEncoder,j="application/octet-stream",ve={".html":"text/html;charset=utf-8",".htm":"text/html;charset=utf-8",".css":"text/css;charset=utf-8",".js":"text/javascript;charset=utf-8",".mjs":"text/javascript;charset=utf-8",".json":"application/json;charset=utf-8",".svg":"image/svg+xml",".txt":"text/plain;charset=utf-8",".xml":"application/xml",".wasm":"application/wasm",".woff":"font/woff",".woff2":"font/woff2",".map":"application/json"};function Re(e,t){let n=e.type;if(n&&n!==j&&n!=="")return n;let r=ye(t).toLowerCase();return ve[r]??j}function Ce(e){let t=e.indexOf(";"),n=(t===-1?e:e.slice(0,t)).trim().toLowerCase();return n.startsWith("text/")||n==="application/javascript"||n==="text/javascript"||n==="application/json"||n==="application/xml"||n==="image/svg+xml"||n.endsWith("+json")||n.endsWith("+xml")}function $e(e){return e.startsWith("text/html")}function Ee(e,t,n=""){return`"${e}-${Math.trunc(t)}${n}"`}function q(e){return e.startsWith("W/")?e.slice(2):e}function Se(e,t){if(e.indexOf(",")===-1)return q(e.trim())===t;return e.split(",").some((n)=>q(n.trim())===t)}function Te(e,t){let n=e.headers.get("If-Modified-Since");if(!n)return!1;let r=Date.parse(n);if(Number.isNaN(r))return!1;return Math.trunc(t/1000)*1000<=r}function Ae(e,t,n){let r=e.headers.get("If-None-Match");return r?Se(r,t):Te(e,n)}function Me(e,t,n){let r=e.headers.get("If-Range");if(!r)return!0;if(r.startsWith('"')||r.startsWith("W/"))return r===t;let a=Date.parse(r);if(Number.isNaN(a))return!1;return a===Math.trunc(n/1000)*1000}function Oe(e){let t=e.headers.get("Accept");if(!t||t==="*/*")return!0;return t.includes("text/html")||t.includes("application/xhtml")}function De(e){let t=e.headers.get("Accept-Encoding")??"";if(t.includes("zstd"))return"zstd";if(t.includes("gzip"))return"gzip";return null}function Ie(e){if(e.startsWith("/__"))return!1;let t=e.lastIndexOf("/");if(t===e.length-1)return!0;return e.indexOf(".",t+1)===-1}function Pe(e,t,n){if(!t)return null;let r=n.replace(/^\/+/,""),a=Ne(r);for(let o of a){let i=ae(e,o);if(!i)continue;let s=le(t,i);if(!s)continue;let c=ce(s,He(o));if(c)return c}return null}function ce(e,t){try{let n=z(e);if(n.isFile())return{path:e,file:Bun.file(e),size:n.size,mtimeMs:n.mtimeMs,kind:t}}catch{}return null}var G=4096;function V(e,t){if(e.size<t)return;let n=e.keys().next().value;if(n!==void 0)e.delete(n)}function A(e,t,n){e.delete(t),e.set(t,n)}var K=500;function ze(e,t,n){let r=new Map,a=new Map;function o(s){let c=r.get(s);if(c&&(n||Date.now()-c.at<K)){if(c.value===null)return A(r,s,c),null;if(n)return A(r,s,c),c.value;let d=ce(c.value.path,c.value.kind);if(d)return A(r,s,c),d}let u=Pe(e,t,s);return V(r,G),r.set(s,{value:u,at:Date.now()}),u}function i(s){let c=a.get(s);if(c&&(n||Date.now()-c.at<K)){if(c.value===null)return A(a,s,c),null;try{if(z(c.value).isDirectory())return A(a,s,c),c.value}catch{}}let u=ke(e,t,s);return V(a,G),a.set(s,{value:u,at:Date.now()}),u}return{resolveCached:o,resolveDirCached:i,invalidate:()=>{r.clear(),a.clear()},size:()=>r.size}}function He(e){if(e.endsWith("/index.html"))return"dir-index";if(e.endsWith(".html"))return"html-ext";return"file"}function Ne(e){if(!e||e===".")return["index.html"];let t=e.endsWith("/"),n=t?e.slice(0,-1):e;if(!n)return["index.html"];if(t)return[`${n}/index.html`];return[n,`${n}.html`,`${n}/index.html`]}function ae(e,t){let n=xe(e)?e:oe(e),r=se(n,t);if(r!==n&&!r.startsWith(n+ie))return null;return r}function le(e,t){try{let n=re(t);if(n!==e&&!n.startsWith(e+ie))return null;return n}catch{return null}}function Fe(e){try{return re(e)}catch{return null}}function ke(e,t,n){if(!t)return null;let r=n.replace(/^\/+/,"").replace(/\/+$/,""),a=ae(e,r||".");if(!a)return null;let o=le(t,a);if(!o)return null;try{return z(o).isDirectory()?o:null}catch{return null}}function Be(e){if(e===null)return"-";if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} kB`;return`${(e/1048576).toFixed(1)} MB`}function Le(e){if(e===null)return"-";let t=new Date(e),n=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0"),o=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${r}-${a} ${o}:${i}`}function _e(e){let t=be(e,{withFileTypes:!0}),n=[];for(let r of t){if(r.name.startsWith("."))continue;let a=r.isDirectory(),o=null,i=null;if(!a)try{let s=z(se(e,r.name));o=s.size,i=s.mtimeMs}catch{}n.push({name:r.name,dir:a,size:o,mtimeMs:i})}return n.sort((r,a)=>{if(r.dir!==a.dir)return r.dir?-1:1;return r.name.localeCompare(a.name)})}function We(e,t){let n=e.endsWith("/")?e:`${e}/`,r=Y(n),a=Ue(e),o=S(e),i=t.map((c)=>{let u=je(r,encodeURIComponent(c.name))+(c.dir?"/":""),d=c.dir?`${c.name}/`:c.name,p=Be(c.size),m=Le(c.mtimeMs);return` <li><a href="${S(u)}">${S(d)}</a> <span class="meta">${S(p)}</span> <span class="meta">${S(m)}</span></li>`}).join(`
|
|
4
|
-
`),s=a!==null?` <li><a href="${S(Y(a))}">../</a> <span class="meta">-</span> <span class="meta">-</span></li>
|
|
5
|
-
`:"";return`<!DOCTYPE html>
|
|
6
|
-
<html lang="en">
|
|
7
|
-
<head>
|
|
8
|
-
<meta charset="utf-8">
|
|
9
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
10
|
-
<title>Index of ${o}</title>
|
|
11
|
-
<style>
|
|
12
|
-
:root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
13
|
-
body { max-width: 60rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
|
|
14
|
-
h1 { font-size: 1.1rem; font-weight: 600; }
|
|
15
|
-
ul { list-style: none; padding: 0; }
|
|
16
|
-
li { padding: 0.2rem 0; display: flex; gap: 2rem; }
|
|
17
|
-
li a { color: inherit; text-decoration: none; flex: 1; }
|
|
18
|
-
li a:hover { text-decoration: underline; }
|
|
19
|
-
.meta { text-align: right; min-width: 5rem; opacity: 0.6; }
|
|
20
|
-
</style>
|
|
21
|
-
</head>
|
|
22
|
-
<body>
|
|
23
|
-
<h1>Index of ${o||"/"}</h1>
|
|
24
|
-
<ul>
|
|
25
|
-
${s}${i}
|
|
26
|
-
</ul>
|
|
27
|
-
</body>
|
|
28
|
-
</html>
|
|
29
|
-
`}function Ue(e){if(e==="/"||e==="")return null;let t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");if(n<=0)return"/";return t.slice(0,n+1)}function Y(e){return e.split("/").map(encodeURIComponent).join("/")}function je(e,t){if(e==="/")return`/${t}`;return`${e.replace(/\/+$/,"")}/${t}`}function qe(e){let t=e.indexOf("//"),n=e.indexOf("/",t===-1?0:t+2);if(n===-1)return"/";let r=e.length,a=e.indexOf("?",n);if(a!==-1&&a<r)r=a;let o=e.indexOf("#",n);if(o!==-1&&o<r)r=o;let i=e.slice(n,r);return i===""?"/":i}function ue(e,t){let n=oe(e.root),r=Fe(n),a=ze(n,r,e.watch),o=Je(),i={opts:e,hub:t,resolveCached:a.resolveCached,resolveDirCached:a.resolveDirCached,getCompressed:o.getCompressed,notFound:null},s=async function(u){let d=qe(u.url),p=u.method.toUpperCase(),m;if(d.includes("%"))try{m=decodeURIComponent(d)}catch{let l=new Response("Bad Request",{status:400});return F(p,d,e,l)}else m=d;try{return await Ge(u,p,m,d,i)}catch(l){console.error(l);let b=new Response("Internal Server Error",{status:500});return F(p,d,e,b)}};return s.invalidateResolutionCache=()=>{a.invalidate(),i.notFound=null},s.invalidateCompressedCache=o.invalidate,s.resolutionCacheSize=a.size,s.compressedCacheBytes=o.bytes,s}function F(e,t,n,r){return k(e,r.status,t,n.quiet),de(e,M(r,n))}function J(e,t){return new Response(null,{status:301,headers:{Location:`${e}/${new URL(t).search}`}})}function X(e,t,n=200){return new Response(t.watch?P(e):e,{status:n,headers:{"Content-Type":"text/html;charset=utf-8","Cache-Control":"no-cache"}})}async function Ge(e,t,n,r,a){let{opts:o,hub:i,resolveCached:s,resolveDirCached:c,getCompressed:u}=a,d=(l)=>F(t,n,o,l);if(t!=="GET"&&t!=="HEAD"){let l=new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return d(l)}if(o.watch&&n===D){let l=new Response(fe,{headers:{"Content-Type":"text/javascript;charset=utf-8","Cache-Control":"no-store"}});return d(l)}if(o.watch&&n===I&&i){let l=i.subscribe();return k(t,200,n,o.quiet),M(l,o)}if(n===D||n===I)return de(t,M(new Response("Not Found",{status:404}),o));let p=s(n);if(p){if(p.kind==="dir-index"&&!n.endsWith("/"))return d(J(r,e.url));return d(await Z(u,e,p,o))}let m=Oe(e);if(o.spa&&m&&Ie(n)){let l=s("/");if(l)return d(await Z(u,e,l,o,!0))}if(o.dir){let l=c(n);if(l){if(!n.endsWith("/"))return d(J(r,e.url));let b=We(n,_e(l));return d(X(b,o))}}if(m){let l=s("/404.html");if(l){let b=a.notFound,y=b&&b.size===l.size&&b.mtimeMs===l.mtimeMs?b.html:await(async()=>{let h=await l.file.text();return a.notFound={size:l.size,mtimeMs:l.mtimeMs,html:h},h})();return d(X(y,o,404))}}return d(new Response("Not Found",{status:404}))}var Ve=67108864;async function Ke(e){let t=new CompressionStream("gzip"),n=t.writable.getWriter();return n.write(e),n.close(),new Uint8Array(await new Response(t.readable).arrayBuffer())}async function Ye(e,t){if(e==="zstd")return new Uint8Array(await Bun.zstdCompress(t));return Ke(t)}function Je(){let e=new Map,t=0,n=new Map;function r(i,s){let c=e.get(i);if(c)e.delete(i),t-=c.data.size;e.set(i,s),t+=s.data.size;while(t>Ve&&e.size>1){let u=e.keys().next().value;if(u===void 0)break;let d=e.get(u);if(e.delete(u),d)t-=d.data.size}}let a=async(i,s,c)=>{let u=`${i.key}:${s}`,d=e.get(u);if(d&&d.size===i.size&&d.mtimeMs===i.mtimeMs)return r(u,d),d.data;let p=n.get(u);if(p&&p.size===i.size&&p.mtimeMs===i.mtimeMs)return p.promise;let m=(async()=>{try{let b=await c(),y=new Blob([await Ye(s,b)]);return r(u,{size:i.size,mtimeMs:i.mtimeMs,data:y}),y}catch{return null}})(),l={size:i.size,mtimeMs:i.mtimeMs,promise:m};return n.set(u,l),m.finally(()=>{if(n.get(u)===l)n.delete(u)}),m};function o(){e.clear(),t=0,n.clear()}return{getCompressed:a,invalidate:o,bytes:()=>t}}async function Q(e,t,n,r,a){let o=De(t);if(!o)return null;let i=await e(r,o,a);if(!i)return null;return n["Content-Encoding"]=o,n["Content-Length"]=String(i.size),delete n["Accept-Ranges"],n.Vary="Accept-Encoding",new Response(i,{status:200,headers:n})}async function Z(e,t,n,r,a=!1){let{path:o,file:i,size:s,mtimeMs:c}=n,u=Re(i,o),d=a||$e(u),p=Ee(s,c,r.watch&&d?"-live":""),m=r.compress&&Ce(u);if(Ae(t,p,c)){let h=ne(p,r,d,c);if(m)h.Vary="Accept-Encoding";return new Response(null,{status:304,headers:h})}let l=ne(p,r,d,c);if(l["Content-Type"]=u,l["Accept-Ranges"]="bytes",m)l.Vary="Accept-Encoding";let b=t.headers.get("Range"),y=b&&Me(t,p,c)?b:null;if(y&&t.method==="GET"){let h=Qe(y,s);if(h==="invalid")return l["Content-Range"]=`bytes */${s}`,new Response(null,{status:416,headers:l});if(h){let{start:w,end:g}=h,x=g-w+1;return l["Content-Range"]=`bytes ${w}-${g}/${s}`,l["Content-Length"]=String(x),new Response(i.slice(w,g+1),{status:206,headers:l})}}if(t.method==="HEAD")return l["Content-Length"]=String(s),new Response(null,{status:200,headers:l});if(r.watch&&d&&t.method==="GET"){if(m){let w=await Q(e,t,l,{key:`${o}\x00live`,size:s,mtimeMs:c},async()=>we.encode(P(await i.text())));if(w)return w}let h=P(await i.text());return l["Content-Length"]=String(Buffer.byteLength(h)),new Response(h,{status:200,headers:l})}if(m&&t.method==="GET"&&s<2000000){let h=await Q(e,t,l,{key:o,size:s,mtimeMs:c},()=>i.bytes());if(h)return h}return l["Content-Length"]=String(s),new Response(i,{status:200,headers:l})}var ee=Number.NaN,te="";function Xe(e){if(e!==ee)ee=e,te=new Date(e).toUTCString();return te}function ne(e,t,n,r){return{ETag:e,"Last-Modified":Xe(r),"Cache-Control":t.watch||!t.cache||n?"no-cache":"public, max-age=31536000, immutable"}}function Qe(e,t){let n=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!n)return null;let r=n[1],a=n[2],o,i;if(r===""&&a==="")return"invalid";if(r===""){let s=Number(a);if(!Number.isFinite(s)||s<=0)return"invalid";o=Math.max(0,t-s),i=t-1}else o=Number(r),i=a===""?t-1:Number(a);if(!Number.isFinite(o)||!Number.isFinite(i)||o<0||i<o||o>=t)return"invalid";return i=Math.min(i,t-1),{start:o,end:i}}function M(e,t){if(!t.cors)return e;return e.headers.set("Access-Control-Allow-Origin","*"),e.headers.set("Access-Control-Allow-Headers","*"),e.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),e}function de(e,t){if(e!=="HEAD")return t;return new Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})}var L={root:".",port:3000,portExplicit:!1,host:"localhost",spa:!1,watch:!1,open:!1,cors:!1,dir:!0,cache:!1,compress:!0,quiet:!1};class v extends Error{constructor(e,t){super(e,t);this.name="RootError"}}class T extends Error{constructor(e,t,n){super(`could not bind to ${e}:${t}`,n);this.name="BindError"}}var st=10;function pe(e){if(e&&typeof e==="object"&&"code"in e&&e.code==="EADDRINUSE")return!0;let t=e instanceof Error?e.message:String(e);return/EADDRINUSE|address already in use/i.test(t)}var D="/__live.js",I="/__events",fe=`(()=>{const e=new EventSource("${I}");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=()=>{e.close();setTimeout(()=>location.reload(),1000)}})()`,me=`<script src="${D}"></script>`;function ot(e,t){return`http://${e.includes(":")?`[${e}]`:e}:${t}`}function P(e){let t=e.toLowerCase().lastIndexOf("</body>");if(t===-1)return e+me;return e.slice(0,t)+me+e.slice(t)}function it(){let e=new Set,t=new TextEncoder,n=t.encode(`: ping
|
|
30
|
-
|
|
31
|
-
`),r=setInterval(()=>{for(let s of e)try{s.enqueue(n)}catch{e.delete(s)}},8000);r.unref();function a(){let s,c=new ReadableStream({start(u){s=u,e.add(u),u.enqueue(t.encode(`: connected
|
|
32
|
-
|
|
33
|
-
`))},cancel(){e.delete(s)}});return new Response(c,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function o(s="reload"){let c=t.encode(`data: ${s}
|
|
34
|
-
|
|
35
|
-
`);for(let u of e)try{u.enqueue(c)}catch{e.delete(u)}}function i(){clearInterval(r);for(let s of e)try{s.close()}catch{}e.clear()}return{subscribe:a,broadcast:o,close:i}}var f={reset:"\x1B[0m",dim:"\x1B[2m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",bold:"\x1B[1m"},ct=/[\x00-\x1f\x7f]/g,at=/[\x00-\x1f\x7f]/;function lt(e){return at.test(e)?e.replace(ct,""):e}var ut=`${f.green}\u2713${f.reset}`,dt=`${f.yellow}\u25CB${f.reset}`,ft=`${f.red}\u2717${f.reset}`,{dim:pt,reset:mt}=f,O=[];function ht(){if(O.length===1)queueMicrotask(he)}function he(){if(O.length===0)return;let e=O.join(`
|
|
36
|
-
`);O=[],process.stdout.write(`${e}
|
|
37
|
-
`)}function k(e,t,n,r){if(r)return;let a=t<300?ut:t<400?dt:ft;O.push(`${a} ${pt}${e}${mt} ${t} ${lt(n)}`),ht()}function B(e,t=!1){if(t)return;console.log(`${f.cyan}\u2502${f.reset} ${e}`)}function gt(e){return e.split(/[/\\]/).some((t)=>t.startsWith(".")||t==="node_modules")}function bt(e){if(e.length===0)return"reload";return e.every((t)=>t?.endsWith(".css"))?"css":"reload"}function yt(){let e=tt();for(let t of Object.values(e))for(let n of t??[])if(n.family==="IPv4"&&!n.internal)return n.address;return null}function xt(e,t,n,r){if(console.log(),console.log(` ${f.bold}deserved${f.reset} ${f.dim}serving${f.reset} ${t}`),console.log(` ${f.green}->${f.reset} ${f.cyan}${e}${f.reset}`),r)console.log(` ${f.green}->${f.reset} ${f.cyan}${r}${f.reset}`);if(n.length)console.log(` ${f.dim}${n.join(" ")}${f.reset}`);console.log()}function wt(e,t){if(e)return;console.log(`${f.yellow}*${f.reset} ${t}`)}function vt(e){if(process.platform==="darwin")return["open",e];if(process.platform==="win32")return["cmd","/c","start","",e];return["xdg-open",e]}async function Rt(e){try{await Bun.spawn(vt(e),{stdout:"ignore",stderr:"ignore"}).exited}catch{console.error(`Could not open browser for ${e}`)}}function Ct(e){try{if(!Ze(e).isDirectory())throw new v(`not a directory: ${e}`)}catch(t){if(t instanceof v)throw t;if(t instanceof Error&&"code"in t&&t.code==="ENOENT")throw new v(`directory not found: ${e}`);throw new v(`not a directory: ${e}`)}}async function _(e){let t=rt(e.root);Ct(t);let n=e.watch?it():void 0,r=ue({...e,root:t},n),a=e.host==="localhost"?"127.0.0.1":e.host,o=async(g)=>{if(e.cors&&g.method==="OPTIONS")return M(new Response(null,{status:204}),e);return r(g)},i=(g)=>Bun.serve({port:g,hostname:a,fetch:o}),s=!e.portExplicit&&e.port!==0,c,u=e.port;try{c=i(u)}catch(g){if(!s||!pe(g))throw new T(e.host,u,{cause:g});let x,R=e.port,C=g;for(let E=1;E<=st;E++){R=e.port+E;try{x=i(R),u=R;break}catch(N){if(!pe(N))throw new T(e.host,R,{cause:N});C=N}}if(!x)throw new T(e.host,R,{cause:C});c=x,B(`port ${e.port} in use, using ${u}`,e.quiet)}let d=e.host==="0.0.0.0"||e.host==="::",p=d?"localhost":e.host,m=ot(p,c.port??e.port),l=d?yt():null,b=l?`http://${l}:${c.port}`:void 0,y=[];if(e.spa)y.push("--spa");if(e.watch)y.push("--watch");if(e.cors)y.push("--cors");if(!e.dir)y.push("--no-dir");if(!e.compress)y.push("--no-compress");if(e.cache)y.push("--cache");xt(m,nt(process.cwd(),t)||".",y,b);let h;if(e.watch&&n){let g=null,x=new Set;h=et(t,{recursive:!0},(R,C)=>{if(C&>(C))return;if(r.invalidateResolutionCache(),r.invalidateCompressedCache(),x.add(C),g)clearTimeout(g);g=setTimeout(()=>{let E=bt([...x]);x.clear(),wt(e.quiet,E),n.broadcast(E)},80)}),B("watching for changes",e.quiet)}let w=async()=>{h?.close(),n?.close(),await c.stop(),he(),B("server stopped",e.quiet)};if(e.open)await Rt(m);return{port:c.port??e.port,hostname:p,url:m,stop:w}}async function Ft(e={}){let t=e.portExplicit??e.port!==void 0;return _({...L,...e,portExplicit:t})}function Et(){console.log(`
|
|
38
|
-
deserved - tiny Bun static file server
|
|
39
|
-
|
|
40
|
-
Usage
|
|
41
|
-
deserved [path] [options]
|
|
42
|
-
|
|
43
|
-
Options
|
|
44
|
-
-p, --port <n> Port (default: 3000, or $PORT; hops to the next
|
|
45
|
-
free port unless set explicitly)
|
|
46
|
-
-H, --host <host> Hostname (default: localhost)
|
|
47
|
-
-s, --spa SPA fallback to index.html
|
|
48
|
-
-w, --watch Live reload on file changes
|
|
49
|
-
-o, --open Open browser
|
|
50
|
-
--cors Enable CORS
|
|
51
|
-
--dir Enable directory listing (default)
|
|
52
|
-
--no-dir Disable directory listing
|
|
53
|
-
--cache Long-lived, immutable cache headers for assets
|
|
54
|
-
--no-cache Disable cache headers (default)
|
|
55
|
-
--compress zstd or gzip, negotiated per request (default)
|
|
56
|
-
--no-compress Disable compression
|
|
57
|
-
-q, --quiet Suppress request logs
|
|
58
|
-
-h, --help Show help
|
|
59
|
-
-v, --version Show version
|
|
60
|
-
|
|
61
|
-
Examples
|
|
62
|
-
deserved .
|
|
63
|
-
deserved dist --spa
|
|
64
|
-
deserved dist --port 8080
|
|
65
|
-
deserved docs --watch --open
|
|
66
|
-
PORT=8080 deserved dist
|
|
67
|
-
`)}function St(e,t=Bun.env){let n=e.slice(2),r={...L},a=r.root,o=!1;for(let i=0;i<n.length;i++){let s=n[i];if(s===void 0)break;if(s==="-h"||s==="--help")Et(),process.exit(0);if(s==="-v"||s==="--version")console.log(U),process.exit(0);if(s==="-s"||s==="--spa"){r.spa=!0;continue}if(s==="-w"||s==="--watch"){r.watch=!0;continue}if(s==="-o"||s==="--open"){r.open=!0;continue}if(s==="--cors"){r.cors=!0;continue}if(s==="--dir"){r.dir=!0;continue}if(s==="--no-dir"){r.dir=!1;continue}if(s==="--cache"){r.cache=!0;continue}if(s==="--no-cache"){r.cache=!1;continue}if(s==="--compress"){r.compress=!0;continue}if(s==="--no-compress"){r.compress=!1;continue}if(s==="-q"||s==="--quiet"){r.quiet=!0;continue}if(s==="-p"||s==="--port"){let c=n[++i];if(!c||c.startsWith("-"))H(`Missing value for ${s}`);r.port=W(c,c),o=!0;continue}if(s==="-H"||s==="--host"){let c=n[++i];if(!c||c.startsWith("-"))H(`Missing value for ${s}`);r.host=c;continue}if(s.startsWith("--port=")){r.port=W(s.slice(7),s),o=!0;continue}if(s.startsWith("--host=")){r.host=s.slice(7);continue}if(s.startsWith("-"))H(`Unknown option: ${s}`);a=s}if(!o&&t.PORT!==void 0)r.port=W(t.PORT,t.PORT);return r.portExplicit=o,r.root=$t(a),r}function W(e,t){let n=Number(e);if(!Number.isInteger(n)||n<0||n>65535)H(`Invalid port: ${t}`);return n}function H(e){console.error(`Error: ${e}`),console.error("Run deserved --help."),process.exit(1)}if(import.meta.main){let e=St(process.argv),t;try{t=await _(e)}catch(r){if(r instanceof v)console.error(`Error: ${r.message}`),console.error("Run deserved --help."),process.exit(1);if(r instanceof T)console.error(`Error: ${r.message}`),console.error(r.cause instanceof Error?r.cause.message:String(r.cause)),process.exit(1);throw r}let n=async()=>{await t.stop(),process.exit(0)};process.on("SIGINT",n),process.on("SIGTERM",n)}export{St as parseArgs};
|
package/handlers.d.ts
DELETED
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
import { type createSseHub, type Options } from "./server";
|
|
2
|
-
export type ResolvedFile = {
|
|
3
|
-
path: string;
|
|
4
|
-
file: Bun.BunFile;
|
|
5
|
-
size: number;
|
|
6
|
-
mtimeMs: number;
|
|
7
|
-
kind: "file" | "html-ext" | "dir-index";
|
|
8
|
-
};
|
|
9
|
-
export type Handler = {
|
|
10
|
-
(req: Request): Promise<Response>;
|
|
11
|
-
invalidateResolutionCache(): void;
|
|
12
|
-
invalidateCompressedCache(): void;
|
|
13
|
-
resolutionCacheSize(): number;
|
|
14
|
-
compressedCacheBytes(): number;
|
|
15
|
-
};
|
|
16
|
-
type Hub = ReturnType<typeof createSseHub>;
|
|
17
|
-
export declare function contentType(file: Bun.BunFile, path: string): string;
|
|
18
|
-
export declare function isCompressible(type: string): boolean;
|
|
19
|
-
export declare function isHtml(type: string): boolean;
|
|
20
|
-
export declare function makeEtag(size: number, mtimeMs: number, tag?: string): string;
|
|
21
|
-
export declare function notModified(req: Request, etag: string): boolean;
|
|
22
|
-
export declare function notModifiedSince(req: Request, mtimeMs: number): boolean;
|
|
23
|
-
export declare function isNotModified(req: Request, etag: string, mtimeMs: number): boolean;
|
|
24
|
-
export declare function ifRangeSatisfied(req: Request, etag: string, mtimeMs: number): boolean;
|
|
25
|
-
export declare function acceptsHtml(req: Request): boolean;
|
|
26
|
-
export type CompressionEncoding = "zstd" | "gzip";
|
|
27
|
-
export declare function pickEncoding(req: Request): CompressionEncoding | null;
|
|
28
|
-
export declare function shouldSpaFallback(pathname: string): boolean;
|
|
29
|
-
export declare function resolveFileWithRoot(rootAbs: string, realRoot: string | null, pathname: string): ResolvedFile | null;
|
|
30
|
-
export declare const RESOLUTION_CACHE_LIMIT = 4096;
|
|
31
|
-
export declare const RESOLUTION_TTL_MS = 500;
|
|
32
|
-
export declare function buildCandidates(relative: string): string[];
|
|
33
|
-
export declare function safeJoin(root: string, relative: string): string | null;
|
|
34
|
-
export declare function realContainedPath(rootAbs: string, full: string): string | null;
|
|
35
|
-
export declare function resolveDirWithRoot(rootAbs: string, realRoot: string | null, pathname: string): string | null;
|
|
36
|
-
type DirEntry = {
|
|
37
|
-
name: string;
|
|
38
|
-
dir: boolean;
|
|
39
|
-
size: number | null;
|
|
40
|
-
mtimeMs: number | null;
|
|
41
|
-
};
|
|
42
|
-
export declare function listDir(dir: string): DirEntry[];
|
|
43
|
-
export declare function directoryListing(pathname: string, entries: DirEntry[]): string;
|
|
44
|
-
export declare function createHandler(opts: Options, hub?: Hub): Handler;
|
|
45
|
-
export declare const COMPRESSED_CACHE_BYTE_BUDGET: number;
|
|
46
|
-
export declare function compress(encoding: CompressionEncoding, raw: Uint8Array<ArrayBuffer>): Promise<Uint8Array<ArrayBuffer>>;
|
|
47
|
-
export declare function baseHeaders(etag: string, opts: Options, isHtmlFile: boolean, mtimeMs: number): Record<string, string>;
|
|
48
|
-
export declare function parseRange(header: string, size: number): {
|
|
49
|
-
start: number;
|
|
50
|
-
end: number;
|
|
51
|
-
} | null | "invalid";
|
|
52
|
-
export declare function withCors(res: Response, opts: Options): Response;
|
|
53
|
-
export {};
|