@johnhenry/sitefile 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/CHANGELOG.md +516 -0
  2. package/README.md +59 -9
  3. package/lib/src/archive-writers.d.ts +12 -2
  4. package/lib/src/archive-writers.js +53 -10
  5. package/lib/src/bake.d.ts +2 -0
  6. package/lib/src/bake.js +30 -1
  7. package/lib/src/bcrypt.d.ts +25 -0
  8. package/lib/src/bcrypt.js +201 -0
  9. package/lib/src/canonical.d.ts +19 -0
  10. package/lib/src/canonical.js +60 -0
  11. package/lib/src/car.d.ts +34 -0
  12. package/lib/src/car.js +203 -0
  13. package/lib/src/checklinks.js +8 -2
  14. package/lib/src/cli/bake.js +4 -3
  15. package/lib/src/cli/build-image.d.ts +1 -0
  16. package/lib/src/cli/build-image.js +1 -0
  17. package/lib/src/cli/common.js +4 -1
  18. package/lib/src/cli/hosts.d.ts +5 -0
  19. package/lib/src/cli/hosts.js +78 -0
  20. package/lib/src/cli/images.js +23 -5
  21. package/lib/src/cli/import-config.d.ts +2 -0
  22. package/lib/src/cli/import-config.js +56 -0
  23. package/lib/src/cli/index.d.ts +6 -1
  24. package/lib/src/cli/index.js +34 -2
  25. package/lib/src/cli/integrity.d.ts +2 -0
  26. package/lib/src/cli/integrity.js +77 -0
  27. package/lib/src/cli/network.d.ts +7 -0
  28. package/lib/src/cli/network.js +14 -3
  29. package/lib/src/cli/serve-keys.d.ts +39 -0
  30. package/lib/src/cli/serve-keys.js +106 -0
  31. package/lib/src/cli/serve-worker.js +119 -8
  32. package/lib/src/cli/servers.d.ts +130 -1
  33. package/lib/src/cli/servers.js +754 -72
  34. package/lib/src/cli/up.d.ts +2 -0
  35. package/lib/src/cli/up.js +193 -0
  36. package/lib/src/cli/watch.d.ts +14 -1
  37. package/lib/src/cli/watch.js +20 -3
  38. package/lib/src/cli.js +138 -18
  39. package/lib/src/csp.d.ts +17 -0
  40. package/lib/src/csp.js +52 -0
  41. package/lib/src/dictionary.d.ts +16 -0
  42. package/lib/src/dictionary.js +89 -0
  43. package/lib/src/epub.d.ts +5 -0
  44. package/lib/src/epub.js +113 -0
  45. package/lib/src/errors.d.ts +22 -9
  46. package/lib/src/errors.js +20 -1
  47. package/lib/src/executor.d.ts +31 -1
  48. package/lib/src/executor.js +231 -24
  49. package/lib/src/explain.js +33 -3
  50. package/lib/src/export-for.d.ts +42 -0
  51. package/lib/src/export-for.js +466 -0
  52. package/lib/src/export-formats.d.ts +2 -2
  53. package/lib/src/export-formats.js +52 -2
  54. package/lib/src/fingerprint.d.ts +3 -1
  55. package/lib/src/fingerprint.js +32 -5
  56. package/lib/src/host-config.d.ts +34 -0
  57. package/lib/src/host-config.js +645 -0
  58. package/lib/src/hosts.d.ts +47 -0
  59. package/lib/src/hosts.js +106 -0
  60. package/lib/src/hreflang.d.ts +25 -0
  61. package/lib/src/hreflang.js +72 -0
  62. package/lib/src/index.d.ts +1 -1
  63. package/lib/src/index.js +1 -1
  64. package/lib/src/integrity.d.ts +115 -0
  65. package/lib/src/integrity.js +273 -0
  66. package/lib/src/language/ast.d.ts +126 -3
  67. package/lib/src/language/ast.js +7 -1
  68. package/lib/src/language/parser.js +189 -7
  69. package/lib/src/language/validate.js +24 -0
  70. package/lib/src/links.d.ts +47 -0
  71. package/lib/src/links.js +289 -3
  72. package/lib/src/lint.d.ts +1 -1
  73. package/lib/src/lint.js +26 -1
  74. package/lib/src/mime-data.d.ts +2 -0
  75. package/lib/src/mime-data.js +92 -0
  76. package/lib/src/oci.d.ts +20 -2
  77. package/lib/src/oci.js +70 -28
  78. package/lib/src/outdated.d.ts +3 -0
  79. package/lib/src/outdated.js +4 -4
  80. package/lib/src/planner.d.ts +87 -2
  81. package/lib/src/planner.js +189 -8
  82. package/lib/src/plugins/cache.d.ts +11 -0
  83. package/lib/src/plugins/cache.js +29 -0
  84. package/lib/src/plugins/host.d.ts +51 -2
  85. package/lib/src/plugins/host.js +141 -16
  86. package/lib/src/plugins/wasm.js +1 -3
  87. package/lib/src/portable.d.ts +8 -0
  88. package/lib/src/portable.js +47 -0
  89. package/lib/src/precache.d.ts +33 -0
  90. package/lib/src/precache.js +75 -0
  91. package/lib/src/precompress.d.ts +19 -0
  92. package/lib/src/precompress.js +35 -0
  93. package/lib/src/qr.d.ts +18 -0
  94. package/lib/src/qr.js +372 -0
  95. package/lib/src/registry-ops.js +4 -2
  96. package/lib/src/reload-client.d.ts +2 -0
  97. package/lib/src/reload-client.js +419 -0
  98. package/lib/src/resources/archive.d.ts +37 -1
  99. package/lib/src/resources/archive.js +353 -71
  100. package/lib/src/resources/convert.js +3 -1
  101. package/lib/src/resources/https.d.ts +9 -1
  102. package/lib/src/resources/https.js +36 -0
  103. package/lib/src/resources/network.d.ts +25 -3
  104. package/lib/src/resources/network.js +77 -6
  105. package/lib/src/secrets.d.ts +12 -3
  106. package/lib/src/secrets.js +18 -5
  107. package/lib/src/serve-auth.d.ts +33 -0
  108. package/lib/src/serve-auth.js +120 -0
  109. package/lib/src/serve-rules.d.ts +83 -7
  110. package/lib/src/serve-rules.js +264 -53
  111. package/lib/src/server.d.ts +529 -11
  112. package/lib/src/server.js +1439 -57
  113. package/lib/src/servers-file.d.ts +36 -0
  114. package/lib/src/servers-file.js +101 -0
  115. package/lib/src/servers.d.ts +115 -7
  116. package/lib/src/servers.js +151 -29
  117. package/lib/src/single-file.d.ts +12 -0
  118. package/lib/src/single-file.js +147 -0
  119. package/lib/src/site.d.ts +58 -0
  120. package/lib/src/site.js +216 -5
  121. package/lib/src/store.js +9 -5
  122. package/lib/src/swbn.d.ts +10 -0
  123. package/lib/src/swbn.js +86 -0
  124. package/lib/src/toml.d.ts +17 -0
  125. package/lib/src/toml.js +323 -0
  126. package/lib/src/wacz.d.ts +6 -0
  127. package/lib/src/wacz.js +96 -0
  128. package/lib/src/warc.d.ts +28 -0
  129. package/lib/src/warc.js +252 -0
  130. package/lib/src/watch.d.ts +12 -1
  131. package/lib/src/watch.js +67 -1
  132. package/lib/src/wbn.d.ts +9 -1
  133. package/lib/src/wbn.js +23 -33
  134. package/lib/src/zstd.d.ts +4 -0
  135. package/lib/src/zstd.js +328 -0
  136. package/package.json +1 -1
