@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.
- package/CHANGELOG.md +516 -0
- package/README.md +59 -9
- package/lib/src/archive-writers.d.ts +12 -2
- package/lib/src/archive-writers.js +53 -10
- package/lib/src/bake.d.ts +2 -0
- package/lib/src/bake.js +30 -1
- package/lib/src/bcrypt.d.ts +25 -0
- package/lib/src/bcrypt.js +201 -0
- package/lib/src/canonical.d.ts +19 -0
- package/lib/src/canonical.js +60 -0
- package/lib/src/car.d.ts +34 -0
- package/lib/src/car.js +203 -0
- package/lib/src/checklinks.js +8 -2
- package/lib/src/cli/bake.js +4 -3
- package/lib/src/cli/build-image.d.ts +1 -0
- package/lib/src/cli/build-image.js +1 -0
- package/lib/src/cli/common.js +4 -1
- package/lib/src/cli/hosts.d.ts +5 -0
- package/lib/src/cli/hosts.js +78 -0
- package/lib/src/cli/images.js +23 -5
- package/lib/src/cli/import-config.d.ts +2 -0
- package/lib/src/cli/import-config.js +56 -0
- package/lib/src/cli/index.d.ts +6 -1
- package/lib/src/cli/index.js +34 -2
- package/lib/src/cli/integrity.d.ts +2 -0
- package/lib/src/cli/integrity.js +77 -0
- package/lib/src/cli/network.d.ts +7 -0
- package/lib/src/cli/network.js +14 -3
- package/lib/src/cli/serve-keys.d.ts +39 -0
- package/lib/src/cli/serve-keys.js +106 -0
- package/lib/src/cli/serve-worker.js +119 -8
- package/lib/src/cli/servers.d.ts +130 -1
- package/lib/src/cli/servers.js +754 -72
- package/lib/src/cli/up.d.ts +2 -0
- package/lib/src/cli/up.js +193 -0
- package/lib/src/cli/watch.d.ts +14 -1
- package/lib/src/cli/watch.js +20 -3
- package/lib/src/cli.js +138 -18
- package/lib/src/csp.d.ts +17 -0
- package/lib/src/csp.js +52 -0
- package/lib/src/dictionary.d.ts +16 -0
- package/lib/src/dictionary.js +89 -0
- package/lib/src/epub.d.ts +5 -0
- package/lib/src/epub.js +113 -0
- package/lib/src/errors.d.ts +22 -9
- package/lib/src/errors.js +20 -1
- package/lib/src/executor.d.ts +31 -1
- package/lib/src/executor.js +231 -24
- package/lib/src/explain.js +33 -3
- package/lib/src/export-for.d.ts +42 -0
- package/lib/src/export-for.js +466 -0
- package/lib/src/export-formats.d.ts +2 -2
- package/lib/src/export-formats.js +52 -2
- package/lib/src/fingerprint.d.ts +3 -1
- package/lib/src/fingerprint.js +32 -5
- package/lib/src/host-config.d.ts +34 -0
- package/lib/src/host-config.js +645 -0
- package/lib/src/hosts.d.ts +47 -0
- package/lib/src/hosts.js +106 -0
- package/lib/src/hreflang.d.ts +25 -0
- package/lib/src/hreflang.js +72 -0
- package/lib/src/index.d.ts +1 -1
- package/lib/src/index.js +1 -1
- package/lib/src/integrity.d.ts +115 -0
- package/lib/src/integrity.js +273 -0
- package/lib/src/language/ast.d.ts +126 -3
- package/lib/src/language/ast.js +7 -1
- package/lib/src/language/parser.js +189 -7
- package/lib/src/language/validate.js +24 -0
- package/lib/src/links.d.ts +47 -0
- package/lib/src/links.js +289 -3
- package/lib/src/lint.d.ts +1 -1
- package/lib/src/lint.js +26 -1
- package/lib/src/mime-data.d.ts +2 -0
- package/lib/src/mime-data.js +92 -0
- package/lib/src/oci.d.ts +20 -2
- package/lib/src/oci.js +70 -28
- package/lib/src/outdated.d.ts +3 -0
- package/lib/src/outdated.js +4 -4
- package/lib/src/planner.d.ts +87 -2
- package/lib/src/planner.js +189 -8
- package/lib/src/plugins/cache.d.ts +11 -0
- package/lib/src/plugins/cache.js +29 -0
- package/lib/src/plugins/host.d.ts +51 -2
- package/lib/src/plugins/host.js +141 -16
- package/lib/src/plugins/wasm.js +1 -3
- package/lib/src/portable.d.ts +8 -0
- package/lib/src/portable.js +47 -0
- package/lib/src/precache.d.ts +33 -0
- package/lib/src/precache.js +75 -0
- package/lib/src/precompress.d.ts +19 -0
- package/lib/src/precompress.js +35 -0
- package/lib/src/qr.d.ts +18 -0
- package/lib/src/qr.js +372 -0
- package/lib/src/registry-ops.js +4 -2
- package/lib/src/reload-client.d.ts +2 -0
- package/lib/src/reload-client.js +419 -0
- package/lib/src/resources/archive.d.ts +37 -1
- package/lib/src/resources/archive.js +353 -71
- package/lib/src/resources/convert.js +3 -1
- package/lib/src/resources/https.d.ts +9 -1
- package/lib/src/resources/https.js +36 -0
- package/lib/src/resources/network.d.ts +25 -3
- package/lib/src/resources/network.js +77 -6
- package/lib/src/secrets.d.ts +12 -3
- package/lib/src/secrets.js +18 -5
- package/lib/src/serve-auth.d.ts +33 -0
- package/lib/src/serve-auth.js +120 -0
- package/lib/src/serve-rules.d.ts +83 -7
- package/lib/src/serve-rules.js +264 -53
- package/lib/src/server.d.ts +529 -11
- package/lib/src/server.js +1439 -57
- package/lib/src/servers-file.d.ts +36 -0
- package/lib/src/servers-file.js +101 -0
- package/lib/src/servers.d.ts +115 -7
- package/lib/src/servers.js +151 -29
- package/lib/src/single-file.d.ts +12 -0
- package/lib/src/single-file.js +147 -0
- package/lib/src/site.d.ts +58 -0
- package/lib/src/site.js +216 -5
- package/lib/src/store.js +9 -5
- package/lib/src/swbn.d.ts +10 -0
- package/lib/src/swbn.js +86 -0
- package/lib/src/toml.d.ts +17 -0
- package/lib/src/toml.js +323 -0
- package/lib/src/wacz.d.ts +6 -0
- package/lib/src/wacz.js +96 -0
- package/lib/src/warc.d.ts +28 -0
- package/lib/src/warc.js +252 -0
- package/lib/src/watch.d.ts +12 -1
- package/lib/src/watch.js +67 -1
- package/lib/src/wbn.d.ts +9 -1
- package/lib/src/wbn.js +23 -33
- package/lib/src/zstd.d.ts +4 -0
- package/lib/src/zstd.js +328 -0
- package/package.json +1 -1
package/lib/src/oci.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
1
2
|
import { readFile } from 'node:fs/promises';
|
|
2
3
|
import path from 'node:path';
|
|
3
4
|
import { gunzipSync } from 'node:zlib';
|
|
@@ -46,8 +47,16 @@ export const ANN = {
|
|
|
46
47
|
files: 'dev.sitefile.files',
|
|
47
48
|
size: 'dev.sitefile.size',
|
|
48
49
|
stored: 'dev.sitefile.created',
|
|
50
|
+
/** The number of site layers (`--oci-layers`, issue #214); absent means one. */
|
|
51
|
+
layers: 'dev.sitefile.layers',
|
|
49
52
|
};
|
|
53
|
+
/** Most site layers `--oci-layers` accepts. */
|
|
54
|
+
export const MAX_OCI_LAYERS = 64;
|
|
50
55
|
const EPOCH_ISO = '1970-01-01T00:00:00Z';
|
|
56
|
+
/** The site layer (0-based, of `n`) a file belongs to: the first 4 bytes of SHA-256 of its path, mod n. */
|
|
57
|
+
export function layerOf(path, n) {
|
|
58
|
+
return n <= 1 ? 0 : createHash('sha256').update(path).digest().readUInt32BE(0) % n;
|
|
59
|
+
}
|
|
51
60
|
/** JSON with sorted keys and no whitespace. */
|
|
52
61
|
export function canonicalJson(v) {
|
|
53
62
|
if (v === null || typeof v !== 'object')
|
|
@@ -81,14 +90,23 @@ function isoOf(epoch) {
|
|
|
81
90
|
export function buildOciImage(tree, options = {}) {
|
|
82
91
|
const root = normalizeOciRoot(options.root);
|
|
83
92
|
const { os, arch } = parsePlatform(options.platform);
|
|
84
|
-
const layerTree = Tree.fromFiles(tree.mountedAt(root));
|
|
85
93
|
const segs = root === '/' ? [] : root.slice(1).split('/');
|
|
86
94
|
const dirs = segs.map((_, i) => segs.slice(0, i + 1).join('/'));
|
|
87
|
-
const tar = writeTar(layerTree, { epoch: options.epoch ?? 0, dirs });
|
|
88
95
|
const uncompressed = options.compression === 'none';
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
96
|
+
const n = options.layers ?? 1;
|
|
97
|
+
if (!Number.isSafeInteger(n) || n < 1 || n > MAX_OCI_LAYERS)
|
|
98
|
+
throw new SitefileError('E_USAGE', `--oci-layers expects an integer from 1 to ${MAX_OCI_LAYERS}`);
|
|
99
|
+
// Every layer carries the root's parent directories; with one layer this is the image it always was.
|
|
100
|
+
const parts = Array.from({ length: n }, () => []);
|
|
101
|
+
for (const [p, f] of tree.entries())
|
|
102
|
+
parts[layerOf(p, n)].push([p, f]);
|
|
103
|
+
const site = parts.map((files) => {
|
|
104
|
+
const tar = writeTar(Tree.fromFiles(Tree.fromFiles(files).mountedAt(root)), { epoch: options.epoch ?? 0, dirs });
|
|
105
|
+
const bytes = uncompressed ? tar : gzipTar(tar);
|
|
106
|
+
const diffId = sha256(tar);
|
|
107
|
+
return { bytes, diffId, digest: uncompressed ? diffId : sha256(bytes) };
|
|
108
|
+
});
|
|
109
|
+
const { bytes: layerBytes, diffId, digest: layerDigest } = site[0];
|
|
92
110
|
const size = tree.entries().reduce((n, [, f]) => n + f.bytes.byteLength, 0);
|
|
93
111
|
const base = options.base;
|
|
94
112
|
const baseCfg = base?.config ?? {};
|
|
@@ -99,6 +117,8 @@ export function buildOciImage(tree, options = {}) {
|
|
|
99
117
|
if (typeof v === 'string')
|
|
100
118
|
labels[k] = v;
|
|
101
119
|
labels[ANN.root] = root;
|
|
120
|
+
if (n > 1)
|
|
121
|
+
labels[ANN.layers] = String(n);
|
|
102
122
|
if (options.title)
|
|
103
123
|
labels[ANN.title] = options.title;
|
|
104
124
|
if (options.source)
|
|
@@ -127,7 +147,7 @@ export function buildOciImage(tree, options = {}) {
|
|
|
127
147
|
os: base && typeof baseCfg.os === 'string' ? baseCfg.os : os,
|
|
128
148
|
created,
|
|
129
149
|
config: { ...baseInner, Labels: labels },
|
|
130
|
-
rootfs: { type: 'layers', diff_ids: [...baseDiffIds, diffId] },
|
|
150
|
+
rootfs: { type: 'layers', diff_ids: [...baseDiffIds, ...site.map((l) => l.diffId)] },
|
|
131
151
|
history: [...baseHistory, { created: isoOf(options.epoch), created_by: 'sitefile', comment: 'static site files', author: 'sitefile' }],
|
|
132
152
|
}));
|
|
133
153
|
const configDigest = sha256(configBytes);
|
|
@@ -142,10 +162,11 @@ export function buildOciImage(tree, options = {}) {
|
|
|
142
162
|
schemaVersion: 2,
|
|
143
163
|
mediaType: MEDIA.manifest,
|
|
144
164
|
config: { mediaType: MEDIA.config, digest: configDigest, size: configBytes.byteLength },
|
|
145
|
-
layers: [...baseLayers, { mediaType: uncompressed ? MEDIA.layerTar : MEDIA.layer, digest:
|
|
165
|
+
layers: [...baseLayers, ...site.map((l) => ({ mediaType: uncompressed ? MEDIA.layerTar : MEDIA.layer, digest: l.digest, size: l.bytes.byteLength }))],
|
|
146
166
|
annotations,
|
|
147
167
|
}));
|
|
148
|
-
|
|
168
|
+
const extraLayers = n > 1 ? new Map(site.slice(1).map((l) => [l.digest, l.bytes])) : undefined;
|
|
169
|
+
return { manifestBytes, manifestDigest: sha256(manifestBytes), configBytes, configDigest, layerBytes, layerDigest, diffId, root, baseLayers, ...(extraLayers ? { extraLayers } : {}) };
|
|
149
170
|
}
|
|
150
171
|
function isRecord(v) {
|
|
151
172
|
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
@@ -213,7 +234,7 @@ baseBlobs = new Map(), referrers = []) {
|
|
|
213
234
|
{ digest: img.manifestDigest, size: img.manifestBytes.byteLength, ...(refName ? { extra: exportNameAnnotations(refName) } : {}) },
|
|
214
235
|
...referrers.map((r) => ({ digest: r.descriptor.digest, size: r.descriptor.size, artifactType: r.descriptor.artifactType, extra: r.descriptor.annotations })),
|
|
215
236
|
];
|
|
216
|
-
const blobs = new Map([[img.manifestDigest, img.manifestBytes], [img.configDigest, img.configBytes], [img.layerDigest, img.layerBytes], ...baseBlobs]);
|
|
237
|
+
const blobs = new Map([[img.manifestDigest, img.manifestBytes], [img.configDigest, img.configBytes], [img.layerDigest, img.layerBytes], ...(img.extraLayers ?? []), ...baseBlobs]);
|
|
217
238
|
for (const r of referrers)
|
|
218
239
|
for (const [d, b] of r.blobs)
|
|
219
240
|
blobs.set(d, b);
|
|
@@ -263,9 +284,23 @@ export function parseConfig(bytes) {
|
|
|
263
284
|
* carries the `dev.sitefile.root` label (built with BASE). -1 when the image is not a Sitefile image.
|
|
264
285
|
*/
|
|
265
286
|
export function siteLayerIndex(m, cfg) {
|
|
287
|
+
return siteLayerIndices(m, cfg)[0] ?? -1;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Indices of every layer holding site files: the last `dev.sitefile.layers` layers (`--oci-layers`),
|
|
291
|
+
* else the one {@link siteLayerIndex} names; empty when the image is not a Sitefile image.
|
|
292
|
+
*/
|
|
293
|
+
export function siteLayerIndices(m, cfg) {
|
|
294
|
+
const raw = cfg.labels[ANN.layers];
|
|
295
|
+
if (raw !== undefined && cfg.labels[ANN.root] !== undefined) {
|
|
296
|
+
const n = /^[1-9][0-9]{0,1}$/.test(raw) ? Number(raw) : 0;
|
|
297
|
+
if (n < 1 || n > MAX_OCI_LAYERS || n > m.layers.length)
|
|
298
|
+
return [];
|
|
299
|
+
return Array.from({ length: n }, (_, i) => m.layers.length - n + i);
|
|
300
|
+
}
|
|
266
301
|
if (m.layers.length === 1)
|
|
267
|
-
return 0;
|
|
268
|
-
return m.layers.length > 1 && cfg.labels[ANN.root] !== undefined ? m.layers.length - 1 :
|
|
302
|
+
return [0];
|
|
303
|
+
return m.layers.length > 1 && cfg.labels[ANN.root] !== undefined ? [m.layers.length - 1] : [];
|
|
269
304
|
}
|
|
270
305
|
/**
|
|
271
306
|
* Decode a site image's files, verifying the layer digest and diff_id.
|
|
@@ -273,28 +308,35 @@ export function siteLayerIndex(m, cfg) {
|
|
|
273
308
|
* `dev.sitefile.root` label, else `/`), or under `rootOverride` (`FROM image … AT <dir>`).
|
|
274
309
|
*/
|
|
275
310
|
export async function extractImageFiles(m, cfg, layerBytes, origin, rootOverride) {
|
|
276
|
-
const
|
|
277
|
-
const
|
|
278
|
-
if (
|
|
311
|
+
const blobs = layerBytes instanceof Uint8Array ? [layerBytes] : layerBytes;
|
|
312
|
+
const indices = siteLayerIndices(m, cfg);
|
|
313
|
+
if (indices.length === 0 || indices.length !== blobs.length || indices.some((i) => m.layers[i]?.mediaType !== MEDIA.layer && m.layers[i]?.mediaType !== MEDIA.layerTar)) {
|
|
279
314
|
throw new SitefileError('E_STORE', `${origin}: not a Sitefile image (only single-layer tar or tar+gzip images, or images built with BASE, hold site files)`);
|
|
280
315
|
}
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
316
|
+
const root = rootOverride ?? cfg.labels[ANN.root] ?? '/';
|
|
317
|
+
let files = [];
|
|
318
|
+
for (const [k, idx] of indices.entries()) {
|
|
319
|
+
const layer = m.layers[idx];
|
|
320
|
+
const bytes = blobs[k];
|
|
321
|
+
if (sha256(bytes) !== layer.digest || bytes.byteLength !== layer.size) {
|
|
322
|
+
throw new SitefileError('E_STORE', `${origin}: layer blob does not match its digest`);
|
|
288
323
|
}
|
|
289
|
-
|
|
290
|
-
|
|
324
|
+
let tar = bytes;
|
|
325
|
+
if (layer.mediaType === MEDIA.layer) {
|
|
326
|
+
try {
|
|
327
|
+
tar = new Uint8Array(gunzipSync(bytes));
|
|
328
|
+
}
|
|
329
|
+
catch (e) {
|
|
330
|
+
throw new SitefileError('E_STORE', `${origin}: layer is not valid gzip`, undefined, { cause: e });
|
|
331
|
+
}
|
|
291
332
|
}
|
|
333
|
+
if (sha256(tar) !== cfg.diffIds[idx])
|
|
334
|
+
throw new SitefileError('E_STORE', `${origin}: layer content does not match the config diff_id`);
|
|
335
|
+
const all = await extractArchive(tar, origin, { maxEntries: 1_000_000, maxTotalBytes: 8 * 2 ** 30, maxRatio: Number.MAX_SAFE_INTEGER });
|
|
336
|
+
files = files.concat(all.subtree(normalizeVirtual(root).path).entries());
|
|
292
337
|
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
const root = rootOverride ?? cfg.labels[ANN.root] ?? '/';
|
|
296
|
-
const all = await extractArchive(tar, origin, { maxEntries: 1_000_000, maxTotalBytes: 8 * 2 ** 30, maxRatio: Number.MAX_SAFE_INTEGER });
|
|
297
|
-
return all.subtree(normalizeVirtual(root).path);
|
|
338
|
+
// Site layers hold disjoint paths; were one repeated, the upper layer wins, as in a container.
|
|
339
|
+
return Tree.empty.withFiles(files, 'overwrite');
|
|
298
340
|
}
|
|
299
341
|
/**
|
|
300
342
|
* Label values for an image built from `contextDir`: the title (directory name),
|
package/lib/src/outdated.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Needs } from './errors.js';
|
|
1
2
|
import { type BuildOptions } from './executor.js';
|
|
2
3
|
/**
|
|
3
4
|
* `sitefile outdated` (issue #104): report, for every remote input, whether what it points at today
|
|
@@ -32,9 +33,11 @@ export interface OutdatedEntry {
|
|
|
32
33
|
readonly status: OutdatedStatus;
|
|
33
34
|
/** Images only (BASE and FROM image): a greater version-like tag of the same shape. */
|
|
34
35
|
readonly newerTag: string | null;
|
|
36
|
+
/** `needs` only when the error carries one (E_HOST_BLOCKED: the host to allow). */
|
|
35
37
|
readonly error: {
|
|
36
38
|
readonly code: string;
|
|
37
39
|
readonly message: string;
|
|
40
|
+
readonly needs?: Needs;
|
|
38
41
|
} | null;
|
|
39
42
|
}
|
|
40
43
|
export interface OutdatedReport {
|
package/lib/src/outdated.js
CHANGED
|
@@ -49,7 +49,7 @@ export function newerVersionTag(current, tags) {
|
|
|
49
49
|
}
|
|
50
50
|
function errorOf(e, secrets) {
|
|
51
51
|
if (isSitefileError(e))
|
|
52
|
-
return { code: e.code, message: redactSecrets(e.detail, secrets) };
|
|
52
|
+
return { code: e.code, message: redactSecrets(e.detail, secrets), ...(e.needs ? { needs: { kind: e.needs.kind, name: e.needs.name, flag: e.needs.flag } } : {}) };
|
|
53
53
|
throw redactError(e, secrets);
|
|
54
54
|
}
|
|
55
55
|
/** An entry with its keys in the documented order (the JSON output is compared across implementations). */
|
|
@@ -89,7 +89,7 @@ export async function outdated(options) {
|
|
|
89
89
|
}
|
|
90
90
|
else {
|
|
91
91
|
try {
|
|
92
|
-
const originHeaders = secretHeaders(spec, options.secrets);
|
|
92
|
+
const originHeaders = secretHeaders(spec, options.secrets, { url: loc.repo, network: policy.network });
|
|
93
93
|
const latest = await resolveRef(loc.repo, loc.ref, { policy, span: spec.span, ...(originHeaders ? { originHeaders } : {}) });
|
|
94
94
|
inputs.push(entry({ ...row, latest, status: statusOf(pin, latest), error: null }));
|
|
95
95
|
}
|
|
@@ -105,7 +105,7 @@ export async function outdated(options) {
|
|
|
105
105
|
const pinnedBy = spec.integrity ? 'integrity' : locked ? 'lockfile' : null;
|
|
106
106
|
const row = { kind: 'import', name, source: url, pin, pinnedBy, newerTag: null };
|
|
107
107
|
try {
|
|
108
|
-
const originHeaders = secretHeaders(spec, options.secrets);
|
|
108
|
+
const originHeaders = secretHeaders(spec, options.secrets, { url, network: policy.network });
|
|
109
109
|
const { bytes } = await fetchRemote(url, policy, undefined, originHeaders ? { originHeaders } : {});
|
|
110
110
|
const latest = sha256(bytes);
|
|
111
111
|
inputs.push(entry({ ...row, latest, status: statusOf(pin, latest), error: null }));
|
|
@@ -120,7 +120,7 @@ export async function outdated(options) {
|
|
|
120
120
|
let sub;
|
|
121
121
|
try {
|
|
122
122
|
sub = await readImportedSitefile(spec, source, importedStageRefs(sp.stages), async (s, loc) => {
|
|
123
|
-
const originHeaders = secretHeaders(s, options.secrets);
|
|
123
|
+
const originHeaders = secretHeaders(s, options.secrets, { url: loc.repo, network: policy.network });
|
|
124
124
|
const want = loc.commit ?? lock?.getGit(loc.url)?.commit;
|
|
125
125
|
const objs = await fetchGitCommit(loc.repo, loc.ref, want, { policy, span: s.span, ...(originHeaders ? { originHeaders } : {}) }, limits);
|
|
126
126
|
return { commit: objs.commit, selection: selectGitPath(objs, loc, limits, s.span) };
|
package/lib/src/planner.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type SourceSpan } from './errors.js';
|
|
2
|
-
import { type EscapeMode, type RedirectStatus, type ExportFormat, type ImportKind, type OciCompression, type Operand, type Program } from './language/ast.js';
|
|
2
|
+
import { type EscapeMode, type RedirectStatus, type ExportFormat, type ExportHost, type ImportKind, type OciCompression, type Operand, type PrecompressFormat, type Program } from './language/ast.js';
|
|
3
3
|
import { type Scalar } from './values.js';
|
|
4
4
|
import { type GitLocation } from './resources/git.js';
|
|
5
5
|
import type { TemplateNode } from './render.js';
|
|
@@ -101,13 +101,45 @@ export interface RedirectSpec {
|
|
|
101
101
|
readonly overwrite: boolean;
|
|
102
102
|
readonly span: SourceSpan;
|
|
103
103
|
}
|
|
104
|
-
/** A HEADER, evaluated; written to `/_headers` at EXPORT. */
|
|
104
|
+
/** A HEADER (or a MIME, as a `Content-Type` rule), evaluated; written to `/_headers` at EXPORT. */
|
|
105
105
|
export interface HeaderSpec {
|
|
106
106
|
readonly pattern: string;
|
|
107
107
|
readonly name: string;
|
|
108
108
|
readonly value: string;
|
|
109
109
|
readonly overwrite: boolean;
|
|
110
110
|
readonly span: SourceSpan;
|
|
111
|
+
/** Set for a MIME line (names it in origins and `why`). */
|
|
112
|
+
readonly instruction?: 'MIME';
|
|
113
|
+
}
|
|
114
|
+
/** A file whose text the planner wrote (ROBOTS: `/robots.txt`, SECURITY_TXT: `/.well-known/security.txt`). */
|
|
115
|
+
export interface TextFileOperation<K extends 'ROBOTS' | 'SECURITY_TXT'> {
|
|
116
|
+
readonly kind: K;
|
|
117
|
+
readonly dest: string;
|
|
118
|
+
readonly text: string;
|
|
119
|
+
readonly overwrite: boolean;
|
|
120
|
+
readonly span: SourceSpan;
|
|
121
|
+
}
|
|
122
|
+
/** A CSP, evaluated: the base policy (checked) and where the per-page policies go. */
|
|
123
|
+
export interface CspSpec {
|
|
124
|
+
readonly policy: string;
|
|
125
|
+
readonly meta: boolean;
|
|
126
|
+
readonly span: SourceSpan;
|
|
127
|
+
}
|
|
128
|
+
/** CSP's base policy when POLICY is not given: same-origin resources only, no plugins, no `<base>` hijacking. */
|
|
129
|
+
export declare const DEFAULT_CSP = "default-src 'self'; base-uri 'self'; object-src 'none'";
|
|
130
|
+
/**
|
|
131
|
+
* LANGUAGES, evaluated, as CANONICAL and SITEMAP see it: the language folders, the DEFAULT language, and the
|
|
132
|
+
* stage's `RENDER … FOR` lines before them (without BY or PAGE), whose documents may set `lang` and
|
|
133
|
+
* `translationKey`.
|
|
134
|
+
*/
|
|
135
|
+
export interface LanguagesSpec {
|
|
136
|
+
readonly codes: readonly string[];
|
|
137
|
+
readonly default?: string;
|
|
138
|
+
readonly sources: ReadonlyArray<{
|
|
139
|
+
readonly as: string;
|
|
140
|
+
readonly list: string;
|
|
141
|
+
readonly dest: Operand;
|
|
142
|
+
}>;
|
|
111
143
|
}
|
|
112
144
|
export type Operation = {
|
|
113
145
|
/** Report the references in the tree's HTML and CSS files that point at nothing. */
|
|
@@ -126,10 +158,42 @@ export type Operation = {
|
|
|
126
158
|
readonly patterns: readonly string[];
|
|
127
159
|
/** `MANIFEST <dest>`: the JSON map of old to new paths. */
|
|
128
160
|
readonly manifest?: string;
|
|
161
|
+
/** `INTEGRITY`: add `integrity="sha384-…"` to the script and stylesheet tags that load a renamed file. */
|
|
162
|
+
readonly integrity?: true;
|
|
129
163
|
/** The EXPORT path: absolute references (`/img/a.png`) in HTML and CSS name files below it. */
|
|
130
164
|
readonly root: string;
|
|
131
165
|
readonly overwrite: boolean;
|
|
132
166
|
readonly span: SourceSpan;
|
|
167
|
+
} | TextFileOperation<'ROBOTS'> | TextFileOperation<'SECURITY_TXT'> | {
|
|
168
|
+
/** Add a canonical link to every page below `root` that has none. */
|
|
169
|
+
readonly kind: 'CANONICAL';
|
|
170
|
+
/** Checked base URL without trailing slashes. */
|
|
171
|
+
readonly base: string;
|
|
172
|
+
readonly pretty: boolean;
|
|
173
|
+
/** The EXPORT path: a page's URL is its path below it. */
|
|
174
|
+
readonly root: string;
|
|
175
|
+
readonly span: SourceSpan;
|
|
176
|
+
/** With LANGUAGES: hreflang alternates too. */
|
|
177
|
+
readonly languages?: LanguagesSpec;
|
|
178
|
+
} | {
|
|
179
|
+
/** Write a `.gz` sidecar for each matching compressible file of at least `min` bytes, when smaller. */
|
|
180
|
+
readonly kind: 'PRECOMPRESS';
|
|
181
|
+
readonly formats: readonly PrecompressFormat[];
|
|
182
|
+
/** Checked absolute patterns, NFC; a trailing `/` became `/**`. */
|
|
183
|
+
readonly patterns: readonly string[];
|
|
184
|
+
readonly min: number;
|
|
185
|
+
readonly overwrite: boolean;
|
|
186
|
+
readonly span: SourceSpan;
|
|
187
|
+
} | {
|
|
188
|
+
/** A precache manifest of the files matching `patterns` (checked, NFC), written to `dest` and/or injected into `into`. */
|
|
189
|
+
readonly kind: 'PRECACHE';
|
|
190
|
+
readonly patterns: readonly string[];
|
|
191
|
+
readonly dest?: string;
|
|
192
|
+
readonly into?: string;
|
|
193
|
+
/** The EXPORT path: URLs are paths below it. */
|
|
194
|
+
readonly root: string;
|
|
195
|
+
readonly overwrite: boolean;
|
|
196
|
+
readonly span: SourceSpan;
|
|
133
197
|
} | {
|
|
134
198
|
/** sitemaps.org XML of the `.html` files in the tree at this point. */
|
|
135
199
|
readonly kind: 'SITEMAP';
|
|
@@ -138,6 +202,8 @@ export type Operation = {
|
|
|
138
202
|
readonly dest: string;
|
|
139
203
|
readonly overwrite: boolean;
|
|
140
204
|
readonly span: SourceSpan;
|
|
205
|
+
/** With LANGUAGES: `xhtml:link` alternates too. */
|
|
206
|
+
readonly languages?: LanguagesSpec;
|
|
141
207
|
} | {
|
|
142
208
|
/** An Atom feed of a list import; `link` is interpolated per element (`${item…}`). */
|
|
143
209
|
readonly kind: 'FEED';
|
|
@@ -261,10 +327,27 @@ export interface Plan {
|
|
|
261
327
|
readonly exportRoot: string | undefined;
|
|
262
328
|
/** `COMPRESSION` clause of EXPORT ... AS oci or wbn (undefined: gzip for oci, none for wbn). */
|
|
263
329
|
readonly exportCompression: OciCompression | undefined;
|
|
330
|
+
/** `KEY <secret-id>` of EXPORT ... AS swbn: the --secret holding the signing key. */
|
|
331
|
+
readonly exportKey?: string;
|
|
332
|
+
/** `FOR <host>` of EXPORT: which host's files the REDIRECT and HEADER rules become (undefined: `_redirects`/`_headers`). */
|
|
333
|
+
readonly exportFor?: {
|
|
334
|
+
readonly host: ExportHost;
|
|
335
|
+
readonly span: SourceSpan;
|
|
336
|
+
};
|
|
264
337
|
/** REDIRECT lines in source order (any stage); EXPORT writes them to `/_redirects`. */
|
|
265
338
|
readonly redirects: readonly RedirectSpec[];
|
|
266
339
|
/** HEADER lines in source order (any stage); EXPORT writes them to `/_headers`. */
|
|
267
340
|
readonly headers: readonly HeaderSpec[];
|
|
341
|
+
/**
|
|
342
|
+
* Set when EXPORT adds `Cache-Control` lines for the fingerprinted files (and the pages) to `/_headers`:
|
|
343
|
+
* the Sitefile has a FINGERPRINT, none of them says `--no-cache-headers`, and no HEADER sets
|
|
344
|
+
* `Cache-Control` itself. `span` is the first FINGERPRINT's (the origin of the lines).
|
|
345
|
+
*/
|
|
346
|
+
readonly cacheHeaders?: {
|
|
347
|
+
readonly span: SourceSpan;
|
|
348
|
+
};
|
|
349
|
+
/** The CSP instruction (any stage): EXPORT adds a policy for every exported page. */
|
|
350
|
+
readonly csp?: CspSpec;
|
|
268
351
|
readonly warnings: readonly string[];
|
|
269
352
|
/**
|
|
270
353
|
* `--target <stage>`: the build stops after this stage and exports its whole tree (see {@link targetPlan}).
|
|
@@ -284,6 +367,8 @@ export declare function plan(program: Program, buildArgs?: Readonly<Record<strin
|
|
|
284
367
|
* name is a usage error that lists the named stages.
|
|
285
368
|
*/
|
|
286
369
|
export declare function targetPlan(p: Plan, name: string): Plan;
|
|
370
|
+
/** PRECOMPRESS leaves smaller files alone: below about 1 KiB compression saves little. */
|
|
371
|
+
export declare const DEFAULT_PRECOMPRESS_MIN = 1024;
|
|
287
372
|
/** A reference to a stage of an imported Sitefile (`FROM theme+assets`, `COPY --from=theme+assets …`). */
|
|
288
373
|
export interface ImportedStageRef {
|
|
289
374
|
/** `theme+assets` */
|
package/lib/src/planner.js
CHANGED
|
@@ -3,10 +3,13 @@ import { importedStage, isFragment, isImageBase, isInline, stageNames } from './
|
|
|
3
3
|
import { normalizeLocal, normalizeVirtual } from './paths.js';
|
|
4
4
|
import { parseRef } from './ref.js';
|
|
5
5
|
import { checkPattern } from './fingerprint.js';
|
|
6
|
-
import {
|
|
6
|
+
import { isLanguageTag } from './hreflang.js';
|
|
7
|
+
import { checkBaseUrl, checkFieldUri, checkCspPolicy, checkHeaderName, checkHeaderValue, checkMimeExtension, checkMimeType, checkRedirectTarget, checkSitePath, pageUrl, parseFeedDate, robotsTxt, securityTxt } from './site.js';
|
|
7
8
|
import { coerce, evaluateOperand } from './values.js';
|
|
8
9
|
import { isGitUri, parseGitUri } from './resources/git.js';
|
|
9
10
|
import { parseFragmentBody } from './language/validate.js';
|
|
11
|
+
/** CSP's base policy when POLICY is not given: same-origin resources only, no plugins, no `<base>` hijacking. */
|
|
12
|
+
export const DEFAULT_CSP = "default-src 'self'; base-uri 'self'; object-src 'none'";
|
|
10
13
|
const URL_RE = /^([A-Za-z][A-Za-z0-9+.-]*):\/\//;
|
|
11
14
|
const IMPORT_REF_RE = /^([A-Za-z_][A-Za-z0-9_]*):(.*)$/s;
|
|
12
15
|
/**
|
|
@@ -22,6 +25,12 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
|
|
|
22
25
|
const tools = [];
|
|
23
26
|
const redirects = [];
|
|
24
27
|
const headers = [];
|
|
28
|
+
const fingerprints = [];
|
|
29
|
+
const sitemapUrls = [];
|
|
30
|
+
const robots = [];
|
|
31
|
+
let csp;
|
|
32
|
+
let languages;
|
|
33
|
+
const mimes = new Map();
|
|
25
34
|
const warnings = [];
|
|
26
35
|
const declaredArgs = new Set();
|
|
27
36
|
const allStageNames = stageNames(program.instructions);
|
|
@@ -32,6 +41,8 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
|
|
|
32
41
|
let exportBase;
|
|
33
42
|
let exportRoot;
|
|
34
43
|
let exportCompression;
|
|
44
|
+
let exportKey;
|
|
45
|
+
let exportFor;
|
|
35
46
|
const bind = (name, raw, type, span, what) => {
|
|
36
47
|
vars.set(name, coerce(raw, type, span, what));
|
|
37
48
|
};
|
|
@@ -185,14 +196,76 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
|
|
|
185
196
|
break;
|
|
186
197
|
case 'SITEMAP': {
|
|
187
198
|
const base = checkBaseUrl(evaluateOperand(ins.base, vars), 'SITEMAP BASE', ins.base.span);
|
|
188
|
-
|
|
199
|
+
const dest = fileDest(ins.dest, vars, '/sitemap.xml', 'SITEMAP');
|
|
200
|
+
sitemapUrls.push(pageUrl(base, dest));
|
|
201
|
+
operations().push({ kind: 'SITEMAP', base, dest, overwrite: ins.overwrite, span: ins.span });
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
case 'ROBOTS': {
|
|
205
|
+
const rules = ins.rules.map((r) => ({ allow: r.allow, path: checkSitePath(evaluateOperand(r.path, vars), `ROBOTS ${r.allow ? 'ALLOW' : 'DISALLOW'} path`, r.path.span) }));
|
|
206
|
+
const op = { kind: 'ROBOTS', dest: fileDest(ins.dest, vars, '/robots.txt', 'ROBOTS'), text: robotsTxt(rules, []), overwrite: ins.overwrite, span: ins.span };
|
|
207
|
+
operations().push(op);
|
|
208
|
+
// The Sitemap lines name every SITEMAP of the Sitefile, also later ones: filled in below.
|
|
209
|
+
if (ins.sitemap)
|
|
210
|
+
robots.push({ op, rules, stage: stages.length - 1 });
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
case 'SECURITY_TXT': {
|
|
214
|
+
const raw = evaluateOperand(ins.expires, vars);
|
|
215
|
+
const date = parseFeedDate(raw);
|
|
216
|
+
if (!date)
|
|
217
|
+
throw new SitefileError('E_VALIDATION', `SECURITY_TXT EXPIRES '${raw}' must be a date (YYYY-MM-DD) or an RFC 3339 date-time; durations are not accepted, so the file is the same on every build`, ins.expires.span);
|
|
218
|
+
const now = Date.now() / 1000;
|
|
219
|
+
if (date.seconds <= now)
|
|
220
|
+
warnings.push(`${program.file}:${ins.span.line}: SECURITY_TXT EXPIRES ${raw} is in the past, so security.txt is already stale (RFC 9116); set a later date`);
|
|
221
|
+
else if (date.seconds - now < 30 * 86400)
|
|
222
|
+
warnings.push(`${program.file}:${ins.span.line}: SECURITY_TXT EXPIRES ${raw} is less than 30 days away; set a later date before it passes`);
|
|
223
|
+
const uri = (o, field, schemes) => checkFieldUri(evaluateOperand(o, vars), field, schemes, o.span);
|
|
224
|
+
const text = securityTxt({
|
|
225
|
+
contact: ins.contact.map((o) => uri(o, 'CONTACT', ['mailto:', 'tel:', 'https://'])),
|
|
226
|
+
expires: date.text,
|
|
227
|
+
encryption: ins.encryption.map((o) => uri(o, 'ENCRYPTION', ['https://', 'openpgp4fpr:', 'dns:'])),
|
|
228
|
+
policy: ins.policy.map((o) => uri(o, 'POLICY', ['https://'])),
|
|
229
|
+
});
|
|
230
|
+
operations().push({ kind: 'SECURITY_TXT', dest: fileDest(ins.dest, vars, '/.well-known/security.txt', 'SECURITY_TXT'), text, overwrite: ins.overwrite, span: ins.span });
|
|
189
231
|
break;
|
|
190
232
|
}
|
|
191
233
|
case 'FINGERPRINT': {
|
|
192
234
|
const patterns = ins.patterns.map((o) => checkPattern(evaluateOperand(o, vars), o.span));
|
|
193
235
|
const manifest = ins.manifest ? fileDest(ins.manifest, vars, '', 'FINGERPRINT MANIFEST') : undefined;
|
|
194
236
|
// `root` is the EXPORT path, filled in below (EXPORT is the last instruction).
|
|
195
|
-
operations().push({
|
|
237
|
+
operations().push({
|
|
238
|
+
kind: 'FINGERPRINT',
|
|
239
|
+
patterns,
|
|
240
|
+
...(manifest !== undefined ? { manifest } : {}),
|
|
241
|
+
...(ins.integrity && { integrity: true }),
|
|
242
|
+
root: '/',
|
|
243
|
+
overwrite: ins.overwrite,
|
|
244
|
+
span: ins.span,
|
|
245
|
+
});
|
|
246
|
+
fingerprints.push({ span: ins.span, headers: !ins.noCacheHeaders });
|
|
247
|
+
break;
|
|
248
|
+
}
|
|
249
|
+
case 'CANONICAL':
|
|
250
|
+
// `root` is the EXPORT path, filled in below.
|
|
251
|
+
operations().push({ kind: 'CANONICAL', base: checkBaseUrl(evaluateOperand(ins.base, vars), 'CANONICAL BASE', ins.base.span), pretty: ins.pretty, root: '/', span: ins.span });
|
|
252
|
+
break;
|
|
253
|
+
case 'PRECOMPRESS':
|
|
254
|
+
operations().push({
|
|
255
|
+
kind: 'PRECOMPRESS',
|
|
256
|
+
formats: ins.formats,
|
|
257
|
+
patterns: ins.patterns.map((o) => checkPattern(evaluateOperand(o, vars), o.span, 'PRECOMPRESS')),
|
|
258
|
+
min: ins.min ? minSize(ins.min, vars) : DEFAULT_PRECOMPRESS_MIN,
|
|
259
|
+
overwrite: ins.overwrite,
|
|
260
|
+
span: ins.span,
|
|
261
|
+
});
|
|
262
|
+
break;
|
|
263
|
+
case 'PRECACHE': {
|
|
264
|
+
const patterns = ins.patterns.map((o) => checkPattern(evaluateOperand(o, vars), o.span, 'PRECACHE'));
|
|
265
|
+
const into = ins.into ? fileDest(ins.into, vars, '', 'PRECACHE INTO') : undefined;
|
|
266
|
+
const dest = ins.dest || !into ? fileDest(ins.dest, vars, '/sw-manifest.json', 'PRECACHE') : undefined;
|
|
267
|
+
// `root` is the EXPORT path, filled in below.
|
|
268
|
+
operations().push({ kind: 'PRECACHE', patterns, ...(dest !== undefined ? { dest } : {}), ...(into !== undefined ? { into } : {}), root: '/', overwrite: ins.overwrite, span: ins.span });
|
|
196
269
|
break;
|
|
197
270
|
}
|
|
198
271
|
case 'CHECKLINKS':
|
|
@@ -233,6 +306,42 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
|
|
|
233
306
|
});
|
|
234
307
|
break;
|
|
235
308
|
}
|
|
309
|
+
case 'LANGUAGES': {
|
|
310
|
+
if (languages)
|
|
311
|
+
throw new SitefileError('E_VALIDATION', `LANGUAGES given twice (line ${languages.span.line} already lists the languages)`, ins.span);
|
|
312
|
+
const codes = [];
|
|
313
|
+
for (const o of ins.codes) {
|
|
314
|
+
const code = languageTag(evaluateOperand(o, vars), o.span);
|
|
315
|
+
if (codes.some((c) => c.toLowerCase() === code.toLowerCase()))
|
|
316
|
+
throw new SitefileError('E_VALIDATION', `LANGUAGES: '${code}' is listed twice`, o.span);
|
|
317
|
+
codes.push(code);
|
|
318
|
+
}
|
|
319
|
+
let dflt;
|
|
320
|
+
if (ins.default) {
|
|
321
|
+
dflt = languageTag(evaluateOperand(ins.default, vars), ins.default.span);
|
|
322
|
+
const d = dflt;
|
|
323
|
+
if (!codes.some((c) => c === d))
|
|
324
|
+
throw new SitefileError('E_VALIDATION', `LANGUAGES … DEFAULT ${d}: '${d}' is not one of the languages listed (${codes.join(' ')})`, ins.default.span);
|
|
325
|
+
}
|
|
326
|
+
languages = { codes, ...(dflt !== undefined ? { default: dflt } : {}), span: ins.span };
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
case 'CSP': {
|
|
330
|
+
if (csp)
|
|
331
|
+
throw new SitefileError('E_VALIDATION', `CSP given twice (line ${csp.span.line} already sets the policy)`, ins.span);
|
|
332
|
+
const policy = ins.policy ? checkCspPolicy(evaluateOperand(ins.policy, vars), ins.policy.span) : DEFAULT_CSP;
|
|
333
|
+
csp = { policy, meta: ins.meta, span: ins.span };
|
|
334
|
+
break;
|
|
335
|
+
}
|
|
336
|
+
case 'MIME': {
|
|
337
|
+
const ext = checkMimeExtension(evaluateOperand(ins.ext, vars), ins.ext.span);
|
|
338
|
+
const prior = mimes.get(ext);
|
|
339
|
+
if (prior !== undefined)
|
|
340
|
+
throw new SitefileError('E_VALIDATION', `MIME ${ext} given twice (line ${prior} already sets its type)`, ins.ext.span);
|
|
341
|
+
mimes.set(ext, ins.span.line);
|
|
342
|
+
headers.push({ pattern: `/*${ext}`, name: 'Content-Type', value: checkMimeType(evaluateOperand(ins.type, vars), ins.type.span), overwrite: false, span: ins.span, instruction: 'MIME' });
|
|
343
|
+
break;
|
|
344
|
+
}
|
|
236
345
|
case 'EXPORT':
|
|
237
346
|
exportPath = normalizeVirtual(evaluateOperand(ins.path, vars), ins.path.span, 'EXPORT path').path;
|
|
238
347
|
exportFormat = ins.format;
|
|
@@ -240,19 +349,49 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
|
|
|
240
349
|
if (ins.at && ins.format !== 'oci')
|
|
241
350
|
throw new SitefileError('E_VALIDATION', 'EXPORT ... AT applies only to AS oci', ins.at.span);
|
|
242
351
|
exportRoot = ins.at ? normalizeVirtual(evaluateOperand(ins.at, vars), ins.at.span, 'EXPORT AT path').path : undefined;
|
|
243
|
-
if (ins.compression && ins.format !== 'oci' && ins.format !== 'wbn')
|
|
244
|
-
throw new SitefileError('E_VALIDATION', 'EXPORT ... COMPRESSION applies only to AS oci and AS
|
|
352
|
+
if (ins.compression && ins.format !== 'oci' && ins.format !== 'wbn' && ins.format !== 'warc')
|
|
353
|
+
throw new SitefileError('E_VALIDATION', 'EXPORT ... COMPRESSION applies only to AS oci, AS wbn and AS warc', ins.compression.span);
|
|
245
354
|
exportCompression = ins.compression?.value;
|
|
355
|
+
if (ins.key && ins.format !== 'swbn')
|
|
356
|
+
throw new SitefileError('E_VALIDATION', 'EXPORT ... KEY applies only to AS swbn', ins.key.span);
|
|
357
|
+
if (ins.format === 'swbn' && !ins.key)
|
|
358
|
+
throw new SitefileError('E_VALIDATION', 'EXPORT ... AS swbn needs KEY <secret-id>: the --secret that holds the Ed25519 signing key', ins.span);
|
|
359
|
+
exportKey = ins.key?.id;
|
|
360
|
+
if (ins.forHost && !['directory', 'zip', 'tar', 'tgz'].includes(ins.format)) {
|
|
361
|
+
throw new SitefileError('E_VALIDATION', `EXPORT ... FOR applies only to AS directory, zip, tar and tgz, not ${ins.format}`, ins.forHost.span);
|
|
362
|
+
}
|
|
363
|
+
exportFor = ins.forHost ? { host: ins.forHost.value, span: ins.forHost.span } : undefined;
|
|
246
364
|
break;
|
|
247
365
|
}
|
|
248
366
|
}
|
|
367
|
+
for (const r of robots) {
|
|
368
|
+
if (sitemapUrls.length === 0)
|
|
369
|
+
throw new SitefileError('E_VALIDATION', 'ROBOTS … SITEMAP: the Sitefile has no SITEMAP to point to (add SITEMAP BASE <url>, or leave out SITEMAP)', r.op.span);
|
|
370
|
+
const ops = stages[r.stage].operations;
|
|
371
|
+
ops[ops.indexOf(r.op)] = { ...r.op, text: robotsTxt(r.rules, [...new Set(sitemapUrls)]) };
|
|
372
|
+
}
|
|
373
|
+
const cspHeader = headers.find((h) => h.name.toLowerCase() === 'content-security-policy');
|
|
374
|
+
if (csp && cspHeader) {
|
|
375
|
+
throw new SitefileError('E_VALIDATION', `CSP and the HEADER on line ${cspHeader.span.line} both set Content-Security-Policy; keep one (put your policy in CSP POLICY "…")`, csp.span);
|
|
376
|
+
}
|
|
249
377
|
for (const st of stages) {
|
|
250
378
|
st.operations.forEach((op, i) => {
|
|
251
|
-
if (op.kind === 'FINGERPRINT')
|
|
379
|
+
if (op.kind === 'FINGERPRINT' || op.kind === 'CANONICAL' || op.kind === 'PRECACHE')
|
|
252
380
|
st.operations[i] = { ...op, root: exportPath ?? '/' };
|
|
253
381
|
if (op.kind === 'CHECKLINKS')
|
|
254
382
|
st.operations[i] = { ...op, root: exportPath ?? '/', redirects: redirects.map((r) => r.from) };
|
|
255
383
|
});
|
|
384
|
+
if (languages) {
|
|
385
|
+
// Each CANONICAL and SITEMAP sees the stage's RENDER … FOR lines before it.
|
|
386
|
+
const sources = [];
|
|
387
|
+
st.operations.forEach((op, i) => {
|
|
388
|
+
if (op.kind === 'RENDER' && op.each && op.each.by === undefined && op.each.page === undefined)
|
|
389
|
+
sources.push({ as: op.each.as, list: op.each.list, dest: op.each.dest });
|
|
390
|
+
if (op.kind === 'CANONICAL' || op.kind === 'SITEMAP') {
|
|
391
|
+
st.operations[i] = { ...op, languages: { codes: languages.codes, ...(languages.default !== undefined ? { default: languages.default } : {}), sources: [...sources] } };
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
}
|
|
256
395
|
}
|
|
257
396
|
// An unnamed stage can be neither a FROM base nor a COPY --from source; only the last one is useful (EXPORT reads it).
|
|
258
397
|
for (const st of stages.slice(0, -1)) {
|
|
@@ -268,7 +407,32 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
|
|
|
268
407
|
// validate() guarantees both; this keeps the types honest.
|
|
269
408
|
throw new SitefileError('E_VALIDATION', 'a Sitefile needs FROM and EXPORT');
|
|
270
409
|
}
|
|
271
|
-
|
|
410
|
+
// FINGERPRINT's Cache-Control lines: unless turned off, or a HEADER already sets Cache-Control.
|
|
411
|
+
const firstFingerprint = fingerprints[0];
|
|
412
|
+
const cacheHeaders = firstFingerprint && fingerprints.every((f) => f.headers) && !headers.some((h) => h.name.toLowerCase() === 'cache-control')
|
|
413
|
+
? { span: firstFingerprint.span }
|
|
414
|
+
: undefined;
|
|
415
|
+
return {
|
|
416
|
+
file: program.file,
|
|
417
|
+
stages,
|
|
418
|
+
vars,
|
|
419
|
+
fragments,
|
|
420
|
+
imports: [...imports.values()],
|
|
421
|
+
plugins,
|
|
422
|
+
tools,
|
|
423
|
+
exportPath,
|
|
424
|
+
exportFormat,
|
|
425
|
+
exportBase,
|
|
426
|
+
exportRoot,
|
|
427
|
+
exportCompression,
|
|
428
|
+
...(exportKey !== undefined ? { exportKey } : {}),
|
|
429
|
+
...(exportFor ? { exportFor } : {}),
|
|
430
|
+
redirects,
|
|
431
|
+
headers,
|
|
432
|
+
...(cacheHeaders ? { cacheHeaders } : {}),
|
|
433
|
+
...(csp ? { csp } : {}),
|
|
434
|
+
warnings,
|
|
435
|
+
};
|
|
272
436
|
}
|
|
273
437
|
/**
|
|
274
438
|
* `--target <name>`: keep the stages up to and including the named one, and export that stage's whole tree
|
|
@@ -284,7 +448,8 @@ export function targetPlan(p, name) {
|
|
|
284
448
|
? `--target '${name}' does not name a stage (stages: ${names.join(', ')})`
|
|
285
449
|
: `--target '${name}' does not name a stage (the Sitefile has no named stages; name one with FROM … AS <name>)`);
|
|
286
450
|
}
|
|
287
|
-
|
|
451
|
+
const { cacheHeaders: _, csp: _csp, ...rest } = p;
|
|
452
|
+
return { ...rest, stages: p.stages.slice(0, index + 1), exportPath: '/', redirects: [], headers: [], target: name };
|
|
288
453
|
}
|
|
289
454
|
/** `IMPORT … SCHEMA <path>`: a local `.json`, `.yaml` or `.yml` file in the build context. */
|
|
290
455
|
function schemaSpec(name, op, vars, span) {
|
|
@@ -313,6 +478,22 @@ function pageSize(op, vars) {
|
|
|
313
478
|
}
|
|
314
479
|
return Number(raw);
|
|
315
480
|
}
|
|
481
|
+
/** PRECOMPRESS leaves smaller files alone: below about 1 KiB compression saves little. */
|
|
482
|
+
export const DEFAULT_PRECOMPRESS_MIN = 1024;
|
|
483
|
+
/** `PRECOMPRESS … MIN <bytes>`: a whole number of bytes. */
|
|
484
|
+
function minSize(op, vars) {
|
|
485
|
+
const raw = evaluateOperand(op, vars);
|
|
486
|
+
if (!/^(0|[1-9][0-9]{0,9})$/.test(raw)) {
|
|
487
|
+
throw new SitefileError('E_VALIDATION', `PRECOMPRESS … MIN: '${raw}' is not a size (a whole number of bytes from 0 to 9999999999)`, op.span);
|
|
488
|
+
}
|
|
489
|
+
return Number(raw);
|
|
490
|
+
}
|
|
491
|
+
/** A LANGUAGES code: a basic BCP 47 tag (`E_VALIDATION` otherwise). */
|
|
492
|
+
function languageTag(raw, span) {
|
|
493
|
+
if (!isLanguageTag(raw))
|
|
494
|
+
throw new SitefileError('E_VALIDATION', `LANGUAGES: '${raw}' is not a language code (a BCP 47 tag such as en, fr or pt-BR)`, span);
|
|
495
|
+
return raw;
|
|
496
|
+
}
|
|
316
497
|
/** `TO <dest>` of SITEMAP/FEED or `MANIFEST <dest>` of FINGERPRINT (a file path), or the default. */
|
|
317
498
|
function fileDest(op, vars, fallback, what) {
|
|
318
499
|
if (!op)
|