@johnhenry/sitefile 0.0.3 → 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.
- package/CHANGELOG.md +49 -0
- package/README.md +4 -3
- package/lib/src/bake.d.ts +2 -0
- package/lib/src/bake.js +30 -1
- package/lib/src/bcrypt.d.ts +25 -0
- package/lib/src/bcrypt.js +201 -0
- package/lib/src/canonical.d.ts +6 -3
- package/lib/src/canonical.js +25 -11
- package/lib/src/cli/index.d.ts +4 -1
- package/lib/src/cli/index.js +5 -2
- package/lib/src/cli/serve-worker.js +76 -3
- package/lib/src/cli/servers.d.ts +7 -1
- package/lib/src/cli/servers.js +56 -17
- package/lib/src/executor.js +42 -5
- package/lib/src/hreflang.d.ts +25 -0
- package/lib/src/hreflang.js +72 -0
- package/lib/src/language/ast.d.ts +11 -1
- package/lib/src/language/parser.js +13 -0
- package/lib/src/language/validate.js +3 -0
- package/lib/src/links.d.ts +14 -0
- package/lib/src/links.js +22 -4
- package/lib/src/planner.d.ts +18 -0
- package/lib/src/planner.js +39 -0
- package/lib/src/reload-client.js +116 -1
- package/lib/src/resources/archive.d.ts +1 -1
- package/lib/src/resources/archive.js +24 -13
- package/lib/src/serve-auth.d.ts +3 -2
- package/lib/src/serve-auth.js +14 -6
- package/lib/src/server.d.ts +92 -1
- package/lib/src/server.js +205 -7
- package/lib/src/servers.d.ts +6 -0
- package/lib/src/site.d.ts +6 -2
- package/lib/src/site.js +21 -8
- package/package.json +1 -1
package/lib/src/reload-client.js
CHANGED
|
@@ -268,14 +268,128 @@ export const RELOAD_CLIENT = String.raw `(function (options) {
|
|
|
268
268
|
overlay = null;
|
|
269
269
|
}
|
|
270
270
|
|
|
271
|
+
// --sync: this page reports where it is (its path and fragment, its title and, with
|
|
272
|
+
// --sync=scroll, how far down it is) and follows the navigation (and scrolling) of the other open
|
|
273
|
+
// pages, unless a form field has focus. It never sends query strings, form contents, keys or cookies.
|
|
274
|
+
var sync = options.sync === "nav" || options.sync === "scroll";
|
|
275
|
+
var syncScroll = options.sync === "scroll";
|
|
276
|
+
function stored(k) {
|
|
277
|
+
try {
|
|
278
|
+
return sessionStorage.getItem(k);
|
|
279
|
+
} catch (_) {
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function store(k, v) {
|
|
284
|
+
try {
|
|
285
|
+
sessionStorage.setItem(k, v);
|
|
286
|
+
} catch (_) {}
|
|
287
|
+
}
|
|
288
|
+
// One ID per tab, kept across its page loads.
|
|
289
|
+
var clientId = sync ? stored("sitefile:client") || "" : "";
|
|
290
|
+
if (sync && !/^[0-9a-f]{16}$/.test(clientId)) {
|
|
291
|
+
var bytes = new Uint8Array(8);
|
|
292
|
+
if (window.crypto && crypto.getRandomValues) crypto.getRandomValues(bytes);
|
|
293
|
+
else for (var b = 0; b < 8; b++) bytes[b] = Math.floor(Math.random() * 256);
|
|
294
|
+
clientId = Array.prototype.map.call(bytes, function (x) { return (x < 16 ? "0" : "") + x.toString(16); }).join("");
|
|
295
|
+
store("sitefile:client", clientId);
|
|
296
|
+
}
|
|
297
|
+
var atKey = "sitefile:at";
|
|
298
|
+
function where() {
|
|
299
|
+
return (location.pathname + location.hash).slice(0, 2048);
|
|
300
|
+
}
|
|
301
|
+
function scrolled() {
|
|
302
|
+
var el = document.scrollingElement || document.documentElement;
|
|
303
|
+
var w = el.scrollWidth - window.innerWidth;
|
|
304
|
+
var h = el.scrollHeight - window.innerHeight;
|
|
305
|
+
var part = function (at, size) { return size > 0 ? Math.min(10000, Math.max(0, Math.round((at / size) * 10000))) : 0; };
|
|
306
|
+
return [part(window.scrollX, w), part(window.scrollY, h)];
|
|
307
|
+
}
|
|
308
|
+
var clientUrl = new URL("client", base).href;
|
|
309
|
+
function report(nav, withScroll) {
|
|
310
|
+
try {
|
|
311
|
+
var body = { id: clientId, url: where(), title: String(document.title || "").slice(0, 200), nav: nav };
|
|
312
|
+
if (withScroll) body.scroll = scrolled();
|
|
313
|
+
fetch(clientUrl, { method: "POST", body: JSON.stringify(body), keepalive: true }).catch(function () {});
|
|
314
|
+
} catch (_) {
|
|
315
|
+
// never let reporting break the page
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
// Once its stream is open, a page reports itself: as a navigation only when this tab showed
|
|
319
|
+
// another page before (not on a reload, a reconnect, a new tab or a page another one led here).
|
|
320
|
+
function arrived() {
|
|
321
|
+
var at = where();
|
|
322
|
+
var before = stored(atKey);
|
|
323
|
+
store(atKey, at);
|
|
324
|
+
report(before !== null && before !== at, syncScroll);
|
|
325
|
+
}
|
|
326
|
+
function moved() {
|
|
327
|
+
var at = where();
|
|
328
|
+
if (stored(atKey) === at) return;
|
|
329
|
+
store(atKey, at);
|
|
330
|
+
report(true, false);
|
|
331
|
+
}
|
|
332
|
+
if (sync) {
|
|
333
|
+
["pushState", "replaceState"].forEach(function (name) {
|
|
334
|
+
var original = history[name];
|
|
335
|
+
if (typeof original !== "function") return;
|
|
336
|
+
history[name] = function () {
|
|
337
|
+
var r = original.apply(this, arguments);
|
|
338
|
+
moved();
|
|
339
|
+
return r;
|
|
340
|
+
};
|
|
341
|
+
});
|
|
342
|
+
window.addEventListener("popstate", moved);
|
|
343
|
+
window.addEventListener("hashchange", moved);
|
|
344
|
+
}
|
|
345
|
+
function editing() {
|
|
346
|
+
var a = document.activeElement;
|
|
347
|
+
if (!a) return false;
|
|
348
|
+
var t = a.localName;
|
|
349
|
+
return t === "input" || t === "textarea" || t === "select" || a.isContentEditable === true;
|
|
350
|
+
}
|
|
351
|
+
var quietUntil = 0;
|
|
352
|
+
function follow(ev) {
|
|
353
|
+
if (!sync || typeof ev.url !== "string" || ev.url.charAt(0) !== "/" || ev.url.charAt(1) === "/") return;
|
|
354
|
+
var hash = ev.url.indexOf("#");
|
|
355
|
+
var path = hash === -1 ? ev.url : ev.url.slice(0, hash);
|
|
356
|
+
if (ev.type === "navigate") {
|
|
357
|
+
if (ev.url === where() || editing()) return;
|
|
358
|
+
store(atKey, ev.url); // the page this leads to is not a navigation of its own
|
|
359
|
+
if (hash !== -1 && path === location.pathname) location.hash = ev.url.slice(hash);
|
|
360
|
+
else location.assign(ev.url);
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
if (!syncScroll || path !== location.pathname || editing()) return;
|
|
364
|
+
if (typeof ev.x !== "number" || typeof ev.y !== "number") return;
|
|
365
|
+
var el = document.scrollingElement || document.documentElement;
|
|
366
|
+
quietUntil = Date.now() + 500; // the scroll this causes is not reported back
|
|
367
|
+
window.scrollTo((ev.x / 10000) * Math.max(0, el.scrollWidth - window.innerWidth), (ev.y / 10000) * Math.max(0, el.scrollHeight - window.innerHeight));
|
|
368
|
+
}
|
|
369
|
+
if (syncScroll) {
|
|
370
|
+
var scrollTimer = null;
|
|
371
|
+
window.addEventListener(
|
|
372
|
+
"scroll",
|
|
373
|
+
function () {
|
|
374
|
+
if (Date.now() < quietUntil || scrollTimer !== null) return;
|
|
375
|
+
scrollTimer = setTimeout(function () {
|
|
376
|
+
scrollTimer = null;
|
|
377
|
+
if (Date.now() >= quietUntil) report(false, true);
|
|
378
|
+
}, 250);
|
|
379
|
+
},
|
|
380
|
+
{ passive: true }
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
|
|
271
384
|
// EventSource reconnects by itself after a dropped connection (the server sends retry: 1000),
|
|
272
385
|
// but gives up for good when an answer is not an event stream (a proxy or tunnel error page):
|
|
273
386
|
// then try again, waiting twice as long each time, up to 30 s.
|
|
274
387
|
var delay = 1000;
|
|
275
388
|
function connect() {
|
|
276
|
-
var source = new EventSource(new URL("reload", base).href);
|
|
389
|
+
var source = new EventSource(new URL(sync ? "reload?client=" + clientId : "reload", base).href);
|
|
277
390
|
source.onopen = function () {
|
|
278
391
|
delay = 1000;
|
|
392
|
+
if (sync) arrived();
|
|
279
393
|
};
|
|
280
394
|
source.onmessage = function (e) {
|
|
281
395
|
var ev;
|
|
@@ -284,6 +398,7 @@ export const RELOAD_CLIENT = String.raw `(function (options) {
|
|
|
284
398
|
} catch (_) {
|
|
285
399
|
ev = { type: "reload" };
|
|
286
400
|
}
|
|
401
|
+
if (ev.type === "navigate" || ev.type === "scroll") return follow(ev);
|
|
287
402
|
if (ev.type === "building") return showBadge();
|
|
288
403
|
if (ev.type === "error") return showError(ev);
|
|
289
404
|
hideBadge();
|
|
@@ -2,7 +2,7 @@ import { type SourceSpan } from '../errors.js';
|
|
|
2
2
|
import { Tree } from '../tree.js';
|
|
3
3
|
import { type ArchiveLimits } from './types.js';
|
|
4
4
|
/**
|
|
5
|
-
* Extract a tar, tar.gz/tgz, zip or Web Bundle (b1/b2) archive into a Tree. The format is detected
|
|
5
|
+
* Extract a tar, tar.gz/tgz, tar.zst/tzst, zip or Web Bundle (b1/b2, plain or gzip-wrapped) archive into a Tree. The format is detected
|
|
6
6
|
* from magic bytes, never from the name. Nothing is inflated beyond the limits,
|
|
7
7
|
* and unsafe entries (absolute or `..` paths, backslashes, NUL, symlinks, hard
|
|
8
8
|
* links, devices) are rejected, not skipped. A single top-level directory is
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
|
|
2
|
-
import { crc32, gunzip as gunzipCb, inflateRaw as inflateRawCb, inflateRawSync } from 'node:zlib';
|
|
2
|
+
import { crc32, gunzip as gunzipCb, inflateRaw as inflateRawCb, inflateRawSync, zstdDecompress as zstdDecompressCb } from 'node:zlib';
|
|
3
3
|
import { promisify } from 'node:util';
|
|
4
4
|
import { SitefileError } from '../errors.js';
|
|
5
5
|
import { normalizeVirtual } from '../paths.js';
|
|
@@ -10,10 +10,11 @@ import { isWebBundle, readWebBundle, webBundleToTree } from './wbn-reader.js';
|
|
|
10
10
|
const RATIO_FLOOR = 1024 * 1024;
|
|
11
11
|
const gunzipAsync = promisify(gunzipCb);
|
|
12
12
|
const inflateRawAsync = promisify(inflateRawCb);
|
|
13
|
+
const zstdDecompressAsync = promisify(zstdDecompressCb);
|
|
13
14
|
/** Tar framing per entry, worst case: header + padding + a pax/GNU long-name header and its padding. */
|
|
14
15
|
const TAR_OVERHEAD_PER_ENTRY = 4 * 512;
|
|
15
16
|
/**
|
|
16
|
-
* Extract a tar, tar.gz/tgz, zip or Web Bundle (b1/b2) archive into a Tree. The format is detected
|
|
17
|
+
* Extract a tar, tar.gz/tgz, tar.zst/tzst, zip or Web Bundle (b1/b2, plain or gzip-wrapped) archive into a Tree. The format is detected
|
|
17
18
|
* from magic bytes, never from the name. Nothing is inflated beyond the limits,
|
|
18
19
|
* and unsafe entries (absolute or `..` paths, backslashes, NUL, symlinks, hard
|
|
19
20
|
* links, devices) are rejected, not skipped. A single top-level directory is
|
|
@@ -23,11 +24,15 @@ export async function extractArchive(bytes, origin, limits = DEFAULT_ARCHIVE_LIM
|
|
|
23
24
|
if (isWebBundle(bytes))
|
|
24
25
|
return webBundleToTree(readWebBundle(bytes, origin, limits, span), origin, span);
|
|
25
26
|
const { add, files } = collector(origin, limits, span, true);
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
const compression = isGzip(bytes) ? 'gzip' : isZstd(bytes) ? 'zstd' : undefined;
|
|
28
|
+
if (compression) {
|
|
29
|
+
const inner = await decompress(compression, bytes, origin, limits, span);
|
|
30
|
+
// gzip(application/webbundle), as @johnhenry/fileable (encode="wbn") and packfile's toArchive() write it
|
|
31
|
+
if (isWebBundle(inner))
|
|
32
|
+
return webBundleToTree(readWebBundle(inner, origin, limits, span), origin, span);
|
|
33
|
+
if (!isTar(inner))
|
|
34
|
+
throw new SitefileError('E_TYPE', `${origin}: ${compression} content is not a tar archive`, span);
|
|
35
|
+
readTar(inner, origin, limits, span, add);
|
|
31
36
|
}
|
|
32
37
|
else if (isZip(bytes)) {
|
|
33
38
|
await readZip(bytes, origin, limits, span, add);
|
|
@@ -37,7 +42,7 @@ export async function extractArchive(bytes, origin, limits = DEFAULT_ARCHIVE_LIM
|
|
|
37
42
|
}
|
|
38
43
|
else {
|
|
39
44
|
const what = otherFormat(bytes);
|
|
40
|
-
throw new SitefileError('E_TYPE', `${origin}: not a recognized archive (${what ?? 'expected tar, tar.gz, zip or web bundle'})`, span);
|
|
45
|
+
throw new SitefileError('E_TYPE', `${origin}: not a recognized archive (${what ?? 'expected tar, tar.gz, tar.zst, zip or web bundle'})`, span);
|
|
41
46
|
}
|
|
42
47
|
return Tree.fromFiles(files);
|
|
43
48
|
}
|
|
@@ -99,8 +104,6 @@ function otherFormat(b) {
|
|
|
99
104
|
const starts = (...m) => b.length >= m.length && m.every((x, i) => b[i] === x);
|
|
100
105
|
if (starts(0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00))
|
|
101
106
|
return 'it is xz-compressed, e.g. .tar.xz; recompress it as .tar.gz or zip';
|
|
102
|
-
if (starts(0x28, 0xb5, 0x2f, 0xfd))
|
|
103
|
-
return 'it is zstd-compressed, e.g. .tar.zst; recompress it as .tar.gz or zip';
|
|
104
107
|
if (starts(0x42, 0x5a, 0x68) && b.length > 3 && b[3] >= 0x31 && b[3] <= 0x39)
|
|
105
108
|
return 'it is bzip2-compressed, e.g. .tar.bz2; recompress it as .tar.gz or zip';
|
|
106
109
|
if (starts(0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c))
|
|
@@ -110,6 +113,8 @@ function otherFormat(b) {
|
|
|
110
113
|
return undefined;
|
|
111
114
|
}
|
|
112
115
|
const isGzip = (b) => b.length > 2 && b[0] === 0x1f && b[1] === 0x8b;
|
|
116
|
+
/** A Zstandard frame (RFC 8878); a stream that starts with a skippable frame is not recognized. */
|
|
117
|
+
const isZstd = (b) => b.length >= 4 && b[0] === 0x28 && b[1] === 0xb5 && b[2] === 0x2f && b[3] === 0xfd;
|
|
113
118
|
const isZip = (b) => b.length >= 4 && b[0] === 0x50 && b[1] === 0x4b && ((b[2] === 3 && b[3] === 4) || (b[2] === 5 && b[3] === 6));
|
|
114
119
|
const isTar = (b) => b.length >= 512 &&
|
|
115
120
|
(ascii(b, 257, 262) === 'ustar' ||
|
|
@@ -131,14 +136,20 @@ function archivePath(name, span) {
|
|
|
131
136
|
throw bad("'..' segment");
|
|
132
137
|
return normalizeVirtual('/' + name, span, 'archive entry').path;
|
|
133
138
|
}
|
|
134
|
-
//
|
|
135
|
-
|
|
139
|
+
// ------------------------------------------------------------ gzip, zstd
|
|
140
|
+
/**
|
|
141
|
+
* Decompress a gzip or zstd stream within the limits (the same ratio and size caps for both). zstd is
|
|
142
|
+
* Node's libzstd (frames that need a window over 128 MiB are refused; rust/src/resources/archive.rs
|
|
143
|
+
* matches what it accepts).
|
|
144
|
+
*/
|
|
145
|
+
async function decompress(kind, bytes, origin, limits, span) {
|
|
136
146
|
const byRatio = Math.max(bytes.length * limits.maxRatio, RATIO_FLOOR);
|
|
137
147
|
// The inflated stream is tar: file data plus headers and padding for every entry.
|
|
138
148
|
const byTotal = limits.maxTotalBytes + (limits.maxEntries + 2) * TAR_OVERHEAD_PER_ENTRY;
|
|
139
149
|
try {
|
|
140
150
|
// Async so a large archive doesn't stall other imports' sockets and timers.
|
|
141
|
-
|
|
151
|
+
const options = { maxOutputLength: Math.min(byRatio, byTotal) };
|
|
152
|
+
return kind === 'gzip' ? await gunzipAsync(bytes, options) : await zstdDecompressAsync(bytes, options);
|
|
142
153
|
}
|
|
143
154
|
catch (e) {
|
|
144
155
|
throw inflateError(e, origin, byRatio <= byTotal, limits, span);
|
package/lib/src/serve-auth.d.ts
CHANGED
|
@@ -14,8 +14,9 @@ export declare function makeVerifier(password: string, salt?: Uint8Array, iterat
|
|
|
14
14
|
/** Whether `password` matches `verifier` (false for a malformed verifier). Constant time in the key comparison. */
|
|
15
15
|
export declare function verifyPassword(verifier: string, password: string): boolean;
|
|
16
16
|
/**
|
|
17
|
-
* An htpasswd file: `user:hash` lines (blank lines and `#` comments skipped).
|
|
18
|
-
*
|
|
17
|
+
* An htpasswd file: `user:hash` lines (blank lines and `#` comments skipped). `{SHA}` (htpasswd -s) and bcrypt
|
|
18
|
+
* (`$2y$`, `$2a$`, `$2b$`, cost 4 to 31; htpasswd -B) entries are accepted; a malformed bcrypt hash, `$apr1$`,
|
|
19
|
+
* crypt and plain-text entries are `E_USAGE` errors naming the user.
|
|
19
20
|
*/
|
|
20
21
|
export declare function parseHtpasswd(text: string, origin: string): AuthEntry[];
|
|
21
22
|
/** The `user` and `password` of an `Authorization: Basic …` value, or undefined. */
|
package/lib/src/serve-auth.js
CHANGED
|
@@ -4,7 +4,9 @@
|
|
|
4
4
|
// A credential is kept only as a verifier, never as the password:
|
|
5
5
|
// pbkdf2-sha256$<iterations>$<salt base64>$<32-byte key base64> (what --auth and SITEFILE_SERVE_AUTH become)
|
|
6
6
|
// {SHA}<base64 SHA-1 of the password> (an htpasswd -s entry, --auth-file)
|
|
7
|
+
// $2y$<cost>$<salt><hash> (also $2a$, $2b$) (an htpasswd -B bcrypt entry, --auth-file; #278)
|
|
7
8
|
import { createHash, pbkdf2Sync, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
9
|
+
import { isBcryptPrefix, parseBcrypt, verifyBcrypt } from './bcrypt.js';
|
|
8
10
|
import { SitefileError } from './errors.js';
|
|
9
11
|
/** PBKDF2 rounds of a verifier made here; checks are cached per server, so this is paid once per credential. */
|
|
10
12
|
export const AUTH_ITERATIONS = 20000;
|
|
@@ -30,6 +32,8 @@ function equal(a, b) {
|
|
|
30
32
|
}
|
|
31
33
|
/** Whether `password` matches `verifier` (false for a malformed verifier). Constant time in the key comparison. */
|
|
32
34
|
export function verifyPassword(verifier, password) {
|
|
35
|
+
if (isBcryptPrefix(verifier))
|
|
36
|
+
return verifyBcrypt(verifier, password);
|
|
33
37
|
const pw = Buffer.from(password, 'utf8');
|
|
34
38
|
if (verifier.startsWith('{SHA}')) {
|
|
35
39
|
const want = b64(verifier.slice(5));
|
|
@@ -46,8 +50,9 @@ export function verifyPassword(verifier, password) {
|
|
|
46
50
|
return equal(pbkdf2Sync(pw, salt, iterations, 32, 'sha256'), want);
|
|
47
51
|
}
|
|
48
52
|
/**
|
|
49
|
-
* An htpasswd file: `user:hash` lines (blank lines and `#` comments skipped).
|
|
50
|
-
*
|
|
53
|
+
* An htpasswd file: `user:hash` lines (blank lines and `#` comments skipped). `{SHA}` (htpasswd -s) and bcrypt
|
|
54
|
+
* (`$2y$`, `$2a$`, `$2b$`, cost 4 to 31; htpasswd -B) entries are accepted; a malformed bcrypt hash, `$apr1$`,
|
|
55
|
+
* crypt and plain-text entries are `E_USAGE` errors naming the user.
|
|
51
56
|
*/
|
|
52
57
|
export function parseHtpasswd(text, origin) {
|
|
53
58
|
const out = [];
|
|
@@ -60,10 +65,13 @@ export function parseHtpasswd(text, origin) {
|
|
|
60
65
|
throw new SitefileError('E_USAGE', `${origin}:${n + 1}: expected user:hash`);
|
|
61
66
|
const user = line.slice(0, i);
|
|
62
67
|
const hash = line.slice(i + 1);
|
|
63
|
-
if (
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
68
|
+
if (isBcryptPrefix(hash)) {
|
|
69
|
+
if (!parseBcrypt(hash))
|
|
70
|
+
throw new SitefileError('E_USAGE', `${origin}:${n + 1}: user '${user}': malformed bcrypt hash (expected $2y$, $2a$ or $2b$, a cost of 04 to 31 and 53 characters of salt and hash)`);
|
|
71
|
+
}
|
|
72
|
+
else if (!/^\{SHA\}[A-Za-z0-9+/]{27}=$/.test(hash)) {
|
|
73
|
+
throw new SitefileError('E_USAGE', `${origin}:${n + 1}: user '${user}': unsupported password hash (only {SHA} and bcrypt entries, htpasswd -s or -B)`);
|
|
74
|
+
}
|
|
67
75
|
out.push({ user, verifier: hash });
|
|
68
76
|
}
|
|
69
77
|
return out;
|
package/lib/src/server.d.ts
CHANGED
|
@@ -176,7 +176,14 @@ export interface LiveReloadOptions {
|
|
|
176
176
|
readonly navigateToChanged?: boolean;
|
|
177
177
|
/** `--reload`: `morph` (default) updates a page in place when only HTML changed; `full` always reloads. */
|
|
178
178
|
readonly reload?: 'full' | 'morph';
|
|
179
|
+
/**
|
|
180
|
+
* `--sync`: pages report where they are ({@link CLIENT_PATH}, listed at {@link CLIENTS_PATH}) and
|
|
181
|
+
* follow each other's navigation (`nav`), and scrolling too (`scroll`, `--sync=scroll`). Unset: off.
|
|
182
|
+
*/
|
|
183
|
+
readonly sync?: SyncMode;
|
|
179
184
|
}
|
|
185
|
+
/** What `--sync` mirrors between open pages: navigation, or navigation and scrolling. */
|
|
186
|
+
export type SyncMode = 'nav' | 'scroll';
|
|
180
187
|
/** The script served at {@link RELOAD_SCRIPT_PATH}: {@link RELOAD_CLIENT} called with `options` (keys in a fixed order). */
|
|
181
188
|
export declare function clientScript(options?: LiveReloadOptions): string;
|
|
182
189
|
/** Reserved for browser console messages (POST) while `serve --watch` runs. */
|
|
@@ -195,6 +202,55 @@ export declare const CONSOLE_WINDOW_MS = 10000;
|
|
|
195
202
|
export declare function consoleLines(body: string, all: boolean): string[] | undefined;
|
|
196
203
|
/** A console POST comes from a page of this server: `Origin` is `http(s)://<Host>`, and `Sec-Fetch-Site` (when sent) is same-origin. */
|
|
197
204
|
export declare function isSameOriginPost(headers: Readonly<Record<string, string | string[] | undefined>>): boolean;
|
|
205
|
+
/** Reserved for location reports (POST) from pages while `serve --watch --sync` runs. */
|
|
206
|
+
export declare const CLIENT_PATH = "/__sitefile/client";
|
|
207
|
+
/** Reserved for the list of connected pages (GET, loopback only, not from a browser) while `serve --watch --sync` runs. */
|
|
208
|
+
export declare const CLIENTS_PATH = "/__sitefile/clients";
|
|
209
|
+
/** Largest location report accepted (bytes). */
|
|
210
|
+
export declare const MAX_CLIENT_BODY = 4096;
|
|
211
|
+
/** At most this many reports are accepted from one page per {@link CLIENT_WINDOW_MS} (more get `429`). */
|
|
212
|
+
export declare const CLIENT_REPORT_LIMIT = 60;
|
|
213
|
+
export declare const CLIENT_WINDOW_MS = 10000;
|
|
214
|
+
/** At most this many pages are tracked (one that left is forgotten first to make room). */
|
|
215
|
+
export declare const MAX_CLIENTS = 64;
|
|
216
|
+
/** One location report from a page's client script (`--sync`). */
|
|
217
|
+
export interface ClientReport {
|
|
218
|
+
/** The tab's ID: 16 lowercase hex digits, kept in its sessionStorage. */
|
|
219
|
+
readonly id: string;
|
|
220
|
+
/** Its path and fragment (`/docs/#intro`): path-absolute, printable ASCII, at most 2048 characters. */
|
|
221
|
+
readonly url: string;
|
|
222
|
+
/** Its `document.title`, cleaned ({@link cleanText}, at most 200 code points). */
|
|
223
|
+
readonly title: string;
|
|
224
|
+
/** The person navigated (the others follow). */
|
|
225
|
+
readonly nav: boolean;
|
|
226
|
+
/** `--sync=scroll`: how far across and down it is scrolled, in 1/10000ths of the scrollable size. */
|
|
227
|
+
readonly scroll?: readonly [number, number];
|
|
228
|
+
}
|
|
229
|
+
/** A location report body (JSON `{id, url, title?, nav?, scroll?}`), or undefined when it is not one. */
|
|
230
|
+
export declare function parseClientReport(body: string): ClientReport | undefined;
|
|
231
|
+
/** The tab ID a page's event stream names (`/__sitefile/reload?client=<id>`, the first `client`), else undefined. */
|
|
232
|
+
export declare function streamClientId(search: string): string | undefined;
|
|
233
|
+
/**
|
|
234
|
+
* Whether a request for {@link CLIENTS_PATH} comes from the operator (Sitefile Desktop, curl), not a
|
|
235
|
+
* page: a loopback client that sends no `Origin` and no `Sec-Fetch-*` header.
|
|
236
|
+
*/
|
|
237
|
+
export declare function isOperatorRequest(remote: string, headers: Readonly<Record<string, string | string[] | undefined>>): boolean;
|
|
238
|
+
/** One `--sync` log line: a page connected (its first report) or went to another URL. */
|
|
239
|
+
export interface ClientLogEntry {
|
|
240
|
+
readonly ts: string;
|
|
241
|
+
readonly event: 'connect' | 'navigate';
|
|
242
|
+
readonly id: string;
|
|
243
|
+
readonly url: string;
|
|
244
|
+
readonly title: string;
|
|
245
|
+
readonly remote: string;
|
|
246
|
+
readonly device: string;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* A `--sync` log line. Text: `client <event> <id> <url> <remote> <device>`. JSON (a stable contract,
|
|
250
|
+
* docs/CLI.md): `{"type":"client","ts","event","id","url","title","remote","device"}`, `title` only
|
|
251
|
+
* when not empty.
|
|
252
|
+
*/
|
|
253
|
+
export declare function clientLogLine(format: 'text' | 'json', e: ClientLogEntry): string;
|
|
198
254
|
/** The event that tells every page to reload. */
|
|
199
255
|
export declare const RELOAD_EVENT = "{\"type\":\"reload\"}";
|
|
200
256
|
/** Sent when a rebuild starts (pages show a Rebuilding badge). */
|
|
@@ -219,18 +275,53 @@ export declare function pageUrlFor(file: string): string;
|
|
|
219
275
|
export declare function reloadEventFor(prev: Tree, next: Tree, cssInject: boolean, navigate?: boolean): string | undefined;
|
|
220
276
|
/** Open live-reload streams; {@link LiveReload.send} gives every page an event ({@link LiveReload.reload}: reload). */
|
|
221
277
|
export declare class LiveReload {
|
|
278
|
+
/** Open streams, with the tab ID each names (`--sync`). */
|
|
222
279
|
private readonly clients;
|
|
280
|
+
/** `--sync`: the pages that reported, in the order they first connected. */
|
|
281
|
+
private readonly known;
|
|
282
|
+
/** `--sync`, else undefined. */
|
|
283
|
+
readonly sync: SyncMode | undefined;
|
|
223
284
|
/** The client script for this session ({@link clientScript}). */
|
|
224
285
|
readonly script: string;
|
|
225
286
|
/** Time between heartbeat comments on an open stream (15 s; tests pass less). */
|
|
226
287
|
private readonly heartbeatMs;
|
|
288
|
+
/**
|
|
289
|
+
* This server process's instance ID (16 hex digits, random). Every stream starts with it as the
|
|
290
|
+
* event ID, so a page that reconnects after a restart (`server restart`, a new `serve --watch`)
|
|
291
|
+
* sends the old one in `Last-Event-ID` and is told to reload.
|
|
292
|
+
*/
|
|
293
|
+
readonly instance: string;
|
|
227
294
|
constructor(options?: LiveReloadOptions, heartbeatMs?: number);
|
|
228
295
|
/**
|
|
229
296
|
* Hold `res` open as a text/event-stream until the client goes away. The headers keep proxies
|
|
230
297
|
* and tunnels from buffering or compressing it, and a comment every 15 s keeps idle
|
|
231
298
|
* connections from being cut (and finds clients that went away).
|
|
232
299
|
*/
|
|
233
|
-
attach(res: http.ServerResponse, headers: Record<string, string
|
|
300
|
+
attach(res: http.ServerResponse, headers: Record<string, string>, lastEventId?: string, client?: {
|
|
301
|
+
readonly id: string;
|
|
302
|
+
readonly remote: string;
|
|
303
|
+
readonly device: string;
|
|
304
|
+
}): void;
|
|
305
|
+
/** `--sync`: the entry for a page whose stream opened (undefined when {@link MAX_CLIENTS} are connected). */
|
|
306
|
+
private track;
|
|
307
|
+
/**
|
|
308
|
+
* `--sync`: take a page's location report. The status to answer: `404` when its stream is not
|
|
309
|
+
* open, `429` over {@link CLIENT_REPORT_LIMIT}, else `204`; then the log line it gives (its first
|
|
310
|
+
* report, or a new URL) and the events sent to the other pages (`navigate`, and `scroll` with
|
|
311
|
+
* `--sync=scroll`).
|
|
312
|
+
*/
|
|
313
|
+
report(r: ClientReport, now: number, format: 'text' | 'json'): {
|
|
314
|
+
status: number;
|
|
315
|
+
log?: string;
|
|
316
|
+
};
|
|
317
|
+
/**
|
|
318
|
+
* `--sync`: the connected pages as {@link CLIENTS_PATH} answers them:
|
|
319
|
+
* `{"clients":[{"id","url","title","remote","device","since","lastSeen"}]}` (one line), by
|
|
320
|
+
* `since`, then `id`. A page that has not reported yet has an empty `url`.
|
|
321
|
+
*/
|
|
322
|
+
clientsJson(): string;
|
|
323
|
+
/** Send `event` to every open page except those of tab `id`. */
|
|
324
|
+
private sendExcept;
|
|
234
325
|
readonly console: boolean;
|
|
235
326
|
private consoleWindow;
|
|
236
327
|
private consoleCount;
|