@johnhenry/sitefile 0.0.2 → 0.0.3

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.
Files changed (130) hide show
  1. package/CHANGELOG.md +467 -0
  2. package/README.md +55 -6
  3. package/lib/src/archive-writers.d.ts +12 -2
  4. package/lib/src/archive-writers.js +53 -10
  5. package/lib/src/canonical.d.ts +16 -0
  6. package/lib/src/canonical.js +46 -0
  7. package/lib/src/car.d.ts +34 -0
  8. package/lib/src/car.js +203 -0
  9. package/lib/src/checklinks.js +8 -2
  10. package/lib/src/cli/bake.js +4 -3
  11. package/lib/src/cli/build-image.d.ts +1 -0
  12. package/lib/src/cli/build-image.js +1 -0
  13. package/lib/src/cli/common.js +4 -1
  14. package/lib/src/cli/hosts.d.ts +5 -0
  15. package/lib/src/cli/hosts.js +78 -0
  16. package/lib/src/cli/images.js +23 -5
  17. package/lib/src/cli/import-config.d.ts +2 -0
  18. package/lib/src/cli/import-config.js +56 -0
  19. package/lib/src/cli/index.d.ts +3 -1
  20. package/lib/src/cli/index.js +31 -2
  21. package/lib/src/cli/integrity.d.ts +2 -0
  22. package/lib/src/cli/integrity.js +77 -0
  23. package/lib/src/cli/network.d.ts +7 -0
  24. package/lib/src/cli/network.js +14 -3
  25. package/lib/src/cli/serve-keys.d.ts +39 -0
  26. package/lib/src/cli/serve-keys.js +106 -0
  27. package/lib/src/cli/serve-worker.js +46 -8
  28. package/lib/src/cli/servers.d.ts +124 -1
  29. package/lib/src/cli/servers.js +705 -62
  30. package/lib/src/cli/up.d.ts +2 -0
  31. package/lib/src/cli/up.js +193 -0
  32. package/lib/src/cli/watch.d.ts +14 -1
  33. package/lib/src/cli/watch.js +20 -3
  34. package/lib/src/cli.js +138 -18
  35. package/lib/src/csp.d.ts +17 -0
  36. package/lib/src/csp.js +52 -0
  37. package/lib/src/dictionary.d.ts +16 -0
  38. package/lib/src/dictionary.js +89 -0
  39. package/lib/src/epub.d.ts +5 -0
  40. package/lib/src/epub.js +113 -0
  41. package/lib/src/errors.d.ts +22 -9
  42. package/lib/src/errors.js +20 -1
  43. package/lib/src/executor.d.ts +31 -1
  44. package/lib/src/executor.js +192 -22
  45. package/lib/src/explain.js +33 -3
  46. package/lib/src/export-for.d.ts +42 -0
  47. package/lib/src/export-for.js +466 -0
  48. package/lib/src/export-formats.d.ts +2 -2
  49. package/lib/src/export-formats.js +52 -2
  50. package/lib/src/fingerprint.d.ts +3 -1
  51. package/lib/src/fingerprint.js +32 -5
  52. package/lib/src/host-config.d.ts +34 -0
  53. package/lib/src/host-config.js +645 -0
  54. package/lib/src/hosts.d.ts +47 -0
  55. package/lib/src/hosts.js +106 -0
  56. package/lib/src/index.d.ts +1 -1
  57. package/lib/src/index.js +1 -1
  58. package/lib/src/integrity.d.ts +115 -0
  59. package/lib/src/integrity.js +273 -0
  60. package/lib/src/language/ast.d.ts +116 -3
  61. package/lib/src/language/ast.js +7 -1
  62. package/lib/src/language/parser.js +176 -7
  63. package/lib/src/language/validate.js +21 -0
  64. package/lib/src/links.d.ts +33 -0
  65. package/lib/src/links.js +271 -3
  66. package/lib/src/lint.d.ts +1 -1
  67. package/lib/src/lint.js +26 -1
  68. package/lib/src/mime-data.d.ts +2 -0
  69. package/lib/src/mime-data.js +92 -0
  70. package/lib/src/oci.d.ts +20 -2
  71. package/lib/src/oci.js +70 -28
  72. package/lib/src/outdated.d.ts +3 -0
  73. package/lib/src/outdated.js +4 -4
  74. package/lib/src/planner.d.ts +69 -2
  75. package/lib/src/planner.js +150 -8
  76. package/lib/src/plugins/cache.d.ts +11 -0
  77. package/lib/src/plugins/cache.js +29 -0
  78. package/lib/src/plugins/host.d.ts +51 -2
  79. package/lib/src/plugins/host.js +141 -16
  80. package/lib/src/plugins/wasm.js +1 -3
  81. package/lib/src/portable.d.ts +8 -0
  82. package/lib/src/portable.js +47 -0
  83. package/lib/src/precache.d.ts +33 -0
  84. package/lib/src/precache.js +75 -0
  85. package/lib/src/precompress.d.ts +19 -0
  86. package/lib/src/precompress.js +35 -0
  87. package/lib/src/qr.d.ts +18 -0
  88. package/lib/src/qr.js +372 -0
  89. package/lib/src/registry-ops.js +4 -2
  90. package/lib/src/reload-client.d.ts +2 -0
  91. package/lib/src/reload-client.js +304 -0
  92. package/lib/src/resources/archive.d.ts +36 -0
  93. package/lib/src/resources/archive.js +338 -67
  94. package/lib/src/resources/convert.js +3 -1
  95. package/lib/src/resources/https.d.ts +9 -1
  96. package/lib/src/resources/https.js +36 -0
  97. package/lib/src/resources/network.d.ts +25 -3
  98. package/lib/src/resources/network.js +77 -6
  99. package/lib/src/secrets.d.ts +12 -3
  100. package/lib/src/secrets.js +18 -5
  101. package/lib/src/serve-auth.d.ts +32 -0
  102. package/lib/src/serve-auth.js +112 -0
  103. package/lib/src/serve-rules.d.ts +83 -7
  104. package/lib/src/serve-rules.js +264 -53
  105. package/lib/src/server.d.ts +437 -10
  106. package/lib/src/server.js +1236 -52
  107. package/lib/src/servers-file.d.ts +36 -0
  108. package/lib/src/servers-file.js +101 -0
  109. package/lib/src/servers.d.ts +109 -7
  110. package/lib/src/servers.js +151 -29
  111. package/lib/src/single-file.d.ts +12 -0
  112. package/lib/src/single-file.js +147 -0
  113. package/lib/src/site.d.ts +54 -0
  114. package/lib/src/site.js +204 -6
  115. package/lib/src/store.js +9 -5
  116. package/lib/src/swbn.d.ts +10 -0
  117. package/lib/src/swbn.js +86 -0
  118. package/lib/src/toml.d.ts +17 -0
  119. package/lib/src/toml.js +323 -0
  120. package/lib/src/wacz.d.ts +6 -0
  121. package/lib/src/wacz.js +96 -0
  122. package/lib/src/warc.d.ts +28 -0
  123. package/lib/src/warc.js +252 -0
  124. package/lib/src/watch.d.ts +12 -1
  125. package/lib/src/watch.js +67 -1
  126. package/lib/src/wbn.d.ts +9 -1
  127. package/lib/src/wbn.js +23 -33
  128. package/lib/src/zstd.d.ts +4 -0
  129. package/lib/src/zstd.js +328 -0
  130. package/package.json +1 -1
