@johnhenry/sitefile 0.0.1 → 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 +480 -3
  2. package/README.md +70 -21
  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 +144 -18
  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
@@ -2,7 +2,7 @@ import { type SourceSpan } from '../errors.js';
2
2
  /**
3
3
  * Plugins run one Node process each, under Node's permission model:
4
4
  *
5
- * node --permission --allow-fs-read=<plugin folder> --input-type=module -e <runner>
5
+ * node --permission --allow-fs-read=<plugin folder> --max-old-space-size=<MiB> --input-type=module -e <runner>
6
6
  *
7
7
  * so a plugin can read files in its own folder and nothing else: no writes,
8
8
  * child processes, workers, native addons, WASI or network, and an empty
@@ -11,12 +11,42 @@ import { type SourceSpan } from '../errors.js';
11
11
  * Node documents the permission model as a "seat belt" for trusted code, not a
12
12
  * defence against deliberately malicious code: plugins are code you choose to
13
13
  * run. Pin them with INTEGRITY.
14
+ *
15
+ * The sandbox is only as strong as the Node that runs it: by default the Node
16
+ * running sitefile (`process.execPath`), or the one named by `--node` /
17
+ * `SITEFILE_NODE` / `BuildOptions.node`. Its version is checked (at least
18
+ * MIN_NODE) before the first plugin starts, and reported with `onNotice`.
19
+ */
20
+ /**
21
+ * The oldest Node that JavaScript plugins run on. Node 25 added network permissions
22
+ * (before it, `--permission` did not block sockets); 26 is the release sitefile
23
+ * requires and tests with (package.json `engines`).
24
+ */
25
+ export declare const MIN_NODE: readonly [26, 0, 0];
26
+ /** The Node binary JavaScript plugins run on, as checked when the first one starts. */
27
+ export interface NodeRuntime {
28
+ /** Absolute real path. */
29
+ readonly path: string;
30
+ /** `process.version` of that binary, e.g. `v26.11.1`. */
31
+ readonly version: string;
32
+ }
33
+ /** `vX.Y.Z` → [X, Y, Z], or undefined. */
34
+ export declare function parseNodeVersion(v: string): [number, number, number] | undefined;
35
+ /**
36
+ * Resolve and check the Node binary for JavaScript plugins (`node`: an absolute path; default
37
+ * `process.execPath`). The error text is the part after `PLUGIN name: `.
14
38
  */
39
+ export declare function checkNode(node: string | undefined, timeoutMs: number): Promise<NodeRuntime>;
15
40
  export interface PluginPolicy {
16
41
  /** Per-call time limit (default 60 s); the process is killed when it passes. */
17
42
  readonly timeoutMs: number;
18
43
  /** Largest result accepted from one call (default 64 MiB). */
19
44
  readonly maxOutputBytes: number;
45
+ /**
46
+ * Memory limit in MiB (default 1024, `--plugin-memory`): a JavaScript plugin's heap
47
+ * (`node --max-old-space-size`) and a wasm plugin's linear memory.
48
+ */
49
+ readonly maxMemoryMiB: number;
20
50
  }
21
51
  export declare const DEFAULT_PLUGIN_POLICY: PluginPolicy;
22
52
  /** A directory TRANSFORM runs at most this many wasm or tool calls at a time (a JS plugin, one). */
@@ -50,13 +80,32 @@ export interface HostStats {
50
80
  /** transform() calls sent to a plugin process. */
51
81
  calls: number;
52
82
  }
