@johnhenry/sitefile 0.0.5 → 0.0.6
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 +61 -0
- package/README.md +46 -9
- package/lib/src/attest.d.ts +3 -2
- package/lib/src/attest.js +3 -2
- package/lib/src/cli/index.d.ts +2 -1
- package/lib/src/cli/index.js +11 -2
- package/lib/src/cli/serve-worker.js +136 -18
- package/lib/src/cli/servers.d.ts +11 -1
- package/lib/src/cli/servers.js +89 -32
- package/lib/src/cli/watch.d.ts +2 -0
- package/lib/src/cli/watch.js +5 -4
- package/lib/src/executor.js +27 -5
- package/lib/src/explain.js +1 -1
- package/lib/src/language/ast.d.ts +12 -0
- package/lib/src/language/parser.js +25 -3
- package/lib/src/language/validate.js +11 -0
- package/lib/src/pattern.d.ts +36 -0
- package/lib/src/pattern.js +389 -0
- package/lib/src/planner.d.ts +8 -0
- package/lib/src/planner.js +4 -2
- package/lib/src/render.d.ts +4 -1
- package/lib/src/render.js +11 -7
- package/lib/src/schema.d.ts +3 -0
- package/lib/src/schema.js +39 -6
- package/lib/src/servers.d.ts +25 -0
- package/lib/src/version.d.ts +7 -0
- package/lib/src/version.js +9 -0
- package/package.json +1 -1
package/lib/src/cli/servers.js
CHANGED
|
@@ -190,7 +190,7 @@ const run = {
|
|
|
190
190
|
name: 'serve',
|
|
191
191
|
summary: 'serve an image, directory or archive file over HTTP',
|
|
192
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
|
|
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 the detached server does the same (a build context or a plain directory) and keeps\nthe build and page options in its record; 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)',
|
|
@@ -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 (-d
|
|
242
|
+
'--watch build the context, serve it, rebuild on change and live-reload pages (also with -d)',
|
|
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)',
|
|
@@ -253,7 +253,7 @@ const run = {
|
|
|
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
|
-
'--reload
|
|
256
|
+
'--reload [full|morph] morph (default): update a page in place when only HTML changed; full: always reload (--watch); without --watch (also -d): pages left open reload after a restart',
|
|
257
257
|
'--sync[=scroll] open pages report where they are and follow each other\'s navigation (=scroll: and scrolling) (--watch, -d --watch)',
|
|
258
258
|
],
|
|
259
259
|
options: {
|
|
@@ -323,19 +323,21 @@ const run = {
|
|
|
323
323
|
async run(v, pos) {
|
|
324
324
|
if (v.watch && !v.detach)
|
|
325
325
|
return serveWatch(v, pos);
|
|
326
|
-
// `-d --watch`: a plain directory
|
|
326
|
+
// `-d --watch`: a plain directory re-read on change, or a build context built and rebuilt on change,
|
|
327
|
+
// by the detached worker (with live reload).
|
|
327
328
|
const watchDetached = !!v.watch;
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
}
|
|
329
|
+
if (!watchDetached)
|
|
330
|
+
for (const f of WATCH_ONLY)
|
|
331
|
+
if (v[f] !== undefined)
|
|
332
|
+
usage(`--${f} needs --watch`);
|
|
333
333
|
if (watchDetached)
|
|
334
334
|
requireArgs(pos, 0, 1, 'a directory');
|
|
335
335
|
else
|
|
336
336
|
requireArgs(pos, 1, 1, 'an image reference, ./directory or archive file');
|
|
337
337
|
const pollMs = watchDetached ? pollOption(!!v.poll, str(v['poll-interval'])) : undefined;
|
|
338
338
|
const sync = watchDetached ? syncOf(v) : undefined;
|
|
339
|
+
// `--reload` without --watch: the live-reload script and stream, so pages reload after a restart.
|
|
340
|
+
const reload = reloadOf(v);
|
|
339
341
|
const bind = parsePublish(str(v.publish));
|
|
340
342
|
const allowedHosts = allowedHostsOf(v);
|
|
341
343
|
const isolate = isolateOf(v);
|
|
@@ -359,6 +361,7 @@ const run = {
|
|
|
359
361
|
usage('--name needs -d (only detached servers are tracked)');
|
|
360
362
|
const store = await Store.open();
|
|
361
363
|
const { label, source } = watchDetached ? await watchedDirectory(pos[0] ?? '.') : await resolveSource(store, pos[0]);
|
|
364
|
+
const watchRecord = watchDetached ? await detachedWatchOf(v, source) : {};
|
|
362
365
|
if (isWildcard(bind.host))
|
|
363
366
|
process.stderr.write(`warning: binding ${bind.host}: the site will be reachable from other machines\n`);
|
|
364
367
|
const keepOsMetadata = !!v['keep-os-metadata'];
|
|
@@ -371,7 +374,8 @@ const run = {
|
|
|
371
374
|
const modified = await servedLastModified(store, source);
|
|
372
375
|
let current = tree;
|
|
373
376
|
const proxy = proxyOption(v);
|
|
374
|
-
const
|
|
377
|
+
const live = reload !== undefined ? new LiveReload({ reload }) : undefined;
|
|
378
|
+
const server = createSiteServer(() => current, { ...(live ? { liveReload: live, warn } : {}), allowedHosts, proxy, cors: !!v.cors, ...(isolate ? { isolate } : {}), ...(cache ? { cache } : {}), ...logging, ...(auth.server ? { auth: auth.server } : {}), ...perIp, ...sharing.server, ...(tls.server ? { tls: tls.server } : {}), compress: !!v.compress, ...(throttle ? { throttle: throttle.limits } : {}), ...(mime ? { mime } : {}), lastModified: () => modified, log: logWriter(logging), ...(content ? { content } : {}), ...(country !== undefined ? { country } : {}), ...spa, ...(base !== undefined ? { base } : {}), ...(rewriteBase !== undefined ? { rewriteBase } : {}), ...(profile ? { profile } : {}), devNotFound: !isWildcard(bind.host) });
|
|
375
379
|
const addr = await listen(server, bind.host, bind.port);
|
|
376
380
|
if (logging.logFormat === 'json')
|
|
377
381
|
process.stdout.write(`${startedLogLine(new Date().toISOString(), label, tree.size, siteUrl(addr.host, addr.port, base, tls.scheme))}\n`);
|
|
@@ -404,7 +408,7 @@ const run = {
|
|
|
404
408
|
for (const f of PROXY_FLAGS)
|
|
405
409
|
if (v[f] !== undefined)
|
|
406
410
|
usage(`--${f} is for a server in the foreground (or --watch), not -d`);
|
|
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);
|
|
411
|
+
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 } : {}), ...(reload !== undefined ? { reload } : {}), ...watchRecord }, warn);
|
|
408
412
|
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)}`);
|
|
409
413
|
return 0;
|
|
410
414
|
},
|
|
@@ -414,14 +418,17 @@ const run = {
|
|
|
414
418
|
* wait until it listens. On failure the record is removed.
|
|
415
419
|
*/
|
|
416
420
|
export async function serveDetached(reg, d, warn) {
|
|
417
|
-
// fail fast on a bad image, directory or archive (or an ignored site-file line with --strict-site-files)
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
421
|
+
// fail fast on a bad image, directory or archive (or an ignored site-file line with --strict-site-files);
|
|
422
|
+
// a build context is built by the worker (a failed first build is served as an error page)
|
|
423
|
+
if (!(d.watch && d.build !== undefined)) {
|
|
424
|
+
const site = await loadServedSite(reg.store, d.source, { keepOsMetadata: !!d.keepOsMetadata, ...(warn ? { warn } : {}) });
|
|
425
|
+
try {
|
|
426
|
+
if (routingFor(d)?.siteFiles !== false)
|
|
427
|
+
checkSiteFiles(site.tree, !!d.strictSiteFiles, warn ?? (() => undefined), site.content);
|
|
428
|
+
}
|
|
429
|
+
finally {
|
|
430
|
+
site.close();
|
|
431
|
+
}
|
|
425
432
|
}
|
|
426
433
|
const { id, name: finalName } = await reg.allocate(d.name);
|
|
427
434
|
const state = {
|
|
@@ -460,6 +467,13 @@ export async function serveDetached(reg, d, warn) {
|
|
|
460
467
|
...(d.watch ? { watch: true } : {}),
|
|
461
468
|
...(d.watch && d.pollMs !== undefined ? { pollMs: d.pollMs } : {}),
|
|
462
469
|
...(d.watch && d.sync !== undefined ? { sync: d.sync } : {}),
|
|
470
|
+
...(d.reload !== undefined ? { reload: d.reload } : {}),
|
|
471
|
+
...(d.watch && d.build !== undefined ? { build: d.build } : {}),
|
|
472
|
+
...(d.watch && d.noCssInject ? { noCssInject: true } : {}),
|
|
473
|
+
...(d.watch && d.console ? { console: true } : {}),
|
|
474
|
+
...(d.watch && d.noOverlay ? { noOverlay: true } : {}),
|
|
475
|
+
...(d.watch && d.navigateToChanged ? { navigateToChanged: true } : {}),
|
|
476
|
+
...(d.watch && d.keepServiceWorkers ? { keepServiceWorkers: true } : {}),
|
|
463
477
|
bind: d.bind,
|
|
464
478
|
host: d.bind.host,
|
|
465
479
|
port: d.bind.port,
|
|
@@ -484,7 +498,8 @@ export async function serveDetached(reg, d, warn) {
|
|
|
484
498
|
*/
|
|
485
499
|
export async function restartDetached(reg, s, graceMs) {
|
|
486
500
|
await stopServer(reg, s, graceMs);
|
|
487
|
-
|
|
501
|
+
if (!(s.watch && s.build !== undefined))
|
|
502
|
+
(await loadServedSite(reg.store, s.source, { keepOsMetadata: !!s.keepOsMetadata })).close();
|
|
488
503
|
const fresh = { ...s, host: s.bind.host, port: s.bind.port, pid: 0, ready: false, started: new Date().toISOString() };
|
|
489
504
|
delete fresh.error;
|
|
490
505
|
await reg.write(fresh);
|
|
@@ -528,22 +543,66 @@ async function terminal(v, addr, base, scheme, warn, restart) {
|
|
|
528
543
|
return { promise, stop: stop ?? (() => undefined) };
|
|
529
544
|
}
|
|
530
545
|
/** The --watch flags `serve -d --watch` takes (it watches a plain directory; the rest are for builds or the page script). */
|
|
531
|
-
|
|
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
|
-
*/
|
|
546
|
+
/** `serve -d --watch [dir]`: the directory (default .) as a source, absolute and real. */
|
|
536
547
|
async function watchedDirectory(arg) {
|
|
537
548
|
const dir = path.resolve(arg);
|
|
538
549
|
const st = await fs.stat(dir).catch(() => undefined);
|
|
539
550
|
if (!st?.isDirectory())
|
|
540
551
|
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
552
|
return { label: dir, source: { kind: 'dir', path: await fs.realpath(dir) } };
|
|
544
553
|
}
|
|
545
|
-
/**
|
|
546
|
-
|
|
554
|
+
/**
|
|
555
|
+
* `serve -d --watch`: what the record keeps besides `watch`, `pollMs`, `sync` and `reload`: the page-script
|
|
556
|
+
* flags, and for a build context (a Sitefile, or -f, --target, --build-arg*, as in the foreground) the
|
|
557
|
+
* build inputs (johnhenry/sitefile#306). Build args are checked here, so a bad one is a usage error now;
|
|
558
|
+
* a bare `--build-arg NAME` is recorded with the value it has now.
|
|
559
|
+
*/
|
|
560
|
+
async function detachedWatchOf(v, source) {
|
|
561
|
+
const dir = source.kind === 'dir' ? source.path : '.';
|
|
562
|
+
const file = str(v.file);
|
|
563
|
+
const target = str(v.target);
|
|
564
|
+
const argFiles = strs(v['build-arg-file']).map((f) => path.resolve(f));
|
|
565
|
+
const argFlags = strs(v['build-arg']);
|
|
566
|
+
const buildFlags = file !== undefined || target !== undefined || argFiles.length > 0 || argFlags.length > 0;
|
|
567
|
+
const page = {
|
|
568
|
+
...(v['no-css-inject'] ? { noCssInject: true } : {}),
|
|
569
|
+
...(v.console ? { console: true } : {}),
|
|
570
|
+
...(v['no-overlay'] ? { noOverlay: true } : {}),
|
|
571
|
+
...(v['navigate-to-changed'] ? { navigateToChanged: true } : {}),
|
|
572
|
+
...(v['keep-service-workers'] ? { keepServiceWorkers: true } : {}),
|
|
573
|
+
};
|
|
574
|
+
if (!buildFlags && !(await isFile(path.join(dir, 'Sitefile'))))
|
|
575
|
+
return page;
|
|
576
|
+
if (v['no-rewrite-base'] && v['rewrite-base'] !== undefined)
|
|
577
|
+
usage('--rewrite-base and --no-rewrite-base cannot be combined');
|
|
578
|
+
await collectBuildArgs(argFiles, argFlags);
|
|
579
|
+
const build = {
|
|
580
|
+
...(file !== undefined ? { sitefile: path.resolve(file) } : {}),
|
|
581
|
+
...(target !== undefined ? { target } : {}),
|
|
582
|
+
...(argFlags.length > 0 ? { buildArgs: argFlags.map((kv) => (kv.includes('=') ? kv : `${kv}=${process.env[kv] ?? ''}`)) } : {}),
|
|
583
|
+
...(argFiles.length > 0 ? { buildArgFiles: argFiles } : {}),
|
|
584
|
+
...(v['no-cache'] ? { noCache: true } : {}),
|
|
585
|
+
...(v['no-lockfile'] ? { noLockfile: true } : {}),
|
|
586
|
+
...(v['no-rewrite-base'] ? { noRewriteBase: true } : {}),
|
|
587
|
+
};
|
|
588
|
+
return { build, ...page };
|
|
589
|
+
}
|
|
590
|
+
/** serve flags that only mean something with --watch (foreground or -d). */
|
|
591
|
+
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', 'no-rewrite-base', 'sync'];
|
|
592
|
+
/**
|
|
593
|
+
* `--reload [full|morph]` (a bare `--reload` arrives as `--reload=`): its mode, `morph` by default;
|
|
594
|
+
* undefined without it. Without --watch it turns on the live-reload script (pages reload after a restart).
|
|
595
|
+
*/
|
|
596
|
+
function reloadOf(v) {
|
|
597
|
+
const s = str(v.reload);
|
|
598
|
+
if (s === undefined)
|
|
599
|
+
return undefined;
|
|
600
|
+
if (s === '' || s === 'morph')
|
|
601
|
+
return 'morph';
|
|
602
|
+
if (s === 'full')
|
|
603
|
+
return 'full';
|
|
604
|
+
return usage(`--reload expects full or morph, got '${s}'`);
|
|
605
|
+
}
|
|
547
606
|
/** `--sync` (a bare `--sync` arrives as `--sync=`): `nav`, or `scroll` for `--sync=scroll`; undefined without it. */
|
|
548
607
|
function syncOf(v) {
|
|
549
608
|
const s = str(v.sync);
|
|
@@ -803,7 +862,7 @@ async function serveWatch(v, pos) {
|
|
|
803
862
|
const plain = !buildFlags && !(await isFile(path.join(context, 'Sitefile')));
|
|
804
863
|
const cssInject = !v['no-css-inject'];
|
|
805
864
|
const navigate = !!v['navigate-to-changed'];
|
|
806
|
-
const reloadMode =
|
|
865
|
+
const reloadMode = reloadOf(v) ?? 'morph';
|
|
807
866
|
const sync = syncOf(v);
|
|
808
867
|
const spa = spaOptions(v);
|
|
809
868
|
const baseFlag = sharing.randomBase ?? parseBase(str(v.base));
|
|
@@ -832,8 +891,6 @@ async function serveWatch(v, pos) {
|
|
|
832
891
|
lastSiteWarnings = text;
|
|
833
892
|
checkSiteFiles(tree, strictSiteFiles, () => undefined);
|
|
834
893
|
};
|
|
835
|
-
if (reloadMode !== 'full' && reloadMode !== 'morph')
|
|
836
|
-
usage(`--reload expects full or morph, got '${reloadMode}'`);
|
|
837
894
|
if (isWildcard(bind.host))
|
|
838
895
|
process.stderr.write(`warning: binding ${bind.host}: the site will be reachable from other machines\n`);
|
|
839
896
|
let current = Tree.empty;
|
package/lib/src/cli/watch.d.ts
CHANGED
|
@@ -24,6 +24,8 @@ export interface WatchLoopOptions {
|
|
|
24
24
|
readonly control?: {
|
|
25
25
|
rebuild?: () => void;
|
|
26
26
|
};
|
|
27
|
+
/** Where the loop's own lines go (each ends in a newline; `err` for stderr). Default: stdout and stderr (`serve -d --watch` stamps them into its log). */
|
|
28
|
+
readonly say?: (line: string, err: boolean) => void;
|
|
27
29
|
}
|
|
28
30
|
/**
|
|
29
31
|
* `--poll` / `--poll-interval <ms>` (the interval implies polling): the poll interval in
|
package/lib/src/cli/watch.js
CHANGED
|
@@ -41,6 +41,7 @@ export async function watchLoop(o) {
|
|
|
41
41
|
// The build itself writes the export, Sitefile.lock and (maybe) the store; none of that is input.
|
|
42
42
|
const ignored = new Set([await resolveReal(resolveStoreHome()), path.join(path.dirname(sitefile), 'Sitefile.lock')]);
|
|
43
43
|
const relevant = (p) => !isIgnoredChange(p, [root], ignored);
|
|
44
|
+
const say = o.say ?? ((line, err) => void (err ? process.stderr : process.stdout).write(line));
|
|
44
45
|
let finish;
|
|
45
46
|
const finished = new Promise((r) => (finish = r));
|
|
46
47
|
let first = true;
|
|
@@ -48,7 +49,7 @@ export async function watchLoop(o) {
|
|
|
48
49
|
if (!first) {
|
|
49
50
|
if (!changed.some(relevant))
|
|
50
51
|
return; // only our own writes
|
|
51
|
-
|
|
52
|
+
say(o.plain ? MSG_CHANGE_PLAIN : MSG_CHANGE, false);
|
|
52
53
|
}
|
|
53
54
|
const r = await o.build();
|
|
54
55
|
for (const w of r.wrote ?? []) {
|
|
@@ -57,7 +58,7 @@ export async function watchLoop(o) {
|
|
|
57
58
|
}
|
|
58
59
|
if (!first) {
|
|
59
60
|
if (r.code !== 0)
|
|
60
|
-
|
|
61
|
+
say(o.plain ? MSG_FAILED_PLAIN : MSG_FAILED, true);
|
|
61
62
|
return;
|
|
62
63
|
}
|
|
63
64
|
first = false;
|
|
@@ -69,10 +70,10 @@ export async function watchLoop(o) {
|
|
|
69
70
|
catch (e) {
|
|
70
71
|
if (!(e instanceof SitefileError))
|
|
71
72
|
throw e;
|
|
72
|
-
|
|
73
|
+
say(`error[${e.code}]: ${e.message}\n`, true);
|
|
73
74
|
return finish(1);
|
|
74
75
|
}
|
|
75
|
-
|
|
76
|
+
say(`Watching ${o.context} for changes (Ctrl-C to stop)\n`, false);
|
|
76
77
|
});
|
|
77
78
|
if (o.control)
|
|
78
79
|
o.control.rebuild = () => scheduler.notify(sitefile);
|
package/lib/src/executor.js
CHANGED
|
@@ -2057,8 +2057,31 @@ function feedFiles(op, env) {
|
|
|
2057
2057
|
if (!Array.isArray(list)) {
|
|
2058
2058
|
throw new SitefileError('E_TYPE', `FEED ${op.list}: '${op.list}' is not a list (import a directory AS markdown)`, op.span);
|
|
2059
2059
|
}
|
|
2060
|
-
|
|
2061
|
-
|
|
2060
|
+
const xmlFile = (title, dest, items) => {
|
|
2061
|
+
const xml = atomXml({ title, siteUrl: op.base + '/', selfUrl: pageUrl(op.base, dest), entries: feedEntries(op, items, env) });
|
|
2062
|
+
return [dest, makeFile(new TextEncoder().encode(xml), origin)];
|
|
2063
|
+
};
|
|
2064
|
+
if (!op.each) {
|
|
2065
|
+
if (list.length === 0)
|
|
2066
|
+
env.warn(`${origin}: '${op.list}' is empty, so the feed has no entries`);
|
|
2067
|
+
return [xmlFile(op.title, op.dest, list)];
|
|
2068
|
+
}
|
|
2069
|
+
// FEED tag … FOR tag IN list BY key: one feed per group, its TO and TITLE evaluated with the group.
|
|
2070
|
+
const { as, by, dest, title } = op.each;
|
|
2071
|
+
const groups = groupBy(list, by, `FEED ${as} FOR ${as} IN ${op.list} BY ${by}`, op.span);
|
|
2072
|
+
if (groups.length === 0)
|
|
2073
|
+
env.warn(`${origin}: FOR ${as} IN ${op.list} BY ${by} writes no feeds: no element has '${by}'`);
|
|
2074
|
+
return groups.map((g) => {
|
|
2075
|
+
const groupEnv = { ...env, loop: { name: as, value: g } };
|
|
2076
|
+
const raw = interpolate(dest, groupEnv);
|
|
2077
|
+
const target = normalizeVirtual(raw, dest.span, `FEED destination for ${as}`);
|
|
2078
|
+
if (target.trailingSlash)
|
|
2079
|
+
throw new SitefileError('E_PATH', `FEED destination '${raw}' must be a file path, not a directory`, dest.span);
|
|
2080
|
+
return xmlFile(title ? interpolate(title, groupEnv) : op.base, target.path, g['items']);
|
|
2081
|
+
});
|
|
2082
|
+
}
|
|
2083
|
+
/** The Atom entries of a FEED's elements, in list order. */
|
|
2084
|
+
function feedEntries(op, list, env) {
|
|
2062
2085
|
const entries = [];
|
|
2063
2086
|
list.forEach((item, i) => {
|
|
2064
2087
|
if (item === null || typeof item !== 'object' || Array.isArray(item)) {
|
|
@@ -2100,8 +2123,7 @@ function feedFiles(op, env) {
|
|
|
2100
2123
|
...(content !== undefined ? { content } : {}),
|
|
2101
2124
|
});
|
|
2102
2125
|
});
|
|
2103
|
-
|
|
2104
|
-
return [[op.dest, makeFile(new TextEncoder().encode(xml), origin)]];
|
|
2126
|
+
return entries;
|
|
2105
2127
|
}
|
|
2106
2128
|
/**
|
|
2107
2129
|
* The files an operation (other than SITEMAP, FINGERPRINT and CHECKLINKS) adds; `opId` is its memo identity
|
|
@@ -2112,7 +2134,7 @@ async function produce(op, tree, env, opId, treeKey) {
|
|
|
2112
2134
|
return produceTransform(op, env, opId);
|
|
2113
2135
|
// A feed reads its list and what its LINK names.
|
|
2114
2136
|
if (op.kind === 'FEED') {
|
|
2115
|
-
const key = env.memo ? memoKey('feed', opId, namesKey(env, operandNames([op.link], new Set([op.list])))) : undefined;
|
|
2137
|
+
const key = env.memo ? memoKey('feed', opId, namesKey(env, operandNames([op.link, op.each?.dest, op.each?.title], new Set([op.list])), op.each?.as)) : undefined;
|
|
2116
2138
|
return memoFiles(env, key, async () => feedFiles(op, env));
|
|
2117
2139
|
}
|
|
2118
2140
|
const origin = `${env.label}:${op.span.line} ${op.kind}`;
|
package/lib/src/explain.js
CHANGED
|
@@ -39,7 +39,7 @@ export function operationLabel(op) {
|
|
|
39
39
|
case 'SITEMAP':
|
|
40
40
|
return `SITEMAP ${op.dest}`;
|
|
41
41
|
case 'FEED':
|
|
42
|
-
return `FEED ${op.list} ${op.dest}`;
|
|
42
|
+
return op.each ? `FEED FOR ${op.each.as} IN ${op.list} BY ${op.each.by}` : `FEED ${op.list} ${op.dest}`;
|
|
43
43
|
case 'FINGERPRINT':
|
|
44
44
|
return `FINGERPRINT ${op.patterns.join(' ')}`;
|
|
45
45
|
case 'CANONICAL':
|
|
@@ -299,12 +299,24 @@ export interface SitemapInstruction {
|
|
|
299
299
|
/**
|
|
300
300
|
* `FEED [--overwrite] <import> BASE <url> LINK <path> [TO <dest>] [TITLE <text>]`: an Atom feed
|
|
301
301
|
* from a list import. LINK is evaluated per element, with the element as `${item…}`.
|
|
302
|
+
* `FEED tag … TO <dest> FOR tag IN <import> BY <key>`: one feed per group (`{ key, count, items }`)
|
|
303
|
+
* of the import's elements; TO and TITLE are evaluated per group with `${tag…}`.
|
|
302
304
|
*/
|
|
303
305
|
export interface FeedInstruction {
|
|
304
306
|
readonly kind: 'FEED';
|
|
305
307
|
readonly span: SourceSpan;
|
|
308
|
+
/** The import (also with FOR, where the subject is the loop variable). */
|
|
306
309
|
readonly list: string;
|
|
307
310
|
readonly listSpan: SourceSpan;
|
|
311
|
+
/** `FOR <as> IN <list> BY <key>`: a feed per group. */
|
|
312
|
+
readonly each?: {
|
|
313
|
+
readonly as: string;
|
|
314
|
+
readonly by: {
|
|
315
|
+
readonly key: string;
|
|
316
|
+
readonly span: SourceSpan;
|
|
317
|
+
};
|
|
318
|
+
readonly span: SourceSpan;
|
|
319
|
+
};
|
|
308
320
|
readonly base: Operand;
|
|
309
321
|
readonly link: Operand;
|
|
310
322
|
/** Default `/feed.xml`. */
|
|
@@ -510,23 +510,45 @@ function parseSitemap(c, span) {
|
|
|
510
510
|
c.expectEnd();
|
|
511
511
|
return { kind: 'SITEMAP', span, base, ...(dest ? { dest } : {}), overwrite: flags.has('overwrite') };
|
|
512
512
|
}
|
|
513
|
-
/**
|
|
513
|
+
/**
|
|
514
|
+
* `FEED [--overwrite] <import> BASE <url> LINK <path> [TO <dest>] [TITLE <text>] [FOR <var> IN <import> BY <key>]`
|
|
515
|
+
* (clauses in this order). With FOR, the subject is the loop variable and TO is required.
|
|
516
|
+
*/
|
|
514
517
|
function parseFeed(c, span) {
|
|
515
518
|
const flags = parseFlags(c, { overwrite: 'bare' });
|
|
516
|
-
const
|
|
517
|
-
const
|
|
519
|
+
const subjectSpan = c.span;
|
|
520
|
+
const subject = c.ident('import name');
|
|
518
521
|
c.expectKeyword('BASE');
|
|
519
522
|
const base = c.operand('base URL');
|
|
520
523
|
c.expectKeyword('LINK');
|
|
521
524
|
const link = c.operand('link path');
|
|
522
525
|
const dest = c.keyword('TO') ? c.operand('destination') : undefined;
|
|
523
526
|
const title = c.keyword('TITLE') ? c.operand('feed title') : undefined;
|
|
527
|
+
let list = subject;
|
|
528
|
+
let listSpan = subjectSpan;
|
|
529
|
+
let each;
|
|
530
|
+
const forAt = c.span;
|
|
531
|
+
if (c.keyword('FOR')) {
|
|
532
|
+
const as = c.ident('loop variable');
|
|
533
|
+
c.expectKeyword('IN');
|
|
534
|
+
listSpan = c.span;
|
|
535
|
+
list = c.ident('list name');
|
|
536
|
+
const byAt = c.span;
|
|
537
|
+
c.expectKeyword('BY');
|
|
538
|
+
each = { as, by: { key: c.ident('group key'), span: byAt }, span: forAt };
|
|
539
|
+
if (subject !== as) {
|
|
540
|
+
throw c.error('E_SYNTAX', `FEED ${subject} … FOR ${as} IN ${list} BY ${each.by.key} writes a feed per group; its subject must be the loop variable: FEED ${as} …`, subjectSpan);
|
|
541
|
+
}
|
|
542
|
+
if (!dest)
|
|
543
|
+
throw c.error('E_SYNTAX', `FEED ${as} … FOR ${as} IN ${list} writes a feed per group, so it needs TO <dest> (such as /tags/\${${as}.key}/feed.xml)`, forAt);
|
|
544
|
+
}
|
|
524
545
|
c.expectEnd();
|
|
525
546
|
return {
|
|
526
547
|
kind: 'FEED',
|
|
527
548
|
span,
|
|
528
549
|
list,
|
|
529
550
|
listSpan,
|
|
551
|
+
...(each && { each }),
|
|
530
552
|
base,
|
|
531
553
|
link,
|
|
532
554
|
...(dest ? { dest } : {}),
|
|
@@ -147,11 +147,15 @@ export function validate(instructions, file) {
|
|
|
147
147
|
const isDest = (ins.kind === 'FEED' && op === ins.link) ||
|
|
148
148
|
(ins.kind === 'RENDER' && (op === ins.dest || op === ins.each?.page?.first)) ||
|
|
149
149
|
(ins.kind === 'TRANSFORM' && (op === ins.dest || ins.options.some((o) => o.value === op) || (ins.args?.includes(op) ?? false)));
|
|
150
|
+
// FEED tag … FOR tag IN list BY key: TO and TITLE may use ${tag.key} for the current group.
|
|
151
|
+
const groupVar = ins.kind === 'FEED' && (op === ins.dest || op === ins.title) ? ins.each?.as : undefined;
|
|
150
152
|
for (const part of op.parts) {
|
|
151
153
|
if (part.kind !== 'var')
|
|
152
154
|
continue;
|
|
153
155
|
if (isDest && part.name === loopVar)
|
|
154
156
|
continue;
|
|
157
|
+
if (groupVar !== undefined && part.name === groupVar)
|
|
158
|
+
continue;
|
|
155
159
|
if (part.path.length > 0) {
|
|
156
160
|
throw new SitefileError('E_SYNTAX', `dotted access \${${[part.name, ...part.path].join('.')}} is only allowed in RENDER templates and for a RENDER … FOR loop variable`, part.span);
|
|
157
161
|
}
|
|
@@ -287,6 +291,13 @@ export function validate(instructions, file) {
|
|
|
287
291
|
throw new SitefileError('E_UNDEFINED', `FEED ${ins.list}: '${ins.list}' is not an IMPORT declared on an earlier line`, ins.listSpan);
|
|
288
292
|
}
|
|
289
293
|
notSitefile(ins.list, `FEED ${ins.list}`, ins.listSpan, sitefiles);
|
|
294
|
+
if (ins.each) {
|
|
295
|
+
const { as, span } = ins.each;
|
|
296
|
+
if (as === FEED_ITEM)
|
|
297
|
+
throw new SitefileError('E_DUPLICATE', `FOR ${as}: '${FEED_ITEM}' is the element in FEED's LINK; pick another loop variable name`, span);
|
|
298
|
+
if (taken(as))
|
|
299
|
+
throw new SitefileError('E_DUPLICATE', `FOR ${as}: '${as}' is already defined; pick another loop variable name`, span);
|
|
300
|
+
}
|
|
290
301
|
break;
|
|
291
302
|
case 'SITEMAP':
|
|
292
303
|
case 'REDIRECT':
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** A compile error: `position` is the 1-based code point index in the pattern. */
|
|
2
|
+
export declare class PatternError extends Error {
|
|
3
|
+
readonly reason: string;
|
|
4
|
+
readonly position: number;
|
|
5
|
+
constructor(reason: string, position: number);
|
|
6
|
+
}
|
|
7
|
+
type Range = readonly [number, number];
|
|
8
|
+
/** A set of code points: ranges, or their complement. */
|
|
9
|
+
interface CharSet {
|
|
10
|
+
readonly ranges: readonly Range[];
|
|
11
|
+
readonly negate: boolean;
|
|
12
|
+
}
|
|
13
|
+
type Inst = {
|
|
14
|
+
readonly op: 'set';
|
|
15
|
+
readonly items: readonly CharSet[];
|
|
16
|
+
readonly negate: boolean;
|
|
17
|
+
} | {
|
|
18
|
+
readonly op: 'bol' | 'eol' | 'match';
|
|
19
|
+
} | {
|
|
20
|
+
readonly op: 'split';
|
|
21
|
+
x: number;
|
|
22
|
+
y: number;
|
|
23
|
+
} | {
|
|
24
|
+
readonly op: 'jmp';
|
|
25
|
+
x: number;
|
|
26
|
+
};
|
|
27
|
+
/** A compiled pattern. */
|
|
28
|
+
export interface Pattern {
|
|
29
|
+
readonly source: string;
|
|
30
|
+
readonly prog: readonly Inst[];
|
|
31
|
+
}
|
|
32
|
+
/** Compile a pattern; throws PatternError. */
|
|
33
|
+
export declare function compilePattern(source: string): Pattern;
|
|
34
|
+
/** Whether the pattern matches somewhere in `text` (Pike VM over code points). */
|
|
35
|
+
export declare function patternMatches(p: Pattern, text: string): boolean;
|
|
36
|
+
export {};
|