@@ -0,0 +1,2 @@
1
+ import { type Command } from './common.js';
2
+ export declare const importConfigCommands: ReadonlyMap<string, Command>;
@@ -0,0 +1,56 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { SitefileError } from '../errors.js';
3
+ import { formatOf, headersText, HOST_FORMATS, importHostConfig, redirectsText } from '../host-config.js';
4
+ import { requireArgs, str, usage } from './common.js';
5
+ const importConfig = {
6
+ name: 'import-config',
7
+ summary: "translate a host's config file into _redirects and _headers",
8
+ usage: 'import-config <file> [--format f] [--redirects | --headers] [--json]',
9
+ description: "Read netlify.toml, vercel.json, firebase.json, staticwebapp.config.json, wrangler.toml / wrangler.json\n([assets]) or .htaccess, and print the _redirects and _headers that sitefile serve understands today.\nEvery rule printed is one serve applies as written; anything else (placeholders, conditions, proxying,\nregular expressions, settings with no _redirects form) is listed on stderr as a warning, never half\ntranslated. The format comes from the file name unless --format is given.",
10
+ flags: [
11
+ `--format <f> ${HOST_FORMATS.join(', ')}`,
12
+ '--redirects print only the _redirects text',
13
+ '--headers print only the _headers text',
14
+ '--json machine-readable output (rules and unsupported entries)',
15
+ ],
16
+ options: { format: { type: 'string' }, redirects: { type: 'boolean' }, headers: { type: 'boolean' }, json: { type: 'boolean' } },
17
+ async run(v, pos) {
18
+ requireArgs(pos, 1, 1, 'a host config file');
19
+ const file = pos[0];
20
+ const given = str(v.format);
21
+ if (given !== undefined && !HOST_FORMATS.includes(given))
22
+ usage(`--format expects one of ${HOST_FORMATS.join(', ')}, got '${given}'`);
23
+ const format = given ?? formatOf(file);
24
+ if (format === undefined)
25
+ usage(`cannot tell the format of '${file}' from its name; pass --format (${HOST_FORMATS.join(', ')})`);
26
+ if (v.redirects && v.headers)
27
+ usage('--redirects and --headers conflict');
28
+ if (v.json && (v.redirects || v.headers))
29
+ usage('--json prints both; drop --redirects/--headers');
30
+ let text;
31
+ try {
32
+ text = await readFile(file, 'utf8');
33
+ }
34
+ catch (e) {
35
+ throw new SitefileError('E_NOT_FOUND', `cannot read '${file}'`, undefined, { cause: e });
36
+ }
37
+ const c = importHostConfig(text, file, format);
38
+ if (v.json) {
39
+ process.stdout.write(JSON.stringify({ format: c.format, redirects: c.redirects, headers: c.headers.map((b) => ({ pattern: b.pattern, headers: b.headers })), unsupported: c.unsupported }, null, 2) + '\n');
40
+ return 0;
41
+ }
42
+ for (const u of c.unsupported)
43
+ process.stderr.write(`warning: ${file}: ${u.entry}: ${u.reason}\n`);
44
+ const r = redirectsText(c);
45
+ const h = headersText(c);
46
+ if (v.redirects)
47
+ process.stdout.write(r);
48
+ else if (v.headers)
49
+ process.stdout.write(h);
50
+ else
51
+ process.stdout.write(`${r ? `# _redirects\n${r}` : ''}${r && h ? '\n' : ''}${h ? `# _headers\n${h}` : ''}`);
52
+ return 0;
53
+ },
54
+ };
55
+ export const importConfigCommands = new Map([['import-config', importConfig]]);
56
+ //# sourceMappingURL=import-config.js.map
@@ -5,6 +5,8 @@ export declare const EXTRA_COMMANDS: readonly string[];
5
5
  * an editor tool. Here `sitefile lsp` is a usage error that points there.
6
6
  */
7
7
  export declare const LSP_UNAVAILABLE = "'sitefile lsp' (the language server) is provided by the Rust implementation: build it with 'cd rust && cargo build --release' and run 'rust/target/release/sitefile lsp' (see docs/LSP.md)";
8
- export declare const EXTRA_HELP = "\nImages (local store: $SITEFILE_HOME or ~/.sitefile):\n sitefile build [context] -t name[:tag] also store the result as an image (repeatable -t)\n sitefile images [--json] [--digests] [-q] list images (alias: image ls)\n sitefile image inspect <ref> [--json] show an image manifest\n sitefile image prune delete unreferenced manifests and blobs\n sitefile image diff <a> <b> added/removed/changed paths\n sitefile tag <src> <dst> add a name:tag\n sitefile rmi [-f] <ref|id>... remove tags / images\n sitefile save <ref> -o out[.zip|.tar|.tar.gz|.wbn] export an image\n sitefile push <registry/name[:tag]> push a (tagged) image to an OCI registry\n sitefile pull <[registry/]name[:tag][@digest]> pull an image (a bare name means Docker Hub)\n\nVariants:\n sitefile bake [targets...] [-f file] [--print] build several targets (matrix, groups) from\n sitefile.bake.yaml; --print shows the plan\n\nOffline builds:\n sitefile vendor [context] [--vendor-dir dir] download remote imports and the BASE image into\n vendor/sitefile; builds then read them from there\n\nPins:\n sitefile outdated [context] [--json] compare remote imports and the BASE image with\n their pins (never changes anything)\n\nBuild cache (TRANSFORM results: $SITEFILE_HOME/cache/transform):\n sitefile cache info [--json] location, entries, size\n sitefile cache prune [--older-than <days>] delete cached results\n sitefile cache prune --max-size <size> shrink evictable data (LRU) to <size>\n sitefile cache du [--json] size of every cache and the store (alias: cache ls)\n Evictable data over $SITEFILE_CACHE_MAX (default 1GiB, 0 = no limit) is deleted after each build.\n\nServing sites (detached servers are tracked by name):\n sitefile serve [--name n] [-p [host:]port] [-d] [--spa] <ref|./dir|file>\n sitefile serve --watch [-p [host:]port] [ctx] build in memory, serve, rebuild + live reload\n sitefile servers [-a] [--json] list servers (alias: server ls)\n sitefile server stop|rm [-f]|restart|logs [-f] <name|id>\n\nEditor support:\n sitefile lsp [--stdio] language server over stdio (Rust build only; docs/LSP.md)\n\nRun 'sitefile <command> --help' for the options of a command.\n";
8
+ export declare const EXTRA_HELP = "\nImages (local store: $SITEFILE_HOME or ~/.sitefile):\n sitefile build [context] -t name[:tag] also store the result as an image (repeatable -t)\n sitefile images [--json] [--digests] [-q] list images (alias: image ls)\n sitefile image inspect <ref> [--json] show an image manifest\n sitefile image prune delete unreferenced manifests and blobs\n sitefile image diff <a> <b> added/removed/changed paths\n sitefile tag <src> <dst> add a name:tag\n sitefile rmi [-f] <ref|id>... remove tags / images\n sitefile save <ref> -o out[.zip|.tar|.tar.gz|.wbn] export an image\n sitefile push <registry/name[:tag]> push a (tagged) image to an OCI registry\n sitefile pull <[registry/]name[:tag][@digest]> pull an image (a bare name means Docker Hub)\n\nIntegrity:\n sitefile build [context] --manifest m.json also write a manifest: every file's size and SHA-256,\n and their Merkle root (save --manifest too)\n sitefile verify <dir|archive|ref> --manifest m.json check a deployed or extracted copy: missing,\n changed and extra files (exit 1 on any)\n sitefile diff <a> <b> [--json] files added, removed and changed between two images,\n directories or archives, and _redirects/_headers rules\n\nVariants:\n sitefile bake [targets...] [-f file] [--print] build several targets (matrix, groups) from\n sitefile.bake.yaml; --print shows the plan\n\nHost config files:\n sitefile import-config <file> [--json] translate netlify.toml, vercel.json, firebase.json,\n staticwebapp.config.json, wrangler.toml or .htaccess\n into _redirects and _headers\n\nOffline builds:\n sitefile vendor [context] [--vendor-dir dir] download remote imports and the BASE image into\n vendor/sitefile; builds then read them from there\n\nPins:\n sitefile outdated [context] [--json] compare remote imports and the BASE image with\n their pins (never changes anything)\n\nNetwork:\n sitefile hosts [context] [--json] list the hosts a build would contact and whether\n --allow-hosts/--network strict allow them (no fetch)\n\nBuild cache (TRANSFORM results: $SITEFILE_HOME/cache/transform):\n sitefile cache info [--json] location, entries, size\n sitefile cache prune [--older-than <days>] delete cached results\n sitefile cache prune --max-size <size> shrink evictable data (LRU) to <size>\n sitefile cache du [--json] size of every cache and the store (alias: cache ls)\n Evictable data over $SITEFILE_CACHE_MAX (default 1GiB, 0 = no limit) is deleted after each build.\n\nServing sites (detached servers are tracked by name):\n sitefile serve [--name n] [-p [host:]port] [-d] [--spa] <ref|./dir|file>\n sitefile serve --watch [-p [host:]port] [ctx] build in memory, serve, rebuild + live reload\n sitefile servers [-a] [--json] list servers (alias: server ls)\n sitefile server stop|rm [-f]|restart|logs [-f] <name|id>\n sitefile up [-f sitefile.servers.yaml] start every server of a servers file (detached, idempotent)\n sitefile down [-f file] stop and remove the servers it started\n sitefile ps [-f file] [--json] list them: running, exited or not created\n\nEditor support:\n sitefile lsp [--stdio] language server over stdio (Rust build only; docs/LSP.md)\n\nRun 'sitefile <command> --help' for the options of a command.\n";
9
9
  export declare function isExtraCommand(name: string | undefined): boolean;
10
10
  export declare function runExtraCommand(argv: readonly string[]): Promise<number>;
11
+ /** `serve --open` takes its path only as `--open=<path>`: a bare `--open` (before `--`) is `--open=`. */
12
+ export declare function optionalOpen(args: readonly string[]): string[];
@@ -5,12 +5,16 @@ import { serverCommands, serverSubcommands } from './servers.js';
5
5
  import { cacheSubcommands } from './cache.js';
6
6
  import { vendorCommands } from './vendor.js';
7
7
  import { outdatedCommands } from './outdated.js';
8
+ import { hostsCommands } from './hosts.js';
8
9
  import { bakeCommands } from './bake.js';
10
+ import { upCommands } from './up.js';
11
+ import { importConfigCommands } from './import-config.js';
12
+ import { integrityCommands } from './integrity.js';
9
13
  /**
10
14
  * Image-store and site-server commands. They live outside cli.ts' build/validate/inspect
11
15
  * parser: each has its own options and `--help`.
12
16
  */
13
- const TOP = new Map([...imageCommands, ...serverCommands, ...registryCommands, ...vendorCommands, ...outdatedCommands, ...bakeCommands].filter(([k]) => !k.includes(' ')));
17
+ const TOP = new Map([...imageCommands, ...serverCommands, ...registryCommands, ...vendorCommands, ...outdatedCommands, ...hostsCommands, ...bakeCommands, ...integrityCommands, ...upCommands, ...importConfigCommands].filter(([k]) => !k.includes(' ')));
14
18
  export const EXTRA_COMMANDS = [...TOP.keys(), 'image', 'server', 'cache', 'lsp'];
15
19
  /**
16
20
  * The language server exists only in the Rust implementation (a tooling
@@ -31,10 +35,23 @@ Images (local store: $SITEFILE_HOME or ~/.sitefile):
31
35
  sitefile push <registry/name[:tag]> push a (tagged) image to an OCI registry
32
36
  sitefile pull <[registry/]name[:tag][@digest]> pull an image (a bare name means Docker Hub)
33
37
 
38
+ Integrity:
39
+ sitefile build [context] --manifest m.json also write a manifest: every file's size and SHA-256,
40
+ and their Merkle root (save --manifest too)
41
+ sitefile verify <dir|archive|ref> --manifest m.json check a deployed or extracted copy: missing,
42
+ changed and extra files (exit 1 on any)
43
+ sitefile diff <a> <b> [--json] files added, removed and changed between two images,
44
+ directories or archives, and _redirects/_headers rules
45
+
34
46
  Variants:
35
47
  sitefile bake [targets...] [-f file] [--print] build several targets (matrix, groups) from
36
48
  sitefile.bake.yaml; --print shows the plan
37
49
 
50
+ Host config files:
51
+ sitefile import-config <file> [--json] translate netlify.toml, vercel.json, firebase.json,
52
+ staticwebapp.config.json, wrangler.toml or .htaccess
53
+ into _redirects and _headers
54
+
38
55
  Offline builds:
39
56
  sitefile vendor [context] [--vendor-dir dir] download remote imports and the BASE image into
40
57
  vendor/sitefile; builds then read them from there
@@ -43,6 +60,10 @@ Pins:
43
60
  sitefile outdated [context] [--json] compare remote imports and the BASE image with
44
61
  their pins (never changes anything)
45
62
 
63
+ Network:
64
+ sitefile hosts [context] [--json] list the hosts a build would contact and whether
65
+ --allow-hosts/--network strict allow them (no fetch)
66
+
46
67
  Build cache (TRANSFORM results: $SITEFILE_HOME/cache/transform):
47
68
  sitefile cache info [--json] location, entries, size
48
69
  sitefile cache prune [--older-than <days>] delete cached results
@@ -55,6 +76,9 @@ Serving sites (detached servers are tracked by name):
55
76
  sitefile serve --watch [-p [host:]port] [ctx] build in memory, serve, rebuild + live reload
56
77
  sitefile servers [-a] [--json] list servers (alias: server ls)
57
78
  sitefile server stop|rm [-f]|restart|logs [-f] <name|id>
79
+ sitefile up [-f sitefile.servers.yaml] start every server of a servers file (detached, idempotent)
80
+ sitefile down [-f file] stop and remove the servers it started
81
+ sitefile ps [-f file] [--json] list them: running, exited or not created
58
82
 
59
83
  Editor support:
60
84
  sitefile lsp [--stdio] language server over stdio (Rust build only; docs/LSP.md)
@@ -90,6 +114,11 @@ export async function runExtraCommand(argv) {
90
114
  const cmd = name === undefined ? undefined : TOP.get(name);
91
115
  if (!cmd)
92
116
  return usageError(`unknown command '${name ?? ''}'`);
93
- return runCommand(cmd, rest);
117
+ return runCommand(cmd, name === 'serve' ? optionalOpen(rest) : rest);
118
+ }
119
+ /** `serve --open` takes its path only as `--open=<path>`: a bare `--open` (before `--`) is `--open=`. */
120
+ export function optionalOpen(args) {
121
+ const end = args.indexOf('--');
122
+ return args.map((a, i) => (a === '--open' && (end === -1 || i < end) ? '--open=' : a));
94
123
  }
95
124
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ import { type Command } from './common.js';
2
+ export declare const integrityCommands: ReadonlyMap<string, Command>;
@@ -0,0 +1,77 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { SitefileError } from '../errors.js';
3
+ import { diffText, diffTrees, loadTarget, manifestOf, parseManifest, pathInside, resolveTarget, verifyText, verifyTree } from '../integrity.js';
4
+ import { Store } from '../store.js';
5
+ import { requireArgs, str, usage } from './common.js';
6
+ const openStore = () => {
7
+ let s;
8
+ return () => (s ??= Store.open());
9
+ };
10
+ const verify = {
11
+ name: 'verify',
12
+ summary: 'check a directory, archive or image against a file manifest',
13
+ usage: 'verify <dir|archive|ref|id> [--manifest <file>] [--json]',
14
+ description: 'Compare a deployed or extracted copy with the manifest written by "build --manifest" or "save --manifest":\nevery file the manifest lists must be there with the same size and SHA-256, and no other file may be.\nPrints one line per difference (missing, changed, extra) and fails with E_INTEGRITY when there is any.\nA directory is read like a build context (hidden files count; .git is skipped); an archive is read from\nits bytes (zip, tar, tar.gz, wbn, OCI archive). A manifest file inside the verified directory is not\ncounted as extra. Without --manifest the target must be an image: its stored blobs are checked.',
15
+ flags: ['--manifest <file> the manifest to check against (JSON, see docs/CLI.md)', '--json machine-readable report'],
16
+ options: { manifest: { type: 'string' }, json: { type: 'boolean' } },
17
+ async run(v, pos) {
18
+ requireArgs(pos, 1, 1, 'a directory, archive file or image reference');
19
+ const arg = pos[0];
20
+ const store = openStore();
21
+ const target = await resolveTarget(arg, store);
22
+ const manifestFile = str(v.manifest);
23
+ if (manifestFile === '')
24
+ usage('--manifest expects a file path');
25
+ if (manifestFile === undefined && target.kind !== 'image')
26
+ usage('verify needs --manifest <file> for a directory or an archive');
27
+ const tree = await loadTarget(target, store);
28
+ let manifest;
29
+ let ignore;
30
+ if (manifestFile !== undefined) {
31
+ const bytes = await fs.readFile(manifestFile).catch((e) => {
32
+ throw new SitefileError(e.code === 'ENOENT' ? 'E_NOT_FOUND' : 'E_INTEGRITY', `cannot read the manifest '${manifestFile}'`);
33
+ });
34
+ manifest = parseManifest(new Uint8Array(bytes), manifestFile);
35
+ if (target.kind === 'dir')
36
+ ignore = await pathInside(target.path, manifestFile);
37
+ }
38
+ else {
39
+ manifest = manifestOf(tree); // loadTree checked every blob against its digest
40
+ }
41
+ const r = verifyTree(tree, manifest, ignore);
42
+ process.stdout.write(v.json ? JSON.stringify(r, null, 2) + '\n' : r.ok ? `OK: ${r.files} file${r.files === 1 ? '' : 's'} match ${r.root}\n` : verifyText(r));
43
+ if (!r.ok) {
44
+ const message = `'${arg}' does not match the manifest: ${r.missing.length} missing, ${r.changed.length} changed, ${r.extra.length} extra`;
45
+ // With --json the report above is the one document on stdout (it already says ok: false),
46
+ // so the error goes to stderr only instead of through the generic --json error output.
47
+ if (v.json) {
48
+ process.stderr.write(`error[E_INTEGRITY]: ${message}\n`);
49
+ return 1;
50
+ }
51
+ throw new SitefileError('E_INTEGRITY', message);
52
+ }
53
+ return 0;
54
+ },
55
+ };
56
+ const diff = {
57
+ name: 'diff',
58
+ summary: 'files changed between two images, directories or archives',
59
+ usage: 'diff <a> <b> [--json] [--exit-code]',
60
+ description: 'List the files added (A), removed (D) and changed (C: content or mode) going from <a> to <b>, with their\nsizes, then the rules added (+) and removed (-) in _redirects and _headers. Each side is a directory, an\narchive file (zip, tar, tar.gz, wbn, OCI archive) or an image reference or ID, read as "sitefile verify"\nreads it (hidden files count). Digests, not timestamps, decide what changed.',
61
+ flags: ['--json machine-readable report (sizes in bytes, digests, modes)', '--exit-code exit 1 when the two differ (default 0 either way)'],
62
+ options: { json: { type: 'boolean' }, 'exit-code': { type: 'boolean' } },
63
+ async run(v, pos) {
64
+ requireArgs(pos, 2, 2, 'two images, directories or archive files');
65
+ const store = openStore();
66
+ const [a, b] = [await resolveTarget(pos[0], store), await resolveTarget(pos[1], store)];
67
+ const r = diffTrees(await loadTarget(a, store), await loadTarget(b, store));
68
+ process.stdout.write(v.json ? JSON.stringify(r, null, 2) + '\n' : diffText(r));
69
+ const same = !r.added.length && !r.removed.length && !r.changed.length && !Object.keys(r.rules).length;
70
+ return v['exit-code'] && !same ? 1 : 0;
71
+ },
72
+ };
73
+ export const integrityCommands = new Map([
74
+ ['verify', verify],
75
+ ['diff', diff],
76
+ ]);
77
+ //# sourceMappingURL=integrity.js.map
@@ -16,6 +16,13 @@ export declare const NETWORK_OPTIONS: {
16
16
  readonly type: 'string';
17
17
  readonly multiple: true;
18
18
  };
19
+ readonly network: {
20
+ readonly type: 'string';
21
+ };
22
+ readonly 'allow-secret-host': {
23
+ readonly type: 'string';
24
+ readonly multiple: true;
25
+ };
19
26
  readonly 'connect-timeout': {
20
27
  readonly type: 'string';
21
28
  };
@@ -1,11 +1,13 @@
1
1
  import { SitefileError } from '../errors.js';
2
- import { mergeNetwork, networkFromEnv, networkProblem, splitList } from '../resources/network.js';
2
+ import { mergeNetwork, networkFromEnv, networkProblem, parseNetworkMode, splitList } from '../resources/network.js';
3
3
  /** parseArgs options for the network flags (build, validate, inspect, graph, why, pull, push, vendor, outdated). */
4
4
  export const NETWORK_OPTIONS = {
5
5
  proxy: { type: 'string' },
6
6
  'no-proxy': { type: 'string', multiple: true },
7
7
  'allow-hosts': { type: 'string', multiple: true },
8
8
  'deny-hosts': { type: 'string', multiple: true },
9
+ network: { type: 'string' },
10
+ 'allow-secret-host': { type: 'string', multiple: true },
9
11
  'connect-timeout': { type: 'string' },
10
12
  'read-timeout': { type: 'string' },
11
13
  };
@@ -16,12 +18,17 @@ export function networkHelp(width) {
16
18
  ['--no-proxy <hosts>', ['hosts reached directly, not through the proxy (NO_PROXY syntax; repeatable,', 'comma-separated; also $SITEFILE_NO_PROXY)']],
17
19
  ['--allow-hosts <hosts>', ['contact only hosts matching these patterns (repeatable, comma-separated;', 'also $SITEFILE_ALLOW_HOSTS)']],
18
20
  ['--deny-hosts <hosts>', ['never contact hosts matching these patterns; beats --allow-hosts', '(repeatable, comma-separated; also $SITEFILE_DENY_HOSTS)']],
21
+ ['--network <mode>', ['open (default) or strict: every host must match --allow-hosts, even with none', 'given (also $SITEFILE_NETWORK)']],
22
+ ['--allow-secret-host <id=host>', ['in strict mode, let IMPORT ... SECRET <id> send its secret to this host', '(a host pattern; repeatable)']],
19
23
  ['--connect-timeout <ms>', ['time limit for opening each connection (also $SITEFILE_FETCH_TIMEOUT)']],
20
24
  ['--read-timeout <ms>', ['longest wait for data on a connection (also $SITEFILE_FETCH_TIMEOUT)']],
21
25
  ];
22
26
  const out = [];
23
27
  for (const [flag, lines] of rows) {
24
- lines.forEach((l, i) => out.push(`${(i === 0 ? flag : '').padEnd(width)}${l}`));
28
+ // A flag wider than the column gets a line of its own.
29
+ if (flag.length >= width)
30
+ out.push(flag);
31
+ lines.forEach((l, i) => out.push(`${(i === 0 && flag.length < width ? flag : '').padEnd(width)}${l}`));
25
32
  }
26
33
  return out;
27
34
  }
