@johnhenry/sitefile 0.0.7 → 0.0.8
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/CHANGELOG.md +84 -1
- package/README.md +5 -0
- package/lib/src/attest.d.ts +12 -3
- package/lib/src/attest.js +15 -10
- package/lib/src/bake.js +2 -1
- package/lib/src/base-image.d.ts +2 -0
- package/lib/src/base-image.js +8 -0
- package/lib/src/cli/build-image.js +4 -2
- package/lib/src/cli/images.js +8 -5
- package/lib/src/cli/servers.js +59 -21
- package/lib/src/cli/watch.d.ts +2 -0
- package/lib/src/cli/watch.js +2 -1
- package/lib/src/cli.js +6 -3
- package/lib/src/dictionary.d.ts +1 -7
- package/lib/src/dictionary.js +1 -35
- package/lib/src/executor.d.ts +16 -5
- package/lib/src/executor.js +127 -58
- package/lib/src/index.d.ts +2 -0
- package/lib/src/index.js +2 -0
- package/lib/src/mime-type.d.ts +6 -0
- package/lib/src/mime-type.js +20 -0
- package/lib/src/nfc.d.ts +6 -0
- package/lib/src/nfc.js +10 -0
- package/lib/src/oci.d.ts +65 -1
- package/lib/src/oci.js +104 -10
- package/lib/src/paths.d.ts +2 -6
- package/lib/src/paths.js +2 -8
- package/lib/src/plugins/env.d.ts +20 -0
- package/lib/src/plugins/env.js +37 -0
- package/lib/src/plugins/exec.d.ts +1 -1
- package/lib/src/plugins/exec.js +3 -2
- package/lib/src/plugins/host.js +3 -2
- package/lib/src/precompress.d.ts +6 -0
- package/lib/src/precompress.js +6 -0
- package/lib/src/recipe.d.ts +37 -0
- package/lib/src/recipe.js +96 -0
- package/lib/src/registry-ops.d.ts +5 -1
- package/lib/src/registry-ops.js +69 -45
- package/lib/src/request-path.d.ts +10 -0
- package/lib/src/request-path.js +42 -0
- package/lib/src/serve-dictionary.d.ts +11 -0
- package/lib/src/serve-dictionary.js +45 -0
- package/lib/src/serve-rules.js +1 -1
- package/lib/src/server.d.ts +16 -229
- package/lib/src/server.js +135 -795
- package/lib/src/servers.d.ts +15 -0
- package/lib/src/servers.js +42 -2
- package/lib/src/site-core.d.ts +368 -0
- package/lib/src/site-core.js +1065 -0
- package/lib/src/site-handler.d.ts +14 -0
- package/lib/src/site-handler.js +32 -0
- package/lib/src/store.d.ts +31 -2
- package/lib/src/store.js +140 -21
- package/lib/src/wbn.d.ts +1 -6
- package/lib/src/wbn.js +2 -18
- package/package.json +5 -1
package/lib/src/server.js
CHANGED
|
@@ -2,89 +2,18 @@ import { randomBytes } from 'node:crypto';
|
|
|
2
2
|
import http from 'node:http';
|
|
3
3
|
import https from 'node:https';
|
|
4
4
|
import os from 'node:os';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
5
|
+
import { Readable } from 'node:stream';
|
|
6
|
+
import { pipeline } from 'node:stream';
|
|
7
|
+
import { SitefileError } from './errors.js';
|
|
8
|
+
import { fetchRemote } from './resources/https.js';
|
|
7
9
|
import { DEFAULT_FETCH_POLICY } from './resources/types.js';
|
|
8
|
-
import {
|
|
9
|
-
import { deltaFor } from './dictionary.js';
|
|
10
|
-
import { nfc } from './paths.js';
|
|
11
|
-
import { gzip } from './deflate.js';
|
|
12
|
-
import { mimeTypeFor } from './wbn.js';
|
|
10
|
+
import { mimeTypeFor } from './mime-type.js';
|
|
13
11
|
import { RELOAD_CLIENT } from './reload-client.js';
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
-
}
|
|
38
|
-
/** Reserved for the live-reload event stream while `serve --watch` runs. */
|
|
39
|
-
export const RELOAD_PATH = '/__sitefile/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>`;
|
|
12
|
+
import { BAD_REQUEST_PAGE, createSiteResponder, ERROR_PAGE, FORBIDDEN_HOST_PAGE, FORBIDDEN_PAGE, hostAllowed, originForm, RELOAD_PATH, RELOAD_SCRIPT, RELOAD_SCRIPT_PATH, siteBaseHeaders, UNAUTHORIZED_PAGE, } from './site-core.js';
|
|
13
|
+
// The pure rules live in the site handler's implementation (`site-core.ts`); the names `server.ts` always exported
|
|
14
|
+
// stay available from here.
|
|
15
|
+
export { acceptsEncoding, acceptsGzip, byteRange, cacheControlFor, createSiteHandler, createSiteResponder, cspBlocksReload, gzipMember, hostAllowed, hostProfile, HOST_PROFILES, HTML_HANDLINGS, httpDate, injectReloadScript, isCompressible, isNavigation, isRebasedType, nearMissPage, nearMisses, normalizeBase, normalizeProductionUrl, originForm, parseAllowedHost, parseHttpDate, preflightHeaders, RELOAD_PATH, RELOAD_SCRIPT, RELOAD_SCRIPT_PATH, rewriteBaseUrls, routingFor, safeSegments, siteBaseHeaders, spaFallback, } from './site-core.js';
|
|
44
16
|
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
17
|
/** Heartbeat interval on the event stream. */
|
|
89
18
|
export const HEARTBEAT_MS = 15_000;
|
|
90
19
|
/** Headers of the event stream (also on HEAD): no proxy buffering (`X-Accel-Buffering`), no compression or other transforms. */
|
|
@@ -454,43 +383,6 @@ export class LiveReload {
|
|
|
454
383
|
return this.clients.size;
|
|
455
384
|
}
|
|
456
385
|
}
|
|
457
|
-
/** `html` with {@link RELOAD_SCRIPT} inserted before the last `</body` (ASCII case-insensitive), else appended. */
|
|
458
|
-
export function injectReloadScript(html) {
|
|
459
|
-
const buf = Buffer.from(html.buffer, html.byteOffset, html.byteLength);
|
|
460
|
-
const at = buf.toString('latin1').toLowerCase().lastIndexOf('</body');
|
|
461
|
-
const script = Buffer.from(RELOAD_SCRIPT);
|
|
462
|
-
return at === -1 ? Buffer.concat([buf, script]) : Buffer.concat([buf.subarray(0, at), script, buf.subarray(at)]);
|
|
463
|
-
}
|
|
464
|
-
const NOT_FOUND_PAGE = '<!doctype html><meta charset="utf-8"><title>404 Not Found</title><h1>404 Not Found</h1>\n';
|
|
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 <name></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';
|
|
470
|
-
const METHOD_PAGE = '<!doctype html><meta charset="utf-8"><title>405 Method Not Allowed</title><h1>405 Method Not Allowed</h1>\n';
|
|
471
|
-
/** Decode a request path into safe segments, or undefined when it is malformed or unsafe. */
|
|
472
|
-
export function safeSegments(rawPath) {
|
|
473
|
-
if (!rawPath.startsWith('/') || rawPath.includes('\\') || rawPath.includes('\0'))
|
|
474
|
-
return undefined;
|
|
475
|
-
const out = [];
|
|
476
|
-
for (const raw of rawPath.split('/')) {
|
|
477
|
-
if (raw === '')
|
|
478
|
-
continue;
|
|
479
|
-
let seg;
|
|
480
|
-
try {
|
|
481
|
-
seg = decodeURIComponent(raw);
|
|
482
|
-
}
|
|
483
|
-
catch {
|
|
484
|
-
return undefined;
|
|
485
|
-
}
|
|
486
|
-
// A decoded '/', '\\', NUL, control character, '.' or '..' could change what is read.
|
|
487
|
-
if (seg === '.' || seg === '..' || /[\\/\u0000-\u001f\u007f]/.test(seg))
|
|
488
|
-
return undefined;
|
|
489
|
-
// Tree paths are NFC; a request for an NFD spelling finds the same file.
|
|
490
|
-
out.push(nfc(seg));
|
|
491
|
-
}
|
|
492
|
-
return out;
|
|
493
|
-
}
|
|
494
386
|
/**
|
|
495
387
|
* An access-log line. Text: `METHOD target STATUS BYTES MSms` (then ` <remote>` with `--log-ip`). JSON, a stable
|
|
496
388
|
* contract (docs/CLI.md): `{"type":"request","ts","method","path","query","status","bytes","ms","encoding","range"}`
|
|
@@ -545,36 +437,6 @@ export function logLineAsJson(line) {
|
|
|
545
437
|
return stoppedLogLine(ts, stopped[1]);
|
|
546
438
|
return jsonLogLine(ts, rest);
|
|
547
439
|
}
|
|
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
440
|
/** Presets: Chrome DevTools' "3G" (1.6 Mbit/s, 150 ms) and "Slow 3G" (400 kbit/s, 400 ms). */
|
|
579
441
|
export const THROTTLE_PRESETS = {
|
|
580
442
|
'3g': { bytesPerSecond: 200_000, latencyMs: 150 },
|
|
@@ -620,26 +482,6 @@ export function parseMimeTypes(text, origin) {
|
|
|
620
482
|
}
|
|
621
483
|
return out;
|
|
622
484
|
}
|
|
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
485
|
/** Loopback, also as an IPv4-mapped IPv6 address (`::ffff:127.0.0.1`). */
|
|
644
486
|
function isLoopbackAddress(ip) {
|
|
645
487
|
return ip === '::1' || /^(::ffff:)?127\./i.test(ip);
|
|
@@ -723,69 +565,10 @@ function isIpv4(s) {
|
|
|
723
565
|
const parts = s.split('.');
|
|
724
566
|
return parts.length === 4 && parts.every((p) => /^[0-9]{1,3}$/.test(p) && Number(p) <= 255);
|
|
725
567
|
}
|
|
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
568
|
/** A request header as one string (repeated headers joined with `, `). */
|
|
766
569
|
function header(v) {
|
|
767
570
|
return Array.isArray(v) ? v.join(', ') : v;
|
|
768
571
|
}
|
|
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
572
|
/** One link-value as Node's `writeEarlyHints` accepts it: `<uri>` and `; param[=value]` pairs. */
|
|
790
573
|
const LINK_VALUE = /^(?:<[^>\r\n]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;
|
|
791
574
|
/**
|
|
@@ -821,256 +604,37 @@ export function earlyHints(link) {
|
|
|
821
604
|
return ['rel=preload', 'rel="preload"', 'rel=preconnect', 'rel="preconnect"'].some((t) => v.includes(t));
|
|
822
605
|
});
|
|
823
606
|
}
|
|
824
|
-
|
|
825
|
-
|
|
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
|
-
}
|
|
867
|
-
function etagMatches(header, etag) {
|
|
868
|
-
if (header === undefined)
|
|
869
|
-
return false;
|
|
870
|
-
if (header.trim() === '*')
|
|
871
|
-
return true;
|
|
872
|
-
return header.split(',').some((t) => t.trim().replace(/^W\//, '') === etag);
|
|
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 === '&' ? '&' : c === '<' ? '<' : c === '>' ? '>' : '"'));
|
|
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');
|
|
607
|
+
function printable(s) {
|
|
608
|
+
return s.replace(/[^\x21-\x7e]/g, (c) => `%${c.charCodeAt(0).toString(16).padStart(2, '0')}`).slice(0, 512);
|
|
994
609
|
}
|
|
995
610
|
/**
|
|
996
|
-
*
|
|
997
|
-
*
|
|
611
|
+
* The site handler's options for a server's: the same rules, with proxying done by `fetchRemote` under
|
|
612
|
+
* the server's fetch policy (https only, public addresses only, an allow-list of hosts; every proxy rule
|
|
613
|
+
* is refused without `proxy`) and the reload script injected when there is a live-reload client.
|
|
998
614
|
*/
|
|
999
|
-
export function
|
|
1000
|
-
const
|
|
1001
|
-
const
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
}
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
}
|
|
1011
|
-
function printable(s) {
|
|
1012
|
-
return s.replace(/[^\x21-\x7e]/g, (c) => `%${c.charCodeAt(0).toString(16).padStart(2, '0')}`).slice(0, 512);
|
|
615
|
+
export function handlerOptionsOf(options) {
|
|
616
|
+
const policy = options.proxy?.policy ?? { ...DEFAULT_FETCH_POLICY, network: { strict: true } };
|
|
617
|
+
const proxy = {
|
|
618
|
+
routes: options.proxy?.routes ?? [],
|
|
619
|
+
fetch: async (target, request) => {
|
|
620
|
+
const r = await fetchRemote(target, policy, undefined, { method: request.method, raw: true, headers: { ...request.headers } });
|
|
621
|
+
return { ...(r.status !== undefined ? { status: r.status } : {}), ...(r.headers !== undefined ? { headers: r.headers } : {}), bytes: r.bytes };
|
|
622
|
+
},
|
|
623
|
+
};
|
|
624
|
+
// `operator`: the fetch above enforces the policy, so the handler's own is not applied (and its 502 bodies, which name the
|
|
625
|
+
// flag to add, are kept). `allowedHosts` is what the adapter has already checked: the handler reads the `Host` header.
|
|
626
|
+
return { ...options, proxy, injectReload: options.liveReload !== undefined, operator: true, allowedHosts: options.allowedHosts ?? ['*'] };
|
|
1013
627
|
}
|
|
1014
628
|
/**
|
|
1015
|
-
*
|
|
1016
|
-
*
|
|
1017
|
-
*
|
|
1018
|
-
*
|
|
1019
|
-
*
|
|
629
|
+
* The Node adapter for the site handler ({@link createSiteResponder}): an HTTP (or HTTPS) server for an
|
|
630
|
+
* immutable Tree. It owns what needs a socket or Node: the listener, the IP rules, the connection cap,
|
|
631
|
+
* the `Host` allow-list, basic authentication, throttling, `103 Early Hints`, the access log, and the
|
|
632
|
+
* live-reload endpoints (event stream, client script, console and client reports). Everything that
|
|
633
|
+
* decides what a path answers is the handler's.
|
|
1020
634
|
*/
|
|
1021
635
|
export function createSiteServer(site, options = {}) {
|
|
1022
|
-
|
|
1023
|
-
const
|
|
1024
|
-
const base = { 'x-content-type-options': 'nosniff', 'cache-control': 'no-cache' };
|
|
1025
|
-
if (options.serverId)
|
|
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
|
-
}
|
|
1036
|
-
// `_redirects` / `_headers` are parsed once per tree (a watched server gets a new tree per rebuild).
|
|
1037
|
-
let rulesTree;
|
|
1038
|
-
let rules = { redirects: [], headers: [] };
|
|
1039
|
-
const rulesFor = (t) => {
|
|
1040
|
-
if (t !== rulesTree) {
|
|
1041
|
-
const text = (p) => {
|
|
1042
|
-
const f = t.get(p);
|
|
1043
|
-
return f ? new TextDecoder().decode(options.content?.read(p) ?? f.bytes) : '';
|
|
1044
|
-
};
|
|
1045
|
-
rules = { redirects: parseRedirectRules(text('/_redirects')), headers: parseHeaderRules(text('/_headers')) };
|
|
1046
|
-
rulesTree = t;
|
|
1047
|
-
}
|
|
1048
|
-
return rules;
|
|
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
|
-
};
|
|
636
|
+
const base = siteBaseHeaders(options);
|
|
637
|
+
const respond = createSiteResponder(site, handlerOptionsOf(options));
|
|
1074
638
|
/** Connections over --max-connections-per-ip: they get one 503. */
|
|
1075
639
|
const busy = new WeakSet();
|
|
1076
640
|
const handler = (req, res) => {
|
|
@@ -1080,11 +644,11 @@ export function createSiteServer(site, options = {}) {
|
|
|
1080
644
|
const shared = !!options.clientInfo && !isLoopbackAddress(req.socket.remoteAddress ?? '');
|
|
1081
645
|
const target = req.url ?? '/';
|
|
1082
646
|
const url = originForm(target);
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
647
|
+
/**
|
|
648
|
+
* Write a response: `headers` are final (the base headers included). A body is bytes or a stream;
|
|
649
|
+
* `bytes` and `note` are what the access log reports; `quiet` keeps the line out of it.
|
|
650
|
+
*/
|
|
651
|
+
const send = (status, headers, body, bytes, note, quiet) => {
|
|
1088
652
|
// 103 Early Hints before an HTML page whose `Link` (from `_headers`) preloads or preconnects.
|
|
1089
653
|
const link = headers.link;
|
|
1090
654
|
const html = String(headers['content-type'] ?? '').startsWith('text/html');
|
|
@@ -1093,34 +657,66 @@ export function createSiteServer(site, options = {}) {
|
|
|
1093
657
|
if (hints.length > 0)
|
|
1094
658
|
res.writeEarlyHints({ link: hints });
|
|
1095
659
|
}
|
|
1096
|
-
const send = buf !== undefined && method !== 'HEAD' && status !== 304 ? buf : undefined;
|
|
1097
|
-
if (send !== undefined)
|
|
1098
|
-
bytes = send.byteLength;
|
|
1099
660
|
const t = options.throttle;
|
|
1100
661
|
if (t === undefined) {
|
|
1101
|
-
res.writeHead(status,
|
|
1102
|
-
|
|
662
|
+
res.writeHead(status, headers);
|
|
663
|
+
if (body === null)
|
|
664
|
+
res.end();
|
|
665
|
+
else if (body instanceof Uint8Array)
|
|
666
|
+
res.end(body);
|
|
667
|
+
else
|
|
668
|
+
pipeline(Readable.fromWeb(body), res, () => undefined);
|
|
1103
669
|
}
|
|
1104
670
|
else {
|
|
1105
671
|
// --throttle: wait the latency, then send the body in 100 ms slices of the bandwidth.
|
|
1106
672
|
const slice = Math.max(1, Math.floor(t.bytesPerSecond / 10));
|
|
1107
673
|
setTimeout(() => {
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
674
|
+
void (async () => {
|
|
675
|
+
res.writeHead(status, headers);
|
|
676
|
+
if (body === null)
|
|
677
|
+
return void res.end();
|
|
678
|
+
// The body is taken a slice at a time (views of the handler's chunks): a large file is never copied whole.
|
|
679
|
+
const reader = body instanceof Uint8Array ? undefined : body.getReader();
|
|
680
|
+
let held = body instanceof Uint8Array ? body : new Uint8Array(0);
|
|
681
|
+
/** Read until a chunk is held (or the body is over: nothing held). */
|
|
682
|
+
const fill = async () => {
|
|
683
|
+
while (held.byteLength === 0 && reader !== undefined) {
|
|
684
|
+
const next = await reader.read();
|
|
685
|
+
if (next.done)
|
|
686
|
+
return;
|
|
687
|
+
held = next.value;
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
const take = async () => {
|
|
691
|
+
const parts = [];
|
|
692
|
+
let have = 0;
|
|
693
|
+
while (have < slice) {
|
|
694
|
+
await fill();
|
|
695
|
+
if (held.byteLength === 0)
|
|
696
|
+
break;
|
|
697
|
+
const part = held.subarray(0, slice - have);
|
|
698
|
+
held = held.subarray(part.byteLength);
|
|
699
|
+
parts.push(part);
|
|
700
|
+
have += part.byteLength;
|
|
701
|
+
}
|
|
702
|
+
return parts;
|
|
703
|
+
};
|
|
704
|
+
const next = async () => {
|
|
705
|
+
if (res.destroyed)
|
|
706
|
+
return void reader?.cancel().catch(() => undefined);
|
|
707
|
+
const parts = await take();
|
|
708
|
+
if (parts.length === 0)
|
|
709
|
+
return void res.end();
|
|
710
|
+
for (const part of parts)
|
|
711
|
+
res.write(part);
|
|
712
|
+
await fill();
|
|
713
|
+
if (held.byteLength === 0)
|
|
714
|
+
res.end();
|
|
715
|
+
else
|
|
716
|
+
setTimeout(() => void next(), 100);
|
|
717
|
+
};
|
|
718
|
+
await next();
|
|
719
|
+
})();
|
|
1124
720
|
}, t.latencyMs);
|
|
1125
721
|
}
|
|
1126
722
|
const ms = Number((process.hrtime.bigint() - started) / 1000n) / 1000;
|
|
@@ -1146,6 +742,15 @@ export function createSiteServer(site, options = {}) {
|
|
|
1146
742
|
...(options.logIp ? { remote: req.socket.remoteAddress ?? '' } : {}),
|
|
1147
743
|
}));
|
|
1148
744
|
};
|
|
745
|
+
/** An answer of the adapter itself (a refusal, a live-reload endpoint). */
|
|
746
|
+
const finish = (status, headers, body, quiet = false) => {
|
|
747
|
+
const buf = body === undefined ? undefined : typeof body === 'string' ? Buffer.from(body) : body;
|
|
748
|
+
const out = {};
|
|
749
|
+
for (const [k, v] of Object.entries({ ...base, ...headers }))
|
|
750
|
+
out[k] = typeof v === 'number' ? String(v) : v;
|
|
751
|
+
const bytes = buf !== undefined && method !== 'HEAD' && status !== 304 ? buf : undefined;
|
|
752
|
+
send(status, out, bytes ?? null, bytes?.byteLength ?? 0, '', quiet);
|
|
753
|
+
};
|
|
1149
754
|
const page = (status, html, extra = {}) => finish(status, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html), ...extra }, html);
|
|
1150
755
|
if (!ipAllowed(options.ipRules, req.socket.remoteAddress ?? ''))
|
|
1151
756
|
return page(403, FORBIDDEN_PAGE);
|
|
@@ -1232,311 +837,46 @@ export function createSiteServer(site, options = {}) {
|
|
|
1232
837
|
const json = live.clientsJson();
|
|
1233
838
|
return finish(200, { 'content-type': 'application/json', 'cache-control': 'no-store', 'content-length': Buffer.byteLength(json) }, json, true);
|
|
1234
839
|
}
|
|
1235
|
-
if (
|
|
1236
|
-
|
|
1237
|
-
const
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
const q = url.indexOf('?');
|
|
1248
|
-
const hash = url.indexOf('#');
|
|
1249
|
-
const end = Math.min(q === -1 ? url.length : q, hash === -1 ? url.length : hash);
|
|
1250
|
-
const rawPath = url.slice(0, end);
|
|
1251
|
-
if (options.liveReload && rawPath === RELOAD_PATH) {
|
|
1252
|
-
if (method === 'HEAD')
|
|
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);
|
|
1262
|
-
}
|
|
1263
|
-
const search = q === -1 ? '' : url.slice(q, hash === -1 || hash < q ? undefined : hash);
|
|
1264
|
-
const allSegs = safeSegments(rawPath);
|
|
1265
|
-
if (!allSegs)
|
|
1266
|
-
return page(400, BAD_REQUEST_PAGE);
|
|
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
|
-
}
|
|
1284
|
-
const vpath = '/' + segs.join('/');
|
|
1285
|
-
// `_headers` patterns match the request path (with its trailing slash).
|
|
1286
|
-
const custom = headersFor(headerRules, vpath + (trailingSlash && segs.length > 0 ? '/' : ''));
|
|
1287
|
-
const sendFile = (status, served) => {
|
|
1288
|
-
const file = tree.get(served);
|
|
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;
|
|
1335
|
-
if (status !== 200)
|
|
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) };
|
|
1344
|
-
if (etagMatches(req.headers['if-none-match'], etag))
|
|
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);
|
|
1366
|
-
};
|
|
1367
|
-
/** The file for a path: exact, `<path>.html` (clean URLs), or `<dir>/index.html` with a trailing slash. */
|
|
1368
|
-
const resolve = (p, slash) => {
|
|
1369
|
-
if (isFile(p) && !(slash && p !== '/'))
|
|
1370
|
-
return p;
|
|
1371
|
-
if (!slash && p !== '/' && isFile(`${p}.html`))
|
|
1372
|
-
return `${p}.html`;
|
|
1373
|
-
if (slash && tree.isDirectory(p)) {
|
|
1374
|
-
const index = p === '/' ? '/index.html' : `${p}/index.html`;
|
|
1375
|
-
if (isFile(index))
|
|
1376
|
-
return index;
|
|
1377
|
-
}
|
|
1378
|
-
return undefined;
|
|
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
|
-
}
|
|
1419
|
-
/** Apply the first matching `_redirects` rule (forced ones, or the others); false when none applies. */
|
|
1420
|
-
const redirect = (forced) => {
|
|
1421
|
-
for (const r of redirects) {
|
|
1422
|
-
if (r.force !== forced)
|
|
1423
|
-
continue;
|
|
1424
|
-
const caps = matchRule(r, vpath, ruleRequest);
|
|
1425
|
-
if (caps === undefined)
|
|
1426
|
-
continue;
|
|
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}`);
|
|
1439
|
-
return true;
|
|
1440
|
-
}
|
|
1441
|
-
// 200 (rewrite), 404, 410 and 451: serve the target path's file with that status.
|
|
1442
|
-
const tq = target.indexOf('?');
|
|
1443
|
-
const tpath = tq === -1 ? target : target.slice(0, tq);
|
|
1444
|
-
const tsegs = safeSegments(tpath);
|
|
1445
|
-
const served = tsegs ? resolve('/' + tsegs.join('/'), tpath.endsWith('/')) : undefined;
|
|
1446
|
-
if (served === undefined)
|
|
1447
|
-
continue;
|
|
1448
|
-
note = ` \u2192 ${encodePath(served)} (_redirects:${r.line})`;
|
|
1449
|
-
sendFile(r.status, served);
|
|
1450
|
-
return true;
|
|
1451
|
-
}
|
|
1452
|
-
return false;
|
|
1453
|
-
};
|
|
1454
|
-
if (redirect(true))
|
|
1455
|
-
return;
|
|
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
|
-
}
|
|
840
|
+
if (method === 'GET' || method === 'HEAD') {
|
|
841
|
+
const q = url.indexOf('?');
|
|
842
|
+
const hash = url.indexOf('#');
|
|
843
|
+
const end = Math.min(q === -1 ? url.length : q, hash === -1 ? url.length : hash);
|
|
844
|
+
const rawPath = url.slice(0, end);
|
|
845
|
+
if (live && rawPath === RELOAD_PATH) {
|
|
846
|
+
if (method === 'HEAD')
|
|
847
|
+
return finish(200, { ...STREAM_HEADERS }, undefined);
|
|
848
|
+
const id = live.sync !== undefined ? streamClientId(url.slice(rawPath.length).split('#', 1)[0]) : undefined;
|
|
849
|
+
const client = id !== undefined ? { id, remote: req.socket.remoteAddress ?? '', device: deviceOf(req.headers['user-agent']) } : undefined;
|
|
850
|
+
live.attach(res, base, header(req.headers['last-event-id']), client); // not access-logged: one long request per open page
|
|
851
|
+
return;
|
|
1492
852
|
}
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
served = slash ? (hasIndex ? index : `${vpath}.html`) : hasHtml ? `${vpath}.html` : index;
|
|
853
|
+
if (live && rawPath === RELOAD_SCRIPT_PATH) {
|
|
854
|
+
// not access-logged either: every page load fetches it
|
|
855
|
+
const js = live.script;
|
|
856
|
+
return finish(200, { 'content-type': 'text/javascript; charset=utf-8', 'content-length': Buffer.byteLength(js) }, js, true);
|
|
1498
857
|
}
|
|
1499
858
|
}
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
}
|
|
1506
|
-
if (served === undefined && redirect(false))
|
|
1507
|
-
return;
|
|
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)`;
|
|
1521
|
-
if (served !== undefined)
|
|
1522
|
-
return sendFile(200, served);
|
|
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
|
-
}
|
|
859
|
+
const headers = new Headers();
|
|
860
|
+
try {
|
|
861
|
+
for (const [k, v] of Object.entries(req.headers))
|
|
862
|
+
if (v !== undefined)
|
|
863
|
+
headers.set(k, Array.isArray(v) ? v.join(', ') : v);
|
|
1532
864
|
}
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
note = ' \u2192 /index.html (no 404.html)';
|
|
1536
|
-
return sendFile(200, '/index.html');
|
|
865
|
+
catch {
|
|
866
|
+
return page(400, BAD_REQUEST_PAGE);
|
|
1537
867
|
}
|
|
1538
|
-
|
|
1539
|
-
|
|
868
|
+
void respond({ method, target, headers }).then((reply) => {
|
|
869
|
+
const r = reply.response;
|
|
870
|
+
const out = {};
|
|
871
|
+
for (const [k, v] of r.headers)
|
|
872
|
+
out[k] = k in out ? [...[out[k]].flat(), v] : v;
|
|
873
|
+
send(r.status, out, r.body, reply.bytes, reply.note, false);
|
|
874
|
+
}, () => {
|
|
875
|
+
if (!res.headersSent)
|
|
876
|
+
page(500, ERROR_PAGE);
|
|
877
|
+
else
|
|
878
|
+
res.destroy();
|
|
879
|
+
});
|
|
1540
880
|
};
|
|
1541
881
|
// HTTPS when a certificate is given (same handler; an https.Server has the http.Server API).
|
|
1542
882
|
const server = options.tls
|