@johnhenry/sitefile 0.0.8 → 0.0.9
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 +20 -0
- package/README.md +7 -1
- package/lib/src/bucket-follow.d.ts +22 -0
- package/lib/src/bucket-follow.js +65 -0
- package/lib/src/bucket.d.ts +270 -0
- package/lib/src/bucket.js +1130 -0
- package/lib/src/cache-limit.d.ts +3 -3
- package/lib/src/cache-limit.js +21 -0
- package/lib/src/cli/bucket.d.ts +2 -0
- package/lib/src/cli/bucket.js +312 -0
- package/lib/src/cli/index.d.ts +1 -1
- package/lib/src/cli/index.js +13 -2
- package/lib/src/cli/serve-worker.js +63 -11
- package/lib/src/cli/servers.js +59 -9
- package/lib/src/cli/up.js +2 -0
- package/lib/src/servers.d.ts +10 -0
- package/lib/src/servers.js +20 -0
- package/package.json +1 -1
package/lib/src/cli/servers.js
CHANGED
|
@@ -15,6 +15,8 @@ import { isRunning, loadDirectoryTree, loadServedTree, pidAlive, servedLastModif
|
|
|
15
15
|
import { BasicAuth, makeVerifier, parseAuthPair, parseHtpasswd } from '../serve-auth.js';
|
|
16
16
|
import { Store } from '../store.js';
|
|
17
17
|
import { Tree } from '../tree.js';
|
|
18
|
+
import { bucketLabel, Buckets, parseBucketSource } from '../bucket.js';
|
|
19
|
+
import { followBucket } from '../bucket-follow.js';
|
|
18
20
|
import { transformCacheDir } from './cache.js';
|
|
19
21
|
import { requireArgs, str, strs, table, usage, usageError } from './common.js';
|
|
20
22
|
import { watchMemo } from '../memo.js';
|
|
@@ -131,6 +133,12 @@ export async function archiveSource(arg) {
|
|
|
131
133
|
* archive file by that name (`site.zip`). Whether a file is an archive is checked when it is loaded.
|
|
132
134
|
*/
|
|
133
135
|
export async function resolveSource(store, arg) {
|
|
136
|
+
const bucket = parseBucketSource(arg);
|
|
137
|
+
if (bucket) {
|
|
138
|
+
const buckets = Buckets.open(store);
|
|
139
|
+
await buckets.resolveDirectory(bucket.name, bucket.prefix === undefined ? [] : bucket.prefix.split('/'));
|
|
140
|
+
return { label: bucketLabel(bucket.name, bucket.prefix), source: { kind: 'bucket', name: bucket.name, ...(bucket.prefix !== undefined ? { prefix: bucket.prefix } : {}) } };
|
|
141
|
+
}
|
|
134
142
|
if (/^(\.\.?|~.*|\.\.?\/.*|\/.*|.*\/)$/.test(arg)) {
|
|
135
143
|
const dir = path.resolve(arg);
|
|
136
144
|
if (await isFile(dir))
|
|
@@ -172,15 +180,17 @@ async function startDetached(reg, state) {
|
|
|
172
180
|
let exited = false;
|
|
173
181
|
child.once('exit', () => (exited = true));
|
|
174
182
|
child.once('error', () => (exited = true));
|
|
175
|
-
const up = await awaitReady(() => reg.read(state.id), () => exited, () => child.kill('SIGKILL')
|
|
183
|
+
const up = await awaitReady(() => reg.read(state.id), () => exited, () => child.kill('SIGKILL'),
|
|
184
|
+
// A build context is ready after its first build (#354), which may take a while.
|
|
185
|
+
state.watch && state.build !== undefined ? { timeoutMs: 120_000 } : {});
|
|
176
186
|
child.unref();
|
|
177
187
|
return up;
|
|
178
188
|
}
|
|
179
189
|
const run = {
|
|
180
190
|
name: 'serve',
|
|
181
|
-
summary: 'serve an image, directory
|
|
182
|
-
usage: 'serve [--name n] [-p [host:]port] [-d] [--spa] <ref|id|./dir|file> | serve [-d] --watch [options] [context]',
|
|
183
|
-
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.',
|
|
191
|
+
summary: 'serve an image, directory, archive file or bucket over HTTP',
|
|
192
|
+
usage: 'serve [--name n] [-p [host:]port] [-d] [--spa] <ref|id|./dir|file|bucket:name[/prefix]> | 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. A bucket (bucket:<name>[/prefix], see "sitefile bucket --help") is followed: a request made after its files change sees the new ones. 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.',
|
|
184
194
|
flags: [
|
|
185
195
|
'--name <n> name for the server (-d only; default site-<6 hex>)',
|
|
186
196
|
'-p, --publish <[host:]port> address to bind (default 127.0.0.1, a free port)',
|
|
@@ -226,6 +236,7 @@ const run = {
|
|
|
226
236
|
'--html-handling <mode> auto, force-slash, drop-slash or none: canonical page URLs (Cloudflare\'s modes)',
|
|
227
237
|
'--country <code> the country _redirects Country= conditions match (there is no geolocation locally)',
|
|
228
238
|
'--strict-site-files refuse to serve when a _redirects or _headers line would be ignored',
|
|
239
|
+
'--max-bytes <n> a bucket: most bytes it may hold in memory (default 2147483648; a larger bucket is an error)',
|
|
229
240
|
'--keep-os-metadata serve __MACOSX, ._*, Thumbs.db and desktop.ini of a directory or archive (default: skipped)',
|
|
230
241
|
'--open[=<path>] open the site (at <path>) in the browser once it is served ($BROWSER, else the system default)',
|
|
231
242
|
'--qr print a QR code of the network URL (with -p 0.0.0.0:...), else of the local URL',
|
|
@@ -261,6 +272,7 @@ const run = {
|
|
|
261
272
|
country: { type: 'string' },
|
|
262
273
|
'strict-site-files': { type: 'boolean' },
|
|
263
274
|
'keep-os-metadata': { type: 'boolean' },
|
|
275
|
+
'max-bytes': { type: 'string' },
|
|
264
276
|
'allowed-host': { type: 'string', multiple: true },
|
|
265
277
|
proxy: { type: 'string', multiple: true },
|
|
266
278
|
'allow-hosts': { type: 'string', multiple: true },
|
|
@@ -315,6 +327,14 @@ const run = {
|
|
|
315
327
|
async run(v, pos) {
|
|
316
328
|
if (v['respond-stdin'])
|
|
317
329
|
refuseWithRespondStdin(v);
|
|
330
|
+
// A bucket is followed on its own; `--watch` on one only adds live reload, as `--reload` does.
|
|
331
|
+
if (v.watch && pos[0]?.startsWith('bucket:')) {
|
|
332
|
+
for (const f of WATCH_ONLY)
|
|
333
|
+
if (v[f] !== undefined && v[f] !== false)
|
|
334
|
+
usage(`--${f} does not apply to a bucket: the server follows it on its own (--watch only turns on live reload, like --reload)`);
|
|
335
|
+
v.watch = false;
|
|
336
|
+
v.reload ??= '';
|
|
337
|
+
}
|
|
318
338
|
if (v.watch && !v.detach)
|
|
319
339
|
return serveWatch(v, pos);
|
|
320
340
|
// `-d --watch`: a plain directory re-read on change, or a build context built and rebuilt on change,
|
|
@@ -327,7 +347,7 @@ const run = {
|
|
|
327
347
|
if (watchDetached)
|
|
328
348
|
requireArgs(pos, 0, 1, 'a directory');
|
|
329
349
|
else
|
|
330
|
-
requireArgs(pos, 1, 1, 'an image reference, ./directory
|
|
350
|
+
requireArgs(pos, 1, 1, 'an image reference, ./directory, archive file or bucket:name');
|
|
331
351
|
const pollMs = watchDetached ? pollOption(!!v.poll, str(v['poll-interval'])) : undefined;
|
|
332
352
|
const sync = watchDetached ? syncOf(v) : undefined;
|
|
333
353
|
// `--reload` without --watch: the live-reload script and stream, so pages reload after a restart.
|
|
@@ -354,18 +374,29 @@ const run = {
|
|
|
354
374
|
if (name !== undefined && !v.detach)
|
|
355
375
|
usage('--name needs -d (only detached servers are tracked)');
|
|
356
376
|
const store = await Store.open();
|
|
357
|
-
const
|
|
377
|
+
const resolved = watchDetached ? await watchedDirectory(pos[0] ?? '.') : await resolveSource(store, pos[0]);
|
|
378
|
+
const label = resolved.label;
|
|
379
|
+
let source = resolved.source;
|
|
380
|
+
const maxBytes = str(v['max-bytes']);
|
|
381
|
+
if (maxBytes !== undefined) {
|
|
382
|
+
if (source.kind !== 'bucket')
|
|
383
|
+
usage('--max-bytes is for a bucket (bucket:<name>)');
|
|
384
|
+
if (!/^[0-9]{1,15}$/.test(maxBytes) || Number(maxBytes) < 1)
|
|
385
|
+
usage(`--max-bytes expects a number of bytes (at least 1), got '${maxBytes}'`);
|
|
386
|
+
source = { ...source, maxBytes: Number(maxBytes) };
|
|
387
|
+
}
|
|
358
388
|
const watchRecord = watchDetached ? await detachedWatchOf(v, source) : {};
|
|
359
389
|
if (isWildcard(bind.host))
|
|
360
390
|
process.stderr.write(`warning: binding ${bind.host}: the site will be reachable from other machines\n`);
|
|
361
391
|
const keepOsMetadata = !!v['keep-os-metadata'];
|
|
362
392
|
const warn = (m) => void process.stderr.write(`warning: ${m}\n`);
|
|
363
393
|
if (!v.detach) {
|
|
364
|
-
const
|
|
394
|
+
const bucketCache = new Map(); // a bucket server's files read so far (reloads read only what changed)
|
|
395
|
+
const { tree, content, close } = await loadServedSite(store, source, { keepOsMetadata, warn, bucketCache });
|
|
365
396
|
if (profile?.siteFiles !== false)
|
|
366
397
|
checkSiteFiles(tree, strictSiteFiles, warn, content);
|
|
367
398
|
warnSpaFallback(tree, spa.spaFallback, warn);
|
|
368
|
-
|
|
399
|
+
let modified = await servedLastModified(store, source);
|
|
369
400
|
let current = tree;
|
|
370
401
|
const proxy = proxyOption(v);
|
|
371
402
|
const live = reload !== undefined ? new LiveReload({ reload }) : undefined;
|
|
@@ -381,9 +412,27 @@ const run = {
|
|
|
381
412
|
process.stdout.write(`${startedLogLine(new Date().toISOString(), label, tree.size, siteUrl(addr.host, addr.port, base, tls.scheme))}\n`);
|
|
382
413
|
else
|
|
383
414
|
process.stdout.write(`Serving ${label} (${tree.size} files) at ${siteUrl(addr.host, addr.port, base, tls.scheme)} (Ctrl-C to stop)\n${networkLines(addr.host, addr.port, base, tls.scheme)}${throttleLine(throttle?.spec)}`);
|
|
415
|
+
const unfollow = source.kind === 'bucket'
|
|
416
|
+
? followBucket(store, source, {
|
|
417
|
+
reload: async () => {
|
|
418
|
+
const next = await loadServedSite(store, source, { keepOsMetadata, warn, bucketCache });
|
|
419
|
+
if (next.tree.digest() === current.digest())
|
|
420
|
+
return;
|
|
421
|
+
if (profile?.siteFiles !== false)
|
|
422
|
+
checkSiteFiles(next.tree, strictSiteFiles, warn, next.content);
|
|
423
|
+
const event = live ? (reloadEventFor(current, next.tree, true, false) ?? OK_EVENT) : undefined;
|
|
424
|
+
current = next.tree;
|
|
425
|
+
modified = await servedLastModified(store, source);
|
|
426
|
+
if (event !== undefined)
|
|
427
|
+
live?.send(event);
|
|
428
|
+
process.stdout.write(`Re-read ${label} (${current.size} files)\n`);
|
|
429
|
+
},
|
|
430
|
+
onError: (e) => warn(`${label}: ${e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : e.message}; serving the last good copy`),
|
|
431
|
+
})
|
|
432
|
+
: undefined;
|
|
384
433
|
const quit = await terminal(v, addr, base, tls.scheme, warn, async () => {
|
|
385
434
|
if (source.kind !== 'dir') {
|
|
386
|
-
process.stdout.write(`Nothing to re-read: ${label} is ${source.kind === 'image' ? 'an image' : 'an archive file'}; start serve again to read it again\n`);
|
|
435
|
+
process.stdout.write(`Nothing to re-read: ${label} is ${source.kind === 'image' ? 'an image' : source.kind === 'bucket' ? 'a bucket, followed on its own' : 'an archive file'}; ${source.kind === 'bucket' ? 'changes are picked up within a second' : 'start serve again to read it again'}\n`);
|
|
387
436
|
return;
|
|
388
437
|
}
|
|
389
438
|
const next = await loadServedSite(store, source, { keepOsMetadata, warn });
|
|
@@ -398,6 +447,7 @@ const run = {
|
|
|
398
447
|
if (why === 'stop-after')
|
|
399
448
|
process.stdout.write(`Stopping: --stop-after ${stop.text} reached\n`);
|
|
400
449
|
quit.stop();
|
|
450
|
+
unfollow?.();
|
|
401
451
|
await closeServer(server);
|
|
402
452
|
close();
|
|
403
453
|
return 0;
|
package/lib/src/cli/up.js
CHANGED
|
@@ -14,6 +14,8 @@ const PATH_LIKE = /^(\.\.?|~.*|\.\.?\/.*|\/.*|.*\/)$/;
|
|
|
14
14
|
* an image reference or ID, else an archive file by that name next to the file.
|
|
15
15
|
*/
|
|
16
16
|
async function fileSource(store, dir, src) {
|
|
17
|
+
if (src.startsWith('bucket:'))
|
|
18
|
+
return resolveSource(store, src);
|
|
17
19
|
if (PATH_LIKE.test(src))
|
|
18
20
|
return resolveSource(store, path.resolve(dir, src));
|
|
19
21
|
try {
|
package/lib/src/servers.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { SiteContent } from './server.js';
|
|
|
2
2
|
import { type ArchiveLimits } from './resources/types.js';
|
|
3
3
|
import { Store } from './store.js';
|
|
4
4
|
import { Tree } from './tree.js';
|
|
5
|
+
import { type BucketReadCache } from './bucket.js';
|
|
5
6
|
import type { CachePreview } from './server.js';
|
|
6
7
|
import type { AuthEntry } from './serve-auth.js';
|
|
7
8
|
/**
|
|
@@ -46,6 +47,13 @@ export interface ServerState {
|
|
|
46
47
|
| {
|
|
47
48
|
readonly kind: 'archive';
|
|
48
49
|
readonly path: string;
|
|
50
|
+
}
|
|
51
|
+
/** A bucket of the store (and a directory of it), read by name; the server follows its changes. */
|
|
52
|
+
| {
|
|
53
|
+
readonly kind: 'bucket';
|
|
54
|
+
readonly name: string;
|
|
55
|
+
readonly prefix?: string; /** `--max-bytes`: most bytes held in memory (absent: the default). */
|
|
56
|
+
readonly maxBytes?: number;
|
|
49
57
|
};
|
|
50
58
|
readonly spa: boolean;
|
|
51
59
|
/** `--spa-exclude`: request paths that never fall back (absent: none). */
|
|
@@ -167,6 +175,8 @@ export interface ServedTreeOptions {
|
|
|
167
175
|
readonly keepOsMetadata?: boolean;
|
|
168
176
|
/** Told how many OS metadata files were skipped. */
|
|
169
177
|
readonly warn?: (message: string) => void;
|
|
178
|
+
/** A bucket server's files read so far: a reload reads only the files that changed and shares the rest. */
|
|
179
|
+
readonly bucketCache?: BucketReadCache;
|
|
170
180
|
}
|
|
171
181
|
/**
|
|
172
182
|
* Load a directory into a Tree through the sandboxed local reader; hidden files (except .well-known)
|
package/lib/src/servers.js
CHANGED
|
@@ -13,6 +13,7 @@ import { LocalContext } from './resources/local.js';
|
|
|
13
13
|
import { DEFAULT_ARCHIVE_LIMITS } from './resources/types.js';
|
|
14
14
|
import { Store } from './store.js';
|
|
15
15
|
import { Tree } from './tree.js';
|
|
16
|
+
import { bucketLabel, Buckets, scanDirectory } from './bucket.js';
|
|
16
17
|
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/;
|
|
17
18
|
export class ServerRegistry {
|
|
18
19
|
store;
|
|
@@ -305,6 +306,11 @@ export async function loadServedTree(store, source, options = {}) {
|
|
|
305
306
|
return loadDirectoryTree(source.path, options);
|
|
306
307
|
case 'archive':
|
|
307
308
|
return loadArchiveTree(source.path, DEFAULT_ARCHIVE_LIMITS, options);
|
|
309
|
+
case 'bucket':
|
|
310
|
+
return served(await Buckets.open(store).loadTree(source.name, source.prefix === undefined ? [] : source.prefix.split('/'), {
|
|
311
|
+
...(options.bucketCache ? { cache: options.bucketCache } : {}),
|
|
312
|
+
...(source.maxBytes !== undefined ? { maxBytes: source.maxBytes } : {}),
|
|
313
|
+
}), bucketLabel(source.name, source.prefix), options);
|
|
308
314
|
}
|
|
309
315
|
}
|
|
310
316
|
/**
|
|
@@ -355,6 +361,20 @@ export async function servedLastModified(store, source) {
|
|
|
355
361
|
await walk(source.path);
|
|
356
362
|
return newest;
|
|
357
363
|
}
|
|
364
|
+
case 'bucket': {
|
|
365
|
+
const b = Buckets.open(store);
|
|
366
|
+
const prefix = source.prefix === undefined ? [] : source.prefix.split('/');
|
|
367
|
+
const dir = await b.resolveDirectory(source.name, prefix).catch(() => undefined);
|
|
368
|
+
if (dir === undefined)
|
|
369
|
+
return undefined;
|
|
370
|
+
let newest;
|
|
371
|
+
for (const f of await scanDirectory(dir, source.name, prefix).catch(() => [])) {
|
|
372
|
+
if (f.path.split('/').some((seg) => seg.startsWith('.') && seg !== '.well-known'))
|
|
373
|
+
continue;
|
|
374
|
+
newest = Math.max(newest ?? 0, secs(f.st.mtimeMs));
|
|
375
|
+
}
|
|
376
|
+
return newest;
|
|
377
|
+
}
|
|
358
378
|
}
|
|
359
379
|
}
|
|
360
380
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/sitefile",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.9",
|
|
4
4
|
"description": "Docker-inspired static artifact builder: compose immutable file trees from local and remote sources, render templates, and export a deployable site. No container runtime, no shell, no runtime dependencies.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"static-site",
|