@@ -44,10 +51,14 @@ export function networkOption(v, env = process.env) {
44
51
  noProxy: strings(v['no-proxy']).flatMap(splitList),
45
52
  allowHosts: strings(v['allow-hosts']).flatMap(splitList),
46
53
  denyHosts: strings(v['deny-hosts']).flatMap(splitList),
54
+ secretHosts: strings(v['allow-secret-host']).flatMap(splitList),
47
55
  connectTimeoutMs: ms(typeof v['connect-timeout'] === 'string' ? v['connect-timeout'] : undefined, '--connect-timeout'),
48
56
  readTimeoutMs: ms(typeof v['read-timeout'] === 'string' ? v['read-timeout'] : undefined, '--read-timeout'),
49
57
  };
50
- const merged = mergeNetwork(networkFromEnv(env), flags);
58
+ const fromEnv = networkFromEnv(env);
59
+ // --network replaces SITEFILE_NETWORK (--network open turns an inherited strict mode off).
60
+ const mode = typeof v.network === 'string' ? (parseNetworkMode(v.network === '' ? '?' : v.network, '--network') ?? false) : undefined;
61
+ const merged = mergeNetwork(mode === undefined ? fromEnv : { ...fromEnv, strict: undefined }, mode ? { ...flags, strict: true } : flags);
51
62
  const problem = networkProblem(merged);
