@johnhenry/sitefile 0.0.2 → 0.0.4

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.
Files changed (136) hide show
  1. package/CHANGELOG.md +516 -0
  2. package/README.md +59 -9
  3. package/lib/src/archive-writers.d.ts +12 -2
  4. package/lib/src/archive-writers.js +53 -10
  5. package/lib/src/bake.d.ts +2 -0
  6. package/lib/src/bake.js +30 -1
  7. package/lib/src/bcrypt.d.ts +25 -0
  8. package/lib/src/bcrypt.js +201 -0
  9. package/lib/src/canonical.d.ts +19 -0
  10. package/lib/src/canonical.js +60 -0
  11. package/lib/src/car.d.ts +34 -0
  12. package/lib/src/car.js +203 -0
  13. package/lib/src/checklinks.js +8 -2
  14. package/lib/src/cli/bake.js +4 -3
  15. package/lib/src/cli/build-image.d.ts +1 -0
  16. package/lib/src/cli/build-image.js +1 -0
  17. package/lib/src/cli/common.js +4 -1
  18. package/lib/src/cli/hosts.d.ts +5 -0
  19. package/lib/src/cli/hosts.js +78 -0
  20. package/lib/src/cli/images.js +23 -5
  21. package/lib/src/cli/import-config.d.ts +2 -0
  22. package/lib/src/cli/import-config.js +56 -0
  23. package/lib/src/cli/index.d.ts +6 -1
  24. package/lib/src/cli/index.js +34 -2
  25. package/lib/src/cli/integrity.d.ts +2 -0
  26. package/lib/src/cli/integrity.js +77 -0
  27. package/lib/src/cli/network.d.ts +7 -0
  28. package/lib/src/cli/network.js +14 -3
  29. package/lib/src/cli/serve-keys.d.ts +39 -0
  30. package/lib/src/cli/serve-keys.js +106 -0
  31. package/lib/src/cli/serve-worker.js +119 -8
  32. package/lib/src/cli/servers.d.ts +130 -1
  33. package/lib/src/cli/servers.js +754 -72
  34. package/lib/src/cli/up.d.ts +2 -0
  35. package/lib/src/cli/up.js +193 -0
  36. package/lib/src/cli/watch.d.ts +14 -1
  37. package/lib/src/cli/watch.js +20 -3
  38. package/lib/src/cli.js +138 -18
  39. package/lib/src/csp.d.ts +17 -0
  40. package/lib/src/csp.js +52 -0
  41. package/lib/src/dictionary.d.ts +16 -0
  42. package/lib/src/dictionary.js +89 -0
  43. package/lib/src/epub.d.ts +5 -0
  44. package/lib/src/epub.js +113 -0
  45. package/lib/src/errors.d.ts +22 -9
  46. package/lib/src/errors.js +20 -1
  47. package/lib/src/executor.d.ts +31 -1
  48. package/lib/src/executor.js +231 -24
  49. package/lib/src/explain.js +33 -3
  50. package/lib/src/export-for.d.ts +42 -0
  51. package/lib/src/export-for.js +466 -0
  52. package/lib/src/export-formats.d.ts +2 -2
  53. package/lib/src/export-formats.js +52 -2
  54. package/lib/src/fingerprint.d.ts +3 -1
  55. package/lib/src/fingerprint.js +32 -5
  56. package/lib/src/host-config.d.ts +34 -0
  57. package/lib/src/host-config.js +645 -0
  58. package/lib/src/hosts.d.ts +47 -0
  59. package/lib/src/hosts.js +106 -0
  60. package/lib/src/hreflang.d.ts +25 -0
  61. package/lib/src/hreflang.js +72 -0
  62. package/lib/src/index.d.ts +1 -1
  63. package/lib/src/index.js +1 -1
  64. package/lib/src/integrity.d.ts +115 -0
  65. package/lib/src/integrity.js +273 -0
  66. package/lib/src/language/ast.d.ts +126 -3
  67. package/lib/src/language/ast.js +7 -1
  68. package/lib/src/language/parser.js +189 -7
  69. package/lib/src/language/validate.js +24 -0
  70. package/lib/src/links.d.ts +47 -0
  71. package/lib/src/links.js +289 -3
  72. package/lib/src/lint.d.ts +1 -1
  73. package/lib/src/lint.js +26 -1
  74. package/lib/src/mime-data.d.ts +2 -0
  75. package/lib/src/mime-data.js +92 -0
  76. package/lib/src/oci.d.ts +20 -2
  77. package/lib/src/oci.js +70 -28
  78. package/lib/src/outdated.d.ts +3 -0
  79. package/lib/src/outdated.js +4 -4
  80. package/lib/src/planner.d.ts +87 -2
  81. package/lib/src/planner.js +189 -8
  82. package/lib/src/plugins/cache.d.ts +11 -0
  83. package/lib/src/plugins/cache.js +29 -0
  84. package/lib/src/plugins/host.d.ts +51 -2
  85. package/lib/src/plugins/host.js +141 -16
  86. package/lib/src/plugins/wasm.js +1 -3
  87. package/lib/src/portable.d.ts +8 -0
  88. package/lib/src/portable.js +47 -0
  89. package/lib/src/precache.d.ts +33 -0
  90. package/lib/src/precache.js +75 -0
  91. package/lib/src/precompress.d.ts +19 -0
  92. package/lib/src/precompress.js +35 -0
  93. package/lib/src/qr.d.ts +18 -0
  94. package/lib/src/qr.js +372 -0
  95. package/lib/src/registry-ops.js +4 -2
  96. package/lib/src/reload-client.d.ts +2 -0
  97. package/lib/src/reload-client.js +419 -0
  98. package/lib/src/resources/archive.d.ts +37 -1
  99. package/lib/src/resources/archive.js +353 -71
  100. package/lib/src/resources/convert.js +3 -1
  101. package/lib/src/resources/https.d.ts +9 -1
  102. package/lib/src/resources/https.js +36 -0
  103. package/lib/src/resources/network.d.ts +25 -3
  104. package/lib/src/resources/network.js +77 -6
  105. package/lib/src/secrets.d.ts +12 -3
  106. package/lib/src/secrets.js +18 -5
  107. package/lib/src/serve-auth.d.ts +33 -0
  108. package/lib/src/serve-auth.js +120 -0
  109. package/lib/src/serve-rules.d.ts +83 -7
  110. package/lib/src/serve-rules.js +264 -53
  111. package/lib/src/server.d.ts +529 -11
  112. package/lib/src/server.js +1439 -57
  113. package/lib/src/servers-file.d.ts +36 -0
  114. package/lib/src/servers-file.js +101 -0
  115. package/lib/src/servers.d.ts +115 -7
  116. package/lib/src/servers.js +151 -29
  117. package/lib/src/single-file.d.ts +12 -0
  118. package/lib/src/single-file.js +147 -0
  119. package/lib/src/site.d.ts +58 -0
  120. package/lib/src/site.js +216 -5
  121. package/lib/src/store.js +9 -5
  122. package/lib/src/swbn.d.ts +10 -0
  123. package/lib/src/swbn.js +86 -0
  124. package/lib/src/toml.d.ts +17 -0
  125. package/lib/src/toml.js +323 -0
  126. package/lib/src/wacz.d.ts +6 -0
  127. package/lib/src/wacz.js +96 -0
  128. package/lib/src/warc.d.ts +28 -0
  129. package/lib/src/warc.js +252 -0
  130. package/lib/src/watch.d.ts +12 -1
  131. package/lib/src/watch.js +67 -1
  132. package/lib/src/wbn.d.ts +9 -1
  133. package/lib/src/wbn.js +23 -33
  134. package/lib/src/zstd.d.ts +4 -0
  135. package/lib/src/zstd.js +328 -0
  136. package/package.json +1 -1
package/lib/src/server.js CHANGED
@@ -1,25 +1,454 @@
1
+ import { randomBytes } from 'node:crypto';
1
2
  import http from 'node:http';
2
- import { SitefileError } from './errors.js';
3
- import { headersFor, matchRedirect, parseHeaderRules, parseRedirectRules } from './serve-rules.js';
3
+ import https from 'node:https';
4
+ import os from 'node:os';
5
+ import { isSitefileError, SitefileError } from './errors.js';
6
+ import { fetchRemote, redactUrl } from './resources/https.js';
7
+ import { DEFAULT_FETCH_POLICY } from './resources/types.js';
8
+ import { globMatch, headersFor, isRewriteStatus, matchRedirect, matchRule, parseHeaderRules, parseRedirectRules, substituteTarget } from './serve-rules.js';
9
+ import { deltaFor } from './dictionary.js';
4
10
  import { nfc } from './paths.js';
11
+ import { gzip } from './deflate.js';
5
12
  import { mimeTypeFor } from './wbn.js';
13
+ import { RELOAD_CLIENT } from './reload-client.js';
14
+ /** Response headers a proxy does not pass on (RFC 9110 section 7.6.1), and the length it recomputes. */
15
+ const HOP_BY_HOP = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'proxy-connection', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'content-length']);
16
+ /** Request headers passed to the upstream (no cookies or credentials: they belong to this server's origin). */
17
+ const PROXY_REQUEST_HEADERS = ['accept', 'accept-language', 'if-none-match', 'if-modified-since', 'range'];
18
+ /** Whether an `accept-encoding` header accepts gzip (`gzip` or `x-gzip` with a non-zero q). */
19
+ export function acceptsGzip(header) {
20
+ if (header === undefined)
21
+ return false;
22
+ return header.split(',').some((part) => {
23
+ const [name, ...params] = part.trim().split(';');
24
+ if (name?.trim().toLowerCase() !== 'gzip' && name?.trim().toLowerCase() !== 'x-gzip')
25
+ return false;
26
+ const q = params.map((x) => x.trim()).find((x) => x.toLowerCase().startsWith('q='));
27
+ return q === undefined || Number(q.slice(2)) > 0;
28
+ });
29
+ }
30
+ /** A gzip member around a raw deflate stream: fixed header (no name, mtime 0, OS unknown), CRC-32 and size. */
31
+ export function gzipMember(deflate, crc, size) {
32
+ const head = Buffer.from([0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 0xff]);
33
+ const tail = Buffer.alloc(8);
34
+ tail.writeUInt32LE(crc >>> 0, 0);
35
+ tail.writeUInt32LE(size % 2 ** 32, 4);
36
+ return Buffer.concat([head, deflate, tail]);
37
+ }
6
38
  /** Reserved for the live-reload event stream while `serve --watch` runs. */
7
39
  export const RELOAD_PATH = '/__sitefile/reload';