package/lib/src/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from 'node:util';
3
3
  import path from 'node:path';
4
- import { SitefileError, isSitefileError } from './errors.js';
4
+ import { errorJson, SitefileError, isSitefileError } from './errors.js';
5
5
  import { build, buildToDirectory, checkPlanPins, lintBuild, planBuild, sitefileCompression } from './executor.js';
6
6
  import { LINT_RULES } from './lint.js';
7
7
  import { compressionFromExtension, defaultOutName, formatFromExtension } from './export-formats.js';
@@ -9,7 +9,7 @@ import { collectBuildArgs } from './build-args.js';
9
9
  import { insecureRegistriesFromEnv, makeClient } from './base-image.js';
10
10
  import { cacheLimitFromEnv } from './cache-limit.js';
11
11
  import { parseCacheRef, RegistryCache } from './registry-cache.js';
12
- import { parseLabels } from './oci.js';
12
+ import { MAX_OCI_LAYERS, parseLabels } from './oci.js';
13
13
  import { EXPORT_FORMATS, parseExportFormat, parseOciCompression } from './language/ast.js';
14
14
  import { DEFAULT_FETCH_POLICY } from './resources/types.js';
15
15
  import { parseLocalRef, refKey } from './ref.js';
@@ -17,13 +17,17 @@ import { EXTRA_HELP, isExtraCommand, runExtraCommand } from './cli/index.js';
17
17
  import { evictAfterBuild, transformCacheDir } from './cli/cache.js';
18
18
  import { storeBuildAsImage, validateImageTags } from './cli/build-image.js';
19
19
  import { SITEFILE_VERSION } from './attest.js';
20
- import { watchLoop } from './cli/watch.js';
20
+ import { pollOption, watchLoop } from './cli/watch.js';
21
21
  import { Profiler } from './profile.js';
22
22
  import { watchMemo } from './memo.js';
23
23
  import { promises as fs } from 'node:fs';
24
24
  import { graphDot, graphText, planGraph, why, whyText } from './explain.js';
25
25
  import { isGitContext, materializeGitContext } from './cli/git-context.js';
26
26
  import { loadSecrets } from './secrets.js';
27
+ import { exportFile } from './exporter.js';
28
+ import { encodeManifest, loadTarget, manifestOf, resolveTarget } from './integrity.js';
29
+ import { addDictionaryDeltas } from './dictionary.js';
30
+ import { Store } from './store.js';
27
31
  import { NETWORK_OPTIONS, networkHelp, networkOption } from './cli/network.js';
28
32
  const VERSION = SITEFILE_VERSION;