52
63
  if (problem)
53
64
  throw new SitefileError('E_USAGE', problem);
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `serve` in a terminal (issue #224): single keys while serving in the foreground, `--open[=path]` and
3
+ * `--qr`. Ported as rust/src/cli/serve_keys.rs (the same keys, messages and QR codes).
4
+ */
5
+ export type KeyAction = 'open' | 'urls' | 'restart' | 'clear' | 'quit' | 'help';
6
+ /** What a key does (letters in either case; Ctrl-C and Ctrl-D quit), or undefined. */
7
+ export declare function keyAction(byte: number): KeyAction | undefined;
8
+ export declare const KEYS_HINT = "Press h for keys\n";
9
+ export declare const KEYS_HELP = "Keys: o open in the browser, u show the URLs, r rebuild (--watch) or re-read the directory, c clear the screen, q quit, h this help\n";
10
+ export declare const CLEAR = "\u001B[2J\u001B[3J\u001B[H";
11
+ /**
12
+ * The URLs to show (below `serve --base`, `https://` for a TLS server): the local one, and when bound to every
13
+ * interface the same network URLs as the start line (one per interface address, IPv4 first).
14
+ */
15
+ export declare function serveUrls(host: string, port: number, base?: string, scheme?: 'http' | 'https'): {
16
+ local: string;
17
+ network: string[];
18
+ };
19
+ /** `u`: the URLs, and a QR code of the first network URL when there is one. */
20
+ export declare function urlsText(urls: {
21
+ local: string;
22
+ network: readonly string[];
23
+ }): string;
24
+ /** `--qr`: the URL and its QR code. */
25
+ export declare function qrText(url: string): string;
26
+ /** `--open=<path>` (or `--open`, `/`) joined to the server's URL. */
27
+ export declare function openUrl(base: string, path: string): string;
28
+ /**
29
+ * Open `url` in the browser: `$BROWSER` when set (a program, run with the URL as its only argument, no
30
+ * shell), else `open` (macOS), `rundll32 url.dll,FileProtocolHandler` (Windows) or `xdg-open`. A failure is
31
+ * a warning: the server keeps running.
32
+ */
33
+ export declare function openBrowser(url: string, warn: (m: string) => void): void;
34
+ /**
35
+ * Read single keys from stdin while serving: when stdin is a terminal (raw mode), or when
36
+ * `SITEFILE_SERVE_KEYS=1` (tests drive it through a pipe). Returns a function that stops reading and
37
+ * restores the terminal, or undefined when keys are off.
38
+ */
39
+ export declare function readKeys(onAction: (a: KeyAction) => void): (() => void) | undefined;
@@ -0,0 +1,106 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { encodeQr, qrTerminal } from '../qr.js';
3
+ import { formatUrl, networkUrls } from '../server.js';
4
+ /** What a key does (letters in either case; Ctrl-C and Ctrl-D quit), or undefined. */
5
+ export function keyAction(byte) {
6
+ if (byte === 3 || byte === 4)
7
+ return 'quit';
8
+ switch (String.fromCharCode(byte).toLowerCase()) {
9
+ case 'o':
10
+ return 'open';
11
+ case 'u':
12
+ return 'urls';
13
+ case 'r':
14
+ return 'restart';
15
+ case 'c':
16
+ return 'clear';
17
+ case 'q':
18
+ return 'quit';
19
+ case 'h':
20
+ return 'help';
21
+ default:
22
+ return undefined;
23
+ }
24
+ }
25
+ export const KEYS_HINT = 'Press h for keys\n';
26
+ export const KEYS_HELP = 'Keys: o open in the browser, u show the URLs, r rebuild (--watch) or re-read the directory, c clear the screen, q quit, h this help\n';
27
+ export const CLEAR = '\x1b[2J\x1b[3J\x1b[H';
28
+ const isWildcard = (h) => h === '0.0.0.0' || h === '::';
29
+ /**
30
+ * The URLs to show (below `serve --base`, `https://` for a TLS server): the local one, and when bound to every
31
+ * interface the same network URLs as the start line (one per interface address, IPv4 first).
32
+ */
33
+ export function serveUrls(host, port, base = '/', scheme = 'http') {
34
+ const path = base.slice(1);
35
+ const local = formatUrl(host, port, scheme) + path;
36
+ return { local, network: isWildcard(host) ? networkUrls(host, port, scheme).map((u) => u + path) : [] };
37
+ }
38
+ /** `u`: the URLs, and a QR code of the first network URL when there is one. */
39
+ export function urlsText(urls) {
40
+ let out = ` Local: ${urls.local}\n`;
41
+ for (const n of urls.network)
42
+ out += ` Network: ${n}\n`;
43
+ if (urls.network[0] !== undefined)
44
+ out += qrText(urls.network[0]);
45
+ return out;
46
+ }
47
+ /** `--qr`: the URL and its QR code. */
48
+ export function qrText(url) {
49
+ const code = encodeQr(url);
50
+ return code ? qrTerminal(code) : '';
51
+ }
52
+ /** `--open=<path>` (or `--open`, `/`) joined to the server's URL. */
53
+ export function openUrl(base, path) {
54
+ return base + path.replace(/^\/+/, '');
55
+ }
56
+ /**
57
+ * Open `url` in the browser: `$BROWSER` when set (a program, run with the URL as its only argument, no
58
+ * shell), else `open` (macOS), `rundll32 url.dll,FileProtocolHandler` (Windows) or `xdg-open`. A failure is
59
+ * a warning: the server keeps running.
60
+ */
61
+ export function openBrowser(url, warn) {
62
+ const browser = process.env['BROWSER'];
63
+ const [cmd, args] = browser !== undefined && browser !== ''
64
+ ? [browser, [url]]
65
+ : process.platform === 'darwin'
66
+ ? ['open', [url]]
67
+ : process.platform === 'win32'
68
+ ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
69
+ : ['xdg-open', [url]];
70
+ try {
71
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
72
+ child.on('error', (e) => warn(`cannot open the browser (${cmd}): ${e.message}`));
73
+ child.unref();
74
+ }
75
+ catch (e) {
76
+ warn(`cannot open the browser (${cmd}): ${e.message}`);
77
+ }
78
+ }
79
+ /**
80
+ * Read single keys from stdin while serving: when stdin is a terminal (raw mode), or when
81
+ * `SITEFILE_SERVE_KEYS=1` (tests drive it through a pipe). Returns a function that stops reading and
82
+ * restores the terminal, or undefined when keys are off.
83
+ */
84
+ export function readKeys(onAction) {
85
+ const tty = !!process.stdin.isTTY;
86
+ if (!tty && process.env['SITEFILE_SERVE_KEYS'] !== '1')
87
+ return undefined;
88
+ if (tty)
89
+ process.stdin.setRawMode(true);
90
+ const onData = (chunk) => {
91
+ for (const b of chunk) {
92
+ const a = keyAction(b);
93
+ if (a)
94
+ onAction(a);
95
+ }
96
+ };
97
+ process.stdin.on('data', onData);
98
+ process.stdin.resume();
99
+ return () => {
100
+ process.stdin.off('data', onData);
101
+ if (tty)
102
+ process.stdin.setRawMode(false);
103
+ process.stdin.pause();
104
+ };
105
+ }
106
+ //# sourceMappingURL=serve-keys.js.map
@@ -1,36 +1,74 @@
1
1
  #!/usr/bin/env node
2
2
  // Detached server process spawned by `sitefile serve -d` / `restart`.
3
3
  // Usage: node serve-worker.js <server id>. State and logs live in $SITEFILE_HOME/servers.
4
+ import { readFile } from 'node:fs/promises';
4
5
  import { SitefileError } from '../errors.js';
5
- import { closeServer, createSiteServer, formatUrl, listen } from '../server.js';
6
- import { loadServedTree, ServerRegistry } from '../servers.js';
7
- const stamp = (m) => void process.stdout.write(`${new Date().toISOString()} ${m}\n`);
6
+ import { BasicAuth, parseHtpasswd } from '../serve-auth.js';
7
+ import { closeServer, createSiteServer, formatUrl, jsonLogLine, listen, parseCidr, parseThrottle, startedLogLine, stoppedLogLine, routingFor } from '../server.js';
8
+ import { loadServedTree, servedLastModified, ServerRegistry, loadServedSite, checkSiteFiles } from '../servers.js';
9
+ let json = false; // `--log-format json`: every line is a JSON object
10
+ const stamp = (m) => {
11
+ const ts = new Date().toISOString();
12
+ process.stdout.write(json ? `${m.startsWith('{') ? m : jsonLogLine(ts, m)}\n` : `${ts} ${m}\n`);
13
+ };
8
14
  async function main() {
9
15
  const id = process.argv[2] ?? '';
10
16
  const reg = await ServerRegistry.open();
11
17
  const state = await reg.read(id);
12
18
  if (!state)
13
19
  throw new SitefileError('E_SERVER', `no state for server '${id}'`);
20
+ json = state.logFormat === 'json';
14
21
  try {
15
- const tree = await loadServedTree(reg.store, state.source);
16
- const server = createSiteServer(tree, { spa: state.spa, serverId: id, log: stamp });
22
+ const left = state.expires === undefined ? undefined : Date.parse(state.expires) - Date.now();
23
+ if (left !== undefined && left <= 0)
24
+ throw new SitefileError('E_SERVER', `server expired at ${state.expires} (--stop-after)`);
25
+ const ipRules = state.allowIp !== undefined || state.denyIp !== undefined ? { allow: (state.allowIp ?? []).flatMap((t) => parseCidr(t) ?? []), deny: (state.denyIp ?? []).flatMap((t) => parseCidr(t) ?? []) } : undefined;
26
+ const loopback = state.bind.host === 'localhost' || state.bind.host === '::1' || /^127\./.test(state.bind.host);
27
+ const { tree, content } = await loadServedSite(reg.store, state.source, { keepOsMetadata: !!state.keepOsMetadata, warn: (m) => stamp(`warning: ${m}`) });
28
+ if (routingFor(state)?.siteFiles !== false)
29
+ checkSiteFiles(tree, !!state.strictSiteFiles, (m) => stamp(`warning: ${m}`), content);
30
+ const modified = await servedLastModified(reg.store, state.source);
31
+ 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) } : {}) });
17
33
  const addr = await listen(server, state.bind.host, state.bind.port);