8
- /** Added to served HTML (before the last `</body>`, else at the end) under `serve --watch`. */
9
- export const RELOAD_SCRIPT = `<script>new EventSource("${RELOAD_PATH}").onmessage=function(){location.reload()}</script>`;
10
- /** Open live-reload streams; {@link LiveReload.reload} tells every page to reload. */
40
+ /** Reserved for the live-reload client script ({@link RELOAD_CLIENT}) while `serve --watch` runs. */
41
+ export const RELOAD_SCRIPT_PATH = '/__sitefile/reload.js';
42
+ /** Added to navigated HTML (before the last `</body>`, else at the end) under `serve --watch`. */
43
+ export const RELOAD_SCRIPT = `<script src="${RELOAD_SCRIPT_PATH}"></script>`;
44
+ export { RELOAD_CLIENT };
45
+ /**
46
+ * Whether a request is a page navigation, which gets the reload script: `Sec-Fetch-Mode: navigate`
47
+ * when the browser sends it, else `Sec-Fetch-Dest` document/iframe/frame, else an `Accept` naming
48
+ * `text/html`. A `fetch()` of an HTML fragment is none of these and is served unchanged.
49
+ */
50
+ export function isNavigation(headers) {
51
+ const one = (k) => {
52
+ const v = headers[k];
53
+ return Array.isArray(v) ? v.join(', ') : v;
54
+ };
55
+ const mode = one('sec-fetch-mode');
56
+ if (mode !== undefined)
57
+ return mode.trim().toLowerCase() === 'navigate';
58
+ const dest = one('sec-fetch-dest');
59
+ if (dest !== undefined)
60
+ return ['document', 'iframe', 'frame'].includes(dest.trim().toLowerCase());
61
+ return (one('accept') ?? '').toLowerCase().includes('text/html');
62
+ }
63
+ /**
64
+ * The directive of a `Content-Security-Policy` value that blocks live reload: `script-src` when
65
+ * a same-origin script cannot run, `connect-src` when the event stream cannot connect, else
66
+ * undefined. A comma separates policies, and each one is enforced. Only `'self'`, `*`, `http:` and
67
+ * `https:` count as allowing the server's own origin (host sources are not matched), and
68
+ * `'strict-dynamic'` makes `'self'` ignored for scripts.
69
+ */
70
+ export function cspBlocksReload(value) {
71
+ for (const policy of value.split(',')) {
72
+ const directives = new Map();
73
+ for (const d of policy.split(';')) {
74
+ const [name, ...sources] = d.trim().split(/[\t\n\f\r ]+/).filter((t) => t !== '');
75
+ if (name !== undefined && !directives.has(name.toLowerCase()))
76
+ directives.set(name.toLowerCase(), sources.map((t) => t.toLowerCase()));
77
+ }
78
+ const effective = (names) => names.map((n) => directives.get(n)).find((v) => v !== undefined);
79
+ const allows = (sources, script) => sources === undefined ||
80
+ (!(script && sources.includes("'strict-dynamic'")) && sources.some((t) => t === "'self'" || t === '*' || t === 'http:' || t === 'https:'));
81
+ if (!allows(effective(['script-src-elem', 'script-src', 'default-src']), true))
82
+ return 'script-src';
83
+ if (!allows(effective(['connect-src', 'default-src']), false))
84
+ return 'connect-src';
85
+ }
86
+ return undefined;
87
+ }
88
+ /** Heartbeat interval on the event stream. */
89
+ export const HEARTBEAT_MS = 15_000;
90
+ /** Headers of the event stream (also on HEAD): no proxy buffering (`X-Accel-Buffering`), no compression or other transforms. */
91
+ export const STREAM_HEADERS = {
92
+ 'content-type': 'text/event-stream',
93
+ 'cache-control': 'no-cache, no-transform',
94
+ 'x-accel-buffering': 'no',
95
+ };
96
+ /** The script served at {@link RELOAD_SCRIPT_PATH}: {@link RELOAD_CLIENT} called with `options` (keys in a fixed order). */
97
+ export function clientScript(options = {}) {
98
+ return `${RELOAD_CLIENT}({"resetServiceWorkers":${options.resetServiceWorkers !== false},"cssInject":${options.cssInject !== false},"console":${options.console === true},"overlay":${options.overlay !== false},"navigateToChanged":${options.navigateToChanged === true},"reload":"${options.reload ?? 'morph'}"${options.sync !== undefined ? `,"sync":"${options.sync}"` : ''}});\n`;
99
+ }
100
+ /** Reserved for browser console messages (POST) while `serve --watch` runs. */
101
+ export const CONSOLE_PATH = '/__sitefile/console';
102
+ /** Largest console message body accepted (bytes). */
103
+ export const MAX_CONSOLE_BODY = 16 * 1024;
104
+ /** At most this many console messages are logged per {@link CONSOLE_WINDOW_MS}. */
105
+ export const CONSOLE_LIMIT = 50;
106
+ export const CONSOLE_WINDOW_MS = 10_000;
107
+ /** `s` with each run of control characters made one space, trimmed, and cut to `max` code points (then `...`). */
108
+ function cleanText(s, max) {
109
+ const t = [...s.replace(/[\u0000-\u001f\u007f]+/g, ' ').trim()];
110
+ return t.length > max ? t.slice(0, max).join('') + '...' : t.join('');
111
+ }
112
+ /**
113
+ * The server-log lines for one console message body (JSON `{level, message, stack, url, line, col}`),
114
+ * or undefined when it is not one. `level` is error, warn, log or info; log and info give no lines
115
+ * unless `all` (`--console`). The first line is `browser <level>: <message> (<url>:<line>:<col>)`;
116
+ * up to 5 stack lines follow, indented.
117
+ */
118
+ export function consoleLines(body, all) {
119
+ let v;
120
+ try {
121
+ v = JSON.parse(body);
122
+ }
123
+ catch {
124
+ return undefined;
125
+ }
126
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
127
+ return undefined;
128
+ const o = v;
129
+ const level = o.level;
130
+ if (level !== 'error' && level !== 'warn' && level !== 'log' && level !== 'info')
131
+ return undefined;
132
+ if ((level === 'log' || level === 'info') && !all)
133
+ return [];
134
+ const message = cleanText(typeof o.message === 'string' ? o.message : '', 1000);
135
+ const num = (x) => (typeof x === 'number' && Number.isInteger(x) && x >= 0 && x <= Number.MAX_SAFE_INTEGER ? x : undefined);
136
+ const url = typeof o.url === 'string' ? cleanText(o.url, 300) : '';
137
+ const line = num(o.line);
138
+ const col = line === undefined ? undefined : num(o.col);
139
+ const at = url === '' ? '' : ` (${url}${line === undefined ? '' : `:${line}`}${col === undefined ? '' : `:${col}`})`;
140
+ const out = [`browser ${level}: ${message}${at}`];
141
+ if (typeof o.stack === 'string') {
142
+ const frames = o.stack
143
+ .split('\n')
144
+ .map((l) => cleanText(l, 300))
145
+ .filter((l) => l !== '' && l !== message);
146
+ for (const f of frames.slice(0, 5))
147
+ out.push(` ${f}`);
148
+ }
149
+ return out;
150
+ }
151
+ /** A console POST comes from a page of this server: `Origin` is `http(s)://<Host>`, and `Sec-Fetch-Site` (when sent) is same-origin. */
152
+ export function isSameOriginPost(headers) {
153
+ const one = (k) => {
154
+ const x = headers[k];
155
+ return Array.isArray(x) ? x.join(', ') : x;
156
+ };
157
+ const origin = one('origin');
158
+ const host = one('host');
159
+ if (origin === undefined || host === undefined || host === '')
160
+ return false;
161
+ const site = one('sec-fetch-site');
162
+ if (site !== undefined && site.trim().toLowerCase() !== 'same-origin')
163
+ return false;
164
+ return origin === `http://${host}` || origin === `https://${host}`;
165
+ }
166
+ /** Reserved for location reports (POST) from pages while `serve --watch --sync` runs. */
167
+ export const CLIENT_PATH = '/__sitefile/client';
168
+ /** Reserved for the list of connected pages (GET, loopback only, not from a browser) while `serve --watch --sync` runs. */
169
+ export const CLIENTS_PATH = '/__sitefile/clients';
170
+ /** Largest location report accepted (bytes). */
171
+ export const MAX_CLIENT_BODY = 4096;
172
+ /** At most this many reports are accepted from one page per {@link CLIENT_WINDOW_MS} (more get `429`). */
173
+ export const CLIENT_REPORT_LIMIT = 60;
174
+ export const CLIENT_WINDOW_MS = 10_000;
175
+ /** At most this many pages are tracked (one that left is forgotten first to make room). */
176
+ export const MAX_CLIENTS = 64;
177
+ const CLIENT_ID = /^[0-9a-f]{16}$/;
178
+ /** A location report body (JSON `{id, url, title?, nav?, scroll?}`), or undefined when it is not one. */
179
+ export function parseClientReport(body) {
180
+ let v;
181
+ try {
182
+ v = JSON.parse(body);
183
+ }
184
+ catch {
185
+ return undefined;
186
+ }
187
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
188
+ return undefined;
189
+ const o = v;
190
+ if (typeof o.id !== 'string' || !CLIENT_ID.test(o.id))
191
+ return undefined;
192
+ if (typeof o.url !== 'string' || o.url.length > 2048 || !/^\/(?!\/)[\x21-\x7e]*$/.test(o.url))
193
+ return undefined;
194
+ if (o.title !== undefined && typeof o.title !== 'string')
195
+ return undefined;
196
+ if (o.nav !== undefined && typeof o.nav !== 'boolean')
197
+ return undefined;
198
+ let scroll;
199
+ if (o.scroll !== undefined) {
200
+ const sc = o.scroll;
201
+ const part = (x) => typeof x === 'number' && Number.isInteger(x) && x >= 0 && x <= 10000;
202
+ if (!Array.isArray(sc) || sc.length !== 2 || !part(sc[0]) || !part(sc[1]))
203
+ return undefined;
204
+ scroll = [sc[0], sc[1]];
205
+ }
206
+ return { id: o.id, url: o.url, title: cleanText(typeof o.title === 'string' ? o.title : '', 200), nav: o.nav === true, ...(scroll ? { scroll } : {}) };
207
+ }
208
+ /** The tab ID a page's event stream names (`/__sitefile/reload?client=<id>`, the first `client`), else undefined. */
209
+ export function streamClientId(search) {
210
+ for (const pair of search.replace(/^\?/, '').split('&')) {
211
+ const eq = pair.indexOf('=');
212
+ if (eq === -1 || pair.slice(0, eq) !== 'client')
213
+ continue;
214
+ const id = pair.slice(eq + 1);
215
+ return CLIENT_ID.test(id) ? id : undefined;
216
+ }
217
+ return undefined;
218
+ }
219
+ /**
220
+ * Whether a request for {@link CLIENTS_PATH} comes from the operator (Sitefile Desktop, curl), not a
221
+ * page: a loopback client that sends no `Origin` and no `Sec-Fetch-*` header.
222
+ */
223
+ export function isOperatorRequest(remote, headers) {
224
+ if (!isLoopbackAddress(remote))
225
+ return false;
226
+ return headers.origin === undefined && headers['sec-fetch-site'] === undefined && headers['sec-fetch-mode'] === undefined;
227
+ }
228
+ /**
229
+ * A `--sync` log line. Text: `client <event> <id> <url> <remote> <device>`. JSON (a stable contract,
230
+ * docs/CLI.md): `{"type":"client","ts","event","id","url","title","remote","device"}`, `title` only
231
+ * when not empty.
232
+ */
233
+ export function clientLogLine(format, e) {
234
+ if (format === 'text')
235
+ return `client ${e.event} ${e.id} ${e.url} ${e.remote} ${e.device}`;
236
+ return `{"type":"client","ts":${JSON.stringify(e.ts)},"event":${JSON.stringify(e.event)},"id":${JSON.stringify(e.id)},"url":${JSON.stringify(e.url)}${e.title !== '' ? `,"title":${JSON.stringify(e.title)}` : ''},"remote":${JSON.stringify(e.remote)},"device":${JSON.stringify(e.device)}}`;
237
+ }
238
+ /** The event that tells every page to reload. */
239
+ export const RELOAD_EVENT = '{"type":"reload"}';
240
+ /** Sent when a rebuild starts (pages show a Rebuilding badge). */
241
+ export const BUILDING_EVENT = '{"type":"building"}';
242
+ /** Sent after a good rebuild that changed nothing (pages clear the badge and any error overlay). */
243
+ export const OK_EVENT = '{"type":"ok"}';
244
+ /** The event for a failed rebuild: `{"type":"error","code","message"[,"file","line","column"]}`. */
245
+ export function errorEvent(e) {
246
+ return JSON.stringify({
247
+ type: 'error',
248
+ code: e.code,
249
+ message: e.detail,
250
+ ...(e.span ? { file: e.span.file, line: e.span.line, column: e.span.column } : {}),
251
+ });
252
+ }
253
+ /**
254
+ * The URL path that serves `file`: `/dir/` for `/dir/index.html` (and `/` for `/index.html`),
255
+ * else the file path; each segment percent-encoded like encodeURIComponent.
256
+ */
257
+ export function pageUrlFor(file) {
258
+ const segs = file.split('/').slice(1);
259
+ if (segs[segs.length - 1] === 'index.html')
260
+ segs[segs.length - 1] = '';
261
+ return '/' + segs.map(encodeURIComponent).join('/');
262
+ }
263
+ /**
264
+ * The live-reload event for a new tree (undefined when no file changed): `{"type":"css","paths":[...]}`
265
+ * when `cssInject` is on and every changed file is a stylesheet that is in both trees (added or
266
+ * removed files always reload), else {@link RELOAD_EVENT}; with `navigate`, a reload where exactly
267
+ * one HTML file was added or changed also names its page: `{"type":"reload","path":"/posts/a/"}`.
268
+ * A reload where only existing HTML files changed (nothing added or removed, no other type) is
269
+ * marked `"morph":true`: pages may update in place. Paths are sorted.
270
+ */
271
+ export function reloadEventFor(prev, next, cssInject, navigate = false) {
272
+ const changed = [];
273
+ const pages = [];
274
+ let cssOnly = cssInject;
275
+ let htmlOnly = true;
276
+ for (const [p, f] of next.entries()) {
277
+ const old = prev.get(p);
278
+ if (old !== undefined && old.digest === f.digest && old.mode === f.mode)
279
+ continue;
280
+ changed.push(p);
281
+ const html = mimeTypeFor(p).startsWith('text/html');
282
+ if (html)
283
+ pages.push(p);
284
+ if (old === undefined || !html)
285
+ htmlOnly = false;
286
+ if (old === undefined || !mimeTypeFor(p).startsWith('text/css'))
287
+ cssOnly = false;
288
+ }
289
+ for (const [p] of prev.entries()) {
290
+ if (!next.isFile(p)) {
291
+ changed.push(p);
292
+ cssOnly = false;
293
+ htmlOnly = false;
294
+ }
295
+ }
296
+ if (changed.length === 0)
297
+ return undefined;
298
+ if (!cssOnly) {
299
+ const path = navigate && pages.length === 1 ? pageUrlFor(pages[0]) : undefined;
300
+ if (path === undefined && !htmlOnly)
301
+ return RELOAD_EVENT;
302
+ return JSON.stringify({ type: 'reload', ...(path !== undefined ? { path } : {}), ...(htmlOnly ? { morph: true } : {}) });
303
+ }
304
+ return JSON.stringify({ type: 'css', paths: changed.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)) });
305
+ }
306
+ /** Open live-reload streams; {@link LiveReload.send} gives every page an event ({@link LiveReload.reload}: reload). */
11
307
  export class LiveReload {
12
- clients = new Set();
13
- /** Hold `res` open as a text/event-stream until the client goes away. */
14
- attach(res, headers) {
15
- res.writeHead(200, { ...headers, 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
16
- res.write('retry: 1000\n\n');
17
- this.clients.add(res);
18
- res.on('close', () => this.clients.delete(res));
308
+ /** Open streams, with the tab ID each names (`--sync`). */
309
+ clients = new Map();
310
+ /** `--sync`: the pages that reported, in the order they first connected. */
311
+ known = new Map();
312
+ /** `--sync`, else undefined. */
313
+ sync;
314
+ /** The client script for this session ({@link clientScript}). */
315
+ script;
316
+ /** Time between heartbeat comments on an open stream (15 s; tests pass less). */
317
+ heartbeatMs;
318
+ /**
319
+ * This server process's instance ID (16 hex digits, random). Every stream starts with it as the
320
+ * event ID, so a page that reconnects after a restart (`server restart`, a new `serve --watch`)
321
+ * sends the old one in `Last-Event-ID` and is told to reload.
322
+ */
323
+ instance = randomBytes(8).toString('hex');
324
+ constructor(options = {}, heartbeatMs = HEARTBEAT_MS) {
325
+ this.script = clientScript(options);
326
+ this.heartbeatMs = heartbeatMs;
327
+ this.console = options.console === true;
328
+ this.sync = options.sync;
329
+ }
330
+ /**
331
+ * Hold `res` open as a text/event-stream until the client goes away. The headers keep proxies
332
+ * and tunnels from buffering or compressing it, and a comment every 15 s keeps idle
333
+ * connections from being cut (and finds clients that went away).
334
+ */
335
+ attach(res, headers, lastEventId, client) {
336
+ res.writeHead(200, { ...headers, ...STREAM_HEADERS });
337
+ res.write(`retry: 1000\n\nid: ${this.instance}\n\n`);
338
+ // A page that was connected to an earlier instance of this server (it restarted) reloads.
339
+ if (lastEventId !== undefined && lastEventId !== '' && lastEventId !== this.instance)
340
+ res.write(`data: ${RELOAD_EVENT}\n\n`);
341
+ // A page opened while the last build is broken shows the error at once.
342
+ if (this.failure !== undefined)
343
+ res.write(`data: ${this.failure}\n\n`);
344
+ const entry = client !== undefined && this.sync !== undefined ? this.track(client) : undefined;
345
+ this.clients.set(res, entry?.id);
346
+ const beat = setInterval(() => res.write(': ping\n\n'), this.heartbeatMs);
347
+ beat.unref();
348
+ res.on('close', () => {
349
+ clearInterval(beat);
350
+ this.clients.delete(res);
351
+ if (entry !== undefined) {
352
+ entry.streams--;
353
+ entry.lastSeen = new Date().toISOString();
354
+ }
355
+ });
356
+ }
357
+ /** `--sync`: the entry for a page whose stream opened (undefined when {@link MAX_CLIENTS} are connected). */
358
+ track(client) {
359
+ const now = new Date().toISOString();
360
+ let entry = this.known.get(client.id);
361
+ if (entry === undefined) {
362
+ if (this.known.size >= MAX_CLIENTS) {
363
+ const gone = [...this.known.values()].find((e) => e.streams === 0);
364
+ if (gone === undefined)
365
+ return undefined;
366
+ this.known.delete(gone.id);
367
+ }
368
+ entry = { id: client.id, remote: client.remote, device: client.device, url: '', title: '', since: now, lastSeen: now, streams: 0, window: 0, count: 0 };
369
+ this.known.set(client.id, entry);
370
+ }
371
+ entry.remote = client.remote;
372
+ entry.device = client.device;
373
+ entry.lastSeen = now;
374
+ entry.streams++;
375
+ return entry;
376
+ }
377
+ /**
378
+ * `--sync`: take a page's location report. The status to answer: `404` when its stream is not
379
+ * open, `429` over {@link CLIENT_REPORT_LIMIT}, else `204`; then the log line it gives (its first
380
+ * report, or a new URL) and the events sent to the other pages (`navigate`, and `scroll` with
381
+ * `--sync=scroll`).
382
+ */
383
+ report(r, now, format) {
384
+ const entry = this.known.get(r.id);
385
+ if (entry === undefined || entry.streams === 0 || this.sync === undefined)
386
+ return { status: 404 };
387
+ if (now - entry.window >= CLIENT_WINDOW_MS) {
388
+ entry.window = now;
389
+ entry.count = 0;
390
+ }
391
+ if (++entry.count > CLIENT_REPORT_LIMIT)
392
+ return { status: 429 };
393
+ const ts = new Date(now).toISOString();
394
+ const event = entry.url === '' ? 'connect' : entry.url !== r.url ? 'navigate' : undefined;
395
+ entry.url = r.url;
396
+ entry.title = r.title;
397
+ entry.lastSeen = ts;
398
+ if (r.nav)
399
+ this.sendExcept(JSON.stringify({ type: 'navigate', url: r.url }), r.id);
400
+ if (r.scroll !== undefined && this.sync === 'scroll')
401
+ this.sendExcept(JSON.stringify({ type: 'scroll', url: r.url, x: r.scroll[0], y: r.scroll[1] }), r.id);
402
+ if (event === undefined)
403
+ return { status: 204 };
404
+ return { status: 204, log: clientLogLine(format, { ts, event, id: r.id, url: r.url, title: r.title, remote: entry.remote, device: entry.device }) };
405
+ }
406
+ /**
407
+ * `--sync`: the connected pages as {@link CLIENTS_PATH} answers them:
408
+ * `{"clients":[{"id","url","title","remote","device","since","lastSeen"}]}` (one line), by
409
+ * `since`, then `id`. A page that has not reported yet has an empty `url`.
410
+ */
411
+ clientsJson() {
412
+ const list = [...this.known.values()].filter((e) => e.streams > 0).sort((a, b) => (a.since < b.since ? -1 : a.since > b.since ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
413
+ const items = list.map((e) => `{"id":${JSON.stringify(e.id)},"url":${JSON.stringify(e.url)},"title":${JSON.stringify(e.title)},"remote":${JSON.stringify(e.remote)},"device":${JSON.stringify(e.device)},"since":${JSON.stringify(e.since)},"lastSeen":${JSON.stringify(e.lastSeen)}}`);
414
+ return `{"clients":[${items.join(',')}]}\n`;
415
+ }
416
+ /** Send `event` to every open page except those of tab `id`. */
417
+ sendExcept(event, id) {
418
+ for (const [c, cid] of this.clients)
419
+ if (cid !== id)
420
+ c.write(`data: ${event}\n\n`);
421
+ }
422
+ console;
423
+ consoleWindow = 0;
424
+ consoleCount = 0;
425
+ /**
426
+ * Whether one more console message may be logged now (at most {@link CONSOLE_LIMIT} per
427
+ * {@link CONSOLE_WINDOW_MS}); the first refused one in a window also returns a notice line.
428
+ */
429
+ admitConsole(now) {
430
+ if (now - this.consoleWindow >= CONSOLE_WINDOW_MS) {
431
+ this.consoleWindow = now;
432
+ this.consoleCount = 0;
433
+ }
434
+ this.consoleCount++;
435
+ if (this.consoleCount <= CONSOLE_LIMIT)
436
+ return { ok: true };
437
+ return this.consoleCount === CONSOLE_LIMIT + 1 ? { ok: false, notice: `browser: more than ${CONSOLE_LIMIT} console messages in 10 s; dropping the rest` } : { ok: false };
438
+ }
439
+ /** The last error event, until a good build: sent to streams that open meanwhile. */
440
+ failure;
441
+ /** Send `event` (one line of JSON) to every open page. */
442
+ send(event) {
443
+ if (event.startsWith('{"type":"error"'))
444
+ this.failure = event;
445
+ else if (event !== BUILDING_EVENT)
446
+ this.failure = undefined;
447
+ for (const c of this.clients.keys())
448
+ c.write(`data: ${event}\n\n`);
19
449
  }
20
450
  reload() {
21
- for (const c of this.clients)
22
- c.write('data: reload\n\n');
451
+ this.send(RELOAD_EVENT);
23
452
  }
24
453
  get size() {
25
454
  return this.clients.size;
@@ -34,6 +463,10 @@ export function injectReloadScript(html) {
34
463
  }
35
464
  const NOT_FOUND_PAGE = '<!doctype html><meta charset="utf-8"><title>404 Not Found</title><h1>404 Not Found</h1>\n';
36
465
  const BAD_REQUEST_PAGE = '<!doctype html><meta charset="utf-8"><title>400 Bad Request</title><h1>400 Bad Request</h1>\n';
466
+ const FORBIDDEN_PAGE = '<!doctype html><meta charset="utf-8"><title>403 Forbidden</title><h1>403 Forbidden</h1>\n';
467
+ const UNAUTHORIZED_PAGE = '<!doctype html><meta charset="utf-8"><title>401 Unauthorized</title><h1>401 Unauthorized</h1>\n';
468
+ const FORBIDDEN_HOST_PAGE = '<!doctype html><meta charset="utf-8"><title>403 Forbidden</title><h1>403 Forbidden</h1><p>This server answers requests for localhost and IP addresses only. To allow another host name, restart it with <code>--allowed-host &lt;name&gt;</code>.</p>\n';
469
+ const ERROR_PAGE = '<!doctype html><meta charset="utf-8"><title>500 Internal Server Error</title><h1>500 Internal Server Error</h1>\n';
37
470
  const METHOD_PAGE = '<!doctype html><meta charset="utf-8"><title>405 Method Not Allowed</title><h1>405 Method Not Allowed</h1>\n';
38
471
  /** Decode a request path into safe segments, or undefined when it is malformed or unsafe. */
39
472
  export function safeSegments(rawPath) {
@@ -58,6 +491,379 @@ export function safeSegments(rawPath) {
58
491
  }
59
492
  return out;
60
493
  }
494
+ /**
495
+ * An access-log line. Text: `METHOD target STATUS BYTES MSms` (then ` <remote>` with `--log-ip`). JSON, a stable
496
+ * contract (docs/CLI.md): `{"type":"request","ts","method","path","query","status","bytes","ms","encoding","range"}`
497
+ * and `"remote"` with `--log-ip`, in that order; `path` and `query` split the target at the first `?` (the `?`
498
+ * dropped), `ms` has one decimal, `range` is the response's `Content-Range` or null.
499
+ */
500
+ export function accessLogLine(format, e) {
501
+ const target = printable(e.target);
502
+ if (format === 'text')
503
+ return `${e.method} ${target} ${e.status} ${e.bytes} ${e.ms.toFixed(1)}ms${e.note ?? ''}${e.remote !== undefined ? ` ${e.remote}` : ''}${e.device !== undefined ? ` ${e.device}` : ''}`;
504
+ const q = target.indexOf('?');
505
+ const path = q === -1 ? target : target.slice(0, q);
506
+ const query = q === -1 ? '' : target.slice(q + 1);
507
+ return (`{"type":"request","ts":${JSON.stringify(e.ts)},"method":${JSON.stringify(e.method)},"path":${JSON.stringify(path)},"query":${JSON.stringify(query)},` +
508
+ `"status":${e.status},"bytes":${e.bytes},"ms":${e.ms.toFixed(1)},"encoding":"identity","range":${e.range === undefined ? 'null' : JSON.stringify(e.range)}` +
509
+ `${e.note !== undefined ? `,"note":${JSON.stringify(e.note.replace(/^ \u2192 /, ''))}` : ''}` +
510
+ `${e.remote !== undefined ? `,"remote":${JSON.stringify(e.remote)}` : ''}${e.device !== undefined ? `,"device":${JSON.stringify(e.device)}` : ''}}`);
511
+ }
512
+ /** A log line that is not a request, as a JSON object (`--log-format json`): `warning: …` and `error…` lines get their own types. */
513
+ export function jsonLogLine(ts, line) {
514
+ const [type, message] = line.startsWith('warning: ') ? ['warning', line.slice(9)] : line.startsWith('error') ? ['error', line] : ['message', line];
515
+ return `{"type":${JSON.stringify(type)},"ts":${JSON.stringify(ts)},"message":${JSON.stringify(message)}}`;
516
+ }
517
+ /** `{"type":"started","ts","site","files","url"}`: a server is listening (`--log-format json`). */
518
+ export function startedLogLine(ts, site, files, url) {
519
+ return `{"type":"started","ts":${JSON.stringify(ts)},"site":${JSON.stringify(site)},"files":${files},"url":${JSON.stringify(url)}}`;
520
+ }
521
+ /** `{"type":"stopped","ts","signal"}`: a server shuts down (`--log-format json`). */
522
+ export function stoppedLogLine(ts, signal) {
523
+ return `{"type":"stopped","ts":${JSON.stringify(ts)},"signal":${JSON.stringify(signal)}}`;
524
+ }
525
+ /**
526
+ * A detached server's log line as JSON (`server logs --json`): JSON lines as they are; a text line
527
+ * (`<ISO time> <rest>`) as a request, started, stopped, warning, error or message object.
528
+ */
529
+ export function logLineAsJson(line) {
530
+ if (line.startsWith('{'))
531
+ return line;
532
+ const m = /^([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.]+Z) (.*)$/.exec(line);
533
+ if (!m)
534
+ return jsonLogLine('', line);
535
+ const [, ts, rest] = m;
536
+ const r = /^([A-Z][A-Z-]*) (\S+) ([0-9]{3}) ([0-9]+) ([0-9]+\.[0-9])ms(?: (\S+))?$/.exec(rest);
537
+ if (r) {
538
+ return accessLogLine('json', { ts, method: r[1], target: r[2], status: Number(r[3]), bytes: Number(r[4]), ms: Number(r[5]), ...(r[6] !== undefined ? { remote: r[6] } : {}) });
539
+ }
540
+ const started = /^serving (.+) \(([0-9]+) files\) at (\S+)$/.exec(rest);
541
+ if (started)
542
+ return startedLogLine(ts, started[1], Number(started[2]), started[3]);
543
+ const stopped = /^received (SIG[A-Z]+), shutting down$/.exec(rest);
544
+ if (stopped)
545
+ return stoppedLogLine(ts, stopped[1]);
546
+ return jsonLogLine(ts, rest);
547
+ }
548
+ /**
549
+ * Whether an `Accept-Encoding` value accepts `coding`: listed (or `*`) with a q-value above 0, ASCII
550
+ * case-insensitive; an explicit entry wins over `*`.
551
+ */
552
+ export function acceptsEncoding(header, coding) {
553
+ if (header === undefined)
554
+ return false;
555
+ let star;
556
+ for (const part of header.split(',')) {
557
+ const [name, ...params] = part.split(';').map((x) => x.trim());
558
+ const n = (name ?? '').replace(/[A-Z]/g, (c) => c.toLowerCase());
559
+ let q = 1;
560
+ for (const p of params) {
561
+ const m = /^[qQ][ \t]*=[ \t]*([0-9.]+)$/.exec(p);
562
+ if (m)
563
+ q = Number(m[1]);
564
+ }
565
+ const ok = Number.isFinite(q) && q > 0;
566
+ if (n === coding)
567
+ return ok;
568
+ if (n === '*')
569
+ star = ok;
570
+ }
571
+ return star ?? false;
572
+ }
573
+ /** Media types worth compressing: `text/*`, JSON, XML, SVG, JavaScript, wasm and `+json`/`+xml` types. */
574
+ export function isCompressible(type) {
575
+ const t = (type.split(';')[0] ?? '').trim();
576
+ return t.startsWith('text/') || t.endsWith('+json') || t.endsWith('+xml') || ['application/json', 'application/xml', 'application/javascript', 'application/wasm', 'image/svg+xml'].includes(t);
577
+ }
578
+ /** Presets: Chrome DevTools' "3G" (1.6 Mbit/s, 150 ms) and "Slow 3G" (400 kbit/s, 400 ms). */
579
+ export const THROTTLE_PRESETS = {
580
+ '3g': { bytesPerSecond: 200_000, latencyMs: 150 },
581
+ 'slow-3g': { bytesPerSecond: 50_000, latencyMs: 400 },
582
+ };
583
+ /** `3g`, `slow-3g` or `<kbit/s>[/<latency ms>]`, else undefined. */
584
+ export function parseThrottle(value) {
585
+ const preset = THROTTLE_PRESETS[value];
586
+ if (preset)
587
+ return preset;
588
+ const m = /^([0-9]{1,7})(?:\/([0-9]{1,5}))?$/.exec(value);
589
+ if (!m || Number(m[1]) === 0)
590
+ return undefined;
591
+ return { bytesPerSecond: Number(m[1]) * 125, latencyMs: Number(m[2] ?? 0) };
592
+ }
593
+ /** A content type `--mime` accepts: `type/subtype`, then optional parameters, printable ASCII. */
594
+ const MIME_VALUE = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*( *;[\x20-\x7e]*)?$/;
595
+ /** `--mime ext=type` (a leading `.` is dropped; the extension is lowercased), else undefined. */
596
+ export function parseMimeFlag(value) {
597
+ const i = value.indexOf('=');
598
+ if (i <= 0)
599
+ return undefined;
600
+ const ext = value.slice(0, i).replace(/^\./, '').replace(/[A-Z]/g, (c) => c.toLowerCase());
601
+ const type = value.slice(i + 1).trim();
602
+ return /^[a-z0-9_+-]+$/.test(ext) && MIME_VALUE.test(type) ? [ext, type] : undefined;
603
+ }
604
+ /** A `mime.types` file (nginx `types { type ext ...; }` or Apache `type ext ...` lines; `#` comments): ext → type. */
605
+ export function parseMimeTypes(text, origin) {
606
+ const out = new Map();
607
+ for (const [n, raw] of text.split('\n').entries()) {
608
+ const line = raw.replace(/#.*$/, '').replace(/^[ \t]*types\b/, ' ').replace(/[{};]/g, ' ').trim();
609
+ if (line === '')
610
+ continue;
611
+ const [type, ...exts] = line.split(/[ \t]+/);
612
+ if (type === undefined || !MIME_VALUE.test(type))
613
+ throw new SitefileError('E_USAGE', `${origin}:${n + 1}: not a content type: ${type ?? ''}`);
614
+ for (const e of exts) {
615
+ const ext = e.replace(/^\./, '').replace(/[A-Z]/g, (c) => c.toLowerCase());
616
+ if (!/^[a-z0-9_+-]+$/.test(ext))
617
+ throw new SitefileError('E_USAGE', `${origin}:${n + 1}: not an extension: ${e}`);
618
+ out.set(ext, type);
619
+ }
620
+ }
621
+ return out;
622
+ }
623
+ /** The `Cache-Control` a file of media `type` gets under `cache`, or undefined to keep `no-cache`. */
624
+ export function cacheControlFor(type, cache) {
625
+ if (cache === undefined)
626
+ return undefined;
627
+ if (type.startsWith('text/html'))
628
+ return cache.maxAgeHtml === undefined ? undefined : `public, max-age=${cache.maxAgeHtml}`;
629
+ if (cache.maxAge === undefined)
630
+ return undefined;
631
+ return `public, max-age=${cache.maxAge}${cache.immutable ? ', immutable' : ''}`;
632
+ }
633
+ /**
634
+ * The origin form of a request target: an absolute-form target (`http://host/path?q`, RFC 9112
635
+ * section 3.2.2, sent by proxies and some clients) loses its scheme and authority (`/path?q`, or
636
+ * `/` for an empty path); any other target is returned as it is. The authority is not checked.
637
+ */
638
+ /** `Access-Control-Request-Headers` echoed in a preflight answer, when it is a plain list of header names. */
639
+ export function preflightHeaders(value) {
640
+ const v = value?.trim();
641
+ return v !== undefined && v !== '' && /^[A-Za-z0-9 \t,!#$%&'*+\-.^_`|~]+$/.test(v) ? v : undefined;
642
+ }
643
+ /** Loopback, also as an IPv4-mapped IPv6 address (`::ffff:127.0.0.1`). */
644
+ function isLoopbackAddress(ip) {
645
+ return ip === '::1' || /^(::ffff:)?127\./i.test(ip);
646
+ }
647
+ /** Address bytes of an IPv4 or IPv6 literal (`::ffff:a.b.c.d` becomes IPv4), else undefined. */
648
+ export function ipBytes(text) {
649
+ const t = text.replace(/^::ffff:(?=[0-9]+\.)/i, '');
650
+ if (isIpv4(t))
651
+ return t.split('.').map(Number);
652
+ if (!/^[0-9A-Fa-f:]+$/.test(t) || !t.includes(':'))
653
+ return undefined;
654
+ const halves = t.split('::');
655
+ if (halves.length > 2)
656
+ return undefined;
657
+ const words = (h) => {
658
+ if (h === '')
659
+ return [];
660
+ const out = [];
661
+ for (const w of h.split(':')) {
662
+ if (!/^[0-9A-Fa-f]{1,4}$/.test(w))
663
+ return undefined;
664
+ out.push(parseInt(w, 16));
665
+ }
666
+ return out;
667
+ };
668
+ const a = words(halves[0]);
669
+ const b = halves.length === 2 ? words(halves[1]) : [];
670
+ if (a === undefined || b === undefined)
671
+ return undefined;
672
+ const fill = halves.length === 2 ? 8 - a.length - b.length : 0;
673
+ if (fill < (halves.length === 2 ? 1 : 0) || a.length + b.length + fill !== 8)
674
+ return undefined;
675
+ return [...a, ...new Array(fill).fill(0), ...b].flatMap((w) => [w >> 8, w & 0xff]);
676
+ }
677
+ /** `a.b.c.d/n`, `x::y/n` or a bare address (a /32 or /128), else undefined. */
678
+ export function parseCidr(text) {
679
+ const [addr, len, extra] = text.trim().split('/');
680
+ if (extra !== undefined || addr === undefined)
681
+ return undefined;
682
+ const bytes = ipBytes(addr);
683
+ if (bytes === undefined)
684
+ return undefined;
685
+ const max = bytes.length * 8;
686
+ if (len !== undefined && !/^[0-9]{1,3}$/.test(len))
687
+ return undefined;
688
+ const prefix = len === undefined ? max : Number(len);
689
+ return prefix <= max ? { bytes, prefix } : undefined;
690
+ }
691
+ function cidrContains(c, ip) {
692
+ if (c.bytes.length !== ip.length)
693
+ return false;
694
+ for (let bit = 0; bit < c.prefix; bit++) {
695
+ const mask = 0x80 >> bit % 8;
696
+ if ((c.bytes[bit >> 3] & mask) !== (ip[bit >> 3] & mask))
697
+ return false;
698
+ }
699
+ return true;
700
+ }
701
+ /** Whether `--allow-ip`/`--deny-ip` let a client in: loopback always; else not denied, and allowed when an allow list is given. */
702
+ export function ipAllowed(rules, remote) {
703
+ if (rules === undefined || isLoopbackAddress(remote))
704
+ return true;
705
+ const ip = ipBytes(remote);
706
+ if (ip === undefined)
707
+ return false;
708
+ if (rules.deny.some((c) => cidrContains(c, ip)))
709
+ return false;
710
+ return rules.allow.length === 0 || rules.allow.some((c) => cidrContains(c, ip));
711
+ }
712
+ /** A short device name from a `User-Agent` (`iPhone`, `iPad`, `Android`, `Windows`, `Mac`, `Linux`), or `other`. */
713
+ export function deviceOf(userAgent) {
714
+ const ua = userAgent ?? '';
715
+ for (const [needle, name] of [['iPhone', 'iPhone'], ['iPad', 'iPad'], ['Android', 'Android'], ['Windows', 'Windows'], ['Macintosh', 'Mac'], ['Linux', 'Linux']]) {
716
+ if (ua.includes(needle))
717
+ return name;
718
+ }
719
+ return 'other';
720
+ }
721
+ /** Whether `s` is a dotted-decimal IPv4 address. */
722
+ function isIpv4(s) {
723
+ const parts = s.split('.');
724
+ return parts.length === 4 && parts.every((p) => /^[0-9]{1,3}$/.test(p) && Number(p) <= 255);
725
+ }
726
+ /**
727
+ * The DNS-rebinding guard of {@link SiteServerOptions.allowedHosts}: whether a `Host` header value
728
+ * may be answered. Always allowed: no list, `*` in the list, no `Host`, an IP address (a rebinding
729
+ * attack needs a name), `localhost` and `*.localhost`. Otherwise the name (ASCII lowercase, without
730
+ * port and trailing dot) must equal an entry, or end with an entry that starts with `.` (or equal
731
+ * it without the dot).
732
+ */
733
+ export function hostAllowed(allowed, host) {
734
+ if (allowed === undefined || allowed.includes('*') || host === undefined)
735
+ return true;
736
+ const h = host.trim();
737
+ if (h === '')
738
+ return true;
739
+ if (h.startsWith('[')) {
740
+ const close = h.indexOf(']');
741
+ return close > 1 && /^[0-9A-Fa-f:.]+$/.test(h.slice(1, close)) && /^(:[0-9]*)?$/.test(h.slice(close + 1));
742
+ }
743
+ const m = /^(.*?)(:[0-9]*)?$/.exec(h);
744
+ let name = m[1].replace(/[A-Z]/g, (c) => c.toLowerCase());
745
+ if (name.endsWith('.'))
746
+ name = name.slice(0, -1);
747
+ if (isIpv4(name) || name === 'localhost' || name.endsWith('.localhost'))
748
+ return true;
749
+ return allowed.some((e) => (e.startsWith('.') ? name === e.slice(1) || name.endsWith(e) : name === e));
750
+ }
751
+ /** An `--allowed-host` value, lowercased: `*`, or a host name (letters, digits, `-`, `.`; a leading `.` for subdomains). */
752
+ export function parseAllowedHost(value) {
753
+ const v = value.trim().replace(/[A-Z]/g, (c) => c.toLowerCase());
754
+ if (v === '*')
755
+ return v;
756
+ return /^\.?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/.test(v) ? v.replace(/\.$/, '') : undefined;
757
+ }
758
+ export function originForm(target) {
759
+ const m = /^https?:\/\/[^/?#]*/i.exec(target);
760
+ if (!m)
761
+ return target;
762
+ const rest = target.slice(m[0].length);
763
+ return rest.startsWith('/') ? rest : '/' + rest;
764
+ }
765
+ /** A request header as one string (repeated headers joined with `, `). */
766
+ function header(v) {
767
+ return Array.isArray(v) ? v.join(', ') : v;
768
+ }
769
+ const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
770
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
771
+ /** An IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`, RFC 9110 section 5.6.7) for Unix seconds. */
772
+ export function httpDate(secs) {
773
+ return new Date(secs * 1000).toUTCString();
774
+ }
775
+ /** Unix seconds of an IMF-fixdate, or undefined for anything else (the obsolete formats too). */
776
+ export function parseHttpDate(value) {
777
+ const m = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), ([0-9]{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) GMT$/.exec(value.trim());
778
+ if (!m)
779
+ return undefined;
780
+ const [day, month, year, h, min, sec] = [Number(m[2]), MONTHS.indexOf(m[3]), Number(m[4]), Number(m[5]), Number(m[6]), Number(m[7])];
781
+ if (day < 1 || h > 23 || min > 59 || sec > 59)
782
+ return undefined;
783
+ const ms = Date.UTC(year, month, day, h, min, sec);
784
+ const d = new Date(ms);
785
+ if (d.getUTCDate() !== day || DAYS[d.getUTCDay()] !== m[1])
786
+ return undefined;
787
+ return ms / 1000;
788
+ }
789
+ /** One link-value as Node's `writeEarlyHints` accepts it: `<uri>` and `; param[=value]` pairs. */
790
+ const LINK_VALUE = /^(?:<[^>\r\n]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;
791
+ /**
792
+ * The link-values of a `Link` header that become `103 Early Hints`: split at commas outside `<…>`
793
+ * and quotes, kept when well formed and `rel=preload` or `rel=preconnect` (ASCII case-insensitive).
794
+ */
795
+ export function earlyHints(link) {
796
+ const parts = [];
797
+ let cur = '';
798
+ let angle = false;
799
+ let quote = false;
800
+ for (const c of link) {
801
+ if (c === '<' && !quote)
802
+ angle = true;
803
+ else if (c === '>' && !quote)
804
+ angle = false;
805
+ else if (c === '"' && !angle)
806
+ quote = !quote;
807
+ if (c === ',' && !angle && !quote) {
808
+ parts.push(cur);
809
+ cur = '';
810
+ }
811
+ else
812
+ cur += c;
813
+ }
814
+ parts.push(cur);
815
+ return parts
816
+ .map((p) => p.trim())
817
+ .filter((p) => {
818
+ if (!LINK_VALUE.test(p))
819
+ return false;
820
+ const v = p.replace(/[A-Z]/g, (c) => c.toLowerCase()).replace(/[ \t]/g, '');
821
+ return ['rel=preload', 'rel="preload"', 'rel=preconnect', 'rel="preconnect"'].some((t) => v.includes(t));
822
+ });
823
+ }
824
+ /** A `bytes=` value's number: digits only; more than 15 digits counts as larger than any file. */
825
+ function rangeNumber(s) {
826
+ if (!/^[0-9]+$/.test(s))
827
+ return undefined;
828
+ return s.length > 15 ? Number.POSITIVE_INFINITY : Number(s);
829
+ }
830
+ /**
831
+ * The byte range a `Range` header asks of a body of `size` bytes: `[start, end]` (inclusive),
832
+ * `'unsatisfiable'` (416), or undefined when the header is absent, malformed, not in bytes, or
833
+ * asks for several ranges (those are ignored: the whole body is sent, as RFC 9110 allows).
834
+ */
835
+ export function byteRange(header, size) {
836
+ if (header === undefined)
837
+ return undefined;
838
+ const v = header.trim();
839
+ if (v.slice(0, 6).toLowerCase() !== 'bytes=')
840
+ return undefined;
841
+ const spec = v.slice(6).trim();
842
+ if (spec.includes(','))
843
+ return undefined;
844
+ const dash = spec.indexOf('-');
845
+ if (dash === -1)
846
+ return undefined;
847
+ const first = spec.slice(0, dash).trim();
848
+ const last = spec.slice(dash + 1).trim();
849
+ if (first === '') {
850
+ const n = rangeNumber(last);
851
+ if (n === undefined)
852
+ return undefined;
853
+ if (n === 0 || size === 0)
854
+ return 'unsatisfiable';
855
+ return [Math.max(0, size - n), size - 1];
856
+ }
857
+ const start = rangeNumber(first);
858
+ if (start === undefined)
859
+ return undefined;
860
+ const end = last === '' ? Number.POSITIVE_INFINITY : rangeNumber(last);
861
+ if (end === undefined || end < start)
862
+ return undefined;
863
+ if (start >= size)
864
+ return 'unsatisfiable';
865
+ return [start, Math.min(end, size - 1)];
866
+ }
61
867
  function etagMatches(header, etag) {
62
868
  if (header === undefined)
63
869
  return false;
@@ -65,14 +871,152 @@ function etagMatches(header, etag) {
65
871
  return true;
66
872
  return header.split(',').some((t) => t.trim().replace(/^W\//, '') === etag);
67
873
  }
874
+ /**
875
+ * The app shell a `--spa` navigation to a missing path gets: `fallback` when given (`--spa-fallback`),
876
+ * else the `200.html` (Surge) or `index.html` of the request's directory or the closest parent that
877
+ * has one, so `/admin/users/5` gets `/admin/index.html` before `/index.html`. Undefined when none exists.
878
+ */
879
+ export function spaFallback(segs, trailingSlash, isFile, fallback) {
880
+ if (fallback !== undefined)
881
+ return isFile(fallback) ? fallback : undefined;
882
+ const dirs = trailingSlash ? segs : segs.slice(0, -1);
883
+ for (let n = dirs.length; n >= 0; n--) {
884
+ const dir = `/${dirs.slice(0, n).map((d) => d + '/').join('')}`;
885
+ for (const name of ['200.html', 'index.html'])
886
+ if (isFile(dir + name))
887
+ return dir + name;
888
+ }
889
+ return undefined;
890
+ }
891
+ export const HTML_HANDLINGS = ['auto', 'force-slash', 'drop-slash', 'none'];
892
+ export const HOST_PROFILES = ['netlify', 'cloudflare', 'vercel', 'github-pages', 'firebase'];
893
+ /**
894
+ * The routing of a host profile, with `--html-handling` replacing its HTML handling (the profile
895
+ * undefined: sitefile's rules, a 307 for the canonical redirects as on Cloudflare).
896
+ *
897
+ * | profile | HTML handling | redirect | `_redirects`/`_headers` | 404 |
898
+ * | netlify | auto | 301 | yes | nearest 404.html |
899
+ * | cloudflare | auto | 307 | yes | nearest 404.html, else /index.html (200) |
900
+ * | vercel | none | 308 | no | /404.html |
901
+ * | github-pages | sitefile's, `/about/` 404 | 301 | no | /404.html |
902
+ * | firebase | none | 301 | no | /404.html |
903
+ */
904
+ export function hostProfile(name, htmlHandling) {
905
+ const base = name === 'netlify'
906
+ ? { htmlHandling: 'auto', redirectStatus: 301, siteFiles: true, notFound: 'nearest', slashHtml: 'redirect' }
907
+ : name === 'cloudflare'
908
+ ? { htmlHandling: 'auto', redirectStatus: 307, siteFiles: true, notFound: 'index', slashHtml: 'redirect' }
909
+ : name === 'vercel'
910
+ ? { htmlHandling: 'none', redirectStatus: 308, siteFiles: false, notFound: 'root', slashHtml: 'redirect' }
911
+ : name === 'github-pages'
912
+ ? { redirectStatus: 301, siteFiles: false, notFound: 'root', slashHtml: 'not-found' }
913
+ : name === 'firebase'
914
+ ? { htmlHandling: 'none', redirectStatus: 301, siteFiles: false, notFound: 'root', slashHtml: 'redirect' }
915
+ : { redirectStatus: 307, siteFiles: true, notFound: 'nearest', slashHtml: 'redirect' };
916
+ return htmlHandling === undefined ? base : { ...base, htmlHandling };
917
+ }
918
+ /** The server's routing profile for the flags (undefined: sitefile's own rules). */
919
+ export function routingFor(o) {
920
+ return o.hostProfile === undefined && o.htmlHandling === undefined ? undefined : hostProfile(o.hostProfile, o.htmlHandling);
921
+ }
922
+ const utf8Order = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
923
+ /**
924
+ * What a missing path almost matched (at most 20): files whose path differs only in ASCII letter case
925
+ * from the path, `<path>.html` or `<path>/index.html` (which work on a case-insensitive disk but not on a
926
+ * host), sorted by path; then `_redirects` rules whose source matches but whose query parameters or
927
+ * conditions do not, in file order.
928
+ */
929
+ export function nearMisses(tree, isFile, vpath, redirects, req) {
930
+ const lower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
931
+ const wanted = new Set([vpath, `${vpath === '/' ? '' : vpath}.html`, `${vpath === '/' ? '' : vpath}/index.html`].map(lower));
932
+ const out = [];
933
+ const files = tree
934
+ .entries()
935
+ .map(([p]) => p)
936
+ .filter((p) => isFile(p) && wanted.has(lower(p)))
937
+ .sort(utf8Order);
938
+ for (const p of files)
939
+ out.push({ path: p, why: 'the letter case differs (a case-insensitive disk finds it, a host does not)' });
940
+ for (const r of redirects) {
941
+ if (matchRedirect(r, vpath) !== undefined && matchRule(r, vpath, req) === undefined) {
942
+ out.push({ line: r.line, why: `matches the path but not its ${r.query.length > 0 ? 'query parameters' : 'conditions'}${r.query.length > 0 && r.conditions.length > 0 ? ' or conditions' : ''}` });
943
+ }
944
+ }
945
+ return out.slice(0, 20);
946
+ }
947
+ const escapeHtml = (s) => s.replace(/[&<>"]/g, (c) => (c === '&' ? '&amp;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : '&quot;'));
948
+ /** The development 404 page listing near misses. */
949
+ export function nearMissPage(vpath, misses, mount = '') {
950
+ let out = `<!doctype html><meta charset="utf-8"><title>404 Not Found</title><h1>404 Not Found</h1>\n<p>Nothing is served at <code>${escapeHtml(vpath)}</code>. Near misses:</p>\n<ul>\n`;
951
+ for (const m of misses) {
952
+ const what = m.path !== undefined ? `<a href="${escapeHtml(mount + encodePath(m.path))}">${escapeHtml(m.path)}</a>` : `<code>_redirects:${m.line}</code>`;
953
+ out += `<li>${what}: ${escapeHtml(m.why)}</li>\n`;
954
+ }
955
+ return out + '</ul>\n';
956
+ }
957
+ /** A `Host` header safe to write into a page: a name, IPv4 or bracketed IPv6 address, and a port. */
958
+ const SAFE_HOST = /^(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::[0-9]{1,5})?$/;
959
+ /** Types `--rewrite-base` rewrites: HTML, CSS and any XML (feeds, sitemaps, SVG). */
960
+ export function isRebasedType(type) {
961
+ return type.startsWith('text/html') || type.startsWith('text/css') || type.split(';', 1)[0].includes('xml');
962
+ }
963
+ /**
964
+ * A production URL for `--rewrite-base`: `scheme://host[/path]` without a trailing slash, query or
965
+ * fragment (`https://example.com/blog/` → `https://example.com/blog`), or undefined when it is not an
966
+ * http(s) URL with a host.
967
+ */
968
+ export function normalizeProductionUrl(raw) {
969
+ const m = /^(https?:\/\/[^/?#\s]+)(\/[^?#\s]*)?$/i.exec(raw.replace(/[?#].*$/, ''));
970
+ if (!m)
971
+ return undefined;
972
+ return m[1] + (m[2] ?? '').replace(/\/+$/, '');
973
+ }
974
+ /**
975
+ * `body` with every `from` (a production URL) replaced by `to` (the local origin and base), where
976
+ * the next byte cannot continue a host or path segment (a letter, digit, `.`, `-`, `_`, `~`, `:` or `%`),
977
+ * so `https://example.com` does not match `https://example.com.evil` and `/blog` not `/blogroll`.
978
+ */
979
+ export function rewriteBaseUrls(body, from, to) {
980
+ const text = Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('latin1');
981
+ let out = '';
982
+ let i = 0;
983
+ for (;;) {
984
+ const at = text.indexOf(from, i);
985
+ if (at === -1)
986
+ break;
987
+ const next = text[at + from.length];
988
+ out += text.slice(i, at) + (next !== undefined && /[A-Za-z0-9._~:%-]/.test(next) ? from : to);
989
+ i = at + from.length;
990
+ }
991
+ if (i === 0)
992
+ return body;
993
+ return Buffer.from(out + text.slice(i), 'latin1');
994
+ }
995
+ /**
996
+ * A `--base` value as `/a/b/` (segments percent-encoded like encodeURIComponent, NFC), `/` for none, or undefined when it is not a
997
+ * safe absolute path. The path of a URL (`https://user.github.io/repo/`) is taken as well.
998
+ */
999
+ export function normalizeBase(raw) {
1000
+ const m = /^https?:\/\/[^/?#]*(\/[^?#]*)?/i.exec(raw);
1001
+ const p = m ? (m[1] ?? '/') : raw;
1002
+ const segs = safeSegments(p.startsWith('/') ? p : '/' + p);
1003
+ if (!segs)
1004
+ return undefined;
1005
+ return segs.length === 0 ? '/' : `/${segs.map(encodeURIComponent).join('/')}/`;
1006
+ }
1007
+ /** A tree path with each segment percent-encoded like encodeURIComponent. */
1008
+ function encodePath(p) {
1009
+ return p.split('/').map(encodeURIComponent).join('/');
1010
+ }
68
1011
  function printable(s) {
69
1012
  return s.replace(/[^\x21-\x7e]/g, (c) => `%${c.charCodeAt(0).toString(16).padStart(2, '0')}`).slice(0, 512);
70
1013
  }
71
1014
  /**
72
1015
  * An HTTP server for an immutable Tree. GET and HEAD only; nothing outside the tree is
73
1016
  * ever reachable because lookups are exact map keys built from validated segments.
74
- * Honours `/404.html`, `/_redirects` and `/_headers` (which it never serves), and answers
75
- * `/about` with `/about.html` when there is no such file or directory.
1017
+ * Honours `/404.html`, `/_redirects` and `/_headers` (which it never serves), answers
1018
+ * `/about` with `/about.html` when there is no such file or directory, and redirects `/about/`
1019
+ * to `/about` when only `/about.html` answers it.
76
1020
  */
77
1021
  export function createSiteServer(site, options = {}) {
78
1022
  // A function is read per request (`serve --watch` swaps in each good rebuild).
@@ -80,6 +1024,15 @@ export function createSiteServer(site, options = {}) {
80
1024
  const base = { 'x-content-type-options': 'nosniff', 'cache-control': 'no-cache' };
81
1025
  if (options.serverId)
82
1026
  base['x-sitefile-server'] = options.serverId;
1027
+ if (options.cors)
1028
+ base['access-control-allow-origin'] = '*';
1029
+ if (options.noindex)
1030
+ base['x-robots-tag'] = 'noindex';
1031
+ if (options.isolate !== undefined) {
1032
+ base['cross-origin-opener-policy'] = 'same-origin';
1033
+ base['cross-origin-embedder-policy'] = options.isolate;
1034
+ base['cross-origin-resource-policy'] = 'same-origin';
1035
+ }
83
1036
  // `_redirects` / `_headers` are parsed once per tree (a watched server gets a new tree per rebuild).
84
1037
  let rulesTree;
85
1038
  let rules = { redirects: [], headers: [] };
@@ -87,69 +1040,329 @@ export function createSiteServer(site, options = {}) {
87
1040
  if (t !== rulesTree) {
88
1041
  const text = (p) => {
89
1042
  const f = t.get(p);
90
- return f ? new TextDecoder().decode(f.bytes) : '';
1043
+ return f ? new TextDecoder().decode(options.content?.read(p) ?? f.bytes) : '';
91
1044
  };
92
1045
  rules = { redirects: parseRedirectRules(text('/_redirects')), headers: parseHeaderRules(text('/_headers')) };
93
1046
  rulesTree = t;
94
1047
  }
95
1048
  return rules;
96
1049
  };
1050
+ // One warning per policy text: a site usually sends the same CSP on every page.
1051
+ const warnedCsp = new Set();
1052
+ const warnCsp = (served, policy) => {
1053
+ if (policy === undefined || options.warn === undefined || warnedCsp.has(policy))
1054
+ return;
1055
+ const blocked = cspBlocksReload(policy);
1056
+ if (blocked === undefined)
1057
+ return;
1058
+ warnedCsp.add(policy);
1059
+ const what = blocked === 'script-src' ? `scripts from 'self' (${RELOAD_SCRIPT_PATH})` : `connections to 'self' (${RELOAD_PATH})`;
1060
+ options.warn(`live reload: the Content-Security-Policy that _headers sets for ${served} does not allow ${what}, so open pages will not reload: ${policy}`);
1061
+ };
1062
+ /** --compress: gzip output by file digest (at most 256 files), so a file is compressed once. */
1063
+ const gzipCache = new Map();
1064
+ const gzipped = (digest, bytes) => {
1065
+ let out = gzipCache.get(digest);
1066
+ if (out === undefined) {
1067
+ if (gzipCache.size >= 256)
1068
+ gzipCache.clear();
1069
+ out = gzip(bytes);
1070
+ gzipCache.set(digest, out);
1071
+ }
1072
+ return out;
1073
+ };
1074
+ /** Connections over --max-connections-per-ip: they get one 503. */
1075
+ const busy = new WeakSet();
97
1076
  const handler = (req, res) => {
98
1077
  const started = process.hrtime.bigint();
99
1078
  const method = req.method ?? 'GET';
100
- const url = req.url ?? '/';
1079
+ /** A non-loopback client of a server with client info: its address and device go into the access log. */
1080
+ const shared = !!options.clientInfo && !isLoopbackAddress(req.socket.remoteAddress ?? '');
1081
+ const target = req.url ?? '/';
1082
+ const url = originForm(target);
101
1083
  let bytes = 0;
102
- const finish = (status, headers, body) => {
1084
+ /** What answered, for the access log (` → /new (_redirects:3)`), when a rule did. */
1085
+ let note = '';
1086
+ const finish = (status, headers, body, quiet = false) => {
103
1087
  const buf = body === undefined ? undefined : typeof body === 'string' ? Buffer.from(body) : body;
104
- res.writeHead(status, { ...base, ...headers });
105
- if (buf !== undefined && method !== 'HEAD' && status !== 304) {
106
- bytes = buf.byteLength;
107
- res.end(buf);
1088
+ // 103 Early Hints before an HTML page whose `Link` (from `_headers`) preloads or preconnects.
1089
+ const link = headers.link;
1090
+ const html = String(headers['content-type'] ?? '').startsWith('text/html');
1091
+ if (status === 200 && method === 'GET' && html && typeof link === 'string' && (req.httpVersionMajor > 1 || req.httpVersionMinor >= 1)) {
1092
+ const hints = earlyHints(link);
1093
+ if (hints.length > 0)
1094
+ res.writeEarlyHints({ link: hints });
1095
+ }
1096
+ const send = buf !== undefined && method !== 'HEAD' && status !== 304 ? buf : undefined;
1097
+ if (send !== undefined)
1098
+ bytes = send.byteLength;
1099
+ const t = options.throttle;
1100
+ if (t === undefined) {
1101
+ res.writeHead(status, { ...base, ...headers });
1102
+ res.end(send);
108
1103
  }
109
1104
  else {
110
- res.end();
1105
+ // --throttle: wait the latency, then send the body in 100 ms slices of the bandwidth.
1106
+ const slice = Math.max(1, Math.floor(t.bytesPerSecond / 10));
1107
+ setTimeout(() => {
1108
+ res.writeHead(status, { ...base, ...headers });
1109
+ if (send === undefined)
1110
+ return void res.end();
1111
+ let at = 0;
1112
+ const next = () => {
1113
+ if (res.destroyed)
1114
+ return;
1115
+ const end = Math.min(send.byteLength, at + slice);
1116
+ res.write(send.subarray(at, end));
1117
+ at = end;
1118
+ if (at >= send.byteLength)
1119
+ res.end();
1120
+ else
1121
+ setTimeout(next, 100);
1122
+ };
1123
+ next();
1124
+ }, t.latencyMs);
111
1125
  }
112
1126
  const ms = Number((process.hrtime.bigint() - started) / 1000n) / 1000;
1127
+ if (quiet)
1128
+ return;
113
1129
  // `servers` probes carry the server's own id; they would only clutter the access log.
114
1130
  if (options.serverId !== undefined && req.headers['x-sitefile-probe'] === options.serverId)
115
1131
  return;
116
- options.log?.(`${method} ${printable(url)} ${status} ${bytes} ${ms.toFixed(1)}ms`);
1132
+ if (options.quiet)
1133
+ return;
1134
+ const range = headers['content-range'];
1135
+ options.log?.(accessLogLine(options.logFormat ?? 'text', {
1136
+ ts: new Date().toISOString(),
1137
+ method,
1138
+ target,
1139
+ status,
1140
+ bytes,
1141
+ ms,
1142
+ ...(range !== undefined ? { range: String(range) } : {}),
1143
+ ...(options.logIp || shared ? { remote: req.socket.remoteAddress ?? '' } : {}),
1144
+ ...(shared ? { device: deviceOf(req.headers['user-agent']) } : {}),
1145
+ ...(note !== '' ? { note } : {}),
1146
+ ...(options.logIp ? { remote: req.socket.remoteAddress ?? '' } : {}),
1147
+ }));
117
1148
  };
118
1149
  const page = (status, html, extra = {}) => finish(status, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html), ...extra }, html);
1150
+ if (!ipAllowed(options.ipRules, req.socket.remoteAddress ?? ''))
1151
+ return page(403, FORBIDDEN_PAGE);
1152
+ if (busy.has(req.socket))
1153
+ return finish(503, { 'retry-after': '1', 'content-length': 0, connection: 'close' }, undefined);
1154
+ // DNS rebinding: a page on another name must not read this server (before anything else).
1155
+ const hostHeader = req.headers.host;
1156
+ if (!hostAllowed(options.allowedHosts, hostHeader))
1157
+ return page(403, FORBIDDEN_HOST_PAGE);
1158
+ // Basic authentication covers everything, the live-reload endpoints too.
1159
+ if (options.auth !== undefined && !options.auth.allows(req.headers.authorization)) {
1160
+ return page(401, UNAUTHORIZED_PAGE, { 'www-authenticate': 'Basic realm="sitefile", charset="UTF-8"' });
1161
+ }
1162
+ const live = options.liveReload;
1163
+ if (live && url.split(/[?#]/, 1)[0] === CONSOLE_PATH) {
1164
+ // Browser console messages (the client script sends them; not access-logged).
1165
+ if (method !== 'POST')
1166
+ return finish(405, { allow: 'POST', 'content-length': 0 }, undefined, true);
1167
+ if (!isSameOriginPost(req.headers))
1168
+ return finish(403, { 'content-length': 0 }, undefined, true);
1169
+ const chunks = [];
1170
+ let size = 0;
1171
+ let tooBig = false;
1172
+ req.on('data', (c) => {
1173
+ size += c.byteLength;
1174
+ if (size > MAX_CONSOLE_BODY)
1175
+ tooBig = true;
1176
+ else
1177
+ chunks.push(c);
1178
+ });
1179
+ req.on('end', () => {
1180
+ if (tooBig)
1181
+ return finish(413, { 'content-length': 0, connection: 'close' }, undefined, true);
1182
+ const lines = consoleLines(Buffer.concat(chunks).toString('utf8'), live.console);
1183
+ if (lines === undefined)
1184
+ return finish(400, { 'content-length': 0 }, undefined, true);
1185
+ if (lines.length > 0) {
1186
+ const admitted = live.admitConsole(Date.now());
1187
+ if (admitted.notice !== undefined)
1188
+ options.log?.(admitted.notice);
1189
+ if (admitted.ok)
1190
+ for (const l of lines)
1191
+ options.log?.(l);
1192
+ }
1193
+ finish(204, {}, undefined, true);
1194
+ });
1195
+ return;
1196
+ }
1197
+ if (live?.sync !== undefined && url.split(/[?#]/, 1)[0] === CLIENT_PATH) {
1198
+ // --sync: a page's location report (the client script sends it; not access-logged).
1199
+ if (method !== 'POST')
1200
+ return finish(405, { allow: 'POST', 'content-length': 0 }, undefined, true);
1201
+ if (!isSameOriginPost(req.headers))
1202
+ return finish(403, { 'content-length': 0 }, undefined, true);
1203
+ const chunks = [];
1204
+ let size = 0;
1205
+ let tooBig = false;
1206
+ req.on('data', (c) => {
1207
+ size += c.byteLength;
1208
+ if (size > MAX_CLIENT_BODY)
1209
+ tooBig = true;
1210
+ else
1211
+ chunks.push(c);
1212
+ });
1213
+ req.on('end', () => {
1214
+ if (tooBig)
1215
+ return finish(413, { 'content-length': 0, connection: 'close' }, undefined, true);
1216
+ const r = parseClientReport(Buffer.concat(chunks).toString('utf8'));
1217
+ if (r === undefined)
1218
+ return finish(400, { 'content-length': 0 }, undefined, true);
1219
+ const done = live.report(r, Date.now(), options.logFormat ?? 'text');
1220
+ if (done.log !== undefined)
1221
+ options.log?.(done.log);
1222
+ finish(done.status, done.status === 204 ? {} : { 'content-length': 0 }, undefined, true);
1223
+ });
1224
+ return;
1225
+ }
1226
+ if (live?.sync !== undefined && url.split(/[?#]/, 1)[0] === CLIENTS_PATH) {
1227
+ // --sync: the connected pages, for Sitefile Desktop and other local tools (not access-logged).
1228
+ if (method !== 'GET' && method !== 'HEAD')
1229
+ return finish(405, { allow: 'GET, HEAD', 'content-length': 0 }, undefined, true);
1230
+ if (!isOperatorRequest(req.socket.remoteAddress ?? '', req.headers))
1231
+ return finish(403, { 'content-length': 0 }, undefined, true);
1232
+ const json = live.clientsJson();
1233
+ return finish(200, { 'content-type': 'application/json', 'cache-control': 'no-store', 'content-length': Buffer.byteLength(json) }, json, true);
1234
+ }
1235
+ if (options.cors && method === 'OPTIONS') {
1236
+ // A CORS preflight: any path, nothing is looked up.
1237
+ const allowHeaders = preflightHeaders(req.headers['access-control-request-headers']);
1238
+ return finish(204, { 'access-control-allow-methods': 'GET, HEAD', ...(allowHeaders !== undefined ? { 'access-control-allow-headers': allowHeaders } : {}), 'access-control-max-age': '600' }, undefined);
1239
+ }
119
1240
  if (method !== 'GET' && method !== 'HEAD')
120
- return page(405, METHOD_PAGE, { allow: 'GET, HEAD' });
1241
+ return page(405, METHOD_PAGE, { allow: options.cors ? 'GET, HEAD, OPTIONS' : 'GET, HEAD' });
121
1242
  const tree = current();
122
- const { redirects, headers: headerRules } = rulesFor(tree);
123
- const isFile = (p) => tree.isFile(p) && p !== '/_redirects' && p !== '/_headers';
1243
+ const profile = options.profile;
1244
+ const siteFiles = profile?.siteFiles !== false;
1245
+ const { redirects, headers: headerRules } = siteFiles ? rulesFor(tree) : { redirects: [], headers: [] };
1246
+ const isFile = (p) => tree.isFile(p) && !(siteFiles && (p === '/_redirects' || p === '/_headers'));
124
1247
  const q = url.indexOf('?');
125
1248
  const hash = url.indexOf('#');
126
1249
  const end = Math.min(q === -1 ? url.length : q, hash === -1 ? url.length : hash);
127
1250
  const rawPath = url.slice(0, end);
128
1251
  if (options.liveReload && rawPath === RELOAD_PATH) {
129
1252
  if (method === 'HEAD')
130
- return finish(200, { 'content-type': 'text/event-stream' }, undefined);
131
- return options.liveReload.attach(res, base); // not access-logged: one long request per open page
1253
+ return finish(200, { ...STREAM_HEADERS }, undefined);
1254
+ const id = options.liveReload.sync !== undefined ? streamClientId(url.slice(rawPath.length).split('#', 1)[0]) : undefined;
1255
+ const client = id !== undefined ? { id, remote: req.socket.remoteAddress ?? '', device: deviceOf(req.headers['user-agent']) } : undefined;
1256
+ return options.liveReload.attach(res, base, header(req.headers['last-event-id']), client); // not access-logged: one long request per open page
1257
+ }
1258
+ if (options.liveReload && rawPath === RELOAD_SCRIPT_PATH) {
1259
+ // not access-logged either: every page load fetches it
1260
+ const js = options.liveReload.script;
1261
+ return finish(200, { 'content-type': 'text/javascript; charset=utf-8', 'content-length': Buffer.byteLength(js) }, js, true);
132
1262
  }
133
1263
  const search = q === -1 ? '' : url.slice(q, hash === -1 || hash < q ? undefined : hash);
134
- const segs = safeSegments(rawPath);
135
- if (!segs)
1264
+ const allSegs = safeSegments(rawPath);
1265
+ if (!allSegs)
136
1266
  return page(400, BAD_REQUEST_PAGE);
137
1267
  const trailingSlash = rawPath.endsWith('/');
1268
+ // `--base`: the site lives under `mount`; requests outside it are 404 (or redirected into it).
1269
+ const baseNow = typeof options.base === 'function' ? options.base() : options.base;
1270
+ const baseSegs = baseNow === undefined ? [] : (safeSegments(baseNow) ?? []);
1271
+ /** The `--base` prefix of generated `Location`s (`''` without one), percent-encoded. */
1272
+ const mount = baseSegs.length === 0 ? '' : '/' + baseSegs.map(encodeURIComponent).join('/');
1273
+ let segs = allSegs;
1274
+ if (baseSegs.length > 0) {
1275
+ const inside = baseSegs.every((b, i) => allSegs[i] === b);
1276
+ if (inside && allSegs.length === baseSegs.length && !trailingSlash)
1277
+ return finish(301, { location: `${mount}/${search}`, 'content-length': 0 }, undefined);
1278
+ if (!inside && allSegs.length === 0 && !options.hideBase)
1279
+ return finish(302, { location: `${mount}/${search}`, 'content-length': 0 }, undefined);
1280
+ if (!inside)
1281
+ return page(404, NOT_FOUND_PAGE);
1282
+ segs = allSegs.slice(baseSegs.length);
1283
+ }
138
1284
  const vpath = '/' + segs.join('/');
139
1285
  // `_headers` patterns match the request path (with its trailing slash).
140
1286
  const custom = headersFor(headerRules, vpath + (trailingSlash && segs.length > 0 ? '/' : ''));
141
1287
  const sendFile = (status, served) => {
142
1288
  const file = tree.get(served);
143
- const type = mimeTypeFor(served);
144
- const live = options.liveReload !== undefined && type.startsWith('text/html');
145
- const body = live ? injectReloadScript(file.bytes) : file.bytes;
1289
+ const ext = served.slice(served.lastIndexOf('/') + 1).split('.').slice(1).pop()?.replace(/[A-Z]/g, (c) => c.toLowerCase());
1290
+ const type = (ext !== undefined ? options.mime?.get(ext) : undefined) ?? mimeTypeFor(served);
1291
+ const live = options.liveReload !== undefined && type.startsWith('text/html') && isNavigation(req.headers);
1292
+ if (live)
1293
+ warnCsp(served, custom['content-security-policy']);
1294
+ const prodNow = typeof options.rewriteBase === 'function' ? options.rewriteBase() : options.rewriteBase;
1295
+ const host = req.headers.host;
1296
+ const rebase = prodNow !== undefined && isRebasedType(type) && host !== undefined && SAFE_HOST.test(host) ? { from: prodNow, to: `http://${host}${mount}` } : undefined;
1297
+ // A `.dcz` sidecar (build --experimental-dictionary): sent when the request offers its dictionary.
1298
+ const delta = live || rebase ? undefined : deltaFor(tree, served, header(req.headers['available-dictionary']), header(req.headers['accept-encoding']));
1299
+ const dictionaryVary = tree.isFile(`${served}.dcz`);
1300
+ // A deflated zip entry goes to a gzip client as is, wrapped in a gzip header and trailer (not for a
1301
+ // range request: ranges are served from the identity body).
1302
+ const deflated = !live && !delta && !rebase && req.headers.range === undefined && acceptsGzip(req.headers['accept-encoding']) ? options.content?.deflated?.(served) : undefined;
1303
+ let body;
1304
+ try {
1305
+ body = deflated ? gzipMember(deflated.deflate, deflated.crc, deflated.size) : (options.content?.read(served) ?? file.bytes);
1306
+ }
1307
+ catch (e) {
1308
+ options.log?.(`error: ${e instanceof SitefileError ? e.message : String(e)}`);
1309
+ return page(500, ERROR_PAGE);
1310
+ }
1311
+ if (rebase)
1312
+ body = rewriteBaseUrls(body, rebase.from, rebase.to);
1313
+ if (live)
1314
+ body = injectReloadScript(body);
1315
+ // Otherwise: a precompressed `<path>.br` / `<path>.gz` the client accepts (br first), else gzip on the fly
1316
+ // under --compress. Range requests, live pages, rebased pages and deltas are never compressed here.
1317
+ const ae = req.headers['accept-encoding'];
1318
+ const plain = !deflated && !delta && !rebase && status === 200;
1319
+ const hasBr = plain && isFile(`${served}.br`);
1320
+ const hasGz = plain && isFile(`${served}.gz`);
1321
+ const onTheFly = plain && !!options.compress && isCompressible(type) && body.byteLength >= 1024;
1322
+ const negotiated = !live && (hasBr || hasGz || onTheFly);
1323
+ let coding;
1324
+ if (negotiated && req.headers.range === undefined) {
1325
+ if (hasBr && acceptsEncoding(ae, 'br'))
1326
+ [coding, body] = ['br', tree.get(`${served}.br`).bytes];
1327
+ else if (hasGz && acceptsEncoding(ae, 'gzip'))
1328
+ [coding, body] = ['gzip', tree.get(`${served}.gz`).bytes];
1329
+ else if (onTheFly && acceptsEncoding(ae, 'gzip'))
1330
+ [coding, body] = ['gzip', gzipped(file.digest, body)];
1331
+ }
1332
+ const varyOn = dictionaryVary ? 'accept-encoding, available-dictionary' : 'accept-encoding';
1333
+ const vary = deflated || negotiated || dictionaryVary ? { vary: varyOn } : {};
1334
+ const encoding = deflated ? { 'content-encoding': 'gzip', ...vary } : coding ? { 'content-encoding': coding, ...vary } : vary;
146
1335
  if (status !== 200)
147
- return finish(status, { 'content-type': type, 'content-length': body.byteLength, ...custom }, body);
148
- // An injected page is a different representation of the file: give it its own ETag.
149
- const etag = `"${file.digest.replace(/^sha256:/, '')}${live ? '-live' : ''}"`;
1336
+ return finish(status, { 'content-type': type, 'content-length': body.byteLength, ...encoding, ...custom }, body);
1337
+ const preview = cacheControlFor(type, options.cache);
1338
+ const cc = preview === undefined ? {} : { 'cache-control': preview };
1339
+ // An injected page, a rebased page, a compressed response and a delta are other representations of the
1340
+ // file: they get their own ETags.
1341
+ const etag = `"${file.digest.replace(/^sha256:/, '')}${rebase ? '-rebased' : ''}${live ? '-live' : ''}${deflated ? '-gzip' : coding ? `-${coding}` : ''}${delta ? '-dcz' : ''}"`;
1342
+ const modified = options.lastModified?.();
1343
+ const lm = modified === undefined ? {} : { 'last-modified': httpDate(modified) };
150
1344
  if (etagMatches(req.headers['if-none-match'], etag))
151
- return finish(304, { ...custom, etag }, undefined);
152
- finish(200, { 'content-type': type, 'content-length': body.byteLength, ...custom, etag }, body);
1345
+ return finish(304, { ...encoding, ...cc, ...custom, etag, ...lm }, undefined);
1346
+ // If-Modified-Since only counts without If-None-Match (RFC 9110 section 13.2.2).
1347
+ const ims = req.headers['if-none-match'] === undefined ? req.headers['if-modified-since'] : undefined;
1348
+ const since = ims === undefined ? undefined : parseHttpDate(ims);
1349
+ if (modified !== undefined && since !== undefined && modified <= since)
1350
+ return finish(304, { ...encoding, ...cc, ...custom, etag, ...lm }, undefined);
1351
+ // The delta is sent whole (no byte ranges of an encoded body).
1352
+ if (delta)
1353
+ return finish(200, { 'content-type': type, 'content-length': delta.byteLength, ...cc, ...custom, ...vary, 'content-encoding': 'dcz', etag, ...lm }, delta);
1354
+ // A single byte range of a GET (`If-Range` must name this ETag); anything else gets the whole file.
1355
+ const ifRange = req.headers['if-range'];
1356
+ const range = method === 'GET' && (ifRange === undefined || ifRange.trim() === etag) ? byteRange(req.headers.range, body.byteLength) : undefined;
1357
+ if (range === 'unsatisfiable') {
1358
+ return finish(416, { ...custom, ...vary, 'accept-ranges': 'bytes', 'content-range': `bytes */${body.byteLength}`, 'content-length': 0 }, undefined);
1359
+ }
1360
+ if (range !== undefined) {
1361
+ const [start, end] = range;
1362
+ const part = body.subarray(start, end + 1);
1363
+ return finish(206, { 'content-type': type, 'content-length': part.byteLength, ...cc, ...encoding, ...custom, etag, ...lm, 'accept-ranges': 'bytes', 'content-range': `bytes ${start}-${end}/${body.byteLength}` }, part);
1364
+ }
1365
+ finish(200, { 'content-type': type, 'content-length': body.byteLength, ...encoding, ...cc, ...custom, etag, ...lm, 'accept-ranges': 'bytes' }, body);
153
1366
  };
154
1367
  /** The file for a path: exact, `<path>.html` (clean URLs), or `<dir>/index.html` with a trailing slash. */
155
1368
  const resolve = (p, slash) => {
@@ -164,26 +1377,75 @@ export function createSiteServer(site, options = {}) {
164
1377
  }
165
1378
  return undefined;
166
1379
  };
1380
+ const one = (k) => {
1381
+ const v = req.headers[k];
1382
+ return Array.isArray(v) ? v.join(', ') : v;
1383
+ };
1384
+ const ruleRequest = { search, acceptLanguage: one('accept-language'), cookie: one('cookie'), country: options.country };
1385
+ /** Answer from `target` (an http(s) URL) under the proxy policy; a refusal or a failed fetch is a 502. */
1386
+ const proxyTo = (target, from) => {
1387
+ note = ` \u2192 ${redactUrl(target)} (proxy, ${from})`;
1388
+ const headers = {};
1389
+ for (const k of PROXY_REQUEST_HEADERS) {
1390
+ const v = one(k);
1391
+ if (v !== undefined)
1392
+ headers[k] = v;
1393
+ }
1394
+ const policy = options.proxy?.policy ?? { ...DEFAULT_FETCH_POLICY, network: { strict: true } };
1395
+ fetchRemote(target, policy, undefined, { method: method === 'HEAD' ? 'HEAD' : 'GET', raw: true, headers }).then((r) => {
1396
+ const out = {};
1397
+ for (const [n, vs] of r.headers ?? [])
1398
+ if (!HOP_BY_HOP.has(n))
1399
+ out[n] = vs.length === 1 ? vs[0] : [...vs];
1400
+ const upstreamLength = r.headers?.find(([n]) => n === 'content-length')?.[1][0];
1401
+ out['content-length'] = method === 'HEAD' && upstreamLength !== undefined ? upstreamLength : String(r.bytes.byteLength);
1402
+ finish(r.status ?? 502, out, r.bytes);
1403
+ }, (e) => {
1404
+ const why = isSitefileError(e) ? `error[${e.code}]: ${e.detail}` : `error: ${String(e)}`;
1405
+ note += ` ${why}`;
1406
+ const text = `502 Bad Gateway: ${why}\n`;
1407
+ finish(502, { 'content-type': 'text/plain; charset=utf-8', 'content-length': Buffer.byteLength(text) }, text);
1408
+ });
1409
+ };
1410
+ // `--proxy` routes come first: they are what this server is asked to front.
1411
+ for (const route of options.proxy?.routes ?? []) {
1412
+ const inside = route.prefix === '/' || vpath === route.prefix || vpath.startsWith(`${route.prefix}/`);
1413
+ if (!inside)
1414
+ continue;
1415
+ const rest = (route.prefix === '/' ? vpath : vpath.slice(route.prefix.length)) + (trailingSlash && segs.length > 0 ? '/' : '');
1416
+ const encoded = rest.split('/').map((p) => encodeURIComponent(p)).join('/');
1417
+ return proxyTo(route.target.replace(/\/$/, '') + encoded + search, `--proxy ${route.prefix}`);
1418
+ }
167
1419
  /** Apply the first matching `_redirects` rule (forced ones, or the others); false when none applies. */
168
1420
  const redirect = (forced) => {
169
1421
  for (const r of redirects) {
170
1422
  if (r.force !== forced)
171
1423
  continue;
172
- const rest = matchRedirect(r, vpath);
173
- if (rest === undefined)
1424
+ const caps = matchRule(r, vpath, ruleRequest);
1425
+ if (caps === undefined)
174
1426
  continue;
175
- const target = r.splat ? r.to.split(':splat').join(rest.split('/').map(encodeURIComponent).join('/')) : r.to;
176
- if (r.status !== 200 && r.status !== 404) {
177
- finish(r.status, { location: target.includes('?') ? target : target + search, 'content-length': 0 }, undefined);
1427
+ const target = substituteTarget(r.to, caps);
1428
+ if (!isRewriteStatus(r.status)) {
1429
+ // A rule that matches query parameters passes on only what its target names.
1430
+ const mounted = target.startsWith('/') ? mount + target : target;
1431
+ const location = mounted.includes('?') || r.query.length > 0 ? mounted : mounted + search;
1432
+ note = ` \u2192 ${location} (_redirects:${r.line})`;
1433
+ finish(r.status, { location, 'content-length': 0 }, undefined);
1434
+ return true;
1435
+ }
1436
+ if (r.status === 200 && /^https?:\/\//i.test(target)) {
1437
+ // A proxy rule (#172): the request's query string goes along unless the target has one.
1438
+ proxyTo(target.includes('?') || r.query.length > 0 ? target : target + search, `_redirects:${r.line}`);
178
1439
  return true;
179
1440
  }
180
- // 200 (rewrite) and 404: serve the target path's file with that status.
1441
+ // 200 (rewrite), 404, 410 and 451: serve the target path's file with that status.
181
1442
  const tq = target.indexOf('?');
182
1443
  const tpath = tq === -1 ? target : target.slice(0, tq);
183
1444
  const tsegs = safeSegments(tpath);
184
1445
  const served = tsegs ? resolve('/' + tsegs.join('/'), tpath.endsWith('/')) : undefined;
185
1446
  if (served === undefined)
186
1447
  continue;
1448
+ note = ` \u2192 ${encodePath(served)} (_redirects:${r.line})`;
187
1449
  sendFile(r.status, served);
188
1450
  return true;
189
1451
  }
@@ -191,22 +1453,115 @@ export function createSiteServer(site, options = {}) {
191
1453
  };
192
1454
  if (redirect(true))
193
1455
  return;
194
- let served = resolve(vpath, trailingSlash);
195
- if (served === undefined && !trailingSlash && tree.isDirectory(vpath)) {
196
- const location = '/' + segs.map(encodeURIComponent).join('/') + '/' + search;
1456
+ const handling = profile?.htmlHandling;
1457
+ let served;
1458
+ if (handling !== undefined) {
1459
+ // `--html-handling` (Cloudflare's modes): one canonical spelling per page, the others redirect to it.
1460
+ const go = (to, slash) => {
1461
+ const path = to.length === 0 ? '/' : '/' + to.map(encodeURIComponent).join('/') + (slash ? '/' : '');
1462
+ finish(profile.redirectStatus, { location: mount + path + search, 'content-length': 0 }, undefined);
1463
+ };
1464
+ const last = segs[segs.length - 1];
1465
+ const index = vpath === '/' ? '/index.html' : `${vpath}/index.html`;
1466
+ const hasIndex = isFile(index);
1467
+ const hasHtml = segs.length > 0 && isFile(`${vpath}.html`);
1468
+ if (!trailingSlash && last !== undefined && last.endsWith('.html') && isFile(vpath) && handling !== 'none') {
1469
+ // `/x.html` and `/x/index.html` are spelled out: send them to the clean form.
1470
+ const dir = segs.slice(0, -1);
1471
+ if (last === 'index.html')
1472
+ return go(dir, dir.length > 0 && handling !== 'drop-slash');
1473
+ return go([...dir, last.slice(0, -'.html'.length)], handling === 'force-slash');
1474
+ }
1475
+ if (!trailingSlash && isFile(vpath))
1476
+ served = vpath;
1477
+ else if (handling === 'none')
1478
+ served = trailingSlash && hasIndex ? index : undefined;
1479
+ else if (segs.length === 0)
1480
+ served = hasIndex ? index : undefined;
1481
+ else if (handling === 'auto') {
1482
+ if (hasIndex) {
1483
+ if (!trailingSlash)
1484
+ return go(segs, true);
1485
+ served = index;
1486
+ }
1487
+ else if (hasHtml) {
1488
+ if (trailingSlash)
1489
+ return go(segs, false);
1490
+ served = `${vpath}.html`;
1491
+ }
1492
+ }
1493
+ else if (hasIndex || hasHtml) {
1494
+ const slash = handling === 'force-slash';
1495
+ if (trailingSlash !== slash)
1496
+ return go(segs, slash);
1497
+ served = slash ? (hasIndex ? index : `${vpath}.html`) : hasHtml ? `${vpath}.html` : index;
1498
+ }
1499
+ }
1500
+ else
1501
+ served = resolve(vpath, trailingSlash);
1502
+ if (handling === undefined && served === undefined && !trailingSlash && tree.isDirectory(vpath)) {
1503
+ const location = mount + '/' + segs.map(encodeURIComponent).join('/') + '/' + search;
197
1504
  return finish(301, { location, 'content-length': 0 }, undefined);
198
1505
  }
199
1506
  if (served === undefined && redirect(false))
200
1507
  return;
201
- if (served === undefined && options.spa && !/\.[^/.]+$/.test(segs[segs.length - 1] ?? '') && isFile('/index.html'))
202
- served = '/index.html';
1508
+ // `/about/` when only `/about.html` answers: redirect to the clean URL `/about` (relative links in the
1509
+ // page then resolve as they do at `/about`). `_redirects` rules for the path come first.
1510
+ if (handling === undefined && profile?.slashHtml !== 'not-found' && served === undefined && trailingSlash && segs.length > 0 && isFile(`${vpath}.html`)) {
1511
+ const location = mount + '/' + segs.map(encodeURIComponent).join('/') + search;
1512
+ return finish(301, { location, 'content-length': 0 }, undefined);
1513
+ }
1514
+ if (served === undefined && options.spa && isNavigation(req.headers) && !(options.spaExclude ?? []).some((g) => globMatch(g, vpath + (trailingSlash && segs.length > 0 ? '/' : '')))) {
1515
+ served = spaFallback(segs, trailingSlash, isFile, options.spaFallback);
1516
+ if (served !== undefined)
1517
+ note = ` \u2192 ${encodePath(served)} (spa fallback)`;
1518
+ }
1519
+ if (served !== undefined && note === '' && served === `${vpath}.html`)
1520
+ note = ` \u2192 ${encodePath(served)} (clean URL)`;
203
1521
  if (served !== undefined)
204
1522
  return sendFile(200, served);
205
- if (isFile('/404.html'))
206
- return sendFile(404, '/404.html');
207
- page(404, NOT_FOUND_PAGE, custom);
1523
+ // The nearest 404.html: in the request's directory, then each parent up to the root (only the
1524
+ // root one for a profile whose host does not look further).
1525
+ const dirs = trailingSlash ? segs : segs.slice(0, -1);
1526
+ for (let n = profile?.notFound === 'root' ? 0 : dirs.length; n >= 0; n--) {
1527
+ const notFound = `/${dirs.slice(0, n).map((d) => d + '/').join('')}404.html`;
1528
+ if (isFile(notFound)) {
1529
+ note = ` \u2192 ${encodePath(notFound)}`;
1530
+ return sendFile(404, notFound);
1531
+ }
1532
+ }
1533
+ // Cloudflare Pages: a site without a 404.html is taken for a single-page app.
1534
+ if (profile?.notFound === 'index' && isFile('/index.html')) {
1535
+ note = ' \u2192 /index.html (no 404.html)';
1536
+ return sendFile(200, '/index.html');
1537
+ }
1538
+ const misses = options.devNotFound ? nearMisses(tree, isFile, vpath, redirects, ruleRequest) : [];
1539
+ page(404, misses.length === 0 ? NOT_FOUND_PAGE : nearMissPage(vpath, misses, mount), custom);
208
1540
  };
209
- const server = http.createServer(handler);
1541
+ // HTTPS when a certificate is given (same handler; an https.Server has the http.Server API).
1542
+ const server = options.tls
1543
+ ? https.createServer({ cert: Buffer.from(options.tls.cert), key: Buffer.from(options.tls.key) }, handler)
1544
+ : http.createServer(handler);
1545
+ const limit = options.maxConnectionsPerIp ?? 0;
1546
+ if (limit > 0) {
1547
+ const perIp = new Map();
1548
+ server.on('connection', (socket) => {
1549
+ const ip = socket.remoteAddress ?? '';
1550
+ if (!options.limitLoopback && isLoopbackAddress(ip))
1551
+ return;
1552
+ const n = (perIp.get(ip) ?? 0) + 1;
1553
+ perIp.set(ip, n);
1554
+ if (n > limit)
1555
+ busy.add(socket);
1556
+ socket.once('close', () => {
1557
+ const left = (perIp.get(ip) ?? 1) - 1;
1558
+ if (left === 0)
1559
+ perIp.delete(ip);
1560
+ else
1561
+ perIp.set(ip, left);
1562
+ });
1563
+ });
1564
+ }
210
1565
  server.on('clientError', (_err, socket) => {
211
1566
  if (socket.writable)
212
1567
  socket.end('HTTP/1.1 400 Bad Request\r\nconnection: close\r\ncontent-length: 0\r\n\r\n');
@@ -239,8 +1594,35 @@ export function closeServer(server) {
239
1594
  server.closeAllConnections();
240
1595
  });
241
1596
  }
242
- export function formatUrl(host, port) {
1597
+ /**
1598
+ * The addresses other machines can reach a server bound to all interfaces at: the up, non-loopback
1599
+ * interface addresses, IPv4 for `0.0.0.0`, IPv4 then IPv6 for `::` (IPv6 link-local `fe80::/10`
1600
+ * left out: it needs a zone), each family sorted as text, without duplicates. Empty for any other bind.
1601
+ */
1602
+ export function networkAddresses(bindHost) {
1603
+ if (bindHost !== '0.0.0.0' && bindHost !== '::')
1604
+ return [];
1605
+ const v4 = new Set();
1606
+ const v6 = new Set();
1607
+ for (const list of Object.values(os.networkInterfaces())) {
1608
+ for (const a of list ?? []) {
1609
+ if (a.internal)
1610
+ continue;
1611
+ if (a.family === 'IPv4')
1612
+ v4.add(a.address);
1613
+ else if (bindHost === '::' && !/^fe[89ab]/i.test(a.address))
1614
+ v6.add(a.address.toLowerCase());
1615
+ }
1616
+ }
1617
+ const sorted = (xs) => [...xs].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
1618
+ return [...sorted(v4), ...sorted(v6)];
1619
+ }
1620
+ /** {@link networkAddresses} as URLs. */
1621
+ export function networkUrls(bindHost, port, scheme = 'http') {
1622
+ return networkAddresses(bindHost).map((a) => formatUrl(a, port, scheme));
1623
+ }
1624
+ export function formatUrl(host, port, scheme = 'http') {
243
1625
  const shown = host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host;
244
- return `http://${shown.includes(':') ? `[${shown}]` : shown}:${port}/`;
1626
+ return `${scheme}://${shown.includes(':') ? `[${shown}]` : shown}:${port}/`;
245
1627
  }
246
1628
  //# sourceMappingURL=server.js.map