29
33
  const HELP = `sitefile ${VERSION} — Docker-inspired static artifact builder
@@ -44,19 +48,23 @@ Options:
44
48
  --target <stage> stop after the named stage and export its whole tree instead of
45
49
  the EXPORT path (EXPORT's format still applies; no _redirects/_headers)
46
50
  -o, --out <path> export destination (build only): a directory for 'directory',
47
- a file for zip, tar, tgz, wbn (*.wbn.gz: a gzipped bundle)
51
+ a file for zip, tar, tgz, wbn (*.wbn.gz: a gzipped bundle), car, html, mhtml, epub
48
52
  -t, --tag <name[:tag]> also store the build as a local image (build only, repeatable);
49
53
  with -t and no -o nothing is written to the context
50
- --format <fmt> directory | zip | tar | tgz (alias tar.gz) | wbn | oci (build only).
54
+ --format <fmt> directory | zip | tar | tgz (alias tar.gz) | wbn | oci | car | html | mhtml | warc | swbn | wacz | epub
55
+ (build only).
51
56
  oci writes an OCI archive for -o *.tar (e.g. site.oci.tar), else an
52
57
  OCI image layout directory.
53
- Default: the --out extension (.zip .tar .tar.gz .tgz .wbn .wbn.gz .oci.tar),
58
+ Default: the --out extension (.zip .tar .tar.gz .tgz .wbn .wbn.gz .oci.tar .car .mhtml
59
+ .warc .warc.gz .swbn .wacz .epub),
54
60
  else the Sitefile's EXPORT ... AS <fmt>
55
61
  --oci-root <path> directory inside an oci image layer (default /srv/www; overrides EXPORT ... AT)
56
62
  --compression <c> gzip or none (build only; overrides EXPORT ... COMPRESSION): the oci site layer
57
63
  (default gzip; none: plain tar), or the whole wbn (default none; gzip:
58
64
  gzip(application/webbundle), also chosen by -o *.wbn.gz)
59
65
  --oci-compression <c> the same as --compression, for oci only
66
+ --oci-layers <n> split the oci image's files over n layers (1-64, default 1) by a hash of each
67
+ path, so pushing a new version uploads only the layers that changed
60
68
  --label <key=value> add an OCI image config label (repeatable)
61
69
  --git-labels add org.opencontainers.image.source/revision from the git checkout
62
70
  (off by default: they change the image ID on every commit)
@@ -69,13 +77,17 @@ Options:
69
77
  --base <image> build the oci image on <image> (runnable; overrides EXPORT ... AS oci BASE);
70
78
  a bare name means Docker Hub. Pin it: nginx:alpine@sha256:...
71
79
  --insecure-registry <h> allow plain http to registry host[:port] (repeatable; localhost always may)
72
- --base-url <url> https URL ending in '/' the files are mounted at (wbn only);
80
+ --base-url <url> https URL ending in '/' the files are mounted at (wbn, mhtml, warc, wacz);
73
81
  overrides EXPORT ... BASE
74
82
  --build-arg <NAME=value> set an ARG (repeatable); --build-arg NAME reads $NAME
75
83
  --secret id=<id>,env=<VAR> | id=<id>,src=<file>
76
84
  a build secret for IMPORT ... SECRET <id> AS HEADER <Name> | AS BEARER
77
85
  (repeatable); sent only to that import's origin, never recorded
78
86
  --plugin-timeout <ms> per-call time limit for TRANSFORM plugins and tools (default 60000)
87
+ --plugin-memory <MiB> memory limit for each plugin: a JavaScript plugin's heap, a wasm
88
+ plugin's linear memory (default 1024)
89
+ --node <path> the Node binary JavaScript plugins run on (absolute path; default
90
+ $SITEFILE_NODE, else the default Node, see docs/PLUGINS.md); must be >= 26
79
91
  --allow-exec <name[=path]> allow a TOOL (external program) to run, resolved on PATH or at
80
92
  the absolute path (repeatable); programs run with your privileges
81
93
  --allow-plugin <name> allow a JavaScript PLUGIN to run (repeatable; wasm plugins need no flag)
@@ -88,11 +100,21 @@ Options:
88
100
  registry cache (build only, once); registry problems only warn
89
101
  --build-arg-file <path> read ARGs from a .json, .yaml/.yml or .env file (repeatable;
90
102
  later files win, --build-arg wins over files)
103
+ --manifest <file> also write a manifest of the exported files (build only): path, size and
104
+ SHA-256 of each, and their Merkle root; check copies with 'sitefile verify'
105
+ --experimental-dictionary <previous>
106
+ Compression Dictionary Transport (experimental, build only): add a .dcz delta
107
+ against <previous> (image, directory or archive) for each changed .js/.css/...
108
+ and Use-As-Dictionary headers; 'serve' answers Available-Dictionary with them
91
109
  --force replace a non-empty --out outside the context
92
110
  --frozen-lockfile fail instead of changing Sitefile.lock
93
111
  --update-lock re-record unpinned URLs whose content changed
94
112
  --strict-pins fail when a remote IMPORT has no INTEGRITY and no lockfile entry, or the
95
113
  BASE image is neither @sha256:-pinned nor locked (build, validate, inspect)
114
+ --lossy with EXPORT ... FOR <host>: leave out, with a warning, REDIRECT and HEADER
115
+ rules the host cannot express (default: an error)
116
+ --strict-paths fail (E_PATH_PORTABLE) instead of warning when an exported path cannot be
117
+ written on Windows, or starts with '_' and there is no /.nojekyll
96
118
  --lint-disable <rules> turn lint rules off (validate; comma-separated rule ids, or all; repeatable)
97
119
  --no-lockfile do not read or write Sitefile.lock
98
120
  --vendor-dir <dir> read remote imports and BASE blobs from this vendor directory (relative
@@ -100,13 +122,19 @@ Options:
100
122
  --allow-http permit plain http:// imports
101
123
  --allow-private-network permit loopback/private network addresses
102
124
  --allow-hardlinks permit hard-linked files in the context (you assert they are safe)
125
+ --keep-os-metadata keep __MACOSX, ._*, .DS_Store, Thumbs.db and desktop.ini in archives
126
+ imported AS tree (default: skipped with a warning)
103
127
  --max-download-bytes <n> per-resource size limit (default ${DEFAULT_FETCH_POLICY.maxBytes})
104
128
  --timeout <ms> per-resource fetch timeout (default ${DEFAULT_FETCH_POLICY.timeoutMs})
105
129
  ${networkHelp(25).map((l) => ` ${l}`).join('\n')}
106
- --json machine-readable output (validate, inspect, graph, why)
130
+ --json machine-readable output (validate, inspect, graph, why); with any
131
+ command, a failure is also printed on stdout as JSON (code, span, needs)
107
132
  --dot Graphviz DOT output (graph only)
108
133
  --watch build, then rebuild when the context, the Sitefile or a
109
134
  --build-arg-file changes (build only; Ctrl-C stops)
135
+ --poll --watch: poll for changes (every 1000 ms) instead of file system
136
+ events (network shares, Docker bind mounts, WSL)
137
+ --poll-interval <ms> --watch: poll every <ms> milliseconds (implies --poll)
110
138
  --profile <file> write a timing trace of the build (Chrome trace event JSON:
111
139
  chrome://tracing, ui.perfetto.dev); --watch rewrites it per build
112
140
  -h, --help show this help
@@ -135,6 +163,7 @@ export async function main(argv, run = {}) {
135
163
  'base-url': { type: 'string' },
136
164
  'oci-root': { type: 'string' },
137
165
  'oci-compression': { type: 'string' },
166
+ 'oci-layers': { type: 'string' },
138
167
  compression: { type: 'string' },
139
168
  label: { type: 'string', multiple: true },
140
169
  'git-labels': { type: 'boolean' },
@@ -147,6 +176,8 @@ export async function main(argv, run = {}) {
147
176
  'build-arg-file': { type: 'string', multiple: true },
148
177
  secret: { type: 'string', multiple: true },
149
178
  'plugin-timeout': { type: 'string' },
179
+ 'plugin-memory': { type: 'string' },
180
+ node: { type: 'string' },
150
181
  'allow-exec': { type: 'string', multiple: true },
151
182
  'allow-plugin': { type: 'string', multiple: true },
152
183
  'allow-plugins': { type: 'boolean' },
@@ -157,18 +188,25 @@ export async function main(argv, run = {}) {
157
188
  'frozen-lockfile': { type: 'boolean' },
158
189
  'update-lock': { type: 'boolean' },
159
190
  'strict-pins': { type: 'boolean' },
191
+ lossy: { type: 'boolean' },
192
+ 'strict-paths': { type: 'boolean' },
160
193
  'lint-disable': { type: 'string', multiple: true },
161
194
  'no-lockfile': { type: 'boolean' },
162
195
  'vendor-dir': { type: 'string' },
163
196
  'allow-http': { type: 'boolean' },
164
197
  'allow-private-network': { type: 'boolean' },
165
198
  'allow-hardlinks': { type: 'boolean' },
199
+ 'keep-os-metadata': { type: 'boolean' },
166
200
  'max-download-bytes': { type: 'string' },
167
201
  timeout: { type: 'string' },
168
202
  json: { type: 'boolean' },
169
203
  dot: { type: 'boolean' },
170
204
  watch: { type: 'boolean' },
205
+ poll: { type: 'boolean' },
206
+ 'poll-interval': { type: 'string' },
171
207
  profile: { type: 'string' },
208
+ manifest: { type: 'string' },
209
+ 'experimental-dictionary': { type: 'string' },
172
210
  help: { type: 'boolean', short: 'h' },
173
211
  version: { type: 'boolean', short: 'v' },
174
212
  },
@@ -228,15 +266,25 @@ export async function main(argv, run = {}) {
228
266
  if (cacheTo.length > 1)
229
267
  return usageError('--cache-to can be given only once');
230
268
  }
269
+ if (!o.watch && (o.poll || o['poll-interval'] !== undefined))
270
+ return usageError(`--${o['poll-interval'] !== undefined ? 'poll-interval' : 'poll'} needs --watch`);
231
271
  if (o.watch && !run.once) {
232
272
  if (command !== 'build')
233
273
  return usageError(`--watch is only for build (and serve --watch), not ${command}`);
234
274
  if ((o.tag ?? []).length)
235
275
  return usageError('--watch cannot be combined with -t');
276
+ let pollMs;
277
+ try {
278
+ pollMs = pollOption(o.poll, o['poll-interval']);
279
+ }
280
+ catch (e) {
281
+ return usageError(e.detail);
282
+ }
236
283
  try {
237
284
  const memo = watchMemo();
238
285
  return await watchLoop({
239
286
  context: contextArg,
287
+ ...(pollMs !== undefined ? { pollMs } : {}),
240
288
  ...(o.file ? { sitefile: o.file } : {}),
241
289
  argFiles: o['build-arg-file'] ?? [],
242
290
  build: async () => {
@@ -254,6 +302,16 @@ export async function main(argv, run = {}) {
254
302
  }
255
303
  if (o.profile === '')
256
304
  return usageError('--profile expects a file path');
305
+ if (o.manifest !== undefined && command !== 'build')
306
+ return usageError('--manifest is only for build');
307
+ if (o.manifest === '')
308
+ return usageError('--manifest expects a file path');
309
+ if (o.manifest !== undefined)
310
+ run.wrote?.push(o.manifest);
311
+ if (o['experimental-dictionary'] !== undefined && command !== 'build')
312
+ return usageError('--experimental-dictionary is only for build');
313
+ if (o['experimental-dictionary'] === '')
314
+ return usageError('--experimental-dictionary expects an image, directory or archive');
257
315
  // --profile: a trace of this command (build, validate, inspect, graph, why), written when it ends.
258
316
  const profiler = o.profile !== undefined ? new Profiler(command) : undefined;
259
317
  if (o.profile !== undefined)
@@ -296,6 +354,14 @@ export async function main(argv, run = {}) {
296
354
  if (!formatOverride)
297
355
  return usageError(`--format expects one of ${EXPORT_FORMATS.join(', ')} (or tar.gz), got '${o.format}'`);
298
356
  }
357
+ let ociLayers;
358
+ if (o['oci-layers'] !== undefined) {
359
+ if (command !== 'build')
360
+ return usageError('--oci-layers is only for build');
361
+ ociLayers = /^[0-9]{1,2}$/.test(o['oci-layers']) ? Number(o['oci-layers']) : 0;
362
+ if (ociLayers < 1 || ociLayers > MAX_OCI_LAYERS)
363
+ return usageError(`--oci-layers expects an integer from 1 to ${MAX_OCI_LAYERS}, got '${o['oci-layers']}'`);
364
+ }
299
365
  let ociCompression;
300
366
  if (o['oci-compression'] !== undefined) {
301
367
  ociCompression = parseOciCompression(o['oci-compression']);
@@ -316,10 +382,10 @@ export async function main(argv, run = {}) {
316
382
  formatOverride = formatFromExtension(o.out);
317
383
  // The default destination depends on the format, which the Sitefile may set.
318
384
  // (A wbn's default name also depends on its COMPRESSION: dist.wbn or dist.wbn.gz.)
319
- const sitefilePlan = command === 'build' && !o.out && (!formatOverride || formatOverride === 'wbn') ? await planBuild({ contextDir: context, ...(file ? { sitefile: file } : {}), buildArgs }) : undefined;
385
+ const sitefilePlan = command === 'build' && !o.out && (!formatOverride || formatOverride === 'wbn' || formatOverride === 'warc') ? await planBuild({ contextDir: context, ...(file ? { sitefile: file } : {}), buildArgs }) : undefined;
320
386
  const sitefileFormat = formatOverride ? undefined : sitefilePlan?.exportFormat;
321
387
  const defaultFormat = formatOverride ?? sitefileFormat ?? 'directory';
322
- const defaultCompression = defaultFormat === 'wbn' ? (compression ?? (sitefilePlan ? sitefileCompression(sitefilePlan, 'wbn') : undefined)) : undefined;
388
+ const defaultCompression = defaultFormat === 'wbn' || defaultFormat === 'warc' ? (compression ?? (sitefilePlan ? sitefileCompression(sitefilePlan, defaultFormat) : undefined)) : undefined;
323
389
  // A Git context's default destination is in the current directory, not the temporary checkout.
324
390
  const out = o.out ?? path.join(fetched ? '.' : context, defaultOutName(defaultFormat, defaultCompression));
325
391
  run.wrote?.push(out);
@@ -334,9 +400,16 @@ export async function main(argv, run = {}) {
334
400
  fetchPolicy,
335
401
  ...(o['no-lockfile'] ? { lockfile: false } : {}),
336
402
  ...(o['vendor-dir'] !== undefined ? { vendorDir: o['vendor-dir'] } : {}),
337
- ...(o['plugin-timeout']
338
- ? { pluginPolicy: { timeoutMs: positiveInt(o['plugin-timeout'], '--plugin-timeout') }, toolPolicy: { timeoutMs: positiveInt(o['plugin-timeout'], '--plugin-timeout') } }
403
+ ...(o['plugin-timeout'] || o['plugin-memory']
404
+ ? {
405
+ pluginPolicy: {
406
+ ...(o['plugin-timeout'] ? { timeoutMs: positiveInt(o['plugin-timeout'], '--plugin-timeout') } : {}),
407
+ ...(o['plugin-memory'] ? { maxMemoryMiB: positiveInt(o['plugin-memory'], '--plugin-memory') } : {}),
408
+ },
409
+ ...(o['plugin-timeout'] ? { toolPolicy: { timeoutMs: positiveInt(o['plugin-timeout'], '--plugin-timeout') } } : {}),
410
+ }
339
411
  : {}),
412
+ ...pluginNode(o.node),
340
413
  ...(o['allow-exec'] ? { allowExec: o['allow-exec'] } : {}),
341
414
  ...(o['allow-plugin'] ? { allowPlugin: o['allow-plugin'] } : {}),
342
415
  allowAllPlugins: !!o['allow-plugins'],
@@ -344,6 +417,7 @@ export async function main(argv, run = {}) {
344
417
  ...(remoteCache ? { remoteCache } : {}),
345
418
  onNotice: (m) => process.stderr.write(`${m}\n`),
346
419
  allowHardlinks: !!o['allow-hardlinks'],
420
+ keepOsMetadata: !!o['keep-os-metadata'],
347
421
  ...(o.platform !== undefined ? { platform: o.platform } : {}),
348
422
  ...(o.base !== undefined ? { baseImage: o.base } : {}),
349
423
  // inspect never pulls; a non-oci export (with no image tag) has no use for a BASE
@@ -352,6 +426,8 @@ export async function main(argv, run = {}) {
352
426
  frozenLockfile: !!o['frozen-lockfile'],
353
427
  updateLock: !!o['update-lock'],
354
428
  strictPins: !!o['strict-pins'],
429
+ lossy: !!o.lossy,
430
+ strictPaths: !!o['strict-paths'],
355
431
  onWarning: (m) => process.stderr.write(`warning: ${m}\n`),
356
432
  ...(profiler ? { profiler, alsoWrites: [o.profile] } : {}),
357
433
  ...(run.memo ? { memo: run.memo } : {}),
@@ -363,13 +439,13 @@ export async function main(argv, run = {}) {
363
439
  const fmt = (o.tag ?? []).length && !o.out ? 'oci' : (formatOverride ?? sitefileFormat ?? (await planBuild(options)).exportFormat);
364
440
  if (fmt === 'oci')
365
441
  ociCompression = compression;
366
- else if (fmt === 'wbn')
442
+ else if (fmt === 'wbn' || fmt === 'warc')
367
443
  wbnCompression = compression;
368
444
  else
369
- return usageError(`--compression applies only to oci and wbn exports, not ${fmt}`);
445
+ return usageError(`--compression applies only to oci, wbn and warc exports, not ${fmt}`);
370
446
  }
371
- if (formatOverride === 'wbn' && o.out)
372
- wbnCompression ??= compressionFromExtension(o.out, 'wbn');
447
+ if ((formatOverride === 'wbn' || formatOverride === 'warc') && o.out)
448
+ wbnCompression ??= compressionFromExtension(o.out, formatOverride);
373
449
  switch (command) {
374
450
  case 'build': {
375
451
  const tags = o.tag ?? [];
@@ -383,6 +459,7 @@ export async function main(argv, run = {}) {
383
459
  contextDir: context,
384
460
  ociRoot: o['oci-root'],
385
461
  ociCompression,
462
+ ociLayers,
386
463
  platform: o.platform,
387
464
  labels,
388
465
  gitLabels: !!o['git-labels'],
@@ -390,12 +467,20 @@ export async function main(argv, run = {}) {
390
467
  build: { contextDir: context, ...(file ? { sitefile: file } : {}), ...(fetched ? { label: o.file ?? 'Sitefile' } : {}), buildArgs },
391
468
  };
392
469
  await remoteCache?.load();
470
+ const dictionaryFrom = await previousBuild(o['experimental-dictionary']);
393
471
  if (tags.length && !o.out) {
394
472
  // -t without -o: store the image only; nothing is written to the context.
395
- await storeBuildAsImage(await build(options), tags, imageInfo);
473
+ const raw = await build(options);
474
+ const built = dictionaryFrom ? { ...raw, output: addDictionaryDeltas(raw.output, dictionaryFrom).tree } : raw;
475
+ if (o.manifest !== undefined)
476
+ await writeManifest(built.output, o.manifest, context, !!o.force);
477
+ await storeBuildAsImage(built, tags, imageInfo);
396
478
  await remoteCache?.push(transformCacheDir());
397
479
  return 0;
398
480
  }
481
+ if (o.manifest !== undefined && (formatOverride ?? sitefileFormat ?? (await planBuild(options)).exportFormat) === 'directory' && isInsideDir(o.manifest, out)) {
482
+ return usageError(`--manifest '${o.manifest}' is inside the exported directory '${out}': write it elsewhere`);
483
+ }
399
484
  const r = await buildToDirectory({
400
485
  ...options,
401
486
  outDir: out,
@@ -404,12 +489,14 @@ export async function main(argv, run = {}) {
404
489
  ...(o['base-url'] !== undefined ? { baseUrl: o['base-url'] } : {}),
405
490
  ...(o['oci-root'] !== undefined ? { ociRoot: o['oci-root'] } : {}),
406
491
  ...(ociCompression !== undefined ? { ociCompression } : {}),
492
+ ...(ociLayers !== undefined ? { ociLayers } : {}),
407
493
  ...(wbnCompression !== undefined ? { wbnCompression } : {}),
408
494
  ...(o.platform !== undefined ? { platform: o.platform } : {}),
409
495
  imageLabels: labels,
410
496
  gitLabels: !!o['git-labels'],
411
497
  ...(tags[0] ? { ociRefName: refKey(parseLocalRef(tags[0])) } : {}),
412
498
  attest,
499
+ ...(dictionaryFrom ? { dictionaryFrom } : {}),
413
500
  });
414
501
  const where = path.relative(process.cwd(), r.outDir) || '.';
415
502
  const n = `${r.output.size} file${r.output.size === 1 ? '' : 's'}`;
@@ -417,7 +504,11 @@ export async function main(argv, run = {}) {
417
504
  ? `Exported ${n} to ${where} (${r.output.digest()})\n`
418
505
  : r.format === 'oci'
419
506
  ? `Exported ${n} to ${where} (oci image ${r.manifestDigest}${r.bytes !== undefined ? `, ${r.bytes} bytes` : ''})\n`
420
- : `Exported ${n} to ${where} (${r.format === 'tgz' ? 'tar.gz' : r.format}, ${r.bytes} bytes, ${r.fileDigest})\n`);
507
+ : `Exported ${n} to ${where} (${r.format === 'tgz' ? 'tar.gz' : r.format}, ${r.bytes} bytes, ${r.fileDigest}${r.rootCid ? `, root ${r.rootCid}` : ''}${r.webBundleId ? `, web bundle id ${r.webBundleId}` : ''})\n`);
508
+ if (r.dictionaryDeltas)
509
+ process.stdout.write(`Dictionary deltas: ${r.dictionaryDeltas.length} (.dcz)\n`);
510
+ if (o.manifest !== undefined)
511
+ await writeManifest(r.output, o.manifest, context, !!o.force);
421
512
  // A Git context's lockfile lives in the temporary checkout: it is used, never written back.
422
513
  if (r.lockfileWritten && !fetched)
423
514
  process.stdout.write('Updated Sitefile.lock\n');
@@ -482,6 +573,9 @@ export async function main(argv, run = {}) {
482
573
  if (isSitefileError(e)) {
483
574
  if (e.code === 'E_USAGE')
484
575
  return usageError(e.detail);
576
+ // With --json, the failure is also machine-readable on stdout (code, span, needs).
577
+ if (o.json)
578
+ process.stdout.write(errorJson(e));
485
579
  process.stderr.write(`error[${e.code}]: ${e.message}\n`);
486
580
  return 1;
487
581
  }
@@ -503,6 +597,32 @@ export async function main(argv, run = {}) {
503
597
  }
504
598
  }
505
599
  }
600
+ /** `--node`, else `$SITEFILE_NODE` (ignored when empty): an absolute path. */
601
+ function pluginNode(flag) {
602
+ const [value, from] = flag !== undefined ? [flag, '--node'] : [process.env['SITEFILE_NODE'] || undefined, 'SITEFILE_NODE'];
603
+ if (value === undefined)
604
+ return {};
605
+ if (!path.isAbsolute(value))
606
+ throw new SitefileError('E_USAGE', `${from} expects an absolute path to a Node binary, got '${value}'`);
607
+ return { node: value };
608
+ }
609
+ /** True when `file` would be written inside the directory `dir` (lexically, from the cwd). */
610
+ function isInsideDir(file, dir) {
611
+ const rel = path.relative(path.resolve(dir), path.resolve(file));
612
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
613
+ }
614
+ /** `--experimental-dictionary <previous>`: the previous build's files (an image, directory or archive). */
615
+ async function previousBuild(arg) {
616
+ if (arg === undefined)
617
+ return undefined;
618
+ let store;
619
+ const open = () => (store ??= Store.open());
620
+ return loadTarget(await resolveTarget(arg, open), open);
621
+ }
622
+ /** `--manifest`: the exported files' manifest, written with the export's destination rules (and --force). */
623
+ async function writeManifest(tree, file, contextDir, force) {
624
+ await exportFile(encodeManifest(manifestOf(tree)), file, { contextDir, force });
625
+ }
506
626
  function positiveInt(raw, flag) {
507
627
  const n = Number(raw);
508
628
  if (!Number.isSafeInteger(n) || n <= 0)
@@ -0,0 +1,17 @@
1
+ import { type HeaderRule } from './site.js';
2
+ import { type FileNode, type Tree } from './tree.js';
3
+ /** `sha256-<base64>` of a text's UTF-8 bytes, as CSP hash sources name it. */
4
+ export declare function cspHash(text: string): string;
5
+ export interface CspResult {
6
+ /** META off: one `Content-Security-Policy` rule per page path (see {@link pagePatterns}), in page order. */
7
+ readonly rules: HeaderRule[];
8
+ /** META on: the pages with the `<meta>` inserted after `<head>`. */
9
+ readonly pages: Array<[string, FileNode]>;
10
+ /** META on: pages with no `<head>` start tag, left as they are. */
11
+ readonly headless: string[];
12
+ }
13
+ /**
14
+ * The policies for the `.html`/`.htm` pages (valid UTF-8) of `tree` below `exportPath`, in path order (UTF-8).
15
+ * `tree` is the whole tree; paths in the results are tree paths, patterns URL paths below `exportPath`.
16
+ */
17
+ export declare function cspPages(tree: Tree, exportPath: string, base: string, meta: boolean, origin: string): CspResult;
package/lib/src/csp.js ADDED
@@ -0,0 +1,52 @@
1
+ // CSP (docs/LANGUAGE.md, "Content Security Policy"): a policy per exported page with the hashes of its
2
+ // inline scripts and styles. Ported as rust/src/csp.rs: both must write the same headers and pages.
3
+ import { createHash } from 'node:crypto';
4
+ import { inlineBlocks, referenceKind } from './links.js';
5
+ import { cspMeta, cspPolicy, pagePatterns } from './site.js';
6
+ import { makeFile } from './tree.js';
7
+ /** `sha256-<base64>` of a text's UTF-8 bytes, as CSP hash sources name it. */
8
+ export function cspHash(text) {
9
+ return 'sha256-' + createHash('sha256').update(text, 'utf8').digest('base64');
10
+ }
11
+ const SPACE_OR_CONTROL = /[\u0000- \u007f]/;
12
+ const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
13
+ /**
14
+ * The policies for the `.html`/`.htm` pages (valid UTF-8) of `tree` below `exportPath`, in path order (UTF-8).
15
+ * `tree` is the whole tree; paths in the results are tree paths, patterns URL paths below `exportPath`.
16
+ */
17
+ export function cspPages(tree, exportPath, base, meta, origin) {
18
+ const rules = [];
19
+ const pages = [];
20
+ const headless = [];
21
+ const entries = tree.entries().sort(([a], [b]) => Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8')));
22
+ for (const [p, node] of entries) {
23
+ if (referenceKind(p) !== 'html')
24
+ continue;
25
+ const url = exportPath === '/' ? p : p.startsWith(exportPath + '/') ? p.slice(exportPath.length) : undefined;
26
+ if (url === undefined)
27
+ continue;
28
+ let text;
29
+ try {
30
+ text = UTF8.decode(node.bytes);
31
+ }
32
+ catch {
33
+ continue;
34
+ }
35
+ const blocks = inlineBlocks(text);
36
+ const policy = cspPolicy(base, blocks.scripts.map(cspHash), blocks.styles.map(cspHash));
37
+ if (!meta) {
38
+ for (const pattern of pagePatterns(url))
39
+ if (!SPACE_OR_CONTROL.test(pattern))
40
+ rules.push({ pattern, name: 'Content-Security-Policy', value: policy });
41
+ }
42
+ else if (blocks.headEnd === undefined) {
43
+ headless.push(p);
44
+ }
45
+ else {
46
+ const out = text.slice(0, blocks.headEnd) + cspMeta(policy) + text.slice(blocks.headEnd);
47
+ pages.push([p, makeFile(new TextEncoder().encode(out), origin, node.mode)]);
48
+ }
49
+ }
50
+ return { rules, pages, headless };
51
+ }
52
+ //# sourceMappingURL=csp.js.map
@@ -0,0 +1,16 @@
1
+ import { Tree } from './tree.js';
2
+ export declare function isDictionaryKind(path: string): boolean;
3
+ export interface DictionaryResult {
4
+ readonly tree: Tree;
5
+ /** Paths that got a `.dcz` delta. */
6
+ readonly deltas: readonly string[];
7
+ }
8
+ /** The exported tree with `.dcz` deltas against `previous` and the `Use-As-Dictionary` headers. */
9
+ export declare function addDictionaryDeltas(tree: Tree, previous: Tree): DictionaryResult;
10
+ /** True when `Accept-Encoding` lists `dcz` with a non-zero quality. */
11
+ export declare function acceptsDcz(acceptEncoding: string | undefined): boolean;
12
+ /**
13
+ * The `dcz` response for `path`: the bytes of `<path>.dcz` when the request accepts `dcz` and its
14
+ * `Available-Dictionary` is the hash the delta was made against; otherwise undefined.
15
+ */
16
+ export declare function deltaFor(tree: Tree, path: string, availableDictionary: string | undefined, acceptEncoding: string | undefined): Uint8Array | undefined;
@@ -0,0 +1,89 @@
1
+ import { SitefileError } from './errors.js';
2
+ import { makeFile, Tree } from './tree.js';
3
+ import { dczEncode } from './zstd.js';
4
+ /**
5
+ * Compression Dictionary Transport (issue #215; experimental, `build --experimental-dictionary`).
6
+ *
7
+ * With the previous build of a site, every text-like asset (`.js`, `.mjs`, `.css`, `.json`, `.wasm`,
8
+ * `.html`) whose content changed but whose path stayed the same gets a `<path>.dcz` sidecar: the new
9
+ * file as a `dcz` delta (Zstandard, src/zstd.ts) against the previous version. Every such asset with a
10
+ * plain path also gets `Use-As-Dictionary: match="<path>"` in `/_headers`, so a browser that has it keeps
11
+ * it as the dictionary for the next version. `serve` answers a request with `Available-Dictionary` and
12
+ * `Accept-Encoding: dcz` from the sidecar when its dictionary hash matches ({@link deltaFor}).
13
+ *
14
+ * A delta is written only when it is smaller than the file, and only when the previous and new
15
+ * versions together fit in an 8 MiB window (what browsers accept for `dcz`).
16
+ */
17
+ const KINDS = ['.js', '.mjs', '.css', '.json', '.wasm', '.html'];
18
+ const MAX_WINDOW = 8 * 1024 * 1024;
19
+ const PLAIN_PATH = /^[A-Za-z0-9/._~-]+$/;
20
+ export function isDictionaryKind(path) {
21
+ const lower = path.toLowerCase();
22
+ return KINDS.some((k) => lower.endsWith(k));
23
+ }
24
+ /** The exported tree with `.dcz` deltas against `previous` and the `Use-As-Dictionary` headers. */
25
+ export function addDictionaryDeltas(tree, previous) {
26
+ const added = [];
27
+ const deltas = [];
28
+ const header = [];
29
+ for (const [p, n] of tree.entries()) {
30
+ if (!isDictionaryKind(p))
31
+ continue;
32
+ if (PLAIN_PATH.test(p))
33
+ header.push(`${p}\n Use-As-Dictionary: match="${p}"\n`);
34
+ const old = previous.get(p);
35
+ if (!old || old.digest === n.digest || old.bytes.byteLength + n.bytes.byteLength > MAX_WINDOW)
36
+ continue;
37
+ const sidecar = `${p}.dcz`;
38
+ if (tree.get(sidecar))
39
+ throw new SitefileError('E_CONFLICT', `--experimental-dictionary: '${sidecar}' already exists in the output`);
40
+ const delta = dczEncode(n.bytes, old.bytes);
41
+ if (delta.byteLength >= n.bytes.byteLength)
42
+ continue;
43
+ added.push([sidecar, makeFile(delta, 'dictionary delta')]);
44
+ deltas.push(p);
45
+ }
46
+ if (header.length > 0) {
47
+ const existing = tree.get('/_headers');
48
+ const before = existing ? new TextDecoder().decode(existing.bytes) : '';
49
+ const text = `${before}${before === '' || before.endsWith('\n') ? '' : '\n'}# Compression Dictionary Transport (sitefile build --experimental-dictionary)\n${header.join('')}`;
50
+ added.push(['/_headers', makeFile(new TextEncoder().encode(text), 'dictionary headers')]);
51
+ }
52
+ return { tree: tree.withFiles(added, 'overwrite'), deltas };
53
+ }
54
+ /** The bytes of an RFC 8941 byte sequence (`:base64:`), or undefined. */
55
+ function sfBinary(v) {
56
+ const m = v === undefined ? null : /^\s*:([A-Za-z0-9+/]*={0,2}):\s*$/.exec(v);
57
+ return m ? new Uint8Array(Buffer.from(m[1], 'base64')) : undefined;
58
+ }
59
+ /** True when `Accept-Encoding` lists `dcz` with a non-zero quality. */
60
+ export function acceptsDcz(acceptEncoding) {
61
+ if (acceptEncoding === undefined)
62
+ return false;
63
+ return acceptEncoding.split(',').some((part) => {
64
+ const [token, ...params] = part.split(';').map((s) => s.trim());
65
+ if (token?.toLowerCase() !== 'dcz')
66
+ return false;
67
+ const q = params.find((p) => /^q=/i.test(p));
68
+ return q === undefined || Number(q.slice(2)) > 0;
69
+ });
70
+ }
71
+ /**
72
+ * The `dcz` response for `path`: the bytes of `<path>.dcz` when the request accepts `dcz` and its
73
+ * `Available-Dictionary` is the hash the delta was made against; otherwise undefined.
74
+ */
75
+ export function deltaFor(tree, path, availableDictionary, acceptEncoding) {
76
+ if (!acceptsDcz(acceptEncoding))
77
+ return undefined;
78
+ const hash = sfBinary(availableDictionary);
79
+ if (!hash || hash.byteLength !== 32)
80
+ return undefined;
81
+ const sidecar = tree.get(`${path}.dcz`);
82
+ if (!sidecar || sidecar.bytes.byteLength < 40)
83
+ return undefined;
84
+ for (let i = 0; i < 32; i++)
85
+ if (sidecar.bytes[8 + i] !== hash[i])
86
+ return undefined;
87
+ return sidecar.bytes;
88
+ }
89
+ //# sourceMappingURL=dictionary.js.map
@@ -0,0 +1,5 @@
1
+ import { Tree } from './tree.js';
2
+ /** The files of the EPUB container (paths as zip entries, with a leading `/`). */
3
+ export declare function epubTree(tree: Tree, epoch?: number): Tree;
4
+ /** `EXPORT … AS epub`: the EPUB file. */
5
+ export declare function writeEpub(tree: Tree, epoch?: number): Uint8Array;