18
34
  await reg.update(id, { pid: process.pid, host: addr.host, port: addr.port, ready: true, error: undefined });
19
- stamp(`serving ${state.image} (${tree.size} files) at ${formatUrl(addr.host, addr.port)}`);
35
+ const root = formatUrl(addr.host, addr.port, state.tlsCert !== undefined ? 'https' : 'http');
36
+ const url = `${root}${(state.base ?? '/').slice(1)}`;
37
+ if (json)
38
+ stamp(startedLogLine(new Date().toISOString(), state.image, tree.size, url));
39
+ else
40
+ stamp(`serving ${state.image} (${tree.size} files) at ${url}`);
20
41
  const stop = (signal) => () => {
21
- stamp(`received ${signal}, shutting down`);
42
+ if (json)
43
+ stamp(stoppedLogLine(new Date().toISOString(), signal));
44
+ else
45
+ stamp(`received ${signal}, shutting down`);
22
46
  void closeServer(server).then(async () => {
23
47
  await reg.update(id, { ready: false }).catch(() => undefined);
24
48
  process.exit(0);
25
49
  });
26
50
  setTimeout(() => process.exit(0), 3000).unref();
27
51
  };
52
+ if (left !== undefined) {
53
+ setTimeout(() => {
54
+ if (json)
55
+ stamp(stoppedLogLine(new Date().toISOString(), 'expired'));
56
+ else
57
+ stamp('--stop-after reached, shutting down');
58
+ void closeServer(server).then(async () => {
59
+ await reg.update(id, { ready: false }).catch(() => undefined);
60
+ process.exit(0);
61
+ });
62
+ setTimeout(() => process.exit(0), 3000).unref();
63
+ }, Math.min(left, 2 ** 31 - 1));
64
+ }
28
65
  process.on('SIGTERM', stop('SIGTERM'));
29
66
  process.on('SIGINT', stop('SIGINT'));
30
67
  }
31
68
  catch (e) {
32
69
  const message = e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : `error: ${e.message}`;
33
- process.stderr.write(`${new Date().toISOString()} ${message}\n`);
70
+ const ts = new Date().toISOString();
71
+ process.stderr.write(json ? `${jsonLogLine(ts, message)}\n` : `${ts} ${message}\n`);
34
72
  await reg.update(id, { pid: 0, ready: false, error: message }).catch(() => undefined);
35
73
  process.exit(1);
36
74
  }