83
+ /** What PluginHost warns when a JavaScript plugin whose results may be reused doesn't export `cache`. */
84
+ export declare function undeclaredCacheWarning(name: string): string;
85
+ /** Where JavaScript plugins' Node comes from, and where to report it. */
86
+ export interface PluginHostOptions {
87
+ /** Absolute path of the Node binary (default: `process.execPath`, the Node running sitefile). */
88
+ readonly node?: string;
89
+ /** Receives `plugins run on node <version> (<path>)` when the first JavaScript plugin starts. */
90
+ readonly onNotice?: (message: string) => void;
91
+ /**
92
+ * The build caches or memoizes results (a cache directory or an incremental rebuild), so a
93
+ * JavaScript plugin that doesn't export `cache` gets one warning.
94
+ */
95
+ readonly reusesResults?: boolean;
96
+ }
53
97
  export declare class PluginHost {
54
98
  private readonly policy;
55
99
  private readonly log;
100
+ private readonly options;
101
+ private readonly warnedCache;
56
102
  private readonly registered;
57
103
  private readonly procs;
58
104
  readonly stats: HostStats;
59
- constructor(policy?: PluginPolicy, log?: (line: string) => void);
105
+ private runtime;
106
+ constructor(policy?: PluginPolicy, log?: (line: string) => void, options?: PluginHostOptions);
107
+ /** The checked Node binary (resolved once, on the first JavaScript plugin). */
108
+ node(): Promise<NodeRuntime>;
60
109
  /**
61
110
  * `file` is the plugin's absolute real path (already sandbox- and integrity-checked).
62
111
  * For a `.wasm` plugin, pass the checked module bytes. Runners start lazily.
@@ -1,9 +1,77 @@
1
- import { spawn } from 'node:child_process';
1
+ import { execFile, spawn } from 'node:child_process';
2
+ import { realpath, stat } from 'node:fs/promises';
2
3
  import os from 'node:os';
3
4
  import path from 'node:path';
4
5
  import { SitefileError } from '../errors.js';
5
6
  import { WasmPlugin } from './wasm.js';
6
- export const DEFAULT_PLUGIN_POLICY = { timeoutMs: 60_000, maxOutputBytes: 64 * 1024 * 1024 };
7
+ /**
8
+ * Plugins run one Node process each, under Node's permission model:
9
+ *
10
+ * node --permission --allow-fs-read=<plugin folder> --max-old-space-size=<MiB> --input-type=module -e <runner>
11
+ *
12
+ * so a plugin can read files in its own folder and nothing else: no writes,
13
+ * child processes, workers, native addons, WASI or network, and an empty
14
+ * environment (no secrets). Requests and results travel over stdin/stdout.
15
+ *
16
+ * Node documents the permission model as a "seat belt" for trusted code, not a
17
+ * defence against deliberately malicious code: plugins are code you choose to
18
+ * run. Pin them with INTEGRITY.
19
+ *
20
+ * The sandbox is only as strong as the Node that runs it: by default the Node
21
+ * running sitefile (`process.execPath`), or the one named by `--node` /
22
+ * `SITEFILE_NODE` / `BuildOptions.node`. Its version is checked (at least
23
+ * MIN_NODE) before the first plugin starts, and reported with `onNotice`.
24
+ */
25
+ /**
26
+ * The oldest Node that JavaScript plugins run on. Node 25 added network permissions
27
+ * (before it, `--permission` did not block sockets); 26 is the release sitefile
28
+ * requires and tests with (package.json `engines`).
29
+ */
30
+ export const MIN_NODE = [26, 0, 0];
31
+ /** `vX.Y.Z` → [X, Y, Z], or undefined. */
32
+ export function parseNodeVersion(v) {
33
+ const m = /^v(\d+)\.(\d+)\.(\d+)$/.exec(v.trim());
34
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : undefined;
35
+ }
36
+ const atLeast = (v, min) => {
37
+ for (let i = 0; i < 3; i++)
38
+ if (v[i] !== min[i])
39
+ return v[i] > min[i];
40
+ return true;
41
+ };
42
+ /**
43
+ * Resolve and check the Node binary for JavaScript plugins (`node`: an absolute path; default
44
+ * `process.execPath`). The error text is the part after `PLUGIN name: `.
45
+ */
46
+ export async function checkNode(node, timeoutMs) {
47
+ const given = node ?? process.execPath;
48
+ const choose = 'choose another with --node or SITEFILE_NODE';
49
+ if (!path.isAbsolute(given))
50
+ throw new Error(`the Node binary must be an absolute path, got '${given}'`);
51
+ let real;
52
+ try {
53
+ real = await realpath(given);
54
+ if (!(await stat(real)).isFile())
55
+ throw new Error('not a file');
56
+ }
57
+ catch {
58
+ throw new Error(`could not start: no Node binary at ${given}`);
59
+ }
60
+ const out = await new Promise((resolve, reject) => execFile(real, ['--version'], { env: {}, timeout: timeoutMs, maxBuffer: 4096 }, (e, stdout) => (e ? reject(e) : resolve(String(stdout))))).catch(() => undefined);
61
+ const parsed = out === undefined ? undefined : parseNodeVersion(out);
62
+ if (!parsed)
63
+ throw new Error(`could not start: ${real} --version did not print a Node version; ${choose}`);
64
+ const version = out.trim();
65
+ if (!atLeast(parsed, MIN_NODE)) {
66
+ throw new Error(`node ${version} (${real}) is too old for the plugin sandbox: JavaScript plugins need Node ${MIN_NODE.join('.')} or later; ${choose}`);
67
+ }
68
+ return { path: real, version };
69
+ }
70
+ export const DEFAULT_PLUGIN_POLICY = { timeoutMs: 60_000, maxOutputBytes: 64 * 1024 * 1024, maxMemoryMiB: 1024 };
71
+ /** What V8 prints when a heap passes --max-old-space-size (followed by a native stack trace). */
72
+ const OUT_OF_MEMORY = 'JavaScript heap out of memory';
73
+ /** V8's out-of-memory report starts with one of these; it and everything after it is not logged. */
74
+ const isFatalReport = (line) => line.startsWith('<--- Last few GCs --->') || line.startsWith('FATAL ERROR:');
7
75
  /** A directory TRANSFORM runs at most this many wasm or tool calls at a time (a JS plugin, one). */
8
76
  export const TRANSFORM_JOBS = Math.max(1, Math.min(4, os.availableParallelism()));
9
77
  /** Prefix that marks protocol lines on the child's stdout; anything else is plugin output. */
@@ -12,8 +80,9 @@ const MARK = '\u0000SITEFILE:';
12
80
  const RUNNER = String.raw `
13
81
  const MARK = '\u0000SITEFILE:';
14
82
  const send = (msg) => process.stdout.write(MARK + JSON.stringify(msg) + '\n');
15
- // Plugin console output goes to stderr so stdout stays a clean channel.
16
- for (const k of ['log', 'info', 'debug']) console[k] = (...a) => process.stderr.write(a.map(String).join(' ') + '\n');
83
+ // Plugin console output goes to stdout as unmarked lines, so it reaches the host before
84
+ // the result that follows it (stderr is another pipe, with no order against stdout).
85
+ for (const k of ['log', 'info', 'debug']) console[k] = (...a) => process.stdout.write(a.map(String).join(' ').split('\n').filter((l) => !l.startsWith(MARK)).join('\n') + '\n');
17
86
  const toB64 = (v) => Buffer.from(typeof v === 'string' ? Buffer.from(v, 'utf8') : v).toString('base64');
18
87
  const isBytes = (v) => typeof v === 'string' || v instanceof Uint8Array;
19
88
  let transform;
@@ -37,9 +106,11 @@ async function handle(msg) {
37
106
  if (typeof api.transform !== 'function') throw new Error('the module must export transform(request), or a default object with transform');
38
107
  if (version !== 1) throw new Error('unsupported plugin apiVersion ' + JSON.stringify(version) + ' (this Sitefile supports 1)');
39
108
  transform = api.transform;
40
- // 'export const cache = false' opts a (non-deterministic) plugin out of the result cache.
109
+ // 'export const cache = false' opts a (non-deterministic) plugin out of the result cache;
110
+ // 'cache = true' says it is deterministic. Without either it is cached, with a warning.
41
111
  const cache = api.cache ?? mod.cache;
42
- send({ type: 'ready', cache: cache !== false });
112
+ if (cache !== undefined && typeof cache !== 'boolean') throw new Error('cache must be true or false, got ' + JSON.stringify(cache));
113
+ send({ type: 'ready', cache: cache !== false, declared: cache !== undefined });
43
114
  } catch (e) {
44
115
  send({ type: 'load-error', message: e && e.message ? e.message : String(e) });
45
116
  }
@@ -76,26 +147,37 @@ class PluginProcess {
76
147
  child;
77
148
  buf = '';
78
149
  stderr = '';
150
+ /** V8 reported that the heap passed the memory limit. */
151
+ outOfMemory = false;
152
+ /** Set once V8's fatal error report starts on stderr: the rest is a native stack trace, not logged. */
153
+ quiet = false;
79
154
  nextId = 1;
80
155
  pending = new Map();
81
156
  /** False when the module exports `cache = false`; known once it has loaded. */
82
157
  cacheable = true;
158
+ /** Whether the module exports `cache` at all; known once it has loaded. */
159
+ declaredCache = true;
83
160
  ready;
84
161
  exited;
85
- constructor(name, file, policy, log, span) {
162
+ constructor(name, file, node, policy, log, span) {
86
163
  this.name = name;
87
164
  this.policy = policy;
88
165
  this.log = log;
89
166
  const dir = path.dirname(file);
90
- this.child = spawn(process.execPath, ['--permission', `--allow-fs-read=${dir}`, '--disable-warning=ExperimentalWarning', '--input-type=module', '-e', RUNNER], { cwd: dir, env: {}, stdio: ['pipe', 'pipe', 'pipe'] });
167
+ this.child = spawn(node, ['--permission', `--allow-fs-read=${dir}`, `--max-old-space-size=${policy.maxMemoryMiB}`, '--disable-warning=ExperimentalWarning', '--input-type=module', '-e', RUNNER], { cwd: dir, env: {}, stdio: ['pipe', 'pipe', 'pipe'] });
91
168
  this.child.stdout.setEncoding('utf8');
92
169
  this.child.stderr.setEncoding('utf8');
93
170
  this.child.stdout.on('data', (chunk) => this.onStdout(chunk));
94
171
  this.child.stderr.on('data', (chunk) => {
95
172
  this.stderr = (this.stderr + chunk).slice(-8192);
96
- for (const line of chunk.split('\n'))
97
- if (line.trim())
173
+ if (this.stderr.includes(OUT_OF_MEMORY))
174
+ this.outOfMemory = true;
175
+ for (const line of chunk.split('\n')) {
176
+ if (isFatalReport(line))
177
+ this.quiet = true;
178
+ if (line.trim() && !this.quiet)
98
179
  this.log(line);
180
+ }
99
181
  });
100
182
  let onReady = () => { };
101
183
  let onLoadError = () => { };
@@ -108,7 +190,8 @@ class PluginProcess {
108
190
  this.onReadyMsg = onReady;
109
191
  this.onLoadError = (m) => onLoadError(new SitefileError('E_PLUGIN', `PLUGIN ${name}: ${m}`, span));
110
192
  this.child.on('error', (e) => this.fail(`could not start: ${e.message}`));
111
- this.child.on('exit', (code, signal) => this.fail(signal ? `stopped by ${signal}` : `exited with code ${code}`));
193
+ // 'close' (not 'exit'): stderr has been read by then, so the reason can say why it died.
194
+ this.child.on('close', (code, signal) => this.fail(signal ? `stopped by ${signal}` : `exited with code ${code}`));
112
195
  this.write({ type: 'load', url: new URL(`file://${file}`).href });
113
196
  }
114
197
  onReadyMsg;
@@ -140,6 +223,7 @@ class PluginProcess {
140
223
  switch (msg['type']) {
141
224
  case 'ready':
142
225
  this.cacheable = msg['cache'] !== false;
226
+ this.declaredCache = msg['declared'] === true;
143
227
  this.onReadyMsg();
144
228
  return;
145
229
  case 'load-error':
@@ -174,6 +258,11 @@ class PluginProcess {
174
258
  fail(reason) {
175
259
  if (this.exited)
176
260
  return;
261
+ if (this.outOfMemory) {
262
+ // The stderr tail would be V8's native stack trace: machine-specific, and no help.
263
+ reason = `ran out of memory (more than the ${this.policy.maxMemoryMiB} MiB limit)`;
264
+ this.stderr = '';
265
+ }
177
266
  this.exited = reason;
178
267
  const tail = this.stderr.trim() ? `\n${this.stderr.trim().split('\n').slice(-5).join('\n')}` : '';
179
268
  const err = new Error(`${reason}${tail}`);
@@ -217,15 +306,34 @@ class PluginProcess {
217
306
  this.child.kill();
218
307
  }
219
308
  }
309
+ /** What PluginHost warns when a JavaScript plugin whose results may be reused doesn't export `cache`. */
310
+ export function undeclaredCacheWarning(name) {
311
+ return `PLUGIN ${name} does not export cache, so its results are reused as if it were deterministic: export const cache = true to confirm, or cache = false if a result can depend on the clock, randomness or an earlier call`;
312
+ }
220
313
  export class PluginHost {
221
314
  policy;
222
315
  log;
316
+ options;
317
+ warnedCache = new Set();
223
318
  registered = new Map();
224
319
  procs = new Map();
225
320
  stats = { spawned: 0, calls: 0 };
226
- constructor(policy = DEFAULT_PLUGIN_POLICY, log = () => { }) {
321
+ runtime;
322
+ constructor(policy = DEFAULT_PLUGIN_POLICY, log = () => { }, options = {}) {
227
323
  this.policy = policy;
228
324
  this.log = log;
325
+ this.options = options;
326
+ }
327
+ /** The checked Node binary (resolved once, on the first JavaScript plugin). */
328
+ node() {
329
+ if (!this.runtime) {
330
+ this.runtime = checkNode(this.options.node, this.policy.timeoutMs).then((rt) => {
331
+ this.options.onNotice?.(`plugins run on node ${rt.version} (${rt.path})`);
332
+ return rt;
333
+ });
334
+ this.runtime.catch(() => { });
335
+ }
336
+ return this.runtime;
229
337
  }
230
338
  /**
231
339
  * `file` is the plugin's absolute real path (already sandbox- and integrity-checked).
@@ -249,14 +357,32 @@ export class PluginHost {
249
357
  const reg = this.registered.get(name);
250
358
  if (!reg)
251
359
  throw new SitefileError('E_UNDEFINED', `unknown plugin '${name}'`, span);
252
- p = reg.wasm
253
- ? new WasmPlugin(name, reg.wasm, this.policy, TRANSFORM_JOBS)
254
- : new PluginProcess(name, reg.file, this.policy, (l) => this.log(`[plugin ${name}] ${l}`), reg.span);
255
- this.procs.set(name, p);
256
- this.stats.spawned++;
360
+ let node;
361
+ if (!reg.wasm) {
362
+ try {
363
+ node = await this.node();
364
+ }
365
+ catch (e) {
366
+ throw new SitefileError('E_PLUGIN', `PLUGIN ${name}: ${e.message}`, reg.span);
367
+ }
368
+ // Another call may have started it while this one waited for the check.
369
+ p = this.procs.get(name);
370
+ }
371
+ if (!p) {
372
+ p = reg.wasm
373
+ ? new WasmPlugin(name, reg.wasm, this.policy, TRANSFORM_JOBS)
374
+ : new PluginProcess(name, reg.file, node.path, this.policy, (l) => this.log(`[plugin ${name}] ${l}`), reg.span);
375
+ this.procs.set(name, p);
376
+ this.stats.spawned++;
377
+ }
257
378
  }
258
379
  this.stats.calls++;
259
- return p.call(request, span);
380
+ const result = await p.call(request, span);
381
+ if (this.options.reusesResults && p instanceof PluginProcess && !p.declaredCache && !this.warnedCache.has(name)) {
382
+ this.warnedCache.add(name);
383
+ this.log(undeclaredCacheWarning(name));
384
+ }
385
+ return result;
260
386
  }
261
387
  /** The folder a registered plugin lives in. */
262
388
  folderOf(name) {
@@ -74,8 +74,6 @@ parentPort.on('message', ({ id, request }) => {
74
74
  }
75
75
  });
76
76
  `;
77
- /** Largest linear memory a wasm plugin may use (default 1 GiB). */
78
- const DEFAULT_MAX_MEMORY = 1024 * 1024 * 1024;
79
77
  /**
80
78
  * A wasm plugin: up to `lanes` workers, so a directory TRANSFORM can run several calls at once.
81
79
  * A call waits for a free worker, and its time limit starts when that worker takes it.
@@ -146,7 +144,7 @@ class WasmLane {
146
144
  return this.worker;
147
145
  const w = new Worker(WORKER, {
148
146
  eval: true,
149
- workerData: { bytes: this.bytes, maxMemory: DEFAULT_MAX_MEMORY },
147
+ workerData: { bytes: this.bytes, maxMemory: this.policy.maxMemoryMiB * 1024 * 1024 },
150
148
  // The worker's own JS heap; wasm memory is checked after each call.
151
149
  resourceLimits: { maxOldGenerationSizeMb: 256 },
152
150
  env: {},
@@ -0,0 +1,8 @@
1
+ /** Why a path cannot be written on Windows, or undefined. */
2
+ export declare function windowsProblem(path: string): string | undefined;
3
+ /**
4
+ * Portability problems of the exported files (`paths` are below the export root, in UTF-8 order): one message
5
+ * per path Windows cannot hold, then one about GitHub Pages when a file or folder starts with `_` (other than
6
+ * `/_headers` and `/_redirects`) and there is no `/.nojekyll`.
7
+ */
8
+ export declare function portabilityProblems(paths: readonly string[]): string[];
@@ -0,0 +1,47 @@
1
+ // Path portability (docs/LANGUAGE.md, "Portable paths"): names that work locally but break on other
2
+ // systems or hosts. Ported as rust/src/portable.rs: both must find the same problems, in the same words.
3
+ /** Windows device names: a file named so (with any extension) cannot be created there. */
4
+ const RESERVED = new Set(['CON', 'PRN', 'AUX', 'NUL', ...[1, 2, 3, 4, 5, 6, 7, 8, 9, '¹', '²', '³'].flatMap((n) => [`COM${n}`, `LPT${n}`])]);
5
+ /** Characters Windows does not allow in a file name. */
6
+ const WINDOWS_CHARS = /[<>:"|?*\\\u0000-\u001f]/;
7
+ /** Why a path cannot be written on Windows, or undefined. */
8
+ export function windowsProblem(path) {
9
+ for (const seg of path.split('/').slice(1)) {
10
+ const bad = WINDOWS_CHARS.exec(seg);
11
+ if (bad) {
12
+ const c = bad[0];
13
+ const shown = c.charCodeAt(0) < 0x20 ? `U+${c.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0')}` : `'${c}'`;
14
+ return `${shown} is not allowed in a Windows file name`;
15
+ }
16
+ if (seg.endsWith('.') || seg.endsWith(' '))
17
+ return `'${seg}' ends with ${seg.endsWith('.') ? 'a dot' : 'a space'}, which Windows drops`;
18
+ const stem = seg.split('.')[0].replace(/ +$/, '').toUpperCase();
19
+ if (RESERVED.has(stem))
20
+ return `'${seg}' is a reserved device name on Windows`;
21
+ }
22
+ return undefined;
23
+ }
24
+ /** Root files Netlify and Cloudflare Pages read; GitHub Pages' Jekyll skipping them does no harm. */
25
+ const HOST_FILES = new Set(['/_headers', '/_redirects']);
26
+ /**
27
+ * Portability problems of the exported files (`paths` are below the export root, in UTF-8 order): one message
28
+ * per path Windows cannot hold, then one about GitHub Pages when a file or folder starts with `_` (other than
29
+ * `/_headers` and `/_redirects`) and there is no `/.nojekyll`.
30
+ */
31
+ export function portabilityProblems(paths) {
32
+ const out = [];
33
+ for (const p of paths) {
34
+ const why = windowsProblem(p);
35
+ if (why)
36
+ out.push(`'${p}' cannot be extracted on Windows: ${why}`);
37
+ }
38
+ if (!paths.includes('/.nojekyll')) {
39
+ const hidden = paths.filter((p) => !HOST_FILES.has(p) && p.split('/').some((s) => s.startsWith('_')));
40
+ if (hidden.length > 0) {
41
+ const shown = hidden.slice(0, 3).join(', ') + (hidden.length > 3 ? `, … (${hidden.length} in all)` : '');
42
+ out.push(`GitHub Pages (with Jekyll) does not publish files or folders whose name starts with '_' (${shown}); if the site is hosted there, add an empty /.nojekyll`);
43
+ }
44
+ }
45
+ return out;
46
+ }
47
+ //# sourceMappingURL=portable.js.map
@@ -0,0 +1,33 @@
1
+ import { type SourceSpan } from './errors.js';
2
+ import { type Tree } from './tree.js';
3
+ /** Where `injectManifest` puts the manifest in a service worker (Workbox's default `injectionPoint`). */
4
+ export declare const INJECTION_POINT = "self.__WB_MANIFEST";
5
+ export interface PrecacheOp {
6
+ readonly patterns: readonly string[];
7
+ readonly dest?: string;
8
+ readonly into?: string;
9
+ readonly root: string;
10
+ readonly overwrite: boolean;
11
+ readonly span: SourceSpan;
12
+ }
13
+ /**
14
+ * The manifest entries: every file matching a pattern below `root` (other than the manifest and the
15
+ * service worker), as `{url, revision}` sorted by URL. The URL is the path below `root`, percent-encoded;
16
+ * the revision is the first 10 hex digits of the file's SHA-256, or null for a file a FINGERPRINT renamed
17
+ * (`fingerprinted`: its name already changes with its content).
18
+ */
19
+ export declare function precacheEntries(tree: Tree, op: PrecacheOp, fingerprinted: ReadonlySet<string>): Array<{
20
+ url: string;
21
+ revision: string | null;
22
+ }>;
23
+ /** The manifest as JSON: one entry per line, two-space indented, with a final newline (`[]` when empty). */
24
+ export declare function precacheJson(entries: ReadonlyArray<{
25
+ url: string;
26
+ revision: string | null;
27
+ }>): string;
28
+ /**
29
+ * Write the manifest to `dest` and/or replace the first `self.__WB_MANIFEST` in the service worker `into`
30
+ * (a file of the tree, valid UTF-8, holding the placeholder: E_VALIDATION otherwise) with the JSON array.
31
+ * Warns when no file matches.
32
+ */
33
+ export declare function precache(tree: Tree, op: PrecacheOp, fingerprinted: ReadonlySet<string>, origin: string, warn: (m: string) => void): Tree;
@@ -0,0 +1,75 @@
1
+ // PRECACHE (docs/LANGUAGE.md, "Precache manifest"): a Workbox-style list of the files a service worker
2
+ // precaches, `[{url, revision}]`. Ported as rust/src/precache.rs: both must write the same bytes.
3
+ import { createHash } from 'node:crypto';
4
+ import { SitefileError } from './errors.js';
5
+ import { globMatches, HASH_LENGTH } from './fingerprint.js';
6
+ import { encodePath } from './links.js';
7
+ import { makeFile } from './tree.js';
8
+ /** Where `injectManifest` puts the manifest in a service worker (Workbox's default `injectionPoint`). */
9
+ export const INJECTION_POINT = 'self.__WB_MANIFEST';
10
+ function utf8Compare(a, b) {
11
+ return Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'));
12
+ }
13
+ /**
14
+ * The manifest entries: every file matching a pattern below `root` (other than the manifest and the
15
+ * service worker), as `{url, revision}` sorted by URL. The URL is the path below `root`, percent-encoded;
16
+ * the revision is the first 10 hex digits of the file's SHA-256, or null for a file a FINGERPRINT renamed
17
+ * (`fingerprinted`: its name already changes with its content).
18
+ */
19
+ export function precacheEntries(tree, op, fingerprinted) {
20
+ const out = [];
21
+ for (const [p, node] of tree.entries()) {
22
+ if (p === op.dest || p === op.into || !op.patterns.some((pat) => globMatches(pat, p)))
23
+ continue;
24
+ const below = op.root === '/' ? p : p.startsWith(op.root + '/') ? p.slice(op.root.length) : undefined;
25
+ if (below === undefined)
26
+ continue;
27
+ const revision = fingerprinted.has(p) ? null : createHash('sha256').update(node.bytes).digest('hex').slice(0, HASH_LENGTH);
28
+ out.push({ url: encodePath(below), revision });
29
+ }
30
+ return out.sort((a, b) => utf8Compare(a.url, b.url));
31
+ }
32
+ /** The manifest as JSON: one entry per line, two-space indented, with a final newline (`[]` when empty). */
33
+ export function precacheJson(entries) {
34
+ if (entries.length === 0)
35
+ return '[]\n';
36
+ return '[\n' + entries.map((e) => ` {"url": ${JSON.stringify(e.url)}, "revision": ${JSON.stringify(e.revision)}}`).join(',\n') + '\n]\n';
37
+ }
38
+ const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
39
+ /**
40
+ * Write the manifest to `dest` and/or replace the first `self.__WB_MANIFEST` in the service worker `into`
41
+ * (a file of the tree, valid UTF-8, holding the placeholder: E_VALIDATION otherwise) with the JSON array.
42
+ * Warns when no file matches.
43
+ */
44
+ export function precache(tree, op, fingerprinted, origin, warn) {
45
+ const entries = precacheEntries(tree, op, fingerprinted);
46
+ if (entries.length === 0)
47
+ warn(`${origin}: no files match ${op.patterns.join(' ')}`);
48
+ const json = precacheJson(entries);
49
+ const files = [];
50
+ if (op.dest !== undefined)
51
+ files.push([op.dest, makeFile(new TextEncoder().encode(json), origin)]);
52
+ if (op.into !== undefined) {
53
+ const sw = tree.get(op.into);
54
+ if (!sw)
55
+ throw new SitefileError('E_VALIDATION', `PRECACHE INTO ${op.into}: there is no such file in the stage (COPY the service worker in first)`, op.span);
56
+ let text;
57
+ try {
58
+ text = UTF8.decode(sw.bytes);
59
+ }
60
+ catch {
61
+ throw new SitefileError('E_VALIDATION', `PRECACHE INTO ${op.into}: the service worker is not UTF-8 text`, op.span);
62
+ }
63
+ const at = text.indexOf(INJECTION_POINT);
64
+ if (at === -1)
65
+ throw new SitefileError('E_VALIDATION', `PRECACHE INTO ${op.into}: the service worker has no ${INJECTION_POINT} to replace with the manifest`, op.span);
66
+ const injected = text.slice(0, at) + json.trimEnd() + text.slice(at + INJECTION_POINT.length);
67
+ files.push([op.into, makeFile(new TextEncoder().encode(injected), origin, sw.mode)]);
68
+ }
69
+ // The service worker is replaced by its injected version; the manifest follows the conflict rules.
70
+ let out = tree;
71
+ for (const [p, node] of files)
72
+ out = out.withFiles([[p, node]], p === op.into || op.overwrite ? 'overwrite' : 'error', op.span);
73
+ return out;
74
+ }
75
+ //# sourceMappingURL=precache.js.map
@@ -0,0 +1,19 @@
1
+ import type { SourceSpan } from './errors.js';
2
+ import { type Tree } from './tree.js';
3
+ /** Extensions (lowercase, after the last dot) of the file types PRECOMPRESS compresses: text, scripts, data, fonts without their own compression. */
4
+ export declare const COMPRESSIBLE: Set<string>;
5
+ /** Whether a path names a compressible file type (by its extension, ASCII case-insensitive). */
6
+ export declare function compressible(path: string): boolean;
7
+ export interface PrecompressOp {
8
+ readonly patterns: readonly string[];
9
+ readonly min: number;
10
+ readonly overwrite: boolean;
11
+ readonly span: SourceSpan;
12
+ }
13
+ /**
14
+ * The tree with a `<path>.gz` sidecar (gzip, fixed header) for every file that matches a pattern, is
15
+ * compressible, has at least `min` bytes, and compresses to fewer bytes than it has. Sidecars keep the
16
+ * file's mode and get the origin `origin`; one that would replace a different file is a conflict unless
17
+ * `overwrite`. Warns when no file matches the patterns.
18
+ */
19
+ export declare function precompress(tree: Tree, op: PrecompressOp, origin: string, warn: (m: string) => void): Tree;
@@ -0,0 +1,35 @@
1
+ import { gzip } from './deflate.js';
2
+ import { globMatches } from './fingerprint.js';
3
+ import { makeFile } from './tree.js';
4
+ /** Extensions (lowercase, after the last dot) of the file types PRECOMPRESS compresses: text, scripts, data, fonts without their own compression. */
5
+ export const COMPRESSIBLE = new Set([
6
+ 'html', 'htm', 'css', 'js', 'mjs', 'cjs', 'json', 'map', 'xml', 'svg', 'txt', 'md', 'csv', 'tsv',
7
+ 'webmanifest', 'rss', 'atom', 'ics', 'vtt', 'yaml', 'yml', 'toml', 'wasm', 'ttf', 'otf', 'eot', 'ico',
8
+ ]);
9
+ /** Whether a path names a compressible file type (by its extension, ASCII case-insensitive). */
10
+ export function compressible(path) {
11
+ const base = path.slice(path.lastIndexOf('/') + 1);
12
+ const dot = base.lastIndexOf('.');
13
+ return dot > 0 && COMPRESSIBLE.has(base.slice(dot + 1).toLowerCase());
14
+ }
15
+ /**
16
+ * The tree with a `<path>.gz` sidecar (gzip, fixed header) for every file that matches a pattern, is
17
+ * compressible, has at least `min` bytes, and compresses to fewer bytes than it has. Sidecars keep the
18
+ * file's mode and get the origin `origin`; one that would replace a different file is a conflict unless
19
+ * `overwrite`. Warns when no file matches the patterns.
20
+ */
21
+ export function precompress(tree, op, origin, warn) {
22
+ const matched = tree.entries().filter(([p]) => op.patterns.some((pat) => globMatches(pat, p)));
23
+ if (matched.length === 0)
24
+ warn(`${origin}: no files match ${op.patterns.join(' ')}`);
25
+ const files = [];
26
+ for (const [p, node] of matched) {
27
+ if (!compressible(p) || node.bytes.byteLength < op.min)
28
+ continue;
29
+ const gz = gzip(node.bytes);
30
+ if (gz.byteLength < node.bytes.byteLength)
31
+ files.push([p + '.gz', makeFile(gz, origin, node.mode)]);
32
+ }
33
+ return files.length ? tree.withFiles(files, op.overwrite ? 'overwrite' : 'error', op.span) : tree;
34
+ }
35
+ //# sourceMappingURL=precompress.js.map
@@ -0,0 +1,18 @@
1
+ /**
2
+ * A QR Code encoder (ISO/IEC 18004), enough for `serve --qr` (issue #224): byte mode, error correction
3
+ * level M, the smallest version (1–40) that fits, and the mask with the lowest penalty. Ported as
4
+ * rust/src/qr.rs; both produce the same modules (test/fixtures/qr/*.txt are checked by both).
5
+ */
6
+ /** A QR Code: `size` × `size` modules, `true` = dark. */
7
+ export interface QrCode {
8
+ readonly version: number;
9
+ readonly size: number;
10
+ readonly modules: readonly (readonly boolean[])[];
11
+ }
12
+ /** Encode `text` (UTF-8) as a QR Code, or undefined when it is too long for version 40. */
13
+ export declare function encodeQr(text: string): QrCode | undefined;
14
+ /**
15
+ * The code for a terminal: two rows of modules per line with `▀`, `▄`, `█` and spaces, and a quiet zone
16
+ * of two modules, dark on a light background (the half blocks are the light parts' complement).
17
+ */
18
+ export declare function qrTerminal(code: QrCode): string;