@johnhenry/sitefile 0.0.3 → 0.0.5

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.
@@ -4,8 +4,9 @@
4
4
  import { readFile } from 'node:fs/promises';
5
5
  import { SitefileError } from '../errors.js';
6
6
  import { BasicAuth, parseHtpasswd } from '../serve-auth.js';
7
- import { closeServer, createSiteServer, formatUrl, jsonLogLine, listen, parseCidr, parseThrottle, startedLogLine, stoppedLogLine, routingFor } from '../server.js';
7
+ import { BUILDING_EVENT, closeServer, createSiteServer, errorEvent, formatUrl, jsonLogLine, listen, LiveReload, OK_EVENT, parseCidr, parseThrottle, reloadEventFor, startedLogLine, stoppedLogLine, routingFor } from '../server.js';
8
8
  import { loadServedTree, servedLastModified, ServerRegistry, loadServedSite, checkSiteFiles } from '../servers.js';
9
+ import { isIgnoredChange, RebuildScheduler, resolveReal, watchPaths } from '../watch.js';
9
10
  let json = false; // `--log-format json`: every line is a JSON object
10
11
  const stamp = (m) => {
11
12
  const ts = new Date().toISOString();
@@ -27,9 +28,12 @@ async function main() {
27
28
  const { tree, content } = await loadServedSite(reg.store, state.source, { keepOsMetadata: !!state.keepOsMetadata, warn: (m) => stamp(`warning: ${m}`) });
28
29
  if (routingFor(state)?.siteFiles !== false)
29
30
  checkSiteFiles(tree, !!state.strictSiteFiles, (m) => stamp(`warning: ${m}`), content);
30
- const modified = await servedLastModified(reg.store, state.source);
31
+ let modified = await servedLastModified(reg.store, state.source);
32
+ let current = tree;
33
+ // `-d --watch`: the directory is re-read on change and open pages reload (or swap stylesheets).
34
+ const live = state.watch && state.source.kind === 'dir' ? new LiveReload(state.sync === 'nav' || state.sync === 'scroll' ? { sync: state.sync } : {}) : undefined;
31
35
  const authEntries = [...(state.auth ?? []), ...(state.authFile !== undefined ? parseHtpasswd(await readFile(state.authFile, 'utf8'), state.authFile) : [])];
32
- const server = createSiteServer(tree, { spa: state.spa, allowedHosts: state.allowedHosts ?? [], cors: !!state.cors, ...(state.isolate ? { isolate: state.isolate } : {}), ...(state.cache ? { cache: state.cache } : {}), ...(json ? { logFormat: 'json' } : {}), logIp: !!state.logIp, quiet: !!state.quiet, ...(authEntries.length > 0 || state.authFile !== undefined ? { auth: new BasicAuth(authEntries) } : {}), ...(state.maxConnectionsPerIp ? { maxConnectionsPerIp: state.maxConnectionsPerIp } : {}), ...(state.hideBase ? { hideBase: true } : {}), ...(ipRules ? { ipRules } : {}), ...(loopback ? {} : { noindex: true }), clientInfo: true, compress: !!state.compress, ...(state.mime ? { mime: new Map(Object.entries(state.mime)) } : {}), ...(state.throttle !== undefined && parseThrottle(state.throttle) ? { throttle: parseThrottle(state.throttle) } : {}), ...(state.tlsCert !== undefined && state.tlsKey !== undefined ? { tls: { cert: await readFile(state.tlsCert), key: await readFile(state.tlsKey) } } : {}), serverId: id, lastModified: () => modified, log: stamp, ...(content ? { content } : {}), ...(state.country !== undefined ? { country: state.country } : {}), ...(state.spaExclude ? { spaExclude: state.spaExclude } : {}), ...(state.spaFallback !== undefined ? { spaFallback: state.spaFallback } : {}), ...(state.base !== undefined ? { base: state.base } : {}), ...(state.rewriteBase !== undefined ? { rewriteBase: state.rewriteBase } : {}), ...(routingFor(state) ? { profile: routingFor(state) } : {}) });
36
+ const server = createSiteServer(() => current, { ...(live ? { liveReload: live } : {}), spa: state.spa, allowedHosts: state.allowedHosts ?? [], cors: !!state.cors, ...(state.isolate ? { isolate: state.isolate } : {}), ...(state.cache ? { cache: state.cache } : {}), ...(json ? { logFormat: 'json' } : {}), logIp: !!state.logIp, quiet: !!state.quiet, ...(authEntries.length > 0 || state.authFile !== undefined ? { auth: new BasicAuth(authEntries) } : {}), ...(state.maxConnectionsPerIp ? { maxConnectionsPerIp: state.maxConnectionsPerIp } : {}), ...(state.hideBase ? { hideBase: true } : {}), ...(ipRules ? { ipRules } : {}), ...(loopback ? {} : { noindex: true }), clientInfo: true, compress: !!state.compress, ...(state.mime ? { mime: new Map(Object.entries(state.mime)) } : {}), ...(state.throttle !== undefined && parseThrottle(state.throttle) ? { throttle: parseThrottle(state.throttle) } : {}), ...(state.tlsCert !== undefined && state.tlsKey !== undefined ? { tls: { cert: await readFile(state.tlsCert), key: await readFile(state.tlsKey) } } : {}), serverId: id, lastModified: () => modified, log: stamp, ...(content ? { content } : {}), ...(state.country !== undefined ? { country: state.country } : {}), ...(state.spaExclude ? { spaExclude: state.spaExclude } : {}), ...(state.spaFallback !== undefined ? { spaFallback: state.spaFallback } : {}), ...(state.base !== undefined ? { base: state.base } : {}), ...(state.rewriteBase !== undefined ? { rewriteBase: state.rewriteBase } : {}), ...(routingFor(state) ? { profile: routingFor(state) } : {}) });
33
37
  const addr = await listen(server, state.bind.host, state.bind.port);
34
38
  await reg.update(id, { pid: process.pid, host: addr.host, port: addr.port, ready: true, error: undefined });
35
39
  const root = formatUrl(addr.host, addr.port, state.tlsCert !== undefined ? 'https' : 'http');
@@ -38,7 +42,14 @@ async function main() {
38
42
  stamp(startedLogLine(new Date().toISOString(), state.image, tree.size, url));
39
43
  else
40
44
  stamp(`serving ${state.image} (${tree.size} files) at ${url}`);
45
+ const unwatch = live
46
+ ? await watchDirectory(reg, state, live, stamp, (next, lastModified) => {
47
+ current = next;
48
+ modified = lastModified;
49
+ }, () => current)
50
+ : () => undefined;
41
51
  const stop = (signal) => () => {
52
+ unwatch();
42
53
  if (json)
43
54
  stamp(stoppedLogLine(new Date().toISOString(), signal));
44
55
  else
@@ -51,6 +62,7 @@ async function main() {
51
62
  };
52
63
  if (left !== undefined) {
53
64
  setTimeout(() => {
65
+ unwatch();
54
66
  if (json)
55
67
  stamp(stoppedLogLine(new Date().toISOString(), 'expired'));
56
68
  else
@@ -73,6 +85,67 @@ async function main() {
73
85
  process.exit(1);
74
86
  }
75
87
  }
88
+ /**
89
+ * `-d --watch`: watch the served directory (file system events, or polling every `state.pollMs`) and,
90
+ * once changes settle, read it again: a good read is served and open pages are told what changed; a
91
+ * failed one is logged, shown in open pages, and the last good copy stays. Returns a function that stops watching.
92
+ */
93
+ async function watchDirectory(reg, state, live, stamp, swap, current) {
94
+ if (state.source.kind !== 'dir')
95
+ return () => undefined;
96
+ const source = state.source;
97
+ const root = source.path;
98
+ const ignored = [await resolveReal(reg.store.home)];
99
+ const relevant = (p) => !isIgnoredChange(p, [root], ignored);
100
+ const warn = (m) => stamp(`warning: ${m}`);
101
+ const siteFiles = routingFor(state)?.siteFiles !== false;
102
+ /** The site-file warnings last logged: a re-read repeats them only when they change. */
103
+ const warningsOf = (t) => {
104
+ const shown = [];
105
+ if (siteFiles)
106
+ checkSiteFiles(t, false, (m) => shown.push(m));
107
+ return shown.join('\n');
108
+ };
109
+ let lastWarnings = warningsOf(current());
110
+ const scheduler = new RebuildScheduler(async () => {
111
+ stamp('Change detected, re-reading');
112
+ live.send(BUILDING_EVENT);
113
+ try {
114
+ const next = await loadServedTree(reg.store, source, { keepOsMetadata: !!state.keepOsMetadata, warn });
115
+ stamp(`Read ${next.size} file${next.size === 1 ? '' : 's'} (${next.digest()})`);
116
+ const warnings = warningsOf(next);
117
+ if (warnings !== lastWarnings && warnings !== '')
118
+ for (const m of warnings.split('\n'))
119
+ warn(m);
120
+ lastWarnings = warnings;
121
+ if (siteFiles)
122
+ checkSiteFiles(next, !!state.strictSiteFiles, () => undefined);
123
+ const event = reloadEventFor(current(), next, true, false) ?? OK_EVENT;
124
+ swap(next, await servedLastModified(reg.store, source));
125
+ live.send(event);
126
+ }
127
+ catch (e) {
128
+ if (!(e instanceof SitefileError))
129
+ throw e;
130
+ stamp(`error[${e.code}]: ${e.message}`);
131
+ live.send(errorEvent(e));
132
+ stamp('Read failed; serving the last good copy');
133
+ }
134
+ });
135
+ const close = watchPaths({
136
+ dirs: [root],
137
+ files: [],
138
+ onChange: (p) => {
139
+ if (relevant(p))
140
+ scheduler.notify(p);
141
+ },
142
+ ...(state.pollMs !== undefined ? { pollMs: state.pollMs, ignore: (p) => !relevant(p) } : {}),
143
+ });
144
+ return () => {
145
+ close();
146
+ scheduler.close();
147
+ };
148
+ }
76
149
  main().catch((e) => {
77
150
  process.stderr.write(`${e?.stack ?? String(e)}\n`);
78
151
  process.exit(1);
@@ -1,4 +1,4 @@
1
- import { type CachePreview, type HostProfileName, type HtmlHandling } from '../server.js';
1
+ import { type CachePreview, type HostProfileName, type HtmlHandling, type SyncMode } from '../server.js';
2
2
  import { ServerRegistry, type ServerState } from '../servers.js';
3
3
  import { type AuthEntry } from '../serve-auth.js';
4
4
  import type { Plan } from '../planner.js';
@@ -108,6 +108,12 @@ export interface DetachedServe {
108
108
  readonly country?: string | undefined;
109
109
  /** `--strict-site-files`. */
110
110
  readonly strictSiteFiles?: boolean | undefined;
111
+ /** `-d --watch`: a directory source re-read on change, with live reload. */
112
+ readonly watch?: boolean | undefined;
113
+ /** `--poll`, `--poll-interval` with `-d --watch`. */
114
+ readonly pollMs?: number | undefined;
115
+ /** `--sync` with `-d --watch`. */
116
+ readonly sync?: SyncMode | undefined;
111
117
  /** The servers file it belongs to (`sitefile up`). */
112
118
  readonly project?: string | undefined;
113
119
  }
@@ -189,8 +189,8 @@ async function startDetached(reg, state) {
189
189
  const run = {
190
190
  name: 'serve',
191
191
  summary: 'serve an image, directory or archive file over HTTP',
192
- usage: 'serve [--name n] [-p [host:]port] [-d] [--spa] <ref|id|./dir|file> | serve --watch [options] [context]',
193
- description: 'Serve an image from the local store, a directory (paths starting with ./, ../ or /), or an archive file over HTTP:\nzip, tar, tar.gz, wbn, or an OCI archive as build -o x.oci.tar and save write it (the format is read from the\nbytes). A directory or archive is a snapshot read at start. GET and HEAD only; no directory listings.\nBinds 127.0.0.1 on a free port unless -p is given;\n0.0.0.0 is bound only when you pass it explicitly. Foreground by default (Ctrl-C stops it); -d detaches and\nrecords the server for servers, server stop, rm, logs and restart.\n\nWith --watch the argument is a build context (default .): its Sitefile is built in memory and served, rebuilt\nwhen the context, the Sitefile or a --build-arg-file changes, and open pages reload after each good rebuild\n(page loads get a small script, /__sitefile/reload.js). A failed rebuild keeps serving the last\ngood build. Nothing is written to the context except Sitefile.lock. A directory with no Sitefile (and no -f,\n--target or --build-arg*) is served as it is and re-read on change. When only stylesheets changed, pages\nswap them in place.',
192
+ usage: 'serve [--name n] [-p [host:]port] [-d] [--spa] <ref|id|./dir|file> | serve [-d] --watch [options] [context]',
193
+ description: 'Serve an image from the local store, a directory (paths starting with ./, ../ or /), or an archive file over HTTP:\nzip, tar, tar.gz, wbn, or an OCI archive as build -o x.oci.tar and save write it (the format is read from the\nbytes). A directory or archive is a snapshot read at start. GET and HEAD only; no directory listings.\nBinds 127.0.0.1 on a free port unless -p is given;\n0.0.0.0 is bound only when you pass it explicitly. Foreground by default (Ctrl-C stops it); -d detaches and\nrecords the server for servers, server stop, rm, logs and restart.\n\nWith --watch the argument is a build context (default .): its Sitefile is built in memory and served, rebuilt\nwhen the context, the Sitefile or a --build-arg-file changes, and open pages reload after each good rebuild\n(page loads get a small script, /__sitefile/reload.js). A failed rebuild keeps serving the last\ngood build. Nothing is written to the context except Sitefile.lock. A directory with no Sitefile (and no -f,\n--target or --build-arg*) is served as it is and re-read on change. When only stylesheets changed, pages\nswap them in place. With -d, --watch takes such a directory only: the detached server re-reads it on change,\nopen pages reload, and pages left open across server restart reload once it is back.',
194
194
  flags: [
195
195
  '--name <n> name for the server (-d only; default site-<6 hex>)',
196
196
  '-p, --publish <[host:]port> address to bind (default 127.0.0.1, a free port)',
@@ -206,7 +206,7 @@ const run = {
206
206
  '--log-ip add the client address to access-log lines',
207
207
  '--quiet no access-log lines',
208
208
  '--auth <user:password> require HTTP basic authentication (repeatable; or SITEFILE_SERVE_AUTH); only a hash is stored',
209
- '--auth-file <htpasswd> users from an htpasswd file ({SHA} entries, htpasswd -s)',
209
+ '--auth-file <htpasswd> users from an htpasswd file ({SHA} or bcrypt: htpasswd -s or -B)',
210
210
  '--max-connections-per-ip <n> open connections one non-loopback client may hold (default 0: no limit; 503 over it)',
211
211
  '--random-route serve the site only under a random secret path (printed in the URL)',
212
212
  '--allow-ip <cidr> only answer clients in this block (repeatable; loopback is always allowed)',
@@ -239,7 +239,7 @@ const run = {
239
239
  '--keep-os-metadata serve __MACOSX, ._*, Thumbs.db and desktop.ini of a directory or archive (default: skipped)',
240
240
  '--open[=<path>] open the site (at <path>) in the browser once it is served ($BROWSER, else the system default)',
241
241
  '--qr print a QR code of the network URL (with -p 0.0.0.0:...), else of the local URL',
242
- '--watch build the context, serve it, rebuild on change and live-reload pages (foreground only)',
242
+ '--watch build the context, serve it, rebuild on change and live-reload pages (-d: a plain directory only)',
243
243
  '-f, --file <path> Sitefile path (--watch; default <context>/Sitefile)',
244
244
  '--target <stage> build up to this stage and serve its whole tree (--watch)',
245
245
  '--build-arg <NAME=value> set an ARG (--watch; repeatable)',
@@ -247,13 +247,14 @@ const run = {
247
247
  '--no-cache do not use the TRANSFORM result cache (--watch)',
248
248
  '--no-lockfile do not read or write Sitefile.lock (--watch)',
249
249
  '--keep-service-workers do not unregister service workers and clear caches before a reload (--watch)',
250
- '--poll poll for changes (every 1000 ms) instead of file system events (--watch)',
251
- '--poll-interval <ms> poll every <ms> milliseconds (--watch; implies --poll)',
250
+ '--poll poll for changes (every 1000 ms) instead of file system events (--watch, -d --watch)',
251
+ '--poll-interval <ms> poll every <ms> milliseconds (--watch, -d --watch; implies --poll)',
252
252
  '--no-css-inject reload the page when only stylesheets changed, instead of swapping them (--watch)',
253
253
  '--console also forward console.log/info from pages to the log, not only errors and warnings (--watch)',
254
254
  '--no-overlay no Rebuilding badge or build-error overlay in pages (--watch)',
255
255
  '--navigate-to-changed after a rebuild that changed one page, open pages go to it (--watch)',
256
256
  '--reload <full|morph> morph (default): update a page in place when only HTML changed; full: always reload (--watch)',
257
+ '--sync[=scroll] open pages report where they are and follow each other\'s navigation (=scroll: and scrolling) (--watch, -d --watch)',
257
258
  ],
258
259
  options: {
259
260
  name: { type: 'string' },
@@ -317,14 +318,24 @@ const run = {
317
318
  'no-overlay': { type: 'boolean' },
318
319
  'navigate-to-changed': { type: 'boolean' },
319
320
  reload: { type: 'string' },
321
+ sync: { type: 'string' },
320
322
  },
321
323
  async run(v, pos) {
322
- if (v.watch)
324
+ if (v.watch && !v.detach)
323
325
  return serveWatch(v, pos);
324
- for (const f of WATCH_ONLY)
325
- if (v[f] !== undefined)
326
- usage(`--${f} needs --watch`);
327
- requireArgs(pos, 1, 1, 'an image reference, ./directory or archive file');
326
+ // `-d --watch`: a plain directory, re-read on change by the detached worker (with live reload).
327
+ const watchDetached = !!v.watch;
328
+ for (const f of WATCH_ONLY) {
329
+ if (v[f] === undefined || (watchDetached && DETACHED_WATCH.includes(f)))
330
+ continue;
331
+ usage(watchDetached ? `--${f} is for serve --watch in the foreground, not -d` : `--${f} needs --watch`);
332
+ }
333
+ if (watchDetached)
334
+ requireArgs(pos, 0, 1, 'a directory');
335
+ else
336
+ requireArgs(pos, 1, 1, 'an image reference, ./directory or archive file');
337
+ const pollMs = watchDetached ? pollOption(!!v.poll, str(v['poll-interval'])) : undefined;
338
+ const sync = watchDetached ? syncOf(v) : undefined;
328
339
  const bind = parsePublish(str(v.publish));
329
340
  const allowedHosts = allowedHostsOf(v);
330
341
  const isolate = isolateOf(v);
@@ -347,7 +358,7 @@ const run = {
347
358
  if (name !== undefined && !v.detach)
348
359
  usage('--name needs -d (only detached servers are tracked)');
349
360
  const store = await Store.open();
350
- const { label, source } = await resolveSource(store, pos[0]);
361
+ const { label, source } = watchDetached ? await watchedDirectory(pos[0] ?? '.') : await resolveSource(store, pos[0]);
351
362
  if (isWildcard(bind.host))
352
363
  process.stderr.write(`warning: binding ${bind.host}: the site will be reachable from other machines\n`);
353
364
  const keepOsMetadata = !!v['keep-os-metadata'];
@@ -393,7 +404,7 @@ const run = {
393
404
  for (const f of PROXY_FLAGS)
394
405
  if (v[f] !== undefined)
395
406
  usage(`--${f} is for a server in the foreground (or --watch), not -d`);
396
- const up = await serveDetached(reg, { label, source, name, bind, keepOsMetadata, allowedHosts, cors: !!v.cors, ...(isolate ? { isolate } : {}), ...(cache ? { cache } : {}), ...logging, ...auth.record, ...perIp, ...sharing.record, ...tls.record, ...(v.compress ? { compress: true } : {}), ...(throttle ? { throttle: throttle.spec } : {}), ...(mime ? { mime: Object.fromEntries(mime) } : {}), country, strictSiteFiles, ...spa, base, rewriteBase, ...profiles }, warn);
407
+ const up = await serveDetached(reg, { label, source, name, bind, keepOsMetadata, allowedHosts, cors: !!v.cors, ...(isolate ? { isolate } : {}), ...(cache ? { cache } : {}), ...logging, ...auth.record, ...perIp, ...sharing.record, ...tls.record, ...(v.compress ? { compress: true } : {}), ...(throttle ? { throttle: throttle.spec } : {}), ...(mime ? { mime: Object.fromEntries(mime) } : {}), country, strictSiteFiles, ...spa, base, rewriteBase, ...profiles, ...(watchDetached ? { watch: true, pollMs, sync } : {}) }, warn);
397
408
  process.stdout.write(`Started ${up.name} (${up.id}) serving ${label} at ${siteUrl(up.host, up.port, up.base, up.tlsCert ? 'https' : 'http')}\n${networkLines(up.host, up.port, up.base, up.tlsCert ? 'https' : 'http')}${throttleLine(up.throttle)}`);
398
409
  return 0;
399
410
  },
@@ -446,6 +457,9 @@ export async function serveDetached(reg, d, warn) {
446
457
  ...(d.mime !== undefined ? { mime: d.mime } : {}),
447
458
  ...(d.country !== undefined ? { country: d.country } : {}),
448
459
  ...(d.strictSiteFiles ? { strictSiteFiles: true } : {}),
460
+ ...(d.watch ? { watch: true } : {}),
461
+ ...(d.watch && d.pollMs !== undefined ? { pollMs: d.pollMs } : {}),
462
+ ...(d.watch && d.sync !== undefined ? { sync: d.sync } : {}),
449
463
  bind: d.bind,
450
464
  host: d.bind.host,
451
465
  port: d.bind.port,
@@ -513,8 +527,34 @@ async function terminal(v, addr, base, scheme, warn, restart) {
513
527
  process.stdout.write(KEYS_HINT);
514
528
  return { promise, stop: stop ?? (() => undefined) };
515
529
  }
530
+ /** The --watch flags `serve -d --watch` takes (it watches a plain directory; the rest are for builds or the page script). */
531
+ const DETACHED_WATCH = ['poll', 'poll-interval', 'sync'];
532
+ /**
533
+ * `serve -d --watch [dir]`: the directory (default .) as a source, absolute and real. A Sitefile project
534
+ * is refused: building on change happens in the foreground (`serve --watch`).
535
+ */
536
+ async function watchedDirectory(arg) {
537
+ const dir = path.resolve(arg);
538
+ const st = await fs.stat(dir).catch(() => undefined);
539
+ if (!st?.isDirectory())
540
+ throw new SitefileError('E_NOT_FOUND', `'${arg}' is not a directory`);
541
+ if (await isFile(path.join(dir, 'Sitefile')))
542
+ usage(`-d --watch serves a plain directory, and ${arg} has a Sitefile: build it with serve --watch in the foreground`);
543
+ return { label: dir, source: { kind: 'dir', path: await fs.realpath(dir) } };
544
+ }
516
545
  /** serve flags that only mean something with --watch. */
517
- const WATCH_ONLY = ['file', 'target', 'build-arg', 'build-arg-file', 'no-cache', 'no-lockfile', 'keep-service-workers', 'poll', 'poll-interval', 'no-css-inject', 'console', 'no-overlay', 'navigate-to-changed', 'reload', 'no-rewrite-base'];
546
+ const WATCH_ONLY = ['file', 'target', 'build-arg', 'build-arg-file', 'no-cache', 'no-lockfile', 'keep-service-workers', 'poll', 'poll-interval', 'no-css-inject', 'console', 'no-overlay', 'navigate-to-changed', 'reload', 'no-rewrite-base', 'sync'];
547
+ /** `--sync` (a bare `--sync` arrives as `--sync=`): `nav`, or `scroll` for `--sync=scroll`; undefined without it. */
548
+ function syncOf(v) {
549
+ const s = str(v.sync);
550
+ if (s === undefined)
551
+ return undefined;
552
+ if (s === '')
553
+ return 'nav';
554
+ if (s === 'scroll')
555
+ return 'scroll';
556
+ return usage(`--sync takes no value or =scroll, got '${s}'`);
557
+ }
518
558
  /**
519
559
  * `serve --watch [context]`: build in memory, serve, rebuild on change, live reload. A directory
520
560
  * without a `Sitefile`, given none of -f, --target, --build-arg and --build-arg-file, is served
@@ -738,8 +778,6 @@ function logWriter(logging) {
738
778
  }
739
779
  async function serveWatch(v, pos) {
740
780
  requireArgs(pos, 0, 1, 'a build context directory');
741
- if (v.detach)
742
- usage('--watch cannot be combined with -d');
743
781
  if (v.name !== undefined)
744
782
  usage('--name needs -d (only detached servers are tracked)');
745
783
  const bind = parsePublish(str(v.publish));
@@ -766,6 +804,7 @@ async function serveWatch(v, pos) {
766
804
  const cssInject = !v['no-css-inject'];
767
805
  const navigate = !!v['navigate-to-changed'];
768
806
  const reloadMode = str(v.reload) ?? 'morph';
807
+ const sync = syncOf(v);
769
808
  const spa = spaOptions(v);
770
809
  const baseFlag = sharing.randomBase ?? parseBase(str(v.base));
771
810
  /** `--base`, else the path of the last good build's EXPORT BASE URL. */
@@ -801,7 +840,7 @@ async function serveWatch(v, pos) {
801
840
  let builtAt; // Last-Modified: the time of the build being served
802
841
  let started = false;
803
842
  const memo = watchMemo();
804
- const live = new LiveReload({ resetServiceWorkers: !v['keep-service-workers'], cssInject, console: !!v.console, overlay: !v['no-overlay'], navigateToChanged: navigate, reload: reloadMode });
843
+ const live = new LiveReload({ resetServiceWorkers: !v['keep-service-workers'], cssInject, console: !!v.console, overlay: !v['no-overlay'], navigateToChanged: navigate, reload: reloadMode, ...(sync ? { sync } : {}) });
805
844
  /** Serve `next` and tell open pages what changed. */
806
845
  const swap = (next) => {
807
846
  const event = started ? (reloadEventFor(current, next, cssInject, navigate) ?? OK_EVENT) : undefined;
@@ -44,12 +44,13 @@ import { groupBy, paginate } from './pages.js';
44
44
  import { parseYaml } from './yaml.js';
45
45
  import { brokenLinks, reportBrokenLinks } from './checklinks.js';
46
46
  import { canonical } from './canonical.js';
47
+ import { alternates, isLanguageTag } from './hreflang.js';
47
48
  import { composeRenames, fingerprint } from './fingerprint.js';
48
49
  import { exportForHost } from './export-for.js';
49
50
  import { portabilityProblems } from './portable.js';
50
51
  import { precache } from './precache.js';
51
52
  import { precompress } from './precompress.js';
52
- import { atomXml, cacheHeaderRules, headersFile, pageUrl, parseFeedDate, redirectsFile, sitemapFiles } from './site.js';
53
+ import { atomXml, cacheHeaderRules, headersFile, pageUrl, parseFeedDate, redirectsFile, sitemapFiles, sitemapPages, SITEMAP_LIMITS } from './site.js';
53
54
  import { cspPages } from './csp.js';
54
55
  /** Read, parse and validate a Sitefile. */
55
56
  export async function loadProgram(options) {
@@ -1352,8 +1353,11 @@ async function executeOp(op, tree, prevKey, env) {
1352
1353
  }
1353
1354
  const opId = memoKey('op', env.envKey, valueKey(op));
1354
1355
  if (op.kind === 'SITEMAP' || op.kind === 'FINGERPRINT' || op.kind === 'CANONICAL' || op.kind === 'PRECOMPRESS' || op.kind === 'PRECACHE' || op.kind === 'CHECKLINKS') {
1355
- // Reads the whole tree: only the chain key can say it is unchanged.
1356
- const key = memoKey('chain', prevKey, opId);
1356
+ // Reads the whole tree: only the chain key can say it is unchanged. With LANGUAGES, also the documents' lists.
1357
+ const langs = (op.kind === 'CANONICAL' || op.kind === 'SITEMAP') && op.languages ? op.languages : undefined;
1358
+ const key = langs
1359
+ ? memoKey('chain', prevKey, opId, namesKey(env, operandNames(langs.sources.map((src) => src.dest), new Set(langs.sources.map((src) => src.list)))))
1360
+ : memoKey('chain', prevKey, opId);
1357
1361
  if (op.kind === 'CHECKLINKS') {
1358
1362
  // The tree is unchanged; a hit skips the check (and its requests) and prints its warnings again.
1359
1363
  const hit = memo.get(key);
@@ -1437,7 +1441,37 @@ function fingerprintOp(op, tree, env) {
1437
1441
  return fingerprint(tree, op, `${env.label}:${op.span.line} FINGERPRINT`, env.warn);
1438
1442
  }
1439
1443
  function canonicalOp(op, tree, env) {
1440
- return canonical(tree, op, `${env.label}:${op.span.line} CANONICAL`, env.warn);
1444
+ return canonical(tree, op, `${env.label}:${op.span.line} CANONICAL`, env.warn, op.languages ? languagesOf(op.languages, 'CANONICAL', op.span, env) : undefined);
1445
+ }
1446
+ /**
1447
+ * LANGUAGES with the translations of the documents of the stage's earlier `RENDER … FOR` lines: an element with
1448
+ * a `translationKey` (text or a number) and a `lang` (text) gives the page its destination names. A `lang` that is
1449
+ * not a language code is `E_VALIDATION`.
1450
+ */
1451
+ function languagesOf(spec, what, span, env) {
1452
+ const docs = new Map();
1453
+ for (const src of spec.sources) {
1454
+ const items = valueOf(src.list, [], span, false, env);
1455
+ if (!Array.isArray(items))
1456
+ continue;
1457
+ items.forEach((item, i) => {
1458
+ if (item === null || typeof item !== 'object' || Array.isArray(item))
1459
+ return;
1460
+ const doc = item;
1461
+ const key = doc['translationKey'];
1462
+ const lang = doc['lang'];
1463
+ if ((typeof key !== 'string' && typeof key !== 'number') || typeof lang !== 'string')
1464
+ return;
1465
+ if (!isLanguageTag(lang)) {
1466
+ const name = typeof doc['path'] === 'string' ? doc['path'] : `#${i + 1}`;
1467
+ throw new SitefileError('E_VALIDATION', `${what}: document '${name}' of '${src.list}' has lang '${lang}', which is not a language code (a BCP 47 tag such as en, fr or pt-BR)`, span);
1468
+ }
1469
+ const target = normalizeVirtual(interpolate(src.dest, { ...env, loop: { name: src.as, value: item } }), src.dest.span, `RENDER destination for ${src.as}`);
1470
+ if (!target.trailingSlash)
1471
+ docs.set(target.path, { lang, key: String(key) });
1472
+ });
1473
+ }
1474
+ return { codes: spec.codes, ...(spec.default !== undefined ? { default: spec.default } : {}), docs };
1441
1475
  }
1442
1476
  function precompressOp(op, tree, env) {
1443
1477
  return precompress(tree, op, `${env.label}:${op.span.line} PRECOMPRESS`, env.warn);
@@ -1447,7 +1481,10 @@ function precacheOp(op, tree, env) {
1447
1481
  }
1448
1482
  function sitemap(op, tree, env) {
1449
1483
  const origin = `${env.label}:${op.span.line} SITEMAP`;
1450
- const files = sitemapFiles(tree, op.base, op.dest).map(([p, xml]) => [p, makeFile(new TextEncoder().encode(xml), origin)]);
1484
+ const alts = op.languages
1485
+ ? alternates(sitemapPages(tree).map((p) => [p, p]), languagesOf(op.languages, 'SITEMAP', op.span, env), 'SITEMAP', op.span)
1486
+ : undefined;
1487
+ const files = sitemapFiles(tree, op.base, op.dest, SITEMAP_LIMITS, alts).map(([p, xml]) => [p, makeFile(new TextEncoder().encode(xml), origin)]);
1451
1488
  return tree.withFiles(files, op.overwrite ? 'overwrite' : 'error', op.span);
1452
1489
  }
1453
1490
  /** Check a plugin file (sandbox, own folder, integrity) and start its process. */
@@ -2,6 +2,7 @@ import { statSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { SitefileError } from './errors.js';
4
4
  import { joinVirtual, normalizeVirtual } from './paths.js';
5
+ import { sidecarSource } from './precompress.js';
5
6
  import { importedStageRefs } from './planner.js';
6
7
  import { importedStage } from './language/ast.js';
7
8
  // `sitefile graph` and `sitefile why` (issue #94): the dependency graph of a plan, and the history of one
@@ -421,7 +422,7 @@ export function why(result, raw, contextDir) {
421
422
  else if (op.kind === 'FINGERPRINT')
422
423
  inputs.push(op.manifest === file ? 'the files it renamed' : 'references to renamed files');
423
424
  else if (op.kind === 'PRECOMPRESS')
424
- inputs.push(`${file.slice(0, -'.gz'.length)} (compressed)`);
425
+ inputs.push(`${sidecarSource(file)} (compressed)`);
425
426
  else
426
427
  inputs.push(`list ${op.list}`);
427
428
  events.push({ location: at(op.span.line), instruction: operationLabel(op), stage: display, path: file, action: prev ? 'overwrite' : 'write', digest: next.digest, inputs });
@@ -0,0 +1,25 @@
1
+ import { type SourceSpan } from './errors.js';
2
+ /** A basic BCP 47 check: a 2-3 letter language, then `-` subtags of 1-8 letters or digits (`en`, `pt-BR`, `zh-Hant-TW`). */
3
+ export declare function isLanguageTag(s: string): boolean;
4
+ /** What a document's frontmatter says about the page it renders: `lang` and `translationKey`. */
5
+ export interface Translation {
6
+ readonly lang: string;
7
+ readonly key: string;
8
+ }
9
+ /** One alternate of a page: its `hreflang` value and the URL path of the translation (the caller makes it absolute). */
10
+ export type Alternate = readonly [hreflang: string, url: string];
11
+ /** LANGUAGES, evaluated, with the translations documents give (tree path -> translation). */
12
+ export interface Languages {
13
+ readonly codes: readonly string[];
14
+ readonly default?: string;
15
+ readonly docs: ReadonlyMap<string, Translation>;
16
+ }
17
+ /**
18
+ * The alternates of every page that has a translation. `pages` are [tree path, URL path] pairs (the URL path
19
+ * is what the language folder is read from). A page a document renders is grouped by its `translationKey`
20
+ * in its `lang`; any other page by its URL path without the language folder (`/fr/about.html` is the `fr`
21
+ * page of `/about.html`), and one in no language folder is the DEFAULT language's (without DEFAULT, it has
22
+ * none). A group of two or more pages gives each of them every page of the group, ordered by language, then
23
+ * `x-default` for the DEFAULT language's page. Two pages of one language in a group are `E_VALIDATION`.
24
+ */
25
+ export declare function alternates(pages: ReadonlyArray<readonly [string, string]>, langs: Languages, what: string, span: SourceSpan): Map<string, Alternate[]>;
@@ -0,0 +1,72 @@
1
+ // LANGUAGES (docs/LANGUAGE.md, "Site files"): which pages translate each other, for the hreflang alternates
2
+ // CANONICAL and SITEMAP write. Ported as rust/src/hreflang.rs: both must find the same groups and messages.
3
+ import { SitefileError } from './errors.js';
4
+ const TAG_RE = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{1,8})*$/;
5
+ /** A basic BCP 47 check: a 2-3 letter language, then `-` subtags of 1-8 letters or digits (`en`, `pt-BR`, `zh-Hant-TW`). */
6
+ export function isLanguageTag(s) {
7
+ return TAG_RE.test(s);
8
+ }
9
+ function utf8Compare(a, b) {
10
+ return Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'));
11
+ }
12
+ /**
13
+ * The alternates of every page that has a translation. `pages` are [tree path, URL path] pairs (the URL path
14
+ * is what the language folder is read from). A page a document renders is grouped by its `translationKey`
15
+ * in its `lang`; any other page by its URL path without the language folder (`/fr/about.html` is the `fr`
16
+ * page of `/about.html`), and one in no language folder is the DEFAULT language's (without DEFAULT, it has
17
+ * none). A group of two or more pages gives each of them every page of the group, ordered by language, then
18
+ * `x-default` for the DEFAULT language's page. Two pages of one language in a group are `E_VALIDATION`.
19
+ */
20
+ export function alternates(pages, langs, what, span) {
21
+ const groups = new Map();
22
+ for (const [path, url] of [...pages].sort((a, b) => utf8Compare(a[0], b[0]))) {
23
+ const doc = langs.docs.get(path);
24
+ let group;
25
+ let lang;
26
+ let label;
27
+ if (doc) {
28
+ group = `k\0${doc.key}`;
29
+ lang = doc.lang;
30
+ label = `translationKey '${doc.key}'`;
31
+ }
32
+ else {
33
+ const slash = url.indexOf('/', 1);
34
+ const folder = slash > 0 ? url.slice(1, slash) : undefined;
35
+ if (folder !== undefined && langs.codes.includes(folder)) {
36
+ lang = folder;
37
+ group = `f\0${url.slice(slash)}`;
38
+ label = `'${url.slice(slash)}'`;
39
+ }
40
+ else if (langs.default !== undefined) {
41
+ lang = langs.default;
42
+ group = `f\0${url}`;
43
+ label = `'${url}'`;
44
+ }
45
+ else
46
+ continue;
47
+ }
48
+ let members = groups.get(group);
49
+ if (!members)
50
+ groups.set(group, (members = []));
51
+ const same = members.find((m) => m.lang.toLowerCase() === lang.toLowerCase());
52
+ if (same) {
53
+ throw new SitefileError('E_VALIDATION', `${what}: ${same.path} and ${path} are both the '${lang}' page of ${label}; a translation group has one page per language`, span);
54
+ }
55
+ members.push({ path, url, lang });
56
+ }
57
+ const out = new Map();
58
+ const dflt = langs.default?.toLowerCase();
59
+ for (const members of groups.values()) {
60
+ if (members.length < 2)
61
+ continue;
62
+ const sorted = [...members].sort((a, b) => (a.lang.toLowerCase() < b.lang.toLowerCase() ? -1 : a.lang.toLowerCase() > b.lang.toLowerCase() ? 1 : 0));
63
+ const alts = sorted.map((m) => [m.lang, m.url]);
64
+ const d = sorted.find((m) => m.lang.toLowerCase() === dflt);
65
+ if (d)
66
+ alts.push(['x-default', d.url]);
67
+ for (const m of members)
68
+ out.set(m.path, alts);
69
+ }
70
+ return out;
71
+ }
72
+ //# sourceMappingURL=hreflang.js.map
@@ -370,10 +370,20 @@ export interface CanonicalInstruction {
370
370
  readonly base: Operand;
371
371
  readonly pretty: boolean;
372
372
  }
373
- /** A PRECOMPRESS sidecar format: `gzip` writes `<file>.gz` (`br` and `zstd` are reserved: no encoder yet). */
374
- export type PrecompressFormat = 'gzip';
375
373
  /**
376
- * `PRECOMPRESS [--overwrite] [gzip]… <pattern>… [MIN <bytes>]`: write a `.gz` sidecar next to each matching
374
+ * `LANGUAGES <code>… [DEFAULT <code>]`: the site's language folders (`/en/…`, `/fr/…`, pages at the root in the
375
+ * DEFAULT language). CANONICAL and SITEMAP write hreflang alternates for the pages that translate each other.
376
+ */
377
+ export interface LanguagesInstruction {
378
+ readonly kind: 'LANGUAGES';
379
+ readonly span: SourceSpan;
380
+ readonly codes: readonly Operand[];
381
+ readonly default?: Operand;
382
+ }
383
+ /** A PRECOMPRESS sidecar format: `gzip` writes `<file>.gz`, `br` writes `<file>.br` (`zstd` is reserved: no encoder yet). */
384
+ export type PrecompressFormat = 'gzip' | 'br';
385
+ /**
386
+ * `PRECOMPRESS [--overwrite] [gzip] [br] <pattern>… [MIN <bytes>]`: write a `.gz` and/or `.br` sidecar next to each matching
377
387
  * compressible file of at least MIN bytes, when it is smaller.
378
388
  */
379
389
  export interface PrecompressInstruction {
@@ -453,7 +463,7 @@ export interface CheckLinksInstruction {
453
463
  /** `--external`: also request http(s) links (under the network policy). */
454
464
  readonly external: boolean;
455
465
  }
456
- export type Instruction = FromInstruction | ArgInstruction | LetInstruction | FragmentInstruction | ImportInstruction | CopyInstruction | RenderInstruction | PluginInstruction | ToolInstruction | TransformInstruction | SitemapInstruction | FeedInstruction | RedirectInstruction | HeaderInstruction | MimeInstruction | FingerprintInstruction | CanonicalInstruction | PrecompressInstruction | RobotsInstruction | SecurityTxtInstruction | PrecacheInstruction | CspInstruction | CheckLinksInstruction | ExportInstruction;
466
+ export type Instruction = FromInstruction | ArgInstruction | LetInstruction | FragmentInstruction | ImportInstruction | CopyInstruction | RenderInstruction | PluginInstruction | ToolInstruction | TransformInstruction | SitemapInstruction | FeedInstruction | RedirectInstruction | HeaderInstruction | MimeInstruction | FingerprintInstruction | CanonicalInstruction | LanguagesInstruction | PrecompressInstruction | RobotsInstruction | SecurityTxtInstruction | PrecacheInstruction | CspInstruction | CheckLinksInstruction | ExportInstruction;
457
467
  /** A parsed and semantically validated Sitefile. */
458
468
  export interface Program {
459
469
  readonly file: string;
@@ -49,6 +49,8 @@ function parseInstruction(c) {
49
49
  return parseFingerprint(c, span);
50
50
  case 'CANONICAL':
51
51
  return parseCanonical(c, span);
52
+ case 'LANGUAGES':
53
+ return parseLanguages(c, span);
52
54
  case 'PRECOMPRESS':
53
55
  return parsePrecompress(c, span);
54
56
  case 'ROBOTS':
@@ -606,9 +608,21 @@ function parseCanonical(c, span) {
606
608
  c.expectEnd();
607
609
  return { kind: 'CANONICAL', span, base, pretty };
608
610
  }
609
- /** Sidecar formats PRECOMPRESS knows; only gzip has an encoder (src/deflate.ts, shared with the Rust port). */
611
+ /** `LANGUAGES <code>… [DEFAULT <code>]` */
612
+ function parseLanguages(c, span) {
613
+ const codes = [];
614
+ while (!c.atEnd() && !c.peekKeyword('DEFAULT'))
615
+ codes.push(c.operand('language code'));
616
+ if (codes.length === 0)
617
+ throw c.error('E_SYNTAX', 'expected a language code (LANGUAGES en fr de DEFAULT en)');
618
+ const dflt = c.keyword('DEFAULT') ? c.operand('default language code') : undefined;
619
+ c.expectEnd();
620
+ return { kind: 'LANGUAGES', span, codes, ...(dflt ? { default: dflt } : {}) };
621
+ }
622
+ /** Sidecar formats PRECOMPRESS knows. gzip uses src/deflate.ts (shared with the Rust port), br node:zlib's Brotli
623
+ * (the Rust port vendors the same C encoder); zstd has no encoder yet. */
610
624
  const PRECOMPRESS_FORMATS = ['gzip', 'br', 'zstd'];
611
- /** `PRECOMPRESS [--overwrite] [gzip]… <pattern>… [MIN <bytes>]` */
625
+ /** `PRECOMPRESS [--overwrite] [gzip] [br] <pattern>… [MIN <bytes>]` */
612
626
  function parsePrecompress(c, span) {
613
627
  const flags = parseFlags(c, { overwrite: 'bare' });
614
628
  const formats = [];
@@ -620,8 +634,8 @@ function parsePrecompress(c, span) {
620
634
  c.reset(mark);
621
635
  break;
622
636
  }
623
- if (w !== 'gzip') {
624
- throw c.error('E_UNSUPPORTED', `PRECOMPRESS ${w} is not supported yet: sitefile has no ${w === 'br' ? 'Brotli' : 'Zstandard'} encoder that writes the same bytes in both implementations (use gzip)`, at);
637
+ if (w === 'zstd') {
638
+ throw c.error('E_UNSUPPORTED', 'PRECOMPRESS zstd is not supported yet: sitefile has no Zstandard encoder that writes the same bytes in both implementations (use gzip or br)', at);
625
639
  }
626
640
  if (formats.includes(w))
627
641
  throw c.error('E_SYNTAX', `${w} given twice`, at);
@@ -52,6 +52,8 @@ export function operandsOf(ins) {
52
52
  return [...ins.patterns, ...(ins.manifest ? [ins.manifest] : [])];
53
53
  case 'CANONICAL':
54
54
  return [ins.base];
55
+ case 'LANGUAGES':
56
+ return [...ins.codes, ...(ins.default ? [ins.default] : [])];
55
57
  case 'PRECOMPRESS':
56
58
  return [...ins.patterns, ...(ins.min ? [ins.min] : [])];
57
59
  case 'ROBOTS':
@@ -292,6 +294,7 @@ export function validate(instructions, file) {
292
294
  case 'MIME':
293
295
  case 'FINGERPRINT':
294
296
  case 'CANONICAL':
297
+ case 'LANGUAGES':
295
298
  case 'PRECOMPRESS':
296
299
  case 'ROBOTS':
297
300
  case 'SECURITY_TXT':
@@ -49,6 +49,20 @@ export declare function integrityTags(text: string): IntegrityTag[];
49
49
  * there is no `</head>`. Comments, declarations and raw text are skipped as in {@link scanHtml}.
50
50
  */
51
51
  export declare function canonicalSlot(text: string): number | 'has' | undefined;
52
+ /** What CANONICAL needs from a page's head: see {@link headLinks}. */
53
+ export interface HeadLinks {
54
+ /** The offset of the first `</head` end tag; undefined when there is none. */
55
+ readonly at: number | undefined;
56
+ /** A `<link>` whose `rel` has the token `canonical` comes before it (or anywhere, without `</head>`). */
57
+ readonly canonical: boolean;
58
+ /** So does a `<link>` whose `rel` has the token `alternate` and that has an `hreflang` attribute. */
59
+ readonly hreflang: boolean;
60
+ }
61
+ /**
62
+ * Where links go in a page's head and which it already has (ASCII case-insensitive `rel` tokens). Comments,
63
+ * declarations and raw text are skipped as in {@link scanHtml}.
64
+ */
65
+ export declare function headLinks(text: string): HeadLinks;
52
66
  /** What CSP needs from a page: its inline script and style texts, in order, and where its `<head>` start tag ends. */
53
67
  export interface InlineBlocks {
54
68
  /** The contents of each `<script>` without a `src` attribute (also empty ones). */