@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
@@ -3,71 +3,210 @@
3
3
  import { safeSegments } from './server.js';
4
4
  const HEADER_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
5
5
  /** Headers the server owns; `_headers` cannot set them. */
6
- const PROTECTED_HEADERS = new Set(['content-length', 'transfer-encoding', 'connection', 'keep-alive', 'etag', 'location']);
7
- const SERVE_STATUSES = new Set([200, 301, 302, 303, 307, 308, 404]);
6
+ const PROTECTED_HEADERS = new Set(['content-length', 'transfer-encoding', 'connection', 'keep-alive', 'etag', 'location', 'accept-ranges', 'content-range', 'last-modified', 'www-authenticate', 'content-encoding']);
7
+ export const SERVE_STATUSES = [200, 301, 302, 303, 307, 308, 404, 410, 451];
8
+ /** Statuses that serve the target path's file with that status instead of redirecting. */
9
+ export const isRewriteStatus = (s) => s === 200 || s === 404 || s === 410 || s === 451;
10
+ const PLACEHOLDER = /^[A-Za-z_][A-Za-z0-9_]*$/;
11
+ const STATUS_FIELD = /^[0-9]{3}!?$/;
12
+ const asciiLower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
13
+ /** `decodeURIComponent` after `+` becomes a space (form encoding), or undefined when malformed. */
14
+ function decodeQueryPart(s) {
15
+ try {
16
+ return decodeURIComponent(s.replace(/\+/g, ' '));
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ }
22
+ /** The decoded `name=value` pairs of a query string (without its `?`); malformed pairs are skipped. */
23
+ export function parseQuery(q) {
24
+ const out = [];
25
+ for (const part of q.split('&')) {
26
+ if (part === '')
27
+ continue;
28
+ const i = part.indexOf('=');
29
+ const name = decodeQueryPart(i === -1 ? part : part.slice(0, i));
30
+ const value = decodeQueryPart(i === -1 ? '' : part.slice(i + 1));
31
+ if (name !== undefined && value !== undefined)
32
+ out.push([name, value]);
33
+ }
34
+ return out;
35
+ }
36
+ const isTargetField = (f) => f.startsWith('/') || /^https?:\/\//i.test(f);
8
37
  /**
9
- * Parse `_redirects`: `from to [status[!]]` per line, `#` comments. Supported: exact paths and a
10
- * trailing `/*` with `:splat` in the target; statuses 301, 302, 303, 307, 308 (redirect), 200
11
- * (rewrite) and 404. Other lines (placeholders, conditions, query matching) are ignored.
38
+ * Parse `_redirects` (Netlify / Cloudflare Pages): `from [name=value…] to [status[!]] [Key=values…]`
39
+ * per line, `#` comments. Supported: literal segments, `:placeholders` (one segment each) and a
40
+ * trailing `/*` (`:splat`); query parameters, literal or `:placeholder`; statuses 301, 302, 303,
41
+ * 307, 308 (redirect), 200 (rewrite), 404, 410 and 451 (the target's file with that status);
42
+ * conditions `Language=`, `Country=` and `Cookie=`. Every other line is in `ignored`, with why.
12
43
  */
13
- export function parseRedirectRules(text) {
14
- const out = [];
15
- for (const line of text.split('\n')) {
16
- const t = line.trim();
44
+ export function parseRedirects(text) {
45
+ const rules = [];
46
+ const ignored = [];
47
+ text.split('\n').forEach((raw, index) => {
48
+ const t = raw.trim();
17
49
  if (t === '' || t.startsWith('#'))
50
+ return;
51
+ const r = parseRedirectLine(t, index + 1);
52
+ if (typeof r === 'string')
53
+ ignored.push({ line: index + 1, reason: r });
54
+ else
55
+ rules.push(r);
56
+ });
57
+ return { rules, ignored };
58
+ }
59
+ /** One non-comment line: its rule, or why it is ignored. */
60
+ function parseRedirectLine(t, line) {
61
+ const fields = t.split(/[ \t]+/);
62
+ const from = fields[0];
63
+ let k = 1;
64
+ const query = [];
65
+ for (; k < fields.length && !isTargetField(fields[k]); k++) {
66
+ const f = fields[k];
67
+ const i = f.indexOf('=');
68
+ if (i <= 0)
69
+ break;
70
+ const name = decodeQueryPart(f.slice(0, i));
71
+ const value = decodeQueryPart(f.slice(i + 1));
72
+ if (name === undefined || value === undefined || (value.startsWith(':') && !PLACEHOLDER.test(value.slice(1)))) {
73
+ return 'bad query parameter (expected name=value or name=:placeholder)';
74
+ }
75
+ query.push([name, value]);
76
+ }
77
+ if (k >= fields.length)
78
+ return "expected 'from [name=value...] to [status] [conditions]'";
79
+ const to = fields[k++];
80
+ let st = '301';
81
+ if (k < fields.length && STATUS_FIELD.test(fields[k]))
82
+ st = fields[k++];
83
+ const conditions = [];
84
+ for (; k < fields.length; k++) {
85
+ const f = fields[k];
86
+ const i = f.indexOf('=');
87
+ if (i <= 0)
88
+ return 'unexpected field (expected a status, then Key=value conditions)';
89
+ const key = asciiLower(f.slice(0, i));
90
+ const values = f
91
+ .slice(i + 1)
92
+ .split(',')
93
+ .filter((x) => x !== '');
94
+ if (key === 'role')
95
+ return 'Role= conditions need Netlify Identity and are not supported';
96
+ if (key !== 'language' && key !== 'country' && key !== 'cookie')
97
+ return 'unsupported condition (supported: Language=, Country=, Cookie=)';
98
+ if (values.length === 0)
99
+ return 'a condition needs at least one value';
100
+ conditions.push({ key, values: key === 'cookie' ? values : values.map(asciiLower) });
101
+ }
102
+ const force = st.endsWith('!');
103
+ const status = Number(force ? st.slice(0, -1) : st);
104
+ if (!SERVE_STATUSES.includes(status))
105
+ return `unsupported status (supported: ${SERVE_STATUSES.join(', ')})`;
106
+ if (!/^[\x21-\x7e]+$/.test(to) || !(to.startsWith('/') || /^https?:\/\/[^/]/i.test(to))) {
107
+ return 'the target must be an absolute path or an http(s) URL, in printable ASCII';
108
+ }
109
+ if (isRewriteStatus(status) && status !== 200 && !to.startsWith('/'))
110
+ return `status ${status} needs a path target`;
111
+ if (!from.startsWith('/'))
112
+ return "the source must be a path starting with '/'";
113
+ const splat = from === '/*' || from.endsWith('/*');
114
+ const prefix = splat ? from.slice(0, -2) : from;
115
+ const segments = [];
116
+ const names = new Set();
117
+ for (const raw of prefix.split('/')) {
118
+ if (raw === '')
18
119
  continue;
19
- const fields = t.split(/[ \t]+/);
20
- if (fields.length < 2 || fields.length > 3)
21
- continue;
22
- const from = fields[0];
23
- const to = fields[1];
24
- const st = fields[2] ?? '301';
25
- const force = st.endsWith('!');
26
- const code = force ? st.slice(0, -1) : st;
27
- if (!/^[0-9]{3}$/.test(code) || !SERVE_STATUSES.has(Number(code)))
28
- continue;
29
- const status = Number(code);
30
- if (!/^[\x21-\x7e]+$/.test(to) || !(to.startsWith('/') || /^https?:\/\/[^/]/i.test(to)))
31
- continue;
32
- if ((status === 200 || status === 404) && !to.startsWith('/'))
33
- continue;
34
- if (!from.startsWith('/'))
35
- continue;
36
- const splat = from === '/*' || from.endsWith('/*');
37
- const prefix = splat ? from.slice(0, -2) : from;
38
- if (prefix.includes('*') || prefix.split('/').some((seg) => seg.startsWith(':')))
39
- continue;
40
- const segs = safeSegments(prefix === '' ? '/' : prefix);
41
- if (!segs)
120
+ if (raw.includes('*'))
121
+ return "'*' is only supported as the last segment of the source";
122
+ if (raw.startsWith(':')) {
123
+ const name = raw.slice(1);
124
+ if (!PLACEHOLDER.test(name))
125
+ return 'bad placeholder (expected :name of letters, digits and _)';
126
+ if (name === 'splat')
127
+ return ":splat is the value of a trailing '*', not a placeholder";
128
+ if (names.has(name))
129
+ return 'a placeholder is used twice in the source';
130
+ names.add(name);
131
+ segments.push({ param: name });
42
132
  continue;
43
- const decoded = '/' + segs.join('/');
44
- out.push({ from: splat && decoded === '/' ? '' : decoded, splat, to, status, force });
133
+ }
134
+ const seg = safeSegments('/' + raw);
135
+ if (!seg)
136
+ return 'the source is not a valid path';
137
+ segments.push({ lit: seg[0] });
45
138
  }
46
- return out;
139
+ const shown = '/' + segments.map((s) => ('param' in s ? `:${s.param}` : s.lit)).join('/');
140
+ return { line, from: splat && shown === '/' ? '' : shown, segments, splat, query, to, status, force, conditions };
47
141
  }
48
- /** Parse `_headers`: a path pattern line (`*` matches anything), then indented `Name: value` lines. */
49
- export function parseHeaderRules(text) {
142
+ /** {@link parseRedirects}' rules. */
143
+ export function parseRedirectRules(text) {
144
+ return parseRedirects(text).rules;
145
+ }
146
+ /** A rule that depends on nothing but the path: no placeholders, query parameters or conditions. */
147
+ export function isPlainRule(r) {
148
+ return r.query.length === 0 && r.conditions.length === 0 && r.segments.every((s) => 'lit' in s);
149
+ }
150
+ /**
151
+ * Parse `_headers`: a path pattern line (`*` matches anything), then indented `Name: value` lines.
152
+ * Every other line is in `ignored`, with why.
153
+ */
154
+ export function parseHeaders(text) {
50
155
  const out = [];
156
+ const ignored = [];
51
157
  let cur;
52
- for (const raw of text.split('\n')) {
158
+ text.split('\n').forEach((raw, index) => {
159
+ const skip = (reason) => void ignored.push({ line: index + 1, reason });
53
160
  const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
54
161
  const t = line.trim();
55
162
  if (t === '' || t.startsWith('#'))
56
- continue;
163
+ return;
57
164
  if (line[0] === ' ' || line[0] === '\t') {
165
+ if (!cur)
166
+ return skip('a header line without a path line above it');
167
+ if (t.startsWith('!'))
168
+ return skip("'! Name' detach lines are not supported");
58
169
  const i = t.indexOf(':');
59
- if (!cur || i <= 0)
60
- continue;
61
- const name = t.slice(0, i).trim().toLowerCase();
170
+ if (i <= 0)
171
+ return skip("expected 'Name: value'");
172
+ const name = asciiLower(t.slice(0, i).trim());
62
173
  const value = t.slice(i + 1).trim();
63
- if (!HEADER_TOKEN.test(name) || !/^[\t\x20-\x7e]*$/.test(value) || PROTECTED_HEADERS.has(name))
64
- continue;
174
+ if (!HEADER_TOKEN.test(name))
175
+ return skip('invalid header name');
176
+ if (!/^[\t\x20-\x7e]*$/.test(value))
177
+ return skip('the value must be printable ASCII');
178
+ if (PROTECTED_HEADERS.has(name))
179
+ return skip('the server sets this header itself');
65
180
  cur.headers.push([name, value]);
66
- continue;
181
+ return;
67
182
  }
68
183
  cur = t.startsWith('/') ? { pattern: t, headers: [] } : undefined;
69
184
  if (cur)
70
185
  out.push(cur);
186
+ else
187
+ skip("a path pattern must start with '/' (indent header lines)");
188
+ });
189
+ return { rules: out, ignored };
190
+ }
191
+ /** {@link parseHeaders}' rules. */
192
+ export function parseHeaderRules(text) {
193
+ return parseHeaders(text).rules;
194
+ }
195
+ /**
196
+ * The warnings for a tree's `/_redirects` and `/_headers` lines `serve` ignores, one per line:
197
+ * `_redirects:3: ignored: <reason>`. `content` reads files a zip served in place holds only as digests.
198
+ */
199
+ export function siteFileWarnings(tree, content) {
200
+ const out = [];
201
+ for (const [file, parse] of [
202
+ ['_redirects', parseRedirects],
203
+ ['_headers', parseHeaders],
204
+ ]) {
205
+ const f = tree.get(`/${file}`);
206
+ if (!f)
207
+ continue;
208
+ for (const i of parse(new TextDecoder().decode(content?.read(`/${file}`) ?? f.bytes)).ignored)
209
+ out.push(`${file}:${i.line}: ignored: ${i.reason}`);
71
210
  }
72
211
  return out;
73
212
  }
@@ -110,14 +249,86 @@ export function headersFor(rules, path) {
110
249
  }
111
250
  return out;
112
251
  }
113
- /** The remainder a rule matches for `path` (`''` for the prefix itself), or undefined. */
252
+ /**
253
+ * The values a rule's source captures from `path` (decoded, no trailing slash): each placeholder,
254
+ * and `splat` (the remainder, `''` for the prefix itself) for a splat rule; undefined when it does
255
+ * not match.
256
+ */
114
257
  export function matchRedirect(r, path) {
115
- if (!r.splat)
116
- return path === r.from ? '' : undefined;
117
- if (r.from === '')
118
- return path.slice(1);
119
- if (path === r.from)
120
- return '';
121
- return path.startsWith(r.from + '/') ? path.slice(r.from.length + 1) : undefined;
258
+ const segs = path.split('/').filter((s) => s !== '');
259
+ const n = r.segments.length;
260
+ if (r.splat ? segs.length < n : segs.length !== n)
261
+ return undefined;
262
+ const caps = new Map();
263
+ for (let i = 0; i < n; i++) {
264
+ const s = r.segments[i];
265
+ if ('param' in s)
266
+ caps.set(s.param, segs[i]);
267
+ else if (s.lit !== segs[i])
268
+ return undefined;
269
+ }
270
+ if (r.splat)
271
+ caps.set('splat', segs.slice(n).join('/'));
272
+ return caps;
273
+ }
274
+ /** Whether `Accept-Language` names a language a `Language=` value matches (`en` matches `en-GB`). */
275
+ function languageMatches(values, header) {
276
+ for (const part of header.split(',')) {
277
+ const [tag, ...params] = part.split(';');
278
+ const q = params.map((p) => p.trim()).find((p) => p.startsWith('q=') || p.startsWith('Q='));
279
+ if (q !== undefined && /^0(\.0{0,3})?$/.test(q.slice(2)))
280
+ continue;
281
+ const t = asciiLower(tag.trim());
282
+ if (t !== '' && values.some((v) => t === v || t.startsWith(`${v}-`)))
283
+ return true;
284
+ }
285
+ return false;
286
+ }
287
+ /** Whether a `Cookie` header has a cookie with one of these names. */
288
+ function cookieMatches(names, header) {
289
+ return header.split(';').some((c) => {
290
+ const i = c.indexOf('=');
291
+ return i > 0 && names.includes(c.slice(0, i).trim());
292
+ });
293
+ }
294
+ /** {@link matchRedirect}, then the rule's query parameters (adding their captures) and conditions. */
295
+ export function matchRule(r, path, req) {
296
+ const caps = matchRedirect(r, path);
297
+ if (!caps)
298
+ return undefined;
299
+ if (r.query.length > 0) {
300
+ const pairs = parseQuery(req.search.slice(1));
301
+ for (const [name, value] of r.query) {
302
+ const hit = pairs.find(([n]) => n === name);
303
+ if (!hit)
304
+ return undefined;
305
+ if (value.startsWith(':'))
306
+ caps.set(value.slice(1), hit[1]);
307
+ else if (hit[1] !== value)
308
+ return undefined;
309
+ }
310
+ }
311
+ for (const c of r.conditions) {
312
+ const ok = c.key === 'language'
313
+ ? languageMatches(c.values, req.acceptLanguage ?? '')
314
+ : c.key === 'country'
315
+ ? req.country !== undefined && c.values.includes(asciiLower(req.country))
316
+ : cookieMatches(c.values, req.cookie ?? '');
317
+ if (!ok)
318
+ return undefined;
319
+ }
320
+ return caps;
321
+ }
322
+ /**
323
+ * A rule's target with `:name` (letters, digits and `_`, the longest run) replaced by the captured
324
+ * value, percent-encoded like encodeURIComponent; `:splat` keeps its slashes. Other names stay.
325
+ */
326
+ export function substituteTarget(to, caps) {
327
+ return to.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, (whole, name) => {
328
+ const v = caps.get(name);
329
+ if (v === undefined)
330
+ return whole;
331
+ return name === 'splat' ? v.split('/').map(encodeURIComponent).join('/') : encodeURIComponent(v);
332
+ });
122
333
  }
123
334
  //# sourceMappingURL=serve-rules.js.map