ssqch 0.7.0 → 0.8.0

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 (153) hide show
  1. package/README.md +6 -4
  2. package/bin/ssqch.js +14 -48
  3. package/bundled/README.md +1247 -0
  4. package/bundled/completions/bash +840 -0
  5. package/bundled/completions/elvish +286 -0
  6. package/bundled/completions/fish +182 -0
  7. package/bundled/completions/powershell +318 -0
  8. package/bundled/completions/zsh +510 -0
  9. package/bundled/ssqch.d.ts +532 -0
  10. package/bundled/starter/engines/index.edge +11 -0
  11. package/bundled/starter/engines/index.ejs +11 -0
  12. package/bundled/starter/engines/index.hbs +11 -0
  13. package/bundled/starter/engines/index.liquid +11 -0
  14. package/bundled/starter/engines/layout.edge +35 -0
  15. package/bundled/starter/engines/layout.ejs +35 -0
  16. package/bundled/starter/engines/layout.hbs +35 -0
  17. package/bundled/starter/engines/layout.liquid +35 -0
  18. package/bundled/starter/gitignore +3 -0
  19. package/bundled/starter/jsconfig.json +11 -0
  20. package/bundled/starter/src/404.md +8 -0
  21. package/bundled/starter/src/_blueprints/posts.md +5 -0
  22. package/bundled/starter/src/_data/site.json +4 -0
  23. package/bundled/starter/src/_includes/layout.jinja +35 -0
  24. package/bundled/starter/src/index.jinja +11 -0
  25. package/bundled/starter/src/posts/i-know-what-i-saw.md +11 -0
  26. package/bundled/starter/src/posts/posts.json +4 -0
  27. package/bundled/starter/src/posts/raiders-of-the-lost-path.md +27 -0
  28. package/bundled/starter/src/posts/the-cache-of-the-wild.md +26 -0
  29. package/bundled/starter/src/posts/the-stump-has-moved.md +15 -0
  30. package/bundled/starter/src/posts/upon-further-review-a-stump.md +18 -0
  31. package/bundled/starter/ssqch.config.js +29 -0
  32. package/bundled/starter-docs/engines/edge/base.edge +41 -0
  33. package/bundled/starter-docs/engines/edge/containers/details.edge +5 -0
  34. package/bundled/starter-docs/engines/edge/containers/tab.edge +4 -0
  35. package/bundled/starter-docs/engines/edge/containers/tabs.edge +5 -0
  36. package/bundled/starter-docs/engines/edge/doc.edge +59 -0
  37. package/bundled/starter-docs/engines/edge/hooks/heading.edge +2 -0
  38. package/bundled/starter-docs/engines/ejs/base.ejs +41 -0
  39. package/bundled/starter-docs/engines/ejs/containers/details.ejs +5 -0
  40. package/bundled/starter-docs/engines/ejs/containers/tab.ejs +4 -0
  41. package/bundled/starter-docs/engines/ejs/containers/tabs.ejs +5 -0
  42. package/bundled/starter-docs/engines/ejs/doc.ejs +59 -0
  43. package/bundled/starter-docs/engines/ejs/hooks/heading.ejs +2 -0
  44. package/bundled/starter-docs/engines/hbs/base.hbs +41 -0
  45. package/bundled/starter-docs/engines/hbs/containers/details.hbs +5 -0
  46. package/bundled/starter-docs/engines/hbs/containers/tab.hbs +4 -0
  47. package/bundled/starter-docs/engines/hbs/containers/tabs.hbs +5 -0
  48. package/bundled/starter-docs/engines/hbs/doc.hbs +58 -0
  49. package/bundled/starter-docs/engines/hbs/hooks/heading.hbs +2 -0
  50. package/bundled/starter-docs/engines/liquid/base.liquid +41 -0
  51. package/bundled/starter-docs/engines/liquid/containers/details.liquid +5 -0
  52. package/bundled/starter-docs/engines/liquid/containers/tab.liquid +4 -0
  53. package/bundled/starter-docs/engines/liquid/containers/tabs.liquid +5 -0
  54. package/bundled/starter-docs/engines/liquid/doc.liquid +60 -0
  55. package/bundled/starter-docs/engines/liquid/hooks/heading.liquid +2 -0
  56. package/bundled/starter-docs/gitignore +4 -0
  57. package/bundled/starter-docs/src/404.md +12 -0
  58. package/bundled/starter-docs/src/_blueprints/docs.md +5 -0
  59. package/bundled/starter-docs/src/_data/nav.yml +10 -0
  60. package/bundled/starter-docs/src/_data/site.json +5 -0
  61. package/bundled/starter-docs/src/_includes/base.jinja +41 -0
  62. package/bundled/starter-docs/src/_includes/containers/details.jinja +5 -0
  63. package/bundled/starter-docs/src/_includes/containers/tab.jinja +4 -0
  64. package/bundled/starter-docs/src/_includes/containers/tabs.jinja +5 -0
  65. package/bundled/starter-docs/src/_includes/doc.jinja +59 -0
  66. package/bundled/starter-docs/src/_includes/hooks/heading.jinja +2 -0
  67. package/bundled/starter-docs/src/assets/docs.css +257 -0
  68. package/bundled/starter-docs/src/assets/docs.js +67 -0
  69. package/bundled/starter-docs/src/docs/docs.json +1 -0
  70. package/bundled/starter-docs/src/docs/guides/deploying.md +77 -0
  71. package/bundled/starter-docs/src/docs/guides/writing.md +65 -0
  72. package/bundled/starter-docs/src/docs/index.md +29 -0
  73. package/bundled/starter-docs/src/docs/install.md +42 -0
  74. package/bundled/starter-docs/src/index.md +13 -0
  75. package/bundled/starter-docs/ssqch.config.js +40 -0
  76. package/bundled/trailheads/from-component-frameworks.md +116 -0
  77. package/bundled/trailheads/from-docusaurus.md +55 -0
  78. package/bundled/trailheads/from-eleventy.md +140 -0
  79. package/bundled/trailheads/from-hexo.md +92 -0
  80. package/bundled/trailheads/from-mkdocs.md +45 -0
  81. package/bundled/trailheads/from-zola.md +71 -0
  82. package/lib/assets.js +235 -3
  83. package/lib/chunk-37KSIVNY.js +29 -0
  84. package/lib/chunk-3GYLOC6Y.js +1017 -0
  85. package/lib/chunk-3NYSSA2C.js +22 -0
  86. package/lib/chunk-3PHCFZEU.js +209 -0
  87. package/lib/chunk-4Q6WMTER.js +32 -0
  88. package/lib/chunk-6XYSFG6V.js +4423 -0
  89. package/lib/chunk-6XYSFG6V.js.LEGAL.txt +41 -0
  90. package/lib/chunk-AD3HAW3W.js +10 -0
  91. package/lib/chunk-AMBFWPZ4.js +118 -0
  92. package/lib/chunk-BOBPVAX2.js +37088 -0
  93. package/lib/chunk-BOBPVAX2.js.LEGAL.txt +27 -0
  94. package/lib/chunk-BRK4MXXO.js +565 -0
  95. package/lib/chunk-C35KIPAR.js +247 -0
  96. package/lib/chunk-CDEPYU7W.js +25 -0
  97. package/lib/chunk-CMUWRPSQ.js +113 -0
  98. package/lib/chunk-DDV6JEC2.js +46 -0
  99. package/lib/chunk-DHHQKW4F.js +71 -0
  100. package/lib/chunk-EIT4ZDT4.js +1485 -0
  101. package/lib/chunk-EZZUUPI4.js +20 -0
  102. package/lib/chunk-F65YUXZ7.js +334 -0
  103. package/lib/chunk-FVZ5JBRI.js +115 -0
  104. package/lib/chunk-FYGE634X.js +44 -0
  105. package/lib/chunk-GOE4ZSAB.js +75 -0
  106. package/lib/chunk-GSKVRAHF.js +44 -0
  107. package/lib/chunk-HR2RU2LY.js +999 -0
  108. package/lib/chunk-HXCLCXRT.js +20 -0
  109. package/lib/chunk-I3PS26CI.js +48 -0
  110. package/lib/chunk-IAFM5ITE.js +11 -0
  111. package/lib/chunk-IRHRK7XB.js +54 -0
  112. package/lib/chunk-JRT7TQQP.js +57 -0
  113. package/lib/chunk-JSPSMIJ2.js +217 -0
  114. package/lib/chunk-KBGE5MCY.js +175 -0
  115. package/lib/chunk-N5QTGQ5N.js +207 -0
  116. package/lib/chunk-NKXEPHRZ.js +136 -0
  117. package/lib/chunk-NUKCUDC4.js +146 -0
  118. package/lib/chunk-RI2L3VGO.js +376 -0
  119. package/lib/chunk-TDGBQNGW.js +251 -0
  120. package/lib/chunk-TN6EEDX2.js +3935 -0
  121. package/lib/chunk-TWCVHOKO.js +1229 -0
  122. package/lib/chunk-UGEGUUBT.js +29 -0
  123. package/lib/chunk-UU43WIZG.js +29 -0
  124. package/lib/chunk-VJWQSYEG.js +119 -0
  125. package/lib/chunk-VVPZ5PDP.js +160 -0
  126. package/lib/chunk-WMOVCQO6.js +1287 -0
  127. package/lib/chunk-WP3RPVUM.js +211 -0
  128. package/lib/chunk-YSH2NMIE.js +502 -0
  129. package/lib/cli.js +540 -0
  130. package/lib/elements.js +180 -3
  131. package/lib/image.js +27 -3
  132. package/lib/links.js +464 -3
  133. package/lib/minify.js +69 -3
  134. package/lib/redirects.js +152 -3
  135. package/lib/rss.js +139 -3
  136. package/lib/sass.js +221 -3
  137. package/lib/sitemap.js +88 -3
  138. package/lib/ssqch.js +28 -0
  139. package/package.json +83 -80
  140. package/src/serve/live.js +174 -0
  141. package/src/serve/not-found.html +31 -0
  142. package/types/globals.d.ts +3 -2
  143. package/types/image.d.ts +7 -3
  144. package/types/index.d.ts +18 -5
  145. package/types/links.d.ts +1 -1
  146. package/types/minify.d.ts +1 -1
  147. package/types/rss.d.ts +1 -1
  148. package/types/sass.d.ts +1 -1
  149. package/wasm/markdown.wasm +0 -0
  150. package/wasm/minify.wasm +0 -0
  151. package/wasm/sass.wasm +0 -0
  152. package/lib/index.js +0 -3
  153. package/platforms.json +0 -6
@@ -0,0 +1,3935 @@
1
+ import { createRequire as __ssqchCreateRequire } from "node:module";
2
+ const require = __ssqchCreateRequire(import.meta.url);
3
+ import {
4
+ budget
5
+ } from "./chunk-IRHRK7XB.js";
6
+ import {
7
+ bytes,
8
+ count
9
+ } from "./chunk-NKXEPHRZ.js";
10
+ import {
11
+ VERSION
12
+ } from "./chunk-AD3HAW3W.js";
13
+ import {
14
+ CONFIG_FILES
15
+ } from "./chunk-DDV6JEC2.js";
16
+ import {
17
+ WebAssembly,
18
+ applyMarkdownOptions,
19
+ checkLanguages,
20
+ defaultMarkdownOptions,
21
+ oriented,
22
+ probeFile,
23
+ site,
24
+ undecodable
25
+ } from "./chunk-EIT4ZDT4.js";
26
+ import {
27
+ closest
28
+ } from "./chunk-FVZ5JBRI.js";
29
+ import {
30
+ globProblem,
31
+ globToRegExp
32
+ } from "./chunk-TDGBQNGW.js";
33
+ import {
34
+ describeThrown,
35
+ hookModules,
36
+ importFile,
37
+ loadedFiles,
38
+ settle,
39
+ watchSettle
40
+ } from "./chunk-C35KIPAR.js";
41
+ import {
42
+ charCount,
43
+ firstChars,
44
+ jsString,
45
+ quoted,
46
+ quotedChar
47
+ } from "./chunk-CMUWRPSQ.js";
48
+ import {
49
+ BuildError,
50
+ Diagnostics,
51
+ TomlError,
52
+ aliasUsed,
53
+ bail,
54
+ context,
55
+ error,
56
+ find,
57
+ isPlainObject,
58
+ messageOf,
59
+ otherGenerator,
60
+ progress,
61
+ readToml,
62
+ toDate,
63
+ tomlReason,
64
+ warn,
65
+ warning
66
+ } from "./chunk-6XYSFG6V.js";
67
+ import {
68
+ compareText,
69
+ displayPath,
70
+ realPath,
71
+ shown
72
+ } from "./chunk-VJWQSYEG.js";
73
+ import {
74
+ __require
75
+ } from "./chunk-I3PS26CI.js";
76
+
77
+ // src/config.ts
78
+ import fs7 from "node:fs";
79
+ import path7 from "node:path";
80
+
81
+ // src/html.ts
82
+ var HTML = 0;
83
+ var SVG = 1;
84
+ var MATH = 2;
85
+ var NAMESPACES = ["html", "svg", "math"];
86
+ var StartTag = class {
87
+ /** The tag's name, in lowercase. */
88
+ name;
89
+ /** The element's namespace, as lol_html gives it. */
90
+ namespace = "html";
91
+ /** Whether the tag ends with `/>`. */
92
+ selfClosing;
93
+ changed = false;
94
+ /** Where the tag's `<` is in the HTML. */
95
+ start = 0;
96
+ html;
97
+ rawName;
98
+ attributes;
99
+ replacement;
100
+ constructor(html, rawName, attributes, selfClosing) {
101
+ this.html = html;
102
+ this.rawName = rawName;
103
+ this.name = rawName.toLowerCase();
104
+ this.attributes = attributes;
105
+ this.selfClosing = selfClosing;
106
+ }
107
+ valueOf(a) {
108
+ if (a.value === void 0) a.value = a.valueStart === -1 ? "" : this.html.slice(a.valueStart, a.valueEnd);
109
+ return a.value;
110
+ }
111
+ /** An attribute's value as it's written (not decoded), `""` for one without a value, or `undefined`. The first of two with one name is the one that counts, as in browsers. */
112
+ get(name) {
113
+ for (const a of this.attributes) if (a.name === name && !a.removed) return this.valueOf(a);
114
+ return void 0;
115
+ }
116
+ /** Takes every attribute with this name off the tag. */
117
+ remove(name) {
118
+ for (const a of this.attributes) {
119
+ if (a.name === name && !a.removed) {
120
+ a.removed = true;
121
+ this.changed = true;
122
+ }
123
+ }
124
+ }
125
+ set(name, value) {
126
+ const found = this.attributes.find((a) => a.name === name && !a.removed);
127
+ if (found) {
128
+ found.value = value;
129
+ found.changed = true;
130
+ } else this.attributes.push({ name, start: -1, nameEnd: -1, valueStart: -1, valueEnd: -1, end: -1, value, changed: true, removed: false });
131
+ this.changed = true;
132
+ }
133
+ /** Every attribute's name, in order, a repeated one each time (as lol_html's `attributes()` lists them). */
134
+ names() {
135
+ const out = [];
136
+ for (const a of this.attributes) if (!a.removed) out.push(a.name);
137
+ return out;
138
+ }
139
+ /** Every attribute, in order, with its value as written (`""` for one without a value): a repeated one each time, as lol_html's `attributes()` lists them, so a tag built from them keeps it. */
140
+ entries() {
141
+ const out = [];
142
+ for (const a of this.attributes) if (!a.removed) out.push([a.name, this.valueOf(a)]);
143
+ return out;
144
+ }
145
+ /** Puts `markup` where the tag is (an `<img>` becoming a `<picture>`). */
146
+ replaceWith(markup) {
147
+ this.replacement = markup;
148
+ this.changed = true;
149
+ }
150
+ /** The tag as text, as lol_html writes a changed one: attributes that weren't changed as they were written, one space between them. */
151
+ toString() {
152
+ if (this.replacement !== void 0) return this.replacement;
153
+ const html = this.html;
154
+ let attributes = "";
155
+ for (const a of this.attributes) {
156
+ if (a.removed) continue;
157
+ attributes += ` ${a.changed ? `${a.start === -1 ? a.name : html.slice(a.start, a.nameEnd)}="${(a.value ?? "").replaceAll('"', "&quot;")}"` : html.slice(a.start, a.end)}`;
158
+ }
159
+ return `<${this.rawName}${attributes}${this.selfClosing ? attributes ? " />" : "/>" : ">"}`;
160
+ }
161
+ };
162
+ var TEXT = 1;
163
+ var SCRIPT = 2;
164
+ var PLAINTEXT = 3;
165
+ var TEXT_KIND = /* @__PURE__ */ new Map([["textarea", TEXT], ["title", TEXT], ["style", TEXT], ["iframe", TEXT], ["xmp", TEXT], ["noembed", TEXT], ["noframes", TEXT], ["noscript", TEXT], ["script", SCRIPT], ["plaintext", PLAINTEXT]]);
166
+ var BREAKOUT = /* @__PURE__ */ new Set(["b", "big", "blockquote", "body", "br", "center", "code", "dd", "div", "dl", "dt", "em", "embed", "h1", "h2", "h3", "h4", "h5", "h6", "head", "hr", "i", "img", "li", "listing", "menu", "meta", "nobr", "ol", "p", "pre", "ruby", "s", "small", "span", "strong", "strike", "sub", "sup", "table", "tt", "u", "ul", "var"]);
167
+ var SVG_HTML = /* @__PURE__ */ new Set(["desc", "title", "foreignobject"]);
168
+ var MATH_TEXT = /* @__PURE__ */ new Set(["mi", "mo", "mn", "ms", "mtext"]);
169
+ var VOID = /* @__PURE__ */ new Set(["area", "base", "basefont", "bgsound", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]);
170
+ var HTML_ENCODINGS = /* @__PURE__ */ new Set(["text/html", "application/xhtml+xml"]);
171
+ var LT = 60;
172
+ var GT = 62;
173
+ var SLASH = 47;
174
+ var BANG = 33;
175
+ var QUESTION = 63;
176
+ var EQUALS = 61;
177
+ var DASH = 45;
178
+ var DQUOTE = 34;
179
+ var SQUOTE = 39;
180
+ var isSpace = (c) => c === 32 || c === 10 || c === 9 || c === 13 || c === 12;
181
+ var isLetter = (c) => (c | 32) >= 97 && (c | 32) <= 122;
182
+ function rewriteHtml(html, handlers) {
183
+ return rewrite(html, handlers, true);
184
+ }
185
+ function openElements(html) {
186
+ const open = [];
187
+ rewrite(html, {
188
+ tag(tag) {
189
+ if (tag.namespace === "html" ? !VOID.has(tag.name) : !tag.selfClosing) open.push(tag.name);
190
+ },
191
+ endTag(name) {
192
+ const at = open.lastIndexOf(name);
193
+ if (at !== -1) open.length = at;
194
+ }
195
+ }, false);
196
+ return open;
197
+ }
198
+ function rewrite(html, handlers, owning) {
199
+ const n = html.length;
200
+ let out = "";
201
+ let copied = 0;
202
+ let i = 0;
203
+ const stack = [HTML];
204
+ let ns = HTML;
205
+ const enter = (to) => {
206
+ stack.push(to);
207
+ ns = to;
208
+ };
209
+ const leave = () => {
210
+ stack.pop();
211
+ ns = stack[stack.length - 1];
212
+ };
213
+ const owners = [];
214
+ const ownedAt = [];
215
+ let open;
216
+ let textFrom = 0;
217
+ const owned = (text) => {
218
+ for (const owner of owners) {
219
+ handlers.rawText?.(owner, text);
220
+ if (owner.name === "style") {
221
+ if (handlers.style) text = handlers.style(text);
222
+ } else if (handlers.script) text = handlers.script(owner, text);
223
+ }
224
+ return text;
225
+ };
226
+ const give = (from, to) => {
227
+ if (to <= from) return;
228
+ const text = html.slice(from, to);
229
+ const changed = owned(text);
230
+ if (changed !== text) {
231
+ out += html.slice(copied, from) + changed;
232
+ copied = to;
233
+ }
234
+ };
235
+ const onTag = handlers.tag;
236
+ const onEnd = handlers.endTag;
237
+ while (i < n) {
238
+ const lt = html.indexOf("<", i);
239
+ if (lt === -1) break;
240
+ const next = html.charCodeAt(lt + 1);
241
+ if (next === BANG) {
242
+ let end2;
243
+ if (html.startsWith("--", lt + 2)) {
244
+ end2 = commentEnd(html, lt + 4);
245
+ if (owners.length !== 0) give(textFrom, lt);
246
+ } else if (ns !== HTML && html.startsWith("[CDATA[", lt + 2)) {
247
+ const close = html.indexOf("]]>", lt + 9);
248
+ end2 = close === -1 ? n : close + 3;
249
+ if (owners.length !== 0) {
250
+ give(textFrom, lt);
251
+ give(lt + 9, close === -1 ? n : close);
252
+ }
253
+ } else {
254
+ const gt = html.indexOf(">", lt + 2);
255
+ end2 = gt === -1 ? n : gt + 1;
256
+ if (owners.length !== 0) give(textFrom, lt);
257
+ }
258
+ i = textFrom = end2;
259
+ continue;
260
+ }
261
+ if (next === SLASH) {
262
+ const after = html.charCodeAt(lt + 2);
263
+ if (isLetter(after)) {
264
+ let q2 = lt + 3;
265
+ for (let c = html.charCodeAt(q2); q2 < n && !isSpace(c) && c !== SLASH && c !== GT; c = html.charCodeAt(++q2)) ;
266
+ let end2;
267
+ if (html.charCodeAt(q2) === GT) end2 = q2 + 1;
268
+ else {
269
+ end2 = scanAttributes(html, q2, n, void 0);
270
+ if (end2 === -1) break;
271
+ }
272
+ if (onEnd !== void 0 || open !== void 0 || stack.length > 1) {
273
+ const name2 = html.slice(lt + 2, q2).toLowerCase();
274
+ if (owners.length !== 0) give(textFrom, lt);
275
+ if (open !== void 0) {
276
+ const at = open.lastIndexOf(name2);
277
+ if (at !== -1) {
278
+ open.length = at;
279
+ while (ownedAt.length !== 0 && ownedAt[ownedAt.length - 1] >= at) {
280
+ owners.pop();
281
+ ownedAt.pop();
282
+ }
283
+ }
284
+ }
285
+ onEnd?.(name2, lt);
286
+ if (stack.length > 1) {
287
+ if (ns === HTML) {
288
+ const outside = stack[stack.length - 2];
289
+ if (outside === MATH ? MATH_TEXT.has(name2) || name2 === "annotation-xml" : SVG_HTML.has(name2)) leave();
290
+ } else if (ns === SVG && name2 === "svg" || ns === MATH && name2 === "math" || name2 === "p" || name2 === "br") leave();
291
+ }
292
+ }
293
+ i = textFrom = end2;
294
+ continue;
295
+ }
296
+ if (after === GT) {
297
+ if (owners.length !== 0) give(textFrom, lt);
298
+ i = textFrom = lt + 3;
299
+ continue;
300
+ }
301
+ if (lt + 2 >= n) break;
302
+ }
303
+ if (next === SLASH || next === QUESTION) {
304
+ const gt = html.indexOf(">", lt + 2);
305
+ if (owners.length !== 0) give(textFrom, lt);
306
+ i = textFrom = gt === -1 ? n : gt + 1;
307
+ continue;
308
+ }
309
+ if (!isLetter(next)) {
310
+ i = lt + 1;
311
+ continue;
312
+ }
313
+ let p = lt + 2;
314
+ for (let c = html.charCodeAt(p); p < n && !isSpace(c) && c !== SLASH && c !== GT; c = html.charCodeAt(++p)) ;
315
+ const rawName = html.slice(lt + 1, p);
316
+ const attributes = [];
317
+ let selfClosing = false;
318
+ if (html.charCodeAt(p) === GT) p++;
319
+ else {
320
+ p = scanAttributes(html, p, n, attributes);
321
+ if (p === -1) break;
322
+ selfClosing = endedSelfClosing;
323
+ }
324
+ const tag = new StartTag(html, rawName, attributes, selfClosing);
325
+ tag.start = lt;
326
+ if (owners.length !== 0) give(textFrom, lt);
327
+ const name = tag.name;
328
+ let kind = 0;
329
+ if (name === "svg") enter(SVG);
330
+ else if (name === "math") enter(MATH);
331
+ else if (ns !== HTML) {
332
+ if (BREAKOUT.has(name)) leave();
333
+ else if (ns === SVG ? SVG_HTML.has(name) : MATH_TEXT.has(name)) {
334
+ if (!selfClosing) enter(HTML);
335
+ } else if (name === "font") {
336
+ if (attributes.some((a) => a.name === "color" || a.name === "size" || a.name === "face")) leave();
337
+ } else if (ns === MATH && name === "annotation-xml") {
338
+ if (!selfClosing && attributes.some((a) => a.name === "encoding" && a.valueStart !== -1 && HTML_ENCODINGS.has(html.slice(a.valueStart, a.valueEnd).toLowerCase()))) enter(HTML);
339
+ }
340
+ } else kind = TEXT_KIND.get(name) ?? 0;
341
+ if (ns !== HTML) tag.namespace = NAMESPACES[ns];
342
+ onTag?.(tag);
343
+ if (tag.changed) {
344
+ out += html.slice(copied, lt) + tag.toString();
345
+ copied = p;
346
+ }
347
+ i = textFrom = p;
348
+ if (ns !== HTML && owning && !selfClosing && (name === "style" || name === "script")) {
349
+ open ??= openElements(html.slice(0, lt));
350
+ owners.push(tag);
351
+ ownedAt.push(open.length);
352
+ }
353
+ if (open !== void 0 && (ns === HTML ? !VOID.has(name) : !selfClosing)) open.push(name);
354
+ if (kind === 0) continue;
355
+ const end = kind === SCRIPT ? scriptEnd(html, p, n) : kind === PLAINTEXT ? n : textEnd(html, p, name);
356
+ if (end > p) {
357
+ const text = html.slice(p, end);
358
+ handlers.rawText?.(tag, text);
359
+ let changed = text;
360
+ if (name === "style") {
361
+ if (handlers.style) changed = handlers.style(text);
362
+ } else if (name === "script" && handlers.script) changed = handlers.script(tag, text);
363
+ if (owners.length !== 0) changed = owned(changed);
364
+ if (changed !== text) {
365
+ out += html.slice(copied, p) + changed;
366
+ copied = end;
367
+ }
368
+ }
369
+ i = textFrom = end;
370
+ }
371
+ if (owners.length !== 0) give(textFrom, n);
372
+ return copied === 0 ? html : out + html.slice(copied);
373
+ }
374
+ var endedSelfClosing = false;
375
+ function scanAttributes(html, p, n, attributes) {
376
+ endedSelfClosing = false;
377
+ while (p < n) {
378
+ let c = html.charCodeAt(p);
379
+ if (isSpace(c)) {
380
+ p++;
381
+ continue;
382
+ }
383
+ if (c === GT) return p + 1;
384
+ if (c === SLASH) {
385
+ if (html.charCodeAt(p + 1) === GT) {
386
+ endedSelfClosing = true;
387
+ return p + 2;
388
+ }
389
+ p++;
390
+ continue;
391
+ }
392
+ const start = p;
393
+ for (c = html.charCodeAt(++p); p < n && !isSpace(c) && c !== SLASH && c !== GT && c !== EQUALS; c = html.charCodeAt(++p)) ;
394
+ const nameEnd = p;
395
+ let q2 = p;
396
+ while (q2 < n && isSpace(html.charCodeAt(q2))) q2++;
397
+ let valueStart = -1;
398
+ let valueEnd = -1;
399
+ let end = nameEnd;
400
+ if (html.charCodeAt(q2) === EQUALS) {
401
+ q2++;
402
+ while (q2 < n && isSpace(html.charCodeAt(q2))) q2++;
403
+ const quote = html.charCodeAt(q2);
404
+ if (quote === DQUOTE || quote === SQUOTE) {
405
+ const close = html.indexOf(quote === DQUOTE ? '"' : "'", q2 + 1);
406
+ if (close === -1) return -1;
407
+ valueStart = q2 + 1;
408
+ valueEnd = close;
409
+ p = end = close + 1;
410
+ } else if (quote === GT) {
411
+ attributes?.push({ name: html.slice(start, nameEnd).toLowerCase(), start, nameEnd, valueStart: -1, valueEnd: -1, end: nameEnd, value: void 0, changed: false, removed: false });
412
+ return q2 + 1;
413
+ } else {
414
+ valueStart = q2;
415
+ for (c = quote; q2 < n && !isSpace(c) && c !== GT; c = html.charCodeAt(++q2)) ;
416
+ valueEnd = q2;
417
+ p = end = q2;
418
+ }
419
+ }
420
+ attributes?.push({ name: html.slice(start, nameEnd).toLowerCase(), start, nameEnd, valueStart, valueEnd, end, value: void 0, changed: false, removed: false });
421
+ }
422
+ return -1;
423
+ }
424
+ function endTagAt(html, at, name) {
425
+ const length = name.length;
426
+ for (let j = 0; j < length; j++) if ((html.charCodeAt(at + j) | 32) !== name.charCodeAt(j)) return false;
427
+ const c = html.charCodeAt(at + length);
428
+ return isSpace(c) || c === SLASH || c === GT;
429
+ }
430
+ function textEnd(html, from, name) {
431
+ for (let k = html.indexOf("</", from); k !== -1; k = html.indexOf("</", k + 2)) if (endTagAt(html, k + 2, name)) return k;
432
+ return html.length;
433
+ }
434
+ function commentEnd(html, from) {
435
+ const first = html.charCodeAt(from);
436
+ if (first === GT) return from + 1;
437
+ if (first === DASH && html.charCodeAt(from + 1) === GT) return from + 2;
438
+ for (let k = html.indexOf("--", from); k !== -1; k = html.indexOf("--", k)) {
439
+ k += 2;
440
+ while (html.charCodeAt(k) === DASH) k++;
441
+ const c = html.charCodeAt(k);
442
+ if (c === GT) return k + 1;
443
+ if (c === BANG && html.charCodeAt(k + 1) === GT) return k + 2;
444
+ }
445
+ return html.length;
446
+ }
447
+ var DATA = 0;
448
+ var ESCAPED = 1;
449
+ var ESCAPED_DASHES = 2;
450
+ var ESCAPED_LT = 3;
451
+ var DOUBLE_START = 4;
452
+ var DOUBLE = 5;
453
+ var DOUBLE_DASHES = 6;
454
+ var DOUBLE_LT = 7;
455
+ var DOUBLE_END_NAME = 8;
456
+ var DOUBLE_END = 9;
457
+ var scriptAt = (html, at) => {
458
+ for (let j = 0; j < 6; j++) if ((html.charCodeAt(at + j) | 32) !== "script".charCodeAt(j)) return false;
459
+ return true;
460
+ };
461
+ function scriptEnd(html, from, n) {
462
+ let state = DATA;
463
+ let i = from;
464
+ for (; ; ) {
465
+ switch (state) {
466
+ case DATA: {
467
+ const lt = html.indexOf("<", i);
468
+ if (lt === -1) return n;
469
+ const c = html.charCodeAt(lt + 1);
470
+ if (c === SLASH) {
471
+ if (endTagAt(html, lt + 2, "script")) return lt;
472
+ i = lt + 2;
473
+ } else if (c === BANG && html.startsWith("--", lt + 2)) {
474
+ i = lt + 4;
475
+ state = ESCAPED_DASHES;
476
+ } else i = lt + 1;
477
+ break;
478
+ }
479
+ case ESCAPED:
480
+ case DOUBLE: {
481
+ let k = i;
482
+ for (let c = html.charCodeAt(k); k < n && c !== LT && !(c === DASH && html.charCodeAt(k + 1) === DASH); c = html.charCodeAt(++k)) ;
483
+ if (k >= n) return n;
484
+ if (html.charCodeAt(k) === LT) {
485
+ i = k + 1;
486
+ state = state === ESCAPED ? ESCAPED_LT : DOUBLE_LT;
487
+ } else {
488
+ i = k + 2;
489
+ state = state === ESCAPED ? ESCAPED_DASHES : DOUBLE_DASHES;
490
+ }
491
+ break;
492
+ }
493
+ case ESCAPED_DASHES:
494
+ case DOUBLE_DASHES: {
495
+ if (i >= n) return n;
496
+ const c = html.charCodeAt(i);
497
+ if (c === DASH) i++;
498
+ else if (c === LT) {
499
+ i++;
500
+ state = state === ESCAPED_DASHES ? ESCAPED_LT : DOUBLE_LT;
501
+ } else if (c === GT) state = DATA;
502
+ else {
503
+ i++;
504
+ state = state === ESCAPED_DASHES ? ESCAPED : DOUBLE;
505
+ }
506
+ break;
507
+ }
508
+ case ESCAPED_LT: {
509
+ if (i >= n) return n;
510
+ if (scriptAt(html, i)) {
511
+ i += 6;
512
+ state = DOUBLE_START;
513
+ } else if (html.charCodeAt(i) === SLASH) {
514
+ if (endTagAt(html, i + 1, "script")) return i - 1;
515
+ i++;
516
+ state = ESCAPED;
517
+ } else state = ESCAPED;
518
+ break;
519
+ }
520
+ case DOUBLE_START:
521
+ case DOUBLE_END: {
522
+ if (i >= n) return n;
523
+ const c = html.charCodeAt(i);
524
+ if (isSpace(c) || c === SLASH || c === GT) {
525
+ i++;
526
+ state = state === DOUBLE_START ? DOUBLE : ESCAPED;
527
+ } else state = state === DOUBLE_START ? ESCAPED : DOUBLE;
528
+ break;
529
+ }
530
+ case DOUBLE_LT: {
531
+ if (i >= n) return n;
532
+ if (html.charCodeAt(i) === SLASH) {
533
+ i++;
534
+ state = DOUBLE_END_NAME;
535
+ } else state = DOUBLE;
536
+ break;
537
+ }
538
+ case DOUBLE_END_NAME: {
539
+ if (i >= n) return n;
540
+ if (scriptAt(html, i)) {
541
+ i += 6;
542
+ state = DOUBLE_END;
543
+ } else state = DOUBLE;
544
+ break;
545
+ }
546
+ }
547
+ }
548
+ }
549
+
550
+ // src/base.ts
551
+ function normalizeBase(base) {
552
+ const trimmed = base.trim();
553
+ if (trimmed === "" || trimmed === "/") return "";
554
+ if (!trimmed.startsWith("/") || trimmed.startsWith("//")) bail(`base must be a URL path starting with /, like "/docs/" (got ${JSON.stringify(base)}); the domain isn't part of it`);
555
+ if (/[?#\\\s]/.test(trimmed) || trimmed.split("/").some((p) => p === ".." || p === ".") || trimmed.includes("//")) bail(`base must be a plain URL path, like "/docs/" (got ${JSON.stringify(base)})`);
556
+ return trimmed.replace(/\/+$/, "");
557
+ }
558
+ var fromRoot = (url) => url.startsWith("/") && !url.startsWith("//");
559
+ function withBase(base, url) {
560
+ return base === "" || !fromRoot(url) ? url : base + url;
561
+ }
562
+ var URL_ATTRIBUTES = ["href", "src", "action", "poster", "data", "formaction", "cite", "xlink:href", "manifest"];
563
+ var SRCSET_ATTRIBUTES = ["srcset", "imagesrcset"];
564
+ var CSS_URL = /url\(\s*(["']|&quot;|&#34;|&#39;|&apos;)?\/((?:[^/)"'&]|&amp;)(?:[^)"'&]|&amp;)*)?(["')]|&quot;|&#34;|&#39;|&apos;)/g;
565
+ var REFRESH = /^(\s*[\d.]+\s*[;,]\s*url\s*=\s*["']?)(\/.*)$/is;
566
+ var SPACE = /[\t\n\f\r ]/;
567
+ function srcsetWithBase(base, srcset) {
568
+ let out = "";
569
+ let i = 0;
570
+ const n = srcset.length;
571
+ while (i < n) {
572
+ let start = i;
573
+ while (i < n && (SPACE.test(srcset[i]) || srcset[i] === ",")) i++;
574
+ out += srcset.slice(start, i);
575
+ start = i;
576
+ while (i < n && !SPACE.test(srcset[i])) i++;
577
+ const url = srcset.slice(start, i);
578
+ if (fromRoot(url)) out += base;
579
+ out += url;
580
+ if (!url.endsWith(",")) {
581
+ start = i;
582
+ while (i < n && srcset[i] !== ",") i++;
583
+ out += srcset.slice(start, i);
584
+ }
585
+ }
586
+ return out;
587
+ }
588
+ function cssWithBase(base, css) {
589
+ if (base === "") return css;
590
+ return css.replace(CSS_URL, (_, open, rest, close) => `url(${open ?? ""}${base}/${rest ?? ""}${close}`);
591
+ }
592
+ function rewriteBase(html, base) {
593
+ if (base === "") return html;
594
+ return rewriteHtml(html, {
595
+ tag(el) {
596
+ for (const attr of URL_ATTRIBUTES) {
597
+ const v = el.get(attr);
598
+ if (v !== void 0 && fromRoot(v.trimStart())) el.set(attr, base + v.trimStart());
599
+ }
600
+ for (const attr of SRCSET_ATTRIBUTES) {
601
+ const v = el.get(attr);
602
+ if (v === void 0) continue;
603
+ const changed = srcsetWithBase(base, v);
604
+ if (changed !== v) el.set(attr, changed);
605
+ }
606
+ const style = el.get("style");
607
+ if (style?.includes("url(")) el.set("style", cssWithBase(base, style));
608
+ if (el.name === "meta" && el.get("http-equiv")?.toLowerCase() === "refresh") {
609
+ const found = REFRESH.exec(el.get("content") ?? "");
610
+ if (found && fromRoot(found[2])) el.set("content", `${found[1]}${base}${found[2]}`);
611
+ }
612
+ },
613
+ style: (css) => css.includes("url(") ? cssWithBase(base, css) : css
614
+ });
615
+ }
616
+
617
+ // src/schema.ts
618
+ import fs from "node:fs";
619
+ import path from "node:path";
620
+ var BUILT_IN_KEYS = ["layout", "permalink", "dynamicPermalink", "tags", "date", "pagination", "computed", "render", "draft", "aliases", "excludeFromCollections", "sitemap", "nav", "title", "description", "lang"];
621
+ var TYPE_NAMES = "string, number, integer, boolean, date, file, object, array, any";
622
+ function parseNumber(word) {
623
+ if (/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(word)) return Number(word);
624
+ const m = /^([+-]?)(inf|infinity|nan)$/i.exec(word);
625
+ if (!m) return void 0;
626
+ if (m[2].toLowerCase() === "nan") return NaN;
627
+ return m[1] === "-" ? -Infinity : Infinity;
628
+ }
629
+ var TypeParser = class {
630
+ src;
631
+ pos = 0;
632
+ constructor(src) {
633
+ this.src = src;
634
+ }
635
+ rest() {
636
+ return this.src.slice(this.pos);
637
+ }
638
+ skipSpaces() {
639
+ const rest = this.rest();
640
+ this.pos += rest.length - rest.trimStart().length;
641
+ }
642
+ eat(token) {
643
+ this.skipSpaces();
644
+ if (this.rest().startsWith(token)) {
645
+ this.pos += token.length;
646
+ return true;
647
+ }
648
+ return false;
649
+ }
650
+ union() {
651
+ const types = [this.postfix()];
652
+ while (this.eat("|")) types.push(this.postfix());
653
+ return types.length === 1 ? types[0] : { kind: "union", types };
654
+ }
655
+ postfix() {
656
+ let type = this.primary();
657
+ while (this.eat("[]")) type = { kind: "list", item: type };
658
+ return type;
659
+ }
660
+ primary() {
661
+ this.skipSpaces();
662
+ const rest = this.rest();
663
+ const first = rest.codePointAt(0) === void 0 ? void 0 : String.fromCodePoint(rest.codePointAt(0));
664
+ if (first === void 0) bail(`a type is missing (types: ${TYPE_NAMES})`);
665
+ if (first === "(") {
666
+ this.pos += 1;
667
+ const type = this.union();
668
+ if (!this.eat(")")) bail("a `(` has no `)`");
669
+ return type;
670
+ }
671
+ if (first === "'" || first === '"') {
672
+ const end = rest.indexOf(first, 1);
673
+ if (end === -1) bail(`a quoted value has no closing ${first}`);
674
+ this.pos += end + 1;
675
+ return { kind: "literal", value: rest.slice(1, end) };
676
+ }
677
+ const word = /^[A-Za-z0-9._-]*/.exec(rest)[0];
678
+ this.pos += word.length;
679
+ switch (word) {
680
+ case "string":
681
+ case "number":
682
+ case "integer":
683
+ case "boolean":
684
+ case "date":
685
+ case "file":
686
+ case "object":
687
+ case "array":
688
+ case "any":
689
+ return { kind: word };
690
+ case "true":
691
+ return { kind: "literal", value: true };
692
+ case "false":
693
+ return { kind: "literal", value: false };
694
+ case "null":
695
+ return { kind: "literal", value: null };
696
+ case "":
697
+ return bail(`unexpected ${quotedChar(first)} (types: ${TYPE_NAMES})`);
698
+ }
699
+ const n = parseNumber(word);
700
+ if (n === void 0) bail(`unknown type ${quoted(word)} (types: ${TYPE_NAMES}; quote a literal value, like "'draft' | 'published'")`);
701
+ return { kind: "literal", value: n };
702
+ }
703
+ };
704
+ function parseType(src) {
705
+ const trimmed = src.trim();
706
+ const optional = trimmed.endsWith("?");
707
+ const parser = new TypeParser(optional ? trimmed.slice(0, -1) : trimmed);
708
+ const type = parser.union();
709
+ parser.skipSpaces();
710
+ if (parser.rest() !== "") bail(`unexpected ${quoted(parser.rest())} in type ${quoted(src)}`);
711
+ return [type, optional];
712
+ }
713
+ var typeOf = (v) => v === null ? "object" : typeof v;
714
+ var isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Date);
715
+ function parseFields(spec, at) {
716
+ if (!isObject(spec)) bail(`${at} must be an object of { field: type }, not ${typeOf(spec)}`);
717
+ const fields = [];
718
+ for (const [key, value] of Object.entries(spec)) {
719
+ const name = key.endsWith("?") ? key.slice(0, -1) : key;
720
+ const [type, optional] = parseFieldType(value, `${at}.${name}`);
721
+ fields.push({ name, optional: optional || key.endsWith("?"), type });
722
+ }
723
+ return fields;
724
+ }
725
+ function parseFieldType(value, at) {
726
+ if (typeof value === "string") {
727
+ try {
728
+ return parseType(value);
729
+ } catch (e) {
730
+ throw new BuildError(`${at}: ${e.message}`);
731
+ }
732
+ }
733
+ if (typeof value === "function") return [{ kind: "check", fn: value }, false];
734
+ if (Array.isArray(value)) {
735
+ if (value.length !== 1) bail(`${at}: a list type has one item, the type of each entry, like ["string"] or [{ name: "string" }]`);
736
+ return [{ kind: "list", item: parseFieldType(value[0], `${at}[]`)[0] }, false];
737
+ }
738
+ if (isObject(value)) return [{ kind: "fields", fields: parseFields(value, at) }, false];
739
+ return bail(`${at} must be a type ("string"), an object of fields, a one-item list, or a function, not ${typeOf(value)}`);
740
+ }
741
+ function parseSchema(name, spec) {
742
+ const at = `schemas.${name}`;
743
+ if (!isObject(spec)) bail(`${at} must be an object with \`fields\`, not ${typeOf(spec)}`);
744
+ const extra = Object.keys(spec).find((k) => !["fields", "files", "unknown"].includes(k));
745
+ if (extra !== void 0) bail(`${at}: "${extra}" isn't an option (options: fields, files, unknown); a schema's fields go in \`fields\``);
746
+ if (!("fields" in spec) || spec.fields === void 0) bail(`${at} needs \`fields\`: { title: "string", date: "date" }`);
747
+ const fields = parseFields(spec.fields, `${at}.fields`);
748
+ let files;
749
+ const given = spec.files;
750
+ if (given !== void 0 && given !== null) {
751
+ let globs;
752
+ if (typeof given === "string") globs = [given];
753
+ else if (Array.isArray(given)) globs = given.map((g) => typeof g === "string" ? g : bail(`${at}.files must be a glob or a list of globs`));
754
+ else bail(`${at}.files must be a glob or a list of globs, not ${typeOf(given)}`);
755
+ files = globs.map((g) => {
756
+ const glob = g.replace(/^(\.\/)+/, "");
757
+ const problem = globProblem(glob);
758
+ if (problem !== void 0) bail(`${at}.files: invalid glob ${quoted(g)}: error parsing glob '${glob}': ${problem}`);
759
+ return globToRegExp(glob);
760
+ });
761
+ }
762
+ let unknown = "allow";
763
+ if (spec.unknown !== void 0 && spec.unknown !== null) {
764
+ const word = jsString(spec.unknown);
765
+ if (word !== "allow" && word !== "warn" && word !== "error") bail(`${at}.unknown must be "allow", "warn" or "error", not ${quoted(word)}`);
766
+ unknown = word;
767
+ }
768
+ return { name, files, fields, unknown };
769
+ }
770
+ function schemaTypes(config) {
771
+ return config.schemas.map((schema) => [schema.name, objectTs(schema.fields, 2)]);
772
+ }
773
+ function covers(schema, rel, tags, inCollections) {
774
+ if (schema.files) return schema.files.some((re) => re.test(rel));
775
+ return inCollections && (schema.name === "all" || tags.includes(schema.name));
776
+ }
777
+ async function check(schema, data, frontKeys, files, root) {
778
+ const found = [];
779
+ checkFields(schema.fields, data, "", { page: data, files, root }, found);
780
+ const problems = found.some((p) => p instanceof Promise) ? (await Promise.all(found)).filter((p) => p !== void 0) : found;
781
+ if (schema.unknown !== "allow") {
782
+ for (const key of frontKeys) {
783
+ const row = find(key, "frontMatter");
784
+ const readAs = row?.alias ? row.ssqch : key;
785
+ if (schema.fields.some((f) => f.name === key || f.name === readAs) || BUILT_IN_KEYS.includes(readAs)) continue;
786
+ const near = closest(key, schema.fields.map((f) => f.name));
787
+ problems.push({ field: key, message: `\`${key}\` isn't a field of this schema${near === void 0 ? "" : ` (did you mean \`${near}\`?)`}`, warning: schema.unknown === "warn" });
788
+ }
789
+ }
790
+ return problems;
791
+ }
792
+ function checkFields(fields, data, prefix, at, out) {
793
+ for (const field of fields) {
794
+ const fieldPath = prefix === "" ? field.name : `${prefix}.${field.name}`;
795
+ const value = Object.prototype.hasOwnProperty.call(data, field.name) ? data[field.name] : void 0;
796
+ if (field.type.kind === "check") {
797
+ checkValue(field.type, value, fieldPath, at, out);
798
+ continue;
799
+ }
800
+ if (value === void 0 || value === null) {
801
+ const nullOk = value === null && acceptsNull(field.type);
802
+ if (!field.optional && !nullOk) out.push({ field: fieldPath, message: `\`${fieldPath}\` is required (${describe(field.type)})`, warning: false });
803
+ continue;
804
+ }
805
+ checkValue(field.type, value, fieldPath, at, out);
806
+ }
807
+ }
808
+ function acceptsNull(type) {
809
+ if (type.kind === "any") return true;
810
+ if (type.kind === "literal") return type.value === null;
811
+ if (type.kind === "union") return type.types.some(acceptsNull);
812
+ return false;
813
+ }
814
+ function matches(type, value, at) {
815
+ const found = [];
816
+ checkValue(type, value, "", at, found);
817
+ return found.length === 0;
818
+ }
819
+ function checkValue(type, value, fieldPath, at, out) {
820
+ const problem = (message) => ({ field: fieldPath, message, warning: false });
821
+ const wrong = (message) => {
822
+ out.push(problem(message));
823
+ };
824
+ const mismatch = () => wrong(`\`${fieldPath}\` must be ${describe(type)}, not ${show(value)}`);
825
+ switch (type.kind) {
826
+ case "any":
827
+ return;
828
+ case "string":
829
+ if (typeof value !== "string") mismatch();
830
+ return;
831
+ case "number":
832
+ if (typeof value !== "number" || Number.isNaN(value)) mismatch();
833
+ return;
834
+ case "integer":
835
+ if (!Number.isInteger(value)) mismatch();
836
+ return;
837
+ case "boolean":
838
+ if (typeof value !== "boolean") mismatch();
839
+ return;
840
+ case "date": {
841
+ const ok = value instanceof Date || typeof value === "string" && toDate(value) !== void 0;
842
+ if (!ok) mismatch();
843
+ return;
844
+ }
845
+ case "file": {
846
+ if (typeof value !== "string" || value.trim() === "") return mismatch();
847
+ const clean = value.split(/[?#]/)[0];
848
+ const fromRoot2 = clean.startsWith("/");
849
+ const file = fromRoot2 ? path.join(at.files.input, clean.slice(1)) : path.join(at.files.pageDir, clean);
850
+ if (!(fs.statSync(file, { throwIfNoEntry: false })?.isFile() ?? false)) wrong(`\`${fieldPath}\` is ${quoted(value)}, but there's no such file ${fromRoot2 ? "in the input folder" : "next to the page"}`);
851
+ return;
852
+ }
853
+ case "object":
854
+ if (!isObject(value)) mismatch();
855
+ return;
856
+ case "array":
857
+ if (!Array.isArray(value)) mismatch();
858
+ return;
859
+ case "literal":
860
+ if (type.value !== value) mismatch();
861
+ return;
862
+ case "union": {
863
+ if (!type.types.some((t) => matches(t, value, at))) mismatch();
864
+ return;
865
+ }
866
+ case "list": {
867
+ if (!Array.isArray(value)) return mismatch();
868
+ for (let i = 0; i < value.length; i++) checkValue(type.item, value[i], `${fieldPath}[${i}]`, at, out);
869
+ return;
870
+ }
871
+ case "fields": {
872
+ if (!isObject(value)) return mismatch();
873
+ return checkFields(type.fields, value, fieldPath, at, out);
874
+ }
875
+ case "check": {
876
+ const failed2 = (e) => problem(`\`${fieldPath}\`: the check failed: ${describeThrown(e, at.root)}`);
877
+ const judge = (answer3) => {
878
+ if (answer3 === true || answer3 === void 0 || answer3 === null) return void 0;
879
+ if (typeof answer3 === "string") return problem(`\`${fieldPath}\` ${answer3}`);
880
+ if (answer3 === false) return problem(`\`${fieldPath}\` isn't valid (${show(value)})`);
881
+ return problem(`\`${fieldPath}\`: the check returned ${typeOf(answer3)}; return true, false or a message`);
882
+ };
883
+ let answer2;
884
+ try {
885
+ answer2 = type.fn(value, at.page);
886
+ } catch (e) {
887
+ out.push(failed2(e));
888
+ return;
889
+ }
890
+ if (answer2 instanceof Promise) out.push(answer2.then(judge, failed2));
891
+ else {
892
+ const found = judge(answer2);
893
+ if (found) out.push(found);
894
+ }
895
+ return;
896
+ }
897
+ }
898
+ }
899
+ function describe(type) {
900
+ switch (type.kind) {
901
+ case "any":
902
+ return "set";
903
+ case "string":
904
+ return "a string";
905
+ case "number":
906
+ return "a number";
907
+ case "integer":
908
+ return "a whole number";
909
+ case "boolean":
910
+ return "true or false";
911
+ case "date":
912
+ return "a date, like 2026-03-14";
913
+ case "file":
914
+ return "a path to a file";
915
+ case "object":
916
+ return "an object";
917
+ case "array":
918
+ return "a list";
919
+ case "literal":
920
+ return show(type.value);
921
+ case "union": {
922
+ const parts = type.types.map(describe);
923
+ return parts.length > 1 ? `${parts.slice(0, -1).join(", ")} or ${parts[parts.length - 1]}` : parts.join("");
924
+ }
925
+ case "list": {
926
+ const item = type.item.kind;
927
+ if (item === "string") return "a list of strings";
928
+ if (item === "number" || item === "integer") return "a list of numbers";
929
+ if (item === "fields" || item === "object") return "a list of objects";
930
+ return "a list";
931
+ }
932
+ case "fields":
933
+ return "an object";
934
+ case "check":
935
+ return "valid";
936
+ }
937
+ }
938
+ function show(value) {
939
+ if (value === void 0) return "missing";
940
+ if (value === null) return "null";
941
+ if (typeof value === "string") return `${quoted(firstChars(value, 60))}${charCount(value) > 60 ? "..." : ""}`;
942
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
943
+ if (value instanceof Date) return `the date ${Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString().slice(0, 10)}`;
944
+ if (Array.isArray(value)) return "a list";
945
+ if (typeof value === "function") return "a function";
946
+ return "an object";
947
+ }
948
+ function keyTs(name) {
949
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : quoted(name);
950
+ }
951
+ function objectTs(fields, depth) {
952
+ if (!fields.length) return "{}";
953
+ const indent = " ".repeat(depth + 1);
954
+ let out = "{\n";
955
+ for (const f of fields) out += `${indent}${keyTs(f.name)}${f.optional ? "?" : ""}: ${typeTs(f.type, depth + 1)};
956
+ `;
957
+ return `${out}${" ".repeat(depth)}}`;
958
+ }
959
+ function typeTs(type, depth) {
960
+ switch (type.kind) {
961
+ case "any":
962
+ case "check":
963
+ return "any";
964
+ case "string":
965
+ case "file":
966
+ return "string";
967
+ case "number":
968
+ case "integer":
969
+ return "number";
970
+ case "boolean":
971
+ return "boolean";
972
+ case "date":
973
+ return "Date | string";
974
+ case "object":
975
+ return "Record<string, any>";
976
+ case "array":
977
+ return "any[]";
978
+ case "literal":
979
+ return typeof type.value === "string" ? quoted(type.value) : String(type.value);
980
+ case "union":
981
+ return type.types.map((t) => typeTs(t, depth)).join(" | ");
982
+ case "list":
983
+ return type.item.kind === "union" || type.item.kind === "date" ? `(${typeTs(type.item, depth)})[]` : `${typeTs(type.item, depth)}[]`;
984
+ case "fields":
985
+ return objectTs(type.fields, depth);
986
+ }
987
+ }
988
+ async function checkPages(site2) {
989
+ const { config, dirs } = site2;
990
+ if (!config.schemas.length) return;
991
+ const seen = /* @__PURE__ */ new Set();
992
+ const errors = [];
993
+ for (const page of site2.pages) {
994
+ const tags = Array.isArray(page.data.tags) ? page.data.tags.filter((t) => typeof t === "string") : [];
995
+ const files = { input: dirs.input, pageDir: path.dirname(page.tpl.input) };
996
+ const file = site2.display(page.tpl.input);
997
+ for (const schema of config.schemas) {
998
+ if (!covers(schema, page.tpl.rel, tags, page.inCollections)) continue;
999
+ for (const problem of await check(schema, page.data, page.tpl.frontKeys, files, dirs.root)) {
1000
+ const message = `${file.replace(/^(\.\/)+/, "")}: ${problem.message} (schema \`${schema.name}\`)`;
1001
+ if (seen.has(message)) continue;
1002
+ seen.add(message);
1003
+ const found = (problem.warning ? warning : error)("schema", message, { file, field: problem.field });
1004
+ if (problem.warning) warn(found);
1005
+ else errors.push(found);
1006
+ }
1007
+ }
1008
+ }
1009
+ if (!errors.length) return;
1010
+ const shown2 = config.verbose ? errors.length : 30;
1011
+ const more = errors.length > shown2 ? `
1012
+ ... and ${errors.length - shown2} more (--verbose lists them all)` : "";
1013
+ const listed = errors.slice(0, shown2).map((d) => d.message);
1014
+ throw new Diagnostics(`${errors.length} content ${errors.length === 1 ? "error" : "errors"}:
1015
+ - ${listed.join("\n - ")}${more}`, errors);
1016
+ }
1017
+
1018
+ // src/fetch.ts
1019
+ import { createHash } from "node:crypto";
1020
+ import fs2 from "node:fs";
1021
+ import path2 from "node:path";
1022
+ var counts = { asked: 0, hits: 0, stale: 0 };
1023
+ var cacheDir = "";
1024
+ var original = globalThis.fetch;
1025
+ var NodeRequest = globalThis.Request;
1026
+ var installed = false;
1027
+ var USER_AGENT = `ssqch/${VERSION}`;
1028
+ function offline() {
1029
+ const value = process.env.SSQCH_OFFLINE;
1030
+ return value !== void 0 && !["", "0", "false"].includes(value);
1031
+ }
1032
+ function summary() {
1033
+ const { asked, hits, stale } = counts;
1034
+ counts.asked = counts.hits = counts.stale = 0;
1035
+ savedThisBuild.clear();
1036
+ const total = asked + hits + stale;
1037
+ if (total === 0) return void 0;
1038
+ let line = `${total} request${total === 1 ? "" : "s"}`;
1039
+ if (hits + stale > 0) line += `, ${hits + stale} from the cache`;
1040
+ if (stale > 0) line += ` (${stale} out of date, after a failed request)`;
1041
+ if (offline()) line += " (--offline: living off the cache)";
1042
+ return line;
1043
+ }
1044
+ function installFetch(root) {
1045
+ cacheDir = path2.join(root, ".cache/ssqch/fetch");
1046
+ if (installed) return;
1047
+ installed = true;
1048
+ globalThis.fetch = ssqchFetch;
1049
+ globalThis.Request = SsqchRequest;
1050
+ }
1051
+ var UNITS = { s: 1, m: 60, h: 3600, d: 86400, w: 604800 };
1052
+ function parseCache(cache) {
1053
+ if (typeof cache === "number" && cache >= 0) return { mode: "max-age", ms: cache * 1e3 };
1054
+ const duration = /^(\d+(?:\.\d+)?)\s*([smhdw])$/.exec(String(cache).trim());
1055
+ if (duration) return { mode: "max-age", ms: Number(duration[1]) * UNITS[duration[2]] * 1e3 };
1056
+ switch (cache) {
1057
+ case "default":
1058
+ case "no-store":
1059
+ case "no-cache":
1060
+ return { mode: "off" };
1061
+ case "force-cache":
1062
+ return { mode: "forever" };
1063
+ case "reload":
1064
+ return { mode: "reload" };
1065
+ case "only-if-cached":
1066
+ return { mode: "only" };
1067
+ }
1068
+ throw new TypeError(`fetch: cache ${JSON.stringify(cache)} isn't a duration like "1h" (s, m, h, d or w), or "force-cache", "reload", "only-if-cached" or "no-store"`);
1069
+ }
1070
+ var NODE_CACHE = /* @__PURE__ */ new Set(["default", "no-store", "reload", "no-cache", "force-cache", "only-if-cached"]);
1071
+ var extras = /* @__PURE__ */ new WeakMap();
1072
+ var SsqchRequest = new Proxy(NodeRequest, {
1073
+ construct(target, args, newTarget) {
1074
+ let [input, init] = args;
1075
+ const from = input instanceof NodeRequest ? extras.get(input) : void 0;
1076
+ let cache = from?.cache;
1077
+ let href = from?.href;
1078
+ if (init !== null && typeof init === "object") {
1079
+ const value = init.cache;
1080
+ if (value !== void 0 && !(typeof value === "string" && NODE_CACHE.has(value))) {
1081
+ const { cache: _ssqch, ...rest } = init;
1082
+ init = rest;
1083
+ if (value !== null) cache = value;
1084
+ } else if (value !== void 0) cache = void 0;
1085
+ }
1086
+ if (!(input instanceof NodeRequest)) {
1087
+ const text = input instanceof URL ? input.href : String(input);
1088
+ const url = URL.canParse(text) ? new URL(text) : void 0;
1089
+ href = void 0;
1090
+ if (url && (url.username || url.password)) {
1091
+ href = url.href;
1092
+ url.username = url.password = "";
1093
+ input = url.href;
1094
+ }
1095
+ }
1096
+ const request = Reflect.construct(target, [input, init], newTarget);
1097
+ if (cache !== void 0 || href !== void 0) extras.set(request, { cache, href });
1098
+ if (cache !== void 0) Object.defineProperty(request, "cache", { value: cache, enumerable: true, configurable: true });
1099
+ return request;
1100
+ }
1101
+ });
1102
+ var MAX_RUNNING = 8;
1103
+ var running = 0;
1104
+ var waiting = [];
1105
+ async function inTurn(work) {
1106
+ if (running >= MAX_RUNNING) await new Promise((resolve) => waiting.push(resolve));
1107
+ else running++;
1108
+ try {
1109
+ return await work();
1110
+ } finally {
1111
+ const next = waiting.shift();
1112
+ if (next) next();
1113
+ else running--;
1114
+ }
1115
+ }
1116
+ var NODE_HTTP_HEADERS = ["host", "keep-alive", "transfer-encoding", "upgrade", "expect"];
1117
+ var BLOCKED_PORTS = /* @__PURE__ */ new Set([1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79, 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6e3, 6566, 6665, 6666, 6667, 6668, 6669, 6679, 6697, 10080]);
1118
+ var send = (request, viaNodeHttp) => viaNodeHttp ? nodeHttpFetch(request) : original(request);
1119
+ var isAbort = (e) => e instanceof DOMException && (e.name === "AbortError" || e.name === "TimeoutError");
1120
+ function reasonOf(e) {
1121
+ let cause = e?.cause;
1122
+ if (cause?.errors?.length && !cause.message) cause = cause.errors[0];
1123
+ const message = String(cause?.message || cause?.code || e?.message || e);
1124
+ return message.replace(/^fetch failed: /, "");
1125
+ }
1126
+ function worded(e, url) {
1127
+ if (e instanceof TypeError && e.message === "fetch failed") {
1128
+ return Object.assign(new TypeError(`fetch failed: ${url}: ${reasonOf(e)}`), { cause: e.cause });
1129
+ }
1130
+ return e;
1131
+ }
1132
+ async function ssqchFetch(input, init) {
1133
+ const options = init !== null && typeof init === "object" ? init : void 0;
1134
+ const from = input instanceof NodeRequest ? extras.get(input) : void 0;
1135
+ const cache = parseCache(options?.cache ?? (input instanceof NodeRequest ? from?.cache ?? input.cache : "default"));
1136
+ let href;
1137
+ if (input instanceof NodeRequest) href = from?.href ?? input.url;
1138
+ else {
1139
+ const text = input instanceof URL ? input.href : String(input);
1140
+ if (!URL.canParse(text)) throw new TypeError(`Invalid URL: ${text}`);
1141
+ href = new URL(text).href;
1142
+ }
1143
+ const target = new URL(href);
1144
+ const masked = new URL(href);
1145
+ masked.password = "";
1146
+ const shown2 = masked.href;
1147
+ if (target.protocol !== "http:" && target.protocol !== "https:") throw new TypeError(`fetch failed: ${shown2}: only http: and https: URLs can be fetched`);
1148
+ let auth;
1149
+ if (target.username || target.password) {
1150
+ auth = `Basic ${Buffer.from(`${target.username}:${target.password}`).toString("base64")}`;
1151
+ target.username = target.password = "";
1152
+ }
1153
+ const { cache: _ssqch, ...rest } = options ?? {};
1154
+ const request = new NodeRequest(input instanceof NodeRequest ? input : target.href, { ...rest, cache: "default" });
1155
+ const asked = [...request.headers];
1156
+ if (auth !== void 0 && !request.headers.has("authorization")) request.headers.set("authorization", auth);
1157
+ if (!request.headers.has("user-agent")) request.headers.set("user-agent", USER_AGENT);
1158
+ const viaNodeHttp = target.port !== "" && BLOCKED_PORTS.has(Number(target.port)) || NODE_HTTP_HEADERS.some((name) => request.headers.has(name));
1159
+ if (request.signal.aborted) throw request.signal.reason;
1160
+ const isOffline = offline();
1161
+ if (cache.mode === "off" && !isOffline) {
1162
+ return inTurn(async () => {
1163
+ counts.asked++;
1164
+ try {
1165
+ return await send(request, viaNodeHttp);
1166
+ } catch (e) {
1167
+ throw worded(e, shown2);
1168
+ }
1169
+ });
1170
+ }
1171
+ const body = new Uint8Array(await request.clone().arrayBuffer());
1172
+ const ask = { method: request.method, url: href, headers: asked, body };
1173
+ return inTurn(() => answer(request, ask, shown2, cache, isOffline, viaNodeHttp));
1174
+ }
1175
+ var DECODED = /* @__PURE__ */ new Set(["gzip", "x-gzip", "deflate", "br"]);
1176
+ async function answer(request, ask, shown2, cache, isOffline, viaNodeHttp) {
1177
+ const copy = cache.mode === "off" ? void 0 : saved(ask);
1178
+ const fresh = (old) => {
1179
+ switch (cache.mode) {
1180
+ case "max-age":
1181
+ return old <= cache.ms;
1182
+ case "forever":
1183
+ case "only":
1184
+ return true;
1185
+ default:
1186
+ return false;
1187
+ }
1188
+ };
1189
+ if (copy && (isOffline || fresh(copy.old))) {
1190
+ counts.hits++;
1191
+ return fromCache(copy, request.url, "hit");
1192
+ }
1193
+ if (!copy && isOffline && cache.mode === "off") throw new TypeError(`fetch failed: ${shown2}: offline (SSQCH_OFFLINE), and this request has no \`cache\` option, so there's no saved copy to use`);
1194
+ if (!copy && isOffline) throw new TypeError(`fetch failed: ${shown2}: offline (SSQCH_OFFLINE), and there's no saved copy in ${cacheDir}`);
1195
+ if (!copy && cache.mode === "only") throw new TypeError(`fetch failed: ${shown2}: no saved copy (cache: "only-if-cached")`);
1196
+ counts.asked++;
1197
+ let response;
1198
+ let failure;
1199
+ let thrown;
1200
+ try {
1201
+ response = await send(request, viaNodeHttp);
1202
+ if (response.status >= 500 || response.status === 429) failure = `answered ${response.status}`;
1203
+ } catch (e) {
1204
+ if (isAbort(e) && e.name !== "TimeoutError") throw e;
1205
+ thrown = worded(e, shown2);
1206
+ failure = e.name === "TimeoutError" ? "timed out (TimeoutError)" : reasonOf(e);
1207
+ }
1208
+ if (failure !== void 0 && copy) {
1209
+ warn(warning("fetch", `fetch: ${shown2} ${failure}; using the copy saved ${age(copy.old)}`));
1210
+ counts.stale++;
1211
+ return fromCache(copy, request.url, "stale");
1212
+ }
1213
+ if (failure !== void 0 && response === void 0) throw thrown;
1214
+ if (response && response.status >= 200 && response.status < 300) {
1215
+ const bytes2 = new Uint8Array(await response.arrayBuffer());
1216
+ const codings = (response.headers.get("content-encoding") ?? "").toLowerCase().split(",").map((c) => c.trim()).filter((c) => c !== "");
1217
+ const decoded = codings.length > 0 && codings.every((c) => DECODED.has(c));
1218
+ const headers = [...response.headers].filter(([k]) => !decoded || k !== "content-encoding" && k !== "content-length");
1219
+ const reply = { status: response.status, statusText: response.statusText, redirected: response.redirected, headers, body: bytes2 };
1220
+ try {
1221
+ await save(ask, reply);
1222
+ } catch (e) {
1223
+ warn(warning("fetch", `fetch: couldn't save ${shown2} in ${cacheDir}: ${e.message}`));
1224
+ }
1225
+ return make(reply, response.url || request.url);
1226
+ }
1227
+ return response;
1228
+ }
1229
+ var REDIRECTS = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
1230
+ var load = () => Promise.all([import("node:http"), import("node:https"), import("node:net"), import("node:stream"), import("node:zlib")]).then(([http, https, net, stream, zlib]) => ({ http: http.default, https: https.default, net: net.default, stream: stream.default, zlib: zlib.default }));
1231
+ var loaded;
1232
+ var nodeModules = () => loaded ??= load();
1233
+ function decoder(zlib, coding) {
1234
+ const sync = { flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH };
1235
+ switch (coding) {
1236
+ case "gzip":
1237
+ case "x-gzip":
1238
+ return zlib.createGunzip(sync);
1239
+ case "deflate":
1240
+ return zlib.createInflate();
1241
+ case "br":
1242
+ return zlib.createBrotliDecompress();
1243
+ }
1244
+ return void 0;
1245
+ }
1246
+ var failed = (reason) => new TypeError("fetch failed", { cause: new Error(reason) });
1247
+ async function nodeHttpFetch(request) {
1248
+ const modules = await nodeModules();
1249
+ let body = request.body === null ? void 0 : Buffer.from(await request.arrayBuffer());
1250
+ let url = new URL(request.url);
1251
+ let method = request.method;
1252
+ const headers = new Headers(request.headers);
1253
+ for (const [name, value] of [["accept", "*/*"], ["accept-language", "*"], ["sec-fetch-mode", "cors"], ["accept-encoding", "gzip, deflate"]]) {
1254
+ if (!headers.has(name)) headers.set(name, value);
1255
+ }
1256
+ let redirected = false;
1257
+ for (let hops = 0; ; hops++) {
1258
+ const res = await exchange(modules, url, method, headers, body, request.signal);
1259
+ const status = res.statusCode ?? 0;
1260
+ const location = res.headers.location;
1261
+ if (!REDIRECTS.has(status) || location === void 0 || request.redirect === "manual") return toResponse(modules, res, url, redirected, method, request.signal);
1262
+ res.resume();
1263
+ if (request.redirect === "error") throw failed("unexpected redirect");
1264
+ if (hops >= 20) throw failed("redirect count exceeded");
1265
+ if (!URL.canParse(location, url.href)) throw failed("invalid redirect location");
1266
+ const next = new URL(location, url);
1267
+ if (next.protocol !== "http:" && next.protocol !== "https:") throw failed("URL scheme must be a HTTP(S) scheme");
1268
+ if (status === 303 ? method !== "GET" && method !== "HEAD" : (status === 301 || status === 302) && method === "POST") {
1269
+ method = "GET";
1270
+ body = void 0;
1271
+ for (const name of ["content-encoding", "content-language", "content-location", "content-type", "content-length", "transfer-encoding"]) headers.delete(name);
1272
+ }
1273
+ if (next.origin !== url.origin) for (const name of ["authorization", "proxy-authorization", "cookie", "host"]) headers.delete(name);
1274
+ url = next;
1275
+ redirected = true;
1276
+ }
1277
+ }
1278
+ function exchange({ http, https, net }, url, method, headers, body, signal) {
1279
+ return new Promise((resolve, reject) => {
1280
+ if (signal.aborted) return reject(signal.reason);
1281
+ const outgoing = {};
1282
+ for (const [name, value] of headers) outgoing[name] = value;
1283
+ if (body !== void 0 && !headers.has("content-length") && !headers.has("transfer-encoding")) outgoing["content-length"] = String(body.length);
1284
+ const options = { method, headers: outgoing };
1285
+ if (url.protocol === "https:" && net.isIP(url.hostname.replace(/^\[|\]$/g, "")) === 0) options.servername = url.hostname;
1286
+ const req = (url.protocol === "https:" ? https : http).request(url, options);
1287
+ const onAbort = () => req.destroy();
1288
+ signal.addEventListener("abort", onAbort, { once: true });
1289
+ req.once("response", (res) => {
1290
+ signal.removeEventListener("abort", onAbort);
1291
+ resolve(res);
1292
+ });
1293
+ req.once("upgrade", (res, socket) => {
1294
+ socket.destroy();
1295
+ reject(failed(`the server switched protocols (${res.statusCode})`));
1296
+ });
1297
+ req.once("error", (e) => {
1298
+ signal.removeEventListener("abort", onAbort);
1299
+ reject(signal.aborted ? signal.reason : new TypeError("fetch failed", { cause: e }));
1300
+ });
1301
+ req.setTimeout(3e5, () => req.destroy(new Error("headers timeout")));
1302
+ req.end(body);
1303
+ });
1304
+ }
1305
+ function toResponse({ stream: { Readable, pipeline }, zlib }, res, url, redirected, method, signal) {
1306
+ const status = res.statusCode ?? 0;
1307
+ const headers = new Headers();
1308
+ for (let i = 0; i < res.rawHeaders.length; i += 2) headers.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
1309
+ let body = null;
1310
+ if (method === "HEAD" || [101, 103, 204, 205, 304].includes(status)) res.resume();
1311
+ else {
1312
+ const codings = String(res.headers["content-encoding"] ?? "").toLowerCase().split(",").map((c) => c.trim()).filter((c) => c !== "");
1313
+ const decoders = codings.length > 0 && codings.every((c) => DECODED.has(c)) ? codings.reverse().map((c) => decoder(zlib, c)) : [];
1314
+ const stream = decoders.length ? pipeline([res, ...decoders], () => {
1315
+ }) : res;
1316
+ body = Readable.toWeb(stream);
1317
+ signal.addEventListener("abort", () => res.destroy(signal.reason), { once: true });
1318
+ }
1319
+ const response = new Response(body, { status: status >= 200 && status <= 599 ? status : 200, statusText: res.statusMessage ?? "", headers });
1320
+ const answered = new URL(url);
1321
+ answered.hash = "";
1322
+ Object.defineProperty(response, "url", { value: answered.href, configurable: true });
1323
+ Object.defineProperty(response, "redirected", { value: redirected, configurable: true });
1324
+ Object.defineProperty(response, "type", { value: "basic", configurable: true });
1325
+ if (status < 200 || status > 599) {
1326
+ Object.defineProperty(response, "status", { value: status, configurable: true });
1327
+ Object.defineProperty(response, "ok", { value: false, configurable: true });
1328
+ }
1329
+ return response;
1330
+ }
1331
+ function cachePaths(ask) {
1332
+ const hash = createHash("sha256");
1333
+ hash.update(ask.method.toUpperCase());
1334
+ hash.update("\n");
1335
+ hash.update(ask.url);
1336
+ const headers = ask.headers.map(([k, v]) => `${k.toLowerCase()}:${v}`).sort();
1337
+ for (const h of headers) {
1338
+ hash.update("\n");
1339
+ hash.update(h);
1340
+ }
1341
+ hash.update("\n\n");
1342
+ hash.update(ask.body);
1343
+ const key = hash.digest("hex").slice(0, 32);
1344
+ return [path2.join(cacheDir, `${key}.json`), path2.join(cacheDir, `${key}.body`)];
1345
+ }
1346
+ var savedThisBuild = /* @__PURE__ */ new Map();
1347
+ function saved(ask) {
1348
+ const [metaPath, bodyPath] = cachePaths(ask);
1349
+ const kept = savedThisBuild.get(metaPath);
1350
+ if (kept) return { ...kept.reply, old: Math.max(0, Date.now() - kept.savedAt * 1e3) };
1351
+ try {
1352
+ const meta = JSON.parse(fs2.readFileSync(metaPath, "utf8"));
1353
+ const body = fs2.readFileSync(bodyPath);
1354
+ if (!Number.isInteger(meta.savedAt) || !Number.isInteger(meta.status) || !Array.isArray(meta.headers)) return void 0;
1355
+ const headers = meta.headers.flatMap((pair) => Array.isArray(pair) && typeof pair[0] === "string" && typeof pair[1] === "string" ? [[pair[0], pair[1]]] : []);
1356
+ return { status: meta.status, statusText: typeof meta.statusText === "string" ? meta.statusText : "", redirected: meta.redirected === true, headers, body, old: Math.max(0, Date.now() - meta.savedAt * 1e3) };
1357
+ } catch {
1358
+ return void 0;
1359
+ }
1360
+ }
1361
+ var writes = 0;
1362
+ async function save(ask, reply) {
1363
+ const [metaPath, bodyPath] = cachePaths(ask);
1364
+ await fs2.promises.mkdir(cacheDir, { recursive: true });
1365
+ const meta = {
1366
+ method: ask.method,
1367
+ status: reply.status,
1368
+ statusText: reply.statusText,
1369
+ redirected: reply.redirected,
1370
+ // Cookies aren't for keeping.
1371
+ headers: reply.headers.filter(([k]) => k.toLowerCase() !== "set-cookie"),
1372
+ savedAt: Math.floor(Date.now() / 1e3)
1373
+ };
1374
+ savedThisBuild.set(metaPath, { reply: { ...reply, headers: meta.headers }, savedAt: meta.savedAt });
1375
+ const put = async (file, bytes2) => {
1376
+ const temp = `${file.replace(/\.[^./\\]+$/, "")}.${process.pid}-${writes++}.tmp`;
1377
+ try {
1378
+ await fs2.promises.writeFile(temp, bytes2);
1379
+ await fs2.promises.rename(temp, file);
1380
+ } catch (e) {
1381
+ await fs2.promises.rm(temp, { force: true });
1382
+ throw e;
1383
+ }
1384
+ };
1385
+ await put(bodyPath, reply.body);
1386
+ await put(metaPath, JSON.stringify(meta, null, 2));
1387
+ }
1388
+ function make(reply, url) {
1389
+ const empty = [101, 204, 205, 304].includes(reply.status);
1390
+ const response = new Response(empty ? null : reply.body, { status: reply.status, statusText: reply.statusText, headers: reply.headers });
1391
+ Object.defineProperty(response, "url", { value: url, configurable: true });
1392
+ Object.defineProperty(response, "redirected", { value: reply.redirected, configurable: true });
1393
+ Object.defineProperty(response, "type", { value: "basic", configurable: true });
1394
+ return response;
1395
+ }
1396
+ function fromCache(copy, url, how) {
1397
+ const headers = copy.headers.filter(([k]) => k.toLowerCase() !== "x-ssqch-cache");
1398
+ headers.push(["x-ssqch-cache", how]);
1399
+ return make({ ...copy, headers }, url);
1400
+ }
1401
+ function age(ms) {
1402
+ const s = Math.floor(ms / 1e3);
1403
+ const [n, unit] = s < 120 ? [s, "second"] : s < 7200 ? [Math.floor(s / 60), "minute"] : s < 172800 ? [Math.floor(s / 3600), "hour"] : [Math.floor(s / 86400), "day"];
1404
+ return `${n} ${unit}${n === 1 ? "" : "s"} ago`;
1405
+ }
1406
+
1407
+ // src/image/processor.ts
1408
+ import fs4 from "node:fs";
1409
+ import os2 from "node:os";
1410
+ import path4 from "node:path";
1411
+
1412
+ // src/blake3.ts
1413
+ import os from "node:os";
1414
+ var IV = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225];
1415
+ var CHUNK_START = 1;
1416
+ var CHUNK_END = 2;
1417
+ var PARENT = 4;
1418
+ var ROOT = 8;
1419
+ var BLOCK_LEN = 64;
1420
+ var CHUNK_LEN = 1024;
1421
+ var LITTLE_ENDIAN = os.endianness() === "LE";
1422
+ function compress(cv, co, m, mo, counter, blockLen, flags, out, oo) {
1423
+ let m0 = m[mo] | 0, m1 = m[mo + 1] | 0, m2 = m[mo + 2] | 0, m3 = m[mo + 3] | 0, m4 = m[mo + 4] | 0, m5 = m[mo + 5] | 0, m6 = m[mo + 6] | 0, m7 = m[mo + 7] | 0;
1424
+ let m8 = m[mo + 8] | 0, m9 = m[mo + 9] | 0, m10 = m[mo + 10] | 0, m11 = m[mo + 11] | 0, m12 = m[mo + 12] | 0, m13 = m[mo + 13] | 0, m14 = m[mo + 14] | 0, m15 = m[mo + 15] | 0;
1425
+ let s0 = cv[co] | 0, s1 = cv[co + 1] | 0, s2 = cv[co + 2] | 0, s3 = cv[co + 3] | 0, s4 = cv[co + 4] | 0, s5 = cv[co + 5] | 0, s6 = cv[co + 6] | 0, s7 = cv[co + 7] | 0;
1426
+ let s8 = IV[0] | 0, s9 = IV[1] | 0, s10 = IV[2] | 0, s11 = IV[3] | 0;
1427
+ let s12 = counter | 0, s13 = Math.floor(counter / 4294967296) | 0, s14 = blockLen | 0, s15 = flags | 0;
1428
+ let t = 0;
1429
+ for (let round = 0; round < 7; round++) {
1430
+ s0 = s0 + s4 + m0 | 0;
1431
+ t = s12 ^ s0;
1432
+ s12 = t >>> 16 | t << 16;
1433
+ s8 = s8 + s12 | 0;
1434
+ t = s4 ^ s8;
1435
+ s4 = t >>> 12 | t << 20;
1436
+ s0 = s0 + s4 + m1 | 0;
1437
+ t = s12 ^ s0;
1438
+ s12 = t >>> 8 | t << 24;
1439
+ s8 = s8 + s12 | 0;
1440
+ t = s4 ^ s8;
1441
+ s4 = t >>> 7 | t << 25;
1442
+ s1 = s1 + s5 + m2 | 0;
1443
+ t = s13 ^ s1;
1444
+ s13 = t >>> 16 | t << 16;
1445
+ s9 = s9 + s13 | 0;
1446
+ t = s5 ^ s9;
1447
+ s5 = t >>> 12 | t << 20;
1448
+ s1 = s1 + s5 + m3 | 0;
1449
+ t = s13 ^ s1;
1450
+ s13 = t >>> 8 | t << 24;
1451
+ s9 = s9 + s13 | 0;
1452
+ t = s5 ^ s9;
1453
+ s5 = t >>> 7 | t << 25;
1454
+ s2 = s2 + s6 + m4 | 0;
1455
+ t = s14 ^ s2;
1456
+ s14 = t >>> 16 | t << 16;
1457
+ s10 = s10 + s14 | 0;
1458
+ t = s6 ^ s10;
1459
+ s6 = t >>> 12 | t << 20;
1460
+ s2 = s2 + s6 + m5 | 0;
1461
+ t = s14 ^ s2;
1462
+ s14 = t >>> 8 | t << 24;
1463
+ s10 = s10 + s14 | 0;
1464
+ t = s6 ^ s10;
1465
+ s6 = t >>> 7 | t << 25;
1466
+ s3 = s3 + s7 + m6 | 0;
1467
+ t = s15 ^ s3;
1468
+ s15 = t >>> 16 | t << 16;
1469
+ s11 = s11 + s15 | 0;
1470
+ t = s7 ^ s11;
1471
+ s7 = t >>> 12 | t << 20;
1472
+ s3 = s3 + s7 + m7 | 0;
1473
+ t = s15 ^ s3;
1474
+ s15 = t >>> 8 | t << 24;
1475
+ s11 = s11 + s15 | 0;
1476
+ t = s7 ^ s11;
1477
+ s7 = t >>> 7 | t << 25;
1478
+ s0 = s0 + s5 + m8 | 0;
1479
+ t = s15 ^ s0;
1480
+ s15 = t >>> 16 | t << 16;
1481
+ s10 = s10 + s15 | 0;
1482
+ t = s5 ^ s10;
1483
+ s5 = t >>> 12 | t << 20;
1484
+ s0 = s0 + s5 + m9 | 0;
1485
+ t = s15 ^ s0;
1486
+ s15 = t >>> 8 | t << 24;
1487
+ s10 = s10 + s15 | 0;
1488
+ t = s5 ^ s10;
1489
+ s5 = t >>> 7 | t << 25;
1490
+ s1 = s1 + s6 + m10 | 0;
1491
+ t = s12 ^ s1;
1492
+ s12 = t >>> 16 | t << 16;
1493
+ s11 = s11 + s12 | 0;
1494
+ t = s6 ^ s11;
1495
+ s6 = t >>> 12 | t << 20;
1496
+ s1 = s1 + s6 + m11 | 0;
1497
+ t = s12 ^ s1;
1498
+ s12 = t >>> 8 | t << 24;
1499
+ s11 = s11 + s12 | 0;
1500
+ t = s6 ^ s11;
1501
+ s6 = t >>> 7 | t << 25;
1502
+ s2 = s2 + s7 + m12 | 0;
1503
+ t = s13 ^ s2;
1504
+ s13 = t >>> 16 | t << 16;
1505
+ s8 = s8 + s13 | 0;
1506
+ t = s7 ^ s8;
1507
+ s7 = t >>> 12 | t << 20;
1508
+ s2 = s2 + s7 + m13 | 0;
1509
+ t = s13 ^ s2;
1510
+ s13 = t >>> 8 | t << 24;
1511
+ s8 = s8 + s13 | 0;
1512
+ t = s7 ^ s8;
1513
+ s7 = t >>> 7 | t << 25;
1514
+ s3 = s3 + s4 + m14 | 0;
1515
+ t = s14 ^ s3;
1516
+ s14 = t >>> 16 | t << 16;
1517
+ s9 = s9 + s14 | 0;
1518
+ t = s4 ^ s9;
1519
+ s4 = t >>> 12 | t << 20;
1520
+ s3 = s3 + s4 + m15 | 0;
1521
+ t = s14 ^ s3;
1522
+ s14 = t >>> 8 | t << 24;
1523
+ s9 = s9 + s14 | 0;
1524
+ t = s4 ^ s9;
1525
+ s4 = t >>> 7 | t << 25;
1526
+ const p0 = m0, p1 = m1, p4 = m4, p5 = m5, p8 = m8;
1527
+ m0 = m2;
1528
+ m1 = m6;
1529
+ m2 = m3;
1530
+ m3 = m10;
1531
+ m4 = m7;
1532
+ m5 = p0;
1533
+ m6 = p4;
1534
+ m7 = m13;
1535
+ m8 = p1;
1536
+ m10 = m12;
1537
+ m12 = m9;
1538
+ m9 = m11;
1539
+ m11 = p5;
1540
+ m13 = m14;
1541
+ m14 = m15;
1542
+ m15 = p8;
1543
+ }
1544
+ out[oo] = s0 ^ s8;
1545
+ out[oo + 1] = s1 ^ s9;
1546
+ out[oo + 2] = s2 ^ s10;
1547
+ out[oo + 3] = s3 ^ s11;
1548
+ out[oo + 4] = s4 ^ s12;
1549
+ out[oo + 5] = s5 ^ s13;
1550
+ out[oo + 6] = s6 ^ s14;
1551
+ out[oo + 7] = s7 ^ s15;
1552
+ }
1553
+ function words(input) {
1554
+ const whole = input.length & ~3;
1555
+ if (LITTLE_ENDIAN && (input.byteOffset & 3) === 0) return new Uint32Array(input.buffer, input.byteOffset, whole >>> 2);
1556
+ const out = new Uint32Array(whole >>> 2);
1557
+ const view = new DataView(input.buffer, input.byteOffset, input.byteLength);
1558
+ for (let i = 0; i < out.length; i++) out[i] = view.getUint32(i * 4, true);
1559
+ return out;
1560
+ }
1561
+ function blake3(input) {
1562
+ const w = words(input);
1563
+ const iv = Uint32Array.from(IV);
1564
+ const block = new Uint32Array(16);
1565
+ const blockBytes = new Uint8Array(block.buffer);
1566
+ const stack = new Uint32Array(8 * 54);
1567
+ let depth = 0;
1568
+ const parent = new Uint32Array(16);
1569
+ const cv = new Uint32Array(8);
1570
+ const chunks = Math.max(1, Math.ceil(input.length / CHUNK_LEN));
1571
+ for (let chunk = 0; chunk < chunks - 1; chunk++) {
1572
+ cv.set(iv);
1573
+ const start = chunk * (CHUNK_LEN / 4);
1574
+ for (let b = 0; b < 16; b++) {
1575
+ const flags2 = (b === 0 ? CHUNK_START : 0) | (b === 15 ? CHUNK_END : 0);
1576
+ compress(cv, 0, w, start + b * 16, chunk, BLOCK_LEN, flags2, cv, 0);
1577
+ }
1578
+ let total = chunk + 1;
1579
+ while ((total & 1) === 0) {
1580
+ depth--;
1581
+ parent.set(stack.subarray(depth * 8, depth * 8 + 8), 0);
1582
+ parent.set(cv, 8);
1583
+ compress(iv, 0, parent, 0, 0, BLOCK_LEN, PARENT, cv, 0);
1584
+ total >>>= 1;
1585
+ }
1586
+ stack.set(cv, depth * 8);
1587
+ depth++;
1588
+ }
1589
+ const last = chunks - 1;
1590
+ const begin = last * CHUNK_LEN;
1591
+ const length = input.length - begin;
1592
+ const blocks = Math.max(1, Math.ceil(length / BLOCK_LEN));
1593
+ cv.set(iv);
1594
+ for (let b = 0; b < blocks - 1; b++) {
1595
+ compress(cv, 0, w, (begin >>> 2) + b * 16, last, BLOCK_LEN, b === 0 ? CHUNK_START : 0, cv, 0);
1596
+ }
1597
+ const tail = begin + (blocks - 1) * BLOCK_LEN;
1598
+ const tailLength = input.length - tail;
1599
+ block.fill(0);
1600
+ blockBytes.set(input.subarray(tail, input.length));
1601
+ if (!LITTLE_ENDIAN) for (let i = 0; i < 16; i++) block[i] = new DataView(blockBytes.buffer).getUint32(i * 4, true);
1602
+ let flags = CHUNK_END | (blocks === 1 ? CHUNK_START : 0);
1603
+ let outCv = cv;
1604
+ let outBlock = block;
1605
+ let counter = last;
1606
+ let blockLen = tailLength;
1607
+ const out = new Uint32Array(8);
1608
+ while (depth > 0) {
1609
+ compress(outCv, 0, outBlock, 0, counter, blockLen, flags, out, 0);
1610
+ depth--;
1611
+ parent.set(stack.subarray(depth * 8, depth * 8 + 8), 0);
1612
+ parent.set(out, 8);
1613
+ outCv = iv;
1614
+ outBlock = parent;
1615
+ counter = 0;
1616
+ blockLen = BLOCK_LEN;
1617
+ flags = PARENT;
1618
+ }
1619
+ compress(outCv, 0, outBlock, 0, counter, blockLen, flags | ROOT, out, 0);
1620
+ const bytes2 = new Uint8Array(32);
1621
+ const view = new DataView(bytes2.buffer);
1622
+ for (let i = 0; i < 8; i++) view.setUint32(i * 4, out[i], true);
1623
+ return bytes2;
1624
+ }
1625
+ function blake3Hex(input) {
1626
+ return Buffer.from(blake3(input)).toString("hex");
1627
+ }
1628
+
1629
+ // src/modules/plugin-util.ts
1630
+ function escapeHtml(s) {
1631
+ return s.replace(/[&<>"'`]/g, (c) => ENTITIES[c]);
1632
+ }
1633
+ var ENTITIES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" };
1634
+ function debugString(s) {
1635
+ let out = '"';
1636
+ for (const c of s) {
1637
+ if (c === '"') out += '\\"';
1638
+ else if (c === "\\") out += "\\\\";
1639
+ else if (c === "\n") out += "\\n";
1640
+ else if (c === "\r") out += "\\r";
1641
+ else if (c === " ") out += "\\t";
1642
+ else if (c === "\0") out += "\\0";
1643
+ else if (c.charCodeAt(0) < 32 || c === "\x7F") out += `\\u{${c.charCodeAt(0).toString(16)}}`;
1644
+ else out += c;
1645
+ }
1646
+ return `${out}"`;
1647
+ }
1648
+ function isoDay(d) {
1649
+ return `${String(d.getUTCFullYear()).padStart(4, "0")}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")}`;
1650
+ }
1651
+
1652
+ // src/image/color.ts
1653
+ var SRGB = [
1654
+ [0.4358437020317384, 0.22237346998171753, 0.01392884984376424],
1655
+ [0.3853088106132035, 0.7170281521655508, 0.09715675318321043],
1656
+ [0.14305951977573775, 0.060598377591300316, 0.7141027109713133]
1657
+ ];
1658
+ function parse(icc) {
1659
+ if (icc.length < 132) return void 0;
1660
+ const size = icc.readUInt32BE(0);
1661
+ if (size > icc.length || size < 132 || icc.subarray(36, 40).toString("latin1") !== "acsp") return void 0;
1662
+ const count2 = icc.readUInt32BE(128);
1663
+ if (132 + count2 * 12 > size) return void 0;
1664
+ const tags = /* @__PURE__ */ new Map();
1665
+ for (let i = 0; i < count2; i++) {
1666
+ const at = 132 + i * 12;
1667
+ const signature = icc.subarray(at, at + 4).toString("latin1");
1668
+ const offset = icc.readUInt32BE(at + 4);
1669
+ const length = icc.readUInt32BE(at + 8);
1670
+ if (offset + length > size || length < 8) return void 0;
1671
+ const data = icc.subarray(offset, offset + length);
1672
+ tags.set(signature, { type: data.subarray(0, 4).toString("latin1"), data });
1673
+ }
1674
+ return { colorSpace: icc.subarray(16, 20).toString("latin1"), pcs: icc.subarray(20, 24).toString("latin1"), tags };
1675
+ }
1676
+ function xyz(profile, tag) {
1677
+ const found = profile.tags.get(tag);
1678
+ if (!found || found.type !== "XYZ " || found.data.length < 20) return void 0;
1679
+ const s15 = (at) => found.data.readInt32BE(at) / 65536;
1680
+ return [s15(8), s15(12), s15(16)];
1681
+ }
1682
+ function readableCurve(profile, tag) {
1683
+ const found = profile.tags.get(tag);
1684
+ if (!found) return false;
1685
+ if (found.type === "curv") return found.data.length >= 12;
1686
+ if (found.type === "para") return found.data.length >= 12 && found.data.readUInt16BE(8) <= 4;
1687
+ return false;
1688
+ }
1689
+ function colorPlan(icc) {
1690
+ if (!icc) return { kind: "keep" };
1691
+ const profile = parse(icc);
1692
+ if (!profile || profile.colorSpace !== "RGB ") return { kind: "keep" };
1693
+ const colorants = [xyz(profile, "rXYZ"), xyz(profile, "gXYZ"), xyz(profile, "bXYZ")];
1694
+ const hasCurves = ["rTRC", "gTRC", "bTRC"].every((t) => profile.tags.has(t));
1695
+ const matrixShaper = colorants.every((c) => c !== void 0 && (c[0] !== 0 || c[1] !== 0 || c[2] !== 0)) && hasCurves;
1696
+ const close = (a, b) => a.every((v, i) => Math.abs(v - b[i]) < 2e-3);
1697
+ if (matrixShaper && colorants.every((c, i) => close(c, SRGB[i]))) return { kind: "keep" };
1698
+ const lut = ["A2B0", "A2B1", "A2B2"].some((t) => profile.tags.has(t));
1699
+ if (profile.pcs !== "XYZ " && profile.pcs !== "Lab ") return { kind: "unsupported", why: "UnsupportedProfileConnection" };
1700
+ if (lut) return { kind: "convert" };
1701
+ if (!matrixShaper) return { kind: "unsupported", why: "UnsupportedProfileConnection" };
1702
+ if (!["rTRC", "gTRC", "bTRC"].every((t) => readableCurve(profile, t))) return { kind: "unsupported", why: "UnsupportedTrc" };
1703
+ return { kind: "convert" };
1704
+ }
1705
+
1706
+ // src/image/hashes.ts
1707
+ import fs3 from "node:fs";
1708
+ import path3 from "node:path";
1709
+ var CACHE_FILE = ".cache/ssqch/image-hashes.json";
1710
+ function stamp(file) {
1711
+ const stat = fs3.statSync(file, { bigint: true });
1712
+ return { size: Number(stat.size), mtime: stat.mtimeNs.toString() };
1713
+ }
1714
+ var HashCache = class {
1715
+ file;
1716
+ entries = /* @__PURE__ */ new Map();
1717
+ used = /* @__PURE__ */ new Set();
1718
+ dirty = false;
1719
+ /** The cache at `file`, once per process: later builds reuse what's in memory. A missing or unreadable file is an empty cache. */
1720
+ load(file) {
1721
+ this.used.clear();
1722
+ if (this.file === file) return;
1723
+ this.entries = parse2(file) ?? /* @__PURE__ */ new Map();
1724
+ this.file = file;
1725
+ this.dirty = false;
1726
+ }
1727
+ get(src, size, mtime, settings) {
1728
+ const e = this.entries.get(src);
1729
+ if (e && e.size === size && e.mtime === mtime && e.settings === settings) {
1730
+ this.used.add(src);
1731
+ return e.id;
1732
+ }
1733
+ return void 0;
1734
+ }
1735
+ put(src, size, mtime, settings, id) {
1736
+ const e = this.entries.get(src);
1737
+ if (!(e && e.size === size && e.mtime === mtime && e.settings === settings && e.id === id)) {
1738
+ this.entries.set(src, { size, mtime, settings, id });
1739
+ this.dirty = true;
1740
+ }
1741
+ this.used.add(src);
1742
+ }
1743
+ /** Writes the cache if it changed, keeping only the images this build used. Nothing for a build that used no images and has no cache. */
1744
+ save() {
1745
+ const file = this.file;
1746
+ if (file === void 0) return;
1747
+ const before = this.entries.size;
1748
+ for (const key of [...this.entries.keys()]) if (!this.used.has(key)) this.entries.delete(key);
1749
+ if (!this.dirty && this.entries.size === before) return;
1750
+ if (this.entries.size === 0 && !fs3.existsSync(file)) return;
1751
+ fs3.mkdirSync(path3.dirname(file), { recursive: true });
1752
+ const tmp = file.replace(/\.json$/, ".json.tmp");
1753
+ fs3.writeFileSync(tmp, serialize(this.entries));
1754
+ fs3.renameSync(tmp, file);
1755
+ this.dirty = false;
1756
+ }
1757
+ };
1758
+ function serialize(entries) {
1759
+ const keys = [...entries.keys()].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
1760
+ const files = {};
1761
+ for (const key of keys) {
1762
+ const e = entries.get(key);
1763
+ files[key] = { size: e.size, mtime: e.mtime, settings: e.settings, id: e.id };
1764
+ }
1765
+ return JSON.stringify({ version: 1, files }, null, 2) + "\n";
1766
+ }
1767
+ function parse2(file) {
1768
+ let doc;
1769
+ try {
1770
+ doc = JSON.parse(fs3.readFileSync(file, "utf8"));
1771
+ } catch {
1772
+ return void 0;
1773
+ }
1774
+ if (doc?.version !== 1 || typeof doc.files !== "object" || doc.files === null) return void 0;
1775
+ const out = /* @__PURE__ */ new Map();
1776
+ for (const [key, v] of Object.entries(doc.files)) {
1777
+ if (Number.isInteger(v?.size) && v.size >= 0 && typeof v.mtime === "string" && /^\d+$/.test(v.mtime) && typeof v.settings === "string" && typeof v.id === "string") {
1778
+ out.set(key, { size: v.size, mtime: v.mtime, settings: v.settings, id: v.id });
1779
+ }
1780
+ }
1781
+ return out;
1782
+ }
1783
+
1784
+ // src/image/quality.ts
1785
+ var WEBP = [[0, 0], [100, 100]];
1786
+ var JPEG = [[50, 66], [60, 72], [70, 80], [80, 89], [90, 97], [92, 100]];
1787
+ var AVIF = [[30, 28], [40, 34], [50, 41], [60, 48], [70, 55], [80, 61], [90, 86], [95, 96], [98, 100]];
1788
+ var EFFORT = [[1, 5], [4, 3], [8, 2], [10, 0]];
1789
+ function lookup(table, x) {
1790
+ let i = 1;
1791
+ while (i < table.length - 1 && x > table[i][0]) i++;
1792
+ const [[x0, y0], [x1, y1]] = [table[i - 1], table[i]];
1793
+ return y0 + (x - x0) * (y1 - y0) / (x1 - x0);
1794
+ }
1795
+ var fromLegacy = (table, x) => Math.min(100, Math.max(1, Math.round(lookup(table, x))));
1796
+ var effortFromSpeed = (speed) => Math.min(9, Math.max(0, Math.round(lookup(EFFORT, speed))));
1797
+ var DEFAULTS = { webpQuality: fromLegacy(WEBP, 75), avifQuality: fromLegacy(AVIF, 50), avifEffort: effortFromSpeed(8), jpegQuality: fromLegacy(JPEG, 80) };
1798
+ function legacyOf(value, low, high, convert, exact, round) {
1799
+ let best;
1800
+ for (let v = low; v <= high; v++) {
1801
+ if (convert(v) !== value) continue;
1802
+ const rank = round ? v % 10 === 0 ? 0 : v % 5 === 0 ? 1 : 2 : 0;
1803
+ const off = Math.abs(exact(v) - value);
1804
+ if (!best || rank < best.rank || rank === best.rank && off < best.off) best = { v, rank, off };
1805
+ }
1806
+ return best?.v;
1807
+ }
1808
+ function legacySettings(o) {
1809
+ const name = (n, value) => n === void 0 ? `s${value}` : String(n);
1810
+ const quality = (table, value) => name(legacyOf(value, 1, 100, (x) => fromLegacy(table, x), (x) => lookup(table, x), true), value);
1811
+ const speed = name(legacyOf(o.avifEffort, 1, 10, effortFromSpeed, (x) => lookup(EFFORT, x), false), o.avifEffort);
1812
+ return `${quality(WEBP, o.webpQuality)}|${quality(AVIF, o.avifQuality)}|${speed}|${quality(JPEG, o.jpegQuality)}`;
1813
+ }
1814
+ function encodeSettings(o) {
1815
+ return {
1816
+ jpeg: { quality: o.jpegQuality, mozjpeg: true },
1817
+ png: { adaptiveFiltering: false, compressionLevel: 6 },
1818
+ webp: { quality: o.webpQuality },
1819
+ avif: { quality: o.avifQuality, effort: o.avifEffort }
1820
+ };
1821
+ }
1822
+
1823
+ // src/image/processor.ts
1824
+ var FORMATS = ["avif", "webp", "jpeg", "png", "gif", "svg", "auto"];
1825
+ function parseFormat(name) {
1826
+ if (name === "jpg") return "jpeg";
1827
+ return FORMATS.includes(name) ? name : void 0;
1828
+ }
1829
+ function mime(format) {
1830
+ return format === "svg" ? "image/svg+xml" : format === "avif" || format === "webp" || format === "jpeg" || format === "png" ? `image/${format}` : "image/gif";
1831
+ }
1832
+ var debugName = (f) => f[0].toUpperCase() + f.slice(1);
1833
+ function fromPath(file) {
1834
+ const ext = path4.extname(file).slice(1).toLowerCase();
1835
+ if (ext === "jpg" || ext === "jpeg") return "jpeg";
1836
+ return ext === "png" || ext === "gif" || ext === "svg" || ext === "webp" ? ext : void 0;
1837
+ }
1838
+ function defaultImageOptions() {
1839
+ return {
1840
+ formats: ["webp", "auto"],
1841
+ widths: [300, 600, 900, 1200, 1500],
1842
+ defaultAttributes: [["loading", "lazy"], ["decoding", "async"], ["sizes", "auto"]],
1843
+ outputSubdir: "img",
1844
+ cacheDir: ".cache/ssqch/img",
1845
+ urlPath: "/img/",
1846
+ ...DEFAULTS,
1847
+ minimumThreshold: 1.25,
1848
+ prune: false,
1849
+ hashCache: true,
1850
+ linkedImages: true
1851
+ };
1852
+ }
1853
+ var fallbackOf = (meta) => [...meta.formats.values()].at(-1) ?? [];
1854
+ var failOn = (source) => source === "jpeg" ? "none" : "truncated";
1855
+ function libvips(e) {
1856
+ const lines = (e instanceof Error ? e.message : String(e)).split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
1857
+ if (!lines.length) return "unknown error";
1858
+ return lines[0].endsWith(":") && lines.length > 1 ? `${lines[0]} ${lines[1]}` : lines[0];
1859
+ }
1860
+ var PIXEL_LIMIT = 16383 * 16383;
1861
+ var LARGEST = { avif: 16384, webp: 16383, jpeg: 65535 };
1862
+ var ORIENT = {
1863
+ 2: (i) => i.flop(),
1864
+ 3: (i) => i.rotate(180),
1865
+ 4: (i) => i.flip(),
1866
+ 5: (i) => i.flip().rotate(90),
1867
+ 6: (i) => i.rotate(90),
1868
+ 7: (i) => i.flip().rotate(270),
1869
+ 8: (i) => i.rotate(270)
1870
+ };
1871
+ var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1872
+ function validWidths(original2, requested, minimumThreshold) {
1873
+ const sorted = requested.map((w) => w === 0 ? original2 : w).sort((a, b) => a - b);
1874
+ let lastBigEnough = true;
1875
+ const out = [];
1876
+ for (const w of sorted) {
1877
+ if (w > original2) {
1878
+ if (lastBigEnough) out.push(original2);
1879
+ continue;
1880
+ }
1881
+ lastBigEnough = original2 > Math.floor(w * minimumThreshold);
1882
+ out.push(w);
1883
+ }
1884
+ const deduped = out.filter((w, i) => i === 0 || w !== out[i - 1]);
1885
+ return deduped.length ? deduped : [original2];
1886
+ }
1887
+ function srcsetAttr(entries) {
1888
+ return entries.length === 1 ? entries[0].url : entries.map((e) => e.srcset).join(", ");
1889
+ }
1890
+ function withoutAuto(sizes) {
1891
+ return sizes.split(",").map((s) => s.trim()).filter((s) => s.toLowerCase() !== "auto").join(", ");
1892
+ }
1893
+ function samePath(p) {
1894
+ const parts = p.split(path4.sep === "\\" ? /[\\/]/ : "/");
1895
+ return parts.filter((part, i) => i === 0 || part !== "" && part !== ".").join("/");
1896
+ }
1897
+ function percentDecode(s) {
1898
+ if (!s.includes("%")) return s;
1899
+ const bytes2 = Buffer.from(s, "utf8");
1900
+ const out = [];
1901
+ for (let i = 0; i < bytes2.length; i++) {
1902
+ if (bytes2[i] === 37 && i + 2 < bytes2.length) {
1903
+ const hex = String.fromCharCode(bytes2[i + 1], bytes2[i + 2]);
1904
+ if (/^[0-9a-fA-F]{2}$/.test(hex)) {
1905
+ out.push(parseInt(hex, 16));
1906
+ i += 2;
1907
+ continue;
1908
+ }
1909
+ }
1910
+ out.push(bytes2[i]);
1911
+ }
1912
+ return Buffer.from(out).toString("utf8");
1913
+ }
1914
+ function joinPath(base, rel) {
1915
+ if (path4.isAbsolute(rel)) return rel;
1916
+ return base.endsWith(path4.sep) || base.endsWith("/") ? base + rel : base + path4.sep + rel;
1917
+ }
1918
+ function joinUrlPath(page, rel) {
1919
+ const clean = page.split(/[?#]/)[0];
1920
+ const dir = clean.slice(0, clean.lastIndexOf("/") + 1);
1921
+ const parts = [];
1922
+ for (const part of [...dir.split("/"), ...rel.split("/")]) {
1923
+ if (part === "" || part === ".") continue;
1924
+ if (part === "..") parts.pop();
1925
+ else parts.push(part);
1926
+ }
1927
+ return `/${parts.join("/")}`;
1928
+ }
1929
+ function svgDimensions(file) {
1930
+ let text;
1931
+ try {
1932
+ text = fs4.readFileSync(file, "utf8");
1933
+ } catch {
1934
+ return void 0;
1935
+ }
1936
+ const start = text.indexOf("<svg");
1937
+ if (start === -1) return void 0;
1938
+ const end = text.indexOf(">", start);
1939
+ if (end === -1) return void 0;
1940
+ const tag = text.slice(start, end);
1941
+ const attr = (name) => {
1942
+ const i = tag.indexOf(` ${name}=`);
1943
+ if (i === -1) return void 0;
1944
+ const quote = tag[i + name.length + 2];
1945
+ if (quote === void 0) return void 0;
1946
+ const rest = tag.slice(i + name.length + 3);
1947
+ const close = rest.indexOf(quote);
1948
+ return close === -1 ? void 0 : rest.slice(0, close);
1949
+ };
1950
+ const num = (v) => {
1951
+ if (v === void 0) return void 0;
1952
+ const n = rustFloat(v.replace(/(px)+$/, "").trim());
1953
+ return n === void 0 ? void 0 : n;
1954
+ };
1955
+ const [w, h] = [num(attr("width")), num(attr("height"))];
1956
+ if (w !== void 0 && h !== void 0) return [toU32(w), toU32(h)];
1957
+ const box = attr("viewBox");
1958
+ if (box === void 0) return void 0;
1959
+ const vb = box.split(/[ ,]/).map(rustFloat).filter((n) => n !== void 0);
1960
+ return vb.length === 4 ? [toU32(vb[2]), toU32(vb[3])] : void 0;
1961
+ }
1962
+ function rustFloat(s) {
1963
+ if (/^[+-]?(\d+\.?\d*([eE][+-]?\d+)?|\.\d+([eE][+-]?\d+)?)$/.test(s)) return Number(s);
1964
+ if (/^[+-]?(inf|infinity)$/i.test(s)) return s.startsWith("-") ? -Infinity : Infinity;
1965
+ if (/^[+-]?nan$/i.test(s)) return NaN;
1966
+ return void 0;
1967
+ }
1968
+ var toU32 = (n) => Number.isNaN(n) ? 0 : Math.min(4294967295, Math.max(0, Math.trunc(n)));
1969
+ function rustDuration(ms) {
1970
+ if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
1971
+ if (ms >= 1) return `${ms.toFixed(2)}ms`;
1972
+ if (ms >= 1e-3) return `${(ms * 1e3).toFixed(2)}\xB5s`;
1973
+ return `${(ms * 1e6).toFixed(2)}ns`;
1974
+ }
1975
+ function pagePathOf(pageUrl) {
1976
+ const scheme = pageUrl.indexOf("://");
1977
+ if (scheme === -1) return pageUrl;
1978
+ const rest = pageUrl.slice(scheme + 3);
1979
+ const slash = rest.indexOf("/");
1980
+ return slash === -1 ? "/" : rest.slice(slash);
1981
+ }
1982
+ var statOf = (p) => fs4.statSync(p, { throwIfNoEntry: false, bigint: true });
1983
+ function publish(cache, out, a = statOf(cache)) {
1984
+ const b = statOf(out);
1985
+ if (a && b && a.size === b.size && b.mtimeNs >= a.mtimeNs) return Number(b.size);
1986
+ fs4.rmSync(out, { force: true });
1987
+ linkOrCopy(cache, out);
1988
+ return Number(a?.size ?? statOf(out)?.size ?? 0);
1989
+ }
1990
+ function linkOrCopy(from, to) {
1991
+ try {
1992
+ fs4.linkSync(from, to);
1993
+ } catch {
1994
+ const [there, source] = [statOf(to), statOf(from)];
1995
+ if (there && source && there.size === source.size) return;
1996
+ fs4.copyFileSync(from, to);
1997
+ }
1998
+ }
1999
+ var READY = Promise.resolve(void 0);
2000
+ var isFile = (p) => fs4.statSync(p, { throwIfNoEntry: false })?.isFile() ?? false;
2001
+ var isEntryFile = (entry, p) => entry.isFile() || entry.isSymbolicLink() && isFile(p);
2002
+ var mtimeOf = (p) => fs4.statSync(p, { throwIfNoEntry: false, bigint: true })?.mtimeNs;
2003
+ var sharpModule;
2004
+ function loadSharp() {
2005
+ if (!sharpModule) {
2006
+ sharpModule = __require("sharp");
2007
+ sharpModule.concurrency(1);
2008
+ sharpModule.cache(false);
2009
+ }
2010
+ return sharpModule;
2011
+ }
2012
+ var ENCODES = os2.availableParallelism();
2013
+ var Queue = class {
2014
+ running = 0;
2015
+ waiting = [];
2016
+ limit;
2017
+ constructor(limit) {
2018
+ this.limit = limit;
2019
+ }
2020
+ /** `task`, once a place is free; `first` goes ahead of everything waiting (the files of a source already decoded, so its pixels are let go of soon). */
2021
+ async run(task, first = false) {
2022
+ if (this.running >= this.limit) await new Promise((resolve) => first ? this.waiting.unshift(resolve) : this.waiting.push(resolve));
2023
+ this.running++;
2024
+ try {
2025
+ return await task();
2026
+ } finally {
2027
+ this.running--;
2028
+ this.waiting.shift()?.();
2029
+ }
2030
+ }
2031
+ };
2032
+ var temporary = 0;
2033
+ var ImageProcessor = class {
2034
+ options;
2035
+ ctx;
2036
+ memo = /* @__PURE__ */ new Map();
2037
+ /** Each file this build makes or reuses, by where it's kept: a file two requests share is made once. */
2038
+ files = /* @__PURE__ */ new Map();
2039
+ /** What each source's first bytes said this build, by its path as given. */
2040
+ headers = /* @__PURE__ */ new Map();
2041
+ /** Which paths are files, as the transform asks, once a build each. */
2042
+ found = /* @__PURE__ */ new Map();
2043
+ /** The folders made this build. */
2044
+ made = /* @__PURE__ */ new Set();
2045
+ /** The size of each file in the output, as it was made or found, for the summary. */
2046
+ sizes = /* @__PURE__ */ new Map();
2047
+ /** Everything this build is still waiting for, settled or not. */
2048
+ pending = [];
2049
+ /** Each source with files still to make that something points at, by its path: one that fails fails the build. */
2050
+ watched = /* @__PURE__ */ new Map();
2051
+ generated = 0;
2052
+ pruned = 0;
2053
+ converted = /* @__PURE__ */ new Set();
2054
+ used = /* @__PURE__ */ new Set();
2055
+ sources = /* @__PURE__ */ new Set();
2056
+ hashes = new HashCache();
2057
+ quiet = false;
2058
+ timings = [];
2059
+ warned = /* @__PURE__ */ new Set();
2060
+ queue = new Queue(ENCODES);
2061
+ settings;
2062
+ /** The settings as image names hold them (`legacySettings`). */
2063
+ named;
2064
+ constructor(options) {
2065
+ this.options = options;
2066
+ this.settings = encodeSettings(options);
2067
+ this.named = legacySettings(options);
2068
+ }
2069
+ /** The project root, once the build has started. */
2070
+ root() {
2071
+ return this.context().root;
2072
+ }
2073
+ context() {
2074
+ if (!this.ctx) throw new BuildError("the image plugin is used before the build started");
2075
+ return this.ctx;
2076
+ }
2077
+ warnOnce(message) {
2078
+ if (this.warned.has(message)) return;
2079
+ this.warned.add(message);
2080
+ warn(warning("images", message));
2081
+ }
2082
+ display(file) {
2083
+ return displayPath(this.context().root, file);
2084
+ }
2085
+ /** Before each build: what the last one did is forgotten (sources may have changed while serving). */
2086
+ startBuild(config) {
2087
+ const root = config.root;
2088
+ const input = path4.resolve(root, config.input);
2089
+ this.ctx = { root, input, output: path4.resolve(root, config.output), verbose: config.verbose };
2090
+ this.memo.clear();
2091
+ this.files.clear();
2092
+ this.headers.clear();
2093
+ this.found.clear();
2094
+ this.made.clear();
2095
+ this.sizes.clear();
2096
+ this.pending = [];
2097
+ this.watched.clear();
2098
+ this.used.clear();
2099
+ this.sources.clear();
2100
+ this.converted.clear();
2101
+ this.timings = [];
2102
+ if (this.options.hashCache) this.hashes.load(path4.join(root, CACHE_FILE));
2103
+ this.generated = 0;
2104
+ this.pruned = 0;
2105
+ }
2106
+ /**
2107
+ * After the pages: every encode they asked for, done. A file that couldn't be made, after a
2108
+ * page, a feed or `imageUrl()` pointed at it, fails the build here (decided 2026-11-18):
2109
+ * they're written already, and a site shouldn't ship markup for a file that isn't there. The
2110
+ * error names the source and what points at it, and in `--format json` each source is an
2111
+ * `images` error with the source as its `file` and the first page's URL as its `url`.
2112
+ */
2113
+ async settle() {
2114
+ while (this.pending.length) {
2115
+ const waiting2 = this.pending;
2116
+ this.pending = [];
2117
+ await Promise.all(waiting2);
2118
+ }
2119
+ const root = this.context().root;
2120
+ const failures = [...this.watched.values()].filter((w) => w.error !== void 0).map((w) => ({ ...w, file: shown(root, w.src) })).sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0);
2121
+ if (!failures.length) return;
2122
+ const said = (f) => {
2123
+ const [first, ...others] = f.by.values();
2124
+ return `images: ${f.error.message}. ${first.name}${others.length ? ` and ${count(others.length)} more` : ""} already ${others.length ? "point" : "points"} at it, so the build stops here rather than publish tracks that lead nowhere`;
2125
+ };
2126
+ const items = failures.map((f) => error("images", said(f), { file: f.file, url: [...f.by.values()].find((b) => b.url !== void 0)?.url }));
2127
+ const more = failures.length > 1 ? ` (and ${count(failures.length - 1)} more ${failures.length === 2 ? "image" : "images"} that failed)` : "";
2128
+ throw new BuildError(`${said(failures[0])}${more}`, items);
2129
+ }
2130
+ /** After the build: `prune`, the hash cache, and with `--verbose` the slowest encodes. */
2131
+ finishBuild() {
2132
+ const ctx = this.context();
2133
+ this.pruned = this.options.prune ? this.prune(path4.join(ctx.output, this.options.outputSubdir)) : 0;
2134
+ if (this.options.hashCache) {
2135
+ try {
2136
+ this.hashes.save();
2137
+ } catch (e) {
2138
+ this.warnOnce(`couldn't write ${path4.join(ctx.root, CACHE_FILE)}: ${e.message}`);
2139
+ }
2140
+ }
2141
+ if (ctx.verbose && !this.quiet && this.timings.length) {
2142
+ const slowest = [...this.timings].sort((a, b) => b[2] - a[2]).slice(0, 10);
2143
+ progress("Slowest images to encode:");
2144
+ for (const [src, files, ms] of slowest) progress(` ${rustDuration(ms).padStart(8)} ${this.display(src)} (${files} files)`);
2145
+ }
2146
+ }
2147
+ /** An `<img src>` as a file: from the input folder for a path starting with `/`, otherwise from the page's own folder. */
2148
+ resolveSrc(src, pageInput) {
2149
+ if (src === "" || src.includes("://") || src.startsWith("//") || src.startsWith("data:")) return void 0;
2150
+ const ctx = this.context();
2151
+ const clean = percentDecode(src.split(/[?#]/)[0]);
2152
+ return clean.startsWith("/") ? joinPath(ctx.input, clean.slice(1)) : joinPath(path4.dirname(pageInput), clean);
2153
+ }
2154
+ /** A site path as a file in the input folder: `/content/logo.png` (or `content/logo.png`) is `<input>/content/logo.png`. `undefined` for a remote or `data:` URL. */
2155
+ resolveSiteSrc(src) {
2156
+ if (src.includes("://") || src.startsWith("//") || src.startsWith("data:")) return void 0;
2157
+ const clean = percentDecode(src.split(/[?#]/)[0]);
2158
+ return joinPath(this.context().input, clean.replace(/^\/+/, ""));
2159
+ }
2160
+ /** What `imageUrl()` returns: one generated copy of the image at site path `src`, `width` pixels wide at most (0 is the original's), in `format`. A remote URL is only `{ url }`. */
2161
+ imageUrl(src, width, format) {
2162
+ if (src.trim() === "") throw new BuildError("imageUrl(): no image given");
2163
+ const file = this.resolveSiteSrc(src);
2164
+ if (file === void 0) return { url: src };
2165
+ if (!this.isSource(file)) throw new BuildError(`imageUrl(): image not found: ${src} (looked for ${this.display(file)})`);
2166
+ const meta = this.generate(file, [width], [format]);
2167
+ this.watch(meta, file, { name: "imageUrl()" });
2168
+ const resolved = format === "auto" ? meta.auto : format;
2169
+ const entries = (resolved !== void 0 ? meta.formats.get(resolved) : void 0) ?? [...meta.formats.values()][0];
2170
+ const e = widest(entries);
2171
+ if (!e) throw new BuildError(`imageUrl(): no image generated for ${src}`);
2172
+ return { url: e.url, width: e.width, height: e.height, type: e.sourceType, format: e.format };
2173
+ }
2174
+ /** The URL a link to `src` should point to: one copy in the source's own format, at its width capped at the largest of `widths`. GIFs and SVGs are their copied files. */
2175
+ linkTarget(src, by) {
2176
+ const cap = this.options.widths.length ? Math.max(...this.options.widths) : 0;
2177
+ const meta = this.generate(src, [cap], ["auto"]);
2178
+ this.watch(meta, src, by);
2179
+ const entry = widest([...meta.formats.values()].flat());
2180
+ if (!entry) throw new Error(`no image generated for ${src}`);
2181
+ return entry.url;
2182
+ }
2183
+ /** Waits, before the build ends, for files of `src` that `by` already points at. One that can't be made fails the build (see `settle`). */
2184
+ watch(meta, src, by) {
2185
+ if (meta.ready === READY) return;
2186
+ const key = samePath(src);
2187
+ let watched = this.watched.get(key);
2188
+ if (!watched) this.watched.set(key, watched = { src, by: /* @__PURE__ */ new Map() });
2189
+ if (!watched.by.has(by.name)) watched.by.set(by.name, by);
2190
+ const noted = watched;
2191
+ this.pending.push(meta.ready.then((e) => {
2192
+ if (e && (noted.error === void 0 || e.message < noted.error.message)) noted.error = e;
2193
+ }));
2194
+ }
2195
+ /** Makes (or reuses) `src` at `widths` in `formats`. */
2196
+ generate(src, widths, formats) {
2197
+ return this.generateNamed(src, widths, formats, void 0);
2198
+ }
2199
+ /**
2200
+ * `generate`, with file names of the site's own instead of ones from a hash: `name` is the
2201
+ * output's URL path without the width and extension (`/assets/sponsors/acme` writes
2202
+ * `/assets/sponsors/acme-200.webp`), inside the image folder without a leading `/`. A file is
2203
+ * encoded again when its source is newer than it.
2204
+ */
2205
+ generateNamed(src, widths, formats, name) {
2206
+ if (name !== void 0) {
2207
+ const last = name.split("/").at(-1) ?? "";
2208
+ if (last === "" || name.split("/").includes("..") || /[\\?#]/.test(name)) {
2209
+ throw new BuildError(`image name ${debugString(name)} must be a URL path without the width and extension, like "/assets/sponsors/acme"`);
2210
+ }
2211
+ }
2212
+ const key = JSON.stringify([samePath(src), widths, formats, name ?? null]);
2213
+ let found = this.memo.get(key);
2214
+ if (found === void 0) {
2215
+ try {
2216
+ found = this.generateUncached(src, widths, formats, name);
2217
+ for (const e of [...found.formats.values()].flat()) this.used.add(e.path);
2218
+ this.sources.add(samePath(src));
2219
+ } catch (e) {
2220
+ found = e instanceof Error ? e : new Error(String(e));
2221
+ } finally {
2222
+ const source = this.headers.get(src);
2223
+ if (source) source.contents = void 0;
2224
+ }
2225
+ this.memo.set(key, found);
2226
+ }
2227
+ if (found instanceof Error) throw found;
2228
+ return found;
2229
+ }
2230
+ /**
2231
+ * A source's format (the real one, from its contents: a `.png` may hold a JPEG; an SVG by its
2232
+ * name), its header and its id, read once a build however many requests name it.
2233
+ */
2234
+ header(src) {
2235
+ let found = this.headers.get(src);
2236
+ if (!found) {
2237
+ const named = fromPath(src);
2238
+ if (named === "svg") found = { format: "svg" };
2239
+ else {
2240
+ let probed;
2241
+ try {
2242
+ probed = probeFile(src, named);
2243
+ } catch (e) {
2244
+ throw new Error(`reading ${src}: ${e.message}`);
2245
+ }
2246
+ if (!probed) throw new Error(`unsupported image type: ${src}`);
2247
+ found = { format: probed.format, probe: probed };
2248
+ }
2249
+ this.headers.set(src, found);
2250
+ }
2251
+ return found;
2252
+ }
2253
+ /** Makes a folder, once a build. */
2254
+ makeDir(dir) {
2255
+ if (this.made.has(dir)) return;
2256
+ fs4.mkdirSync(dir, { recursive: true });
2257
+ this.made.add(dir);
2258
+ }
2259
+ /** Whether `file` is a file, asked once a build. */
2260
+ isSource(file) {
2261
+ let found = this.found.get(file);
2262
+ if (found === void 0) this.found.set(file, found = isFile(file));
2263
+ return found;
2264
+ }
2265
+ generateUncached(src, widths, formats, name) {
2266
+ const ctx = this.context();
2267
+ const source = this.header(src);
2268
+ const srcFormat = source.format;
2269
+ const readHeader = () => source.probe;
2270
+ let outDir;
2271
+ let urlPath;
2272
+ let id;
2273
+ if (name === void 0) {
2274
+ outDir = path4.join(ctx.output, this.options.outputSubdir);
2275
+ urlPath = this.options.urlPath;
2276
+ id = source.id ??= this.hashId(src, srcFormat === "svg" || srcFormat === "gif" ? void 0 : readHeader, (contents) => {
2277
+ source.contents = contents;
2278
+ });
2279
+ } else {
2280
+ const rel = name.replace(/^\//, "");
2281
+ const slash = rel.lastIndexOf("/");
2282
+ const [dir, stem] = slash === -1 ? ["", rel] : [`${rel.slice(0, slash)}/`, rel.slice(slash + 1)];
2283
+ if (name.startsWith("/")) [outDir, urlPath] = [path4.join(ctx.output, dir), `/${dir}`];
2284
+ else [outDir, urlPath] = [path4.join(ctx.output, this.options.outputSubdir, dir), `${this.options.urlPath}${dir}`];
2285
+ id = stem;
2286
+ }
2287
+ this.makeDir(outDir);
2288
+ let cacheDir2;
2289
+ if (this.options.cacheDir !== null) {
2290
+ const base = path4.join(ctx.root, this.options.cacheDir);
2291
+ cacheDir2 = name === void 0 ? base : path4.join(base, "named", path4.relative(ctx.output, outDir));
2292
+ try {
2293
+ this.makeDir(cacheDir2);
2294
+ } catch (e) {
2295
+ throw new Error(`creating the image cache ${cacheDir2}: ${e.message}`);
2296
+ }
2297
+ }
2298
+ const sourceTime = name === void 0 ? void 0 : mtimeOf(src);
2299
+ const entry = (format, width, height, file) => ({
2300
+ format,
2301
+ width,
2302
+ height,
2303
+ url: `${urlPath}${file}`,
2304
+ path: path4.join(outDir, file),
2305
+ sourceType: mime(format),
2306
+ srcset: `${urlPath}${file} ${width}w`
2307
+ });
2308
+ const copyGif = srcFormat === "gif" && formats.every((f) => f === "auto" || f === "gif" || f === "webp" || f === "avif");
2309
+ if (srcFormat === "svg" || copyGif) {
2310
+ const [w, h] = srcFormat === "gif" ? [readHeader().width, readHeader().height] : svgDimensions(src) ?? [0, 0];
2311
+ const e = entry(srcFormat, w, h, w > 0 ? `${id}-${w}.${srcFormat}` : `${id}.${srcFormat}`);
2312
+ const t = mtimeOf(e.path);
2313
+ if (!(t !== void 0 && (sourceTime === void 0 || t >= sourceTime)) && !this.files.has(e.path)) {
2314
+ fs4.copyFileSync(src, e.path);
2315
+ this.generated++;
2316
+ }
2317
+ this.files.set(e.path, "reused");
2318
+ return { formats: /* @__PURE__ */ new Map([[srcFormat, [e]]]), auto: formats.includes("auto") ? srcFormat : void 0, ready: READY };
2319
+ }
2320
+ const probed = readHeader();
2321
+ const [w0, h0] = oriented(probed);
2322
+ const targets = validWidths(w0, widths, this.options.minimumThreshold);
2323
+ const meta = { formats: /* @__PURE__ */ new Map(), auto: formats.includes("auto") ? srcFormat : void 0, ready: READY };
2324
+ const plan = colorPlan(probed.icc);
2325
+ const started = {};
2326
+ const fresh = (st) => st !== void 0 && (sourceTime === void 0 || st.mtimeNs >= sourceTime);
2327
+ const steps = [];
2328
+ for (const asked of formats) {
2329
+ const f = asked === "auto" ? srcFormat : asked;
2330
+ if (meta.formats.has(f)) continue;
2331
+ const entries = [];
2332
+ for (const w of targets) {
2333
+ const h = Math.max(1, Math.floor(h0 * w / w0));
2334
+ const e = entry(f, w, h, `${id}-${w}.${f}`);
2335
+ const file = cacheDir2 === void 0 ? e.path : path4.join(cacheDir2, path4.basename(e.path));
2336
+ const step = { e, file, earlier: this.files.get(file) };
2337
+ if (step.earlier === void 0) {
2338
+ const inCache = statOf(file);
2339
+ const inOutput = file !== e.path && !fresh(inCache) ? statOf(e.path) : void 0;
2340
+ if (fresh(inCache)) [step.found, step.stat] = ["cache", inCache];
2341
+ else if (fresh(inOutput)) [step.found, step.stat] = ["output", inOutput];
2342
+ }
2343
+ steps.push(step);
2344
+ entries.push(e);
2345
+ }
2346
+ meta.formats.set(f, entries);
2347
+ }
2348
+ const encodes = steps.filter((s) => s.earlier === void 0 && s.found === void 0);
2349
+ if (encodes.length) {
2350
+ this.check(src, source, probed);
2351
+ for (const { e } of encodes) {
2352
+ const largest = LARGEST[e.format];
2353
+ if (largest !== void 0 && (e.width > largest || e.height > largest)) throw new Error(`encoding ${this.display(e.path)} from ${src}: ${e.width}x${e.height} is larger than ${e.format.toUpperCase()} allows (${largest} pixels a side)`);
2354
+ }
2355
+ }
2356
+ for (const s of steps) {
2357
+ if (s.found === void 0) continue;
2358
+ const cached = s.file !== s.e.path;
2359
+ if (s.found === "cache") {
2360
+ if (cached) {
2361
+ try {
2362
+ this.sizes.set(s.e.path, publish(s.file, s.e.path, s.stat));
2363
+ } catch (e) {
2364
+ throw new Error(`copying ${s.e.path} into the output: ${e.message}`);
2365
+ }
2366
+ } else this.sizes.set(s.e.path, Number(s.stat.size));
2367
+ } else {
2368
+ try {
2369
+ linkOrCopy(s.e.path, s.file);
2370
+ } catch (e) {
2371
+ throw new Error(`copying ${s.e.path} into the image cache: ${e.message}`);
2372
+ }
2373
+ this.sizes.set(s.e.path, Number(s.stat.size));
2374
+ }
2375
+ this.files.set(s.file, "reused");
2376
+ }
2377
+ const jobs = encodes.map(({ e, file }) => ({ src, source: probed.format, probe: probed, format: e.format, width: e.width, height: e.height, file, orientation: probed.orientation, out: e.path, sourceTime, plan, started }));
2378
+ const made = this.encodeAll(jobs);
2379
+ jobs.forEach((job, i) => this.files.set(job.file, made[i]));
2380
+ const theirs = steps.flatMap((s) => s.earlier !== void 0 && s.earlier !== "reused" ? [s.earlier] : []);
2381
+ if (!made.length && !theirs.length) return meta;
2382
+ meta.ready = Promise.all([Promise.all(made), ...theirs]).then(
2383
+ ([done]) => {
2384
+ const encoded = done.filter((m) => m === "encoded").length;
2385
+ if (encoded) {
2386
+ if (plan.kind === "convert") this.converted.add(samePath(src));
2387
+ this.encoded(src, encoded, meta, performance.now() - (started.at ?? performance.now()));
2388
+ }
2389
+ return void 0;
2390
+ },
2391
+ (e) => e
2392
+ );
2393
+ return meta;
2394
+ }
2395
+ /**
2396
+ * Whether `src` can be decoded, as 0.7's decoders would have found (see `undecodable`), read
2397
+ * once a build. Throws 0.7's warning for one that can't: `decoding <file>: <why>`.
2398
+ */
2399
+ check(src, source, probed) {
2400
+ if (source.damage === void 0) {
2401
+ if (probed.width * probed.height > PIXEL_LIMIT) source.damage = `${probed.width}x${probed.height} is more pixels than ssqch decodes (${count(PIXEL_LIMIT)})`;
2402
+ else if (probed.format === "jpeg") source.damage = null;
2403
+ else {
2404
+ let contents = source.contents;
2405
+ if (!contents) {
2406
+ try {
2407
+ contents = fs4.readFileSync(src);
2408
+ } catch (e) {
2409
+ throw new Error(`reading ${src}: ${e.message}`);
2410
+ }
2411
+ }
2412
+ source.damage = undecodable(contents, probed.format) ?? null;
2413
+ }
2414
+ }
2415
+ if (source.damage !== null) throw new Error(`decoding ${src}: ${source.damage}`);
2416
+ }
2417
+ /**
2418
+ * A request's files to encode, each made into the cache and linked into the output (or made
2419
+ * there without a cache). A PNG's are made from its pixels decoded once, since sharp can't
2420
+ * shrink a PNG while it decodes it the way it does a JPEG or a WebP; a JPEG's and a WebP's are
2421
+ * each made from the file, which is quicker for them.
2422
+ */
2423
+ encodeAll(jobs) {
2424
+ if (!jobs.length) return [];
2425
+ const shared = jobs.filter((j) => j.source === "png" && !(j.format === "png" && j.probe.sixteen));
2426
+ let pixels;
2427
+ if (shared.length > 1) {
2428
+ const first = shared[0];
2429
+ pixels = this.queue.run(() => {
2430
+ first.started.at ??= performance.now();
2431
+ this.notePlan(first.src, first.plan);
2432
+ return this.decode(first);
2433
+ });
2434
+ pixels.catch(() => {
2435
+ });
2436
+ }
2437
+ return jobs.map((job) => {
2438
+ const done = pixels && shared.includes(job) ? pixels.then((p) => this.queue.run(() => this.encodeFrom(job, p), true)) : this.queue.run(() => {
2439
+ job.started.at ??= performance.now();
2440
+ this.notePlan(job.src, job.plan);
2441
+ return this.encodeFrom(job);
2442
+ });
2443
+ return done.then(() => {
2444
+ this.generated++;
2445
+ if (job.file !== job.out) {
2446
+ try {
2447
+ this.sizes.set(job.out, publish(job.file, job.out));
2448
+ } catch (e) {
2449
+ throw new Error(`copying ${job.out} into the output: ${e.message}`);
2450
+ }
2451
+ } else this.sizes.set(job.out, Number(statOf(job.out)?.size ?? 0));
2452
+ return "encoded";
2453
+ });
2454
+ });
2455
+ }
2456
+ /** A source whose profile can't be converted to sRGB is named, once, when it's first encoded. */
2457
+ notePlan(src, plan) {
2458
+ if (plan.kind === "unsupported") {
2459
+ this.warnOnce(`${this.display(src)} has a color profile ssqch can't convert to sRGB (${plan.why}), so its colors may look washed out. HDR photos from newer iPhones do this; converting the source to sRGB once fixes it (on macOS: sips -m "/System/Library/ColorSync/Profiles/sRGB Profile.icc" <file>)`);
2460
+ }
2461
+ }
2462
+ /** A line for each source encoded, as it's done. */
2463
+ encoded(src, files, meta, ms) {
2464
+ if (!this.quiet) progress(`[ssqch] Encoded ${this.display(src)} into ${files} file${files === 1 ? "" : "s"} (${[...meta.formats.keys()].join(", ")}) in ${rustDuration(ms)}`);
2465
+ this.timings.push([src, files, ms]);
2466
+ }
2467
+ /**
2468
+ * A short, URL-safe id from the source's contents and the encoder settings, as 0.7 made it
2469
+ * (BLAKE3, and the settings written as the 0.7 numbers they convert from, `legacySettings`,
2470
+ * so the names don't change with the upgrade). Not the path or the modification time: a
2471
+ * fresh clone gives every file a new one, which would make every CI build a cold one. The
2472
+ * hash cache only saves reading files whose size and time haven't changed. An image that
2473
+ * gets converted to sRGB has that in its id too.
2474
+ */
2475
+ hashId(src, header, read) {
2476
+ const o = this.options;
2477
+ const settings = this.named;
2478
+ const cacheKey = `${settings}|color1`;
2479
+ let size;
2480
+ let mtime;
2481
+ try {
2482
+ ({ size, mtime } = stamp(src));
2483
+ } catch {
2484
+ throw new Error(`image not found: ${src}`);
2485
+ }
2486
+ if (o.hashCache) {
2487
+ const id2 = this.hashes.get(src, size, mtime, cacheKey);
2488
+ if (id2 !== void 0) return id2;
2489
+ }
2490
+ let contents;
2491
+ try {
2492
+ contents = fs4.readFileSync(src);
2493
+ } catch (e) {
2494
+ throw new Error(`reading ${src}: ${e.message}`);
2495
+ }
2496
+ read?.(contents);
2497
+ const parts = [contents, Buffer.from(settings)];
2498
+ if (header && colorPlan(header().icc).kind === "convert") parts.push(Buffer.from("|srgb"));
2499
+ const hash = blake3(Buffer.concat(parts));
2500
+ let id = "";
2501
+ for (let i = 0; i < 10; i++) id += ALPHABET[hash[i] & 63];
2502
+ if (o.hashCache) this.hashes.put(src, size, mtime, cacheKey, id);
2503
+ return id;
2504
+ }
2505
+ /**
2506
+ * A source's pixels, turned by its EXIF orientation and converted to sRGB from its colour
2507
+ * profile (which sharp does for any profile): what a PNG's files are made from.
2508
+ */
2509
+ async decode(job) {
2510
+ const sharp = loadSharp();
2511
+ try {
2512
+ const image = (ORIENT[job.orientation] ?? ((i) => i))(sharp(job.src, { failOn: failOn(job.source) }));
2513
+ return await image.raw().toBuffer({ resolveWithObject: true });
2514
+ } catch (e) {
2515
+ throw new Error(`decoding ${this.display(job.src)}: ${libvips(e)}`);
2516
+ }
2517
+ }
2518
+ /**
2519
+ * One file, from the source's decoded `pixels`, or from the file: turned, in sRGB, resized
2520
+ * with Catmull-Rom (the filter 0.7 used), and encoded as 0.7 wrote it. A JPEG has no alpha, and
2521
+ * 0.7 dropped it keeping the colour under it, so that's done before the resize: sharp resizes
2522
+ * with the colour weighted by the alpha, which is black where it's clear. A PNG of a grey
2523
+ * source is grey, and of a 16-bit one 16 bits, as 0.7's were.
2524
+ */
2525
+ async encodeFrom(job, pixels) {
2526
+ if (job.format === "gif" || job.format === "svg" || job.format === "auto") throw new Error(`encoding ${job.file}: cannot encode ${debugName(job.format)}`);
2527
+ const sharp = loadSharp();
2528
+ const settings = this.settings;
2529
+ const tmp = `${job.file.slice(0, job.file.length - path4.extname(job.file).length)}.${job.format}.${temporary++}.tmp`;
2530
+ try {
2531
+ const fromFile = () => (ORIENT[job.orientation] ?? ((i) => i))(sharp(job.src, { failOn: failOn(job.source) }));
2532
+ let image;
2533
+ if (job.format === "jpeg" && job.source !== "jpeg" && (!pixels || pixels.info.channels % 2 === 0)) {
2534
+ const opaque = await (pixels ? sharp(pixels.data, { raw: pixels.info }) : fromFile()).removeAlpha().raw().toBuffer({ resolveWithObject: true });
2535
+ image = sharp(opaque.data, { raw: opaque.info });
2536
+ } else image = pixels ? sharp(pixels.data, { raw: pixels.info }) : fromFile();
2537
+ image = image.resize(job.width, job.height, { fit: "fill", kernel: "cubic" });
2538
+ if (job.format === "png" && (job.probe.grey || job.probe.sixteen)) image = image.toColourspace(job.probe.grey ? job.probe.sixteen ? "grey16" : "b-w" : "rgb16");
2539
+ if (job.format === "jpeg") image = image.jpeg(settings.jpeg);
2540
+ else if (job.format === "png") image = image.png(settings.png);
2541
+ else if (job.format === "webp") image = image.webp(settings.webp);
2542
+ else image = image.avif(settings.avif);
2543
+ await image.toFile(tmp);
2544
+ fs4.renameSync(tmp, job.file);
2545
+ } catch (e) {
2546
+ try {
2547
+ fs4.rmSync(tmp, { force: true });
2548
+ } catch {
2549
+ }
2550
+ throw new Error(`encoding ${this.display(job.out)} from ${this.display(job.src)}: ${libvips(e)}`);
2551
+ }
2552
+ }
2553
+ /** The summary's `Images` line: the files this build used, from how many sources, and how many it had to encode. */
2554
+ summary() {
2555
+ if (this.used.size === 0 && this.pruned === 0) return void 0;
2556
+ let size = 0;
2557
+ for (const p of this.used) size += this.sizes.get(p) ?? fs4.statSync(p, { throwIfNoEntry: false })?.size ?? 0;
2558
+ const sources = this.sources.size;
2559
+ const encoded = Math.min(this.generated, this.used.size);
2560
+ let line = `${count(this.used.size)} file${this.used.size === 1 ? "" : "s"} from ${count(sources)} source${sources === 1 ? "" : "s"}, ${bytes(size)}: ${count(encoded)} encoded, ${count(this.used.size - encoded)} reused`;
2561
+ if (this.converted.size > 0) line += ` (${count(this.converted.size)} source${this.converted.size === 1 ? "" : "s"} converted to sRGB)`;
2562
+ if (this.options.prune) line += `, ${count(this.pruned)} pruned`;
2563
+ return line;
2564
+ }
2565
+ /** Deletes the files in `dir` that this build didn't make or reuse, and their copies in the cache. Counts the output's. */
2566
+ prune(dir) {
2567
+ const ctx = this.context();
2568
+ let removed = 0;
2569
+ let entries = [];
2570
+ try {
2571
+ entries = fs4.readdirSync(dir, { withFileTypes: true });
2572
+ } catch {
2573
+ }
2574
+ for (const entry of entries) {
2575
+ const p = path4.join(dir, entry.name);
2576
+ if (!this.used.has(p) && isEntryFile(entry, p)) {
2577
+ try {
2578
+ fs4.rmSync(p);
2579
+ } catch (e) {
2580
+ throw new Error(`pruning ${p}: ${e.message}`);
2581
+ }
2582
+ removed++;
2583
+ }
2584
+ }
2585
+ if (this.options.cacheDir !== null) {
2586
+ const names = new Set([...this.used].filter((p) => path4.dirname(p) === dir).map((p) => path4.basename(p)));
2587
+ const cache = path4.join(ctx.root, this.options.cacheDir);
2588
+ let cached = [];
2589
+ try {
2590
+ cached = fs4.readdirSync(cache, { withFileTypes: true });
2591
+ } catch {
2592
+ }
2593
+ for (const entry of cached) {
2594
+ const p = path4.join(cache, entry.name);
2595
+ if (!names.has(entry.name) && isEntryFile(entry, p)) {
2596
+ try {
2597
+ fs4.rmSync(p);
2598
+ } catch (e) {
2599
+ throw new Error(`pruning ${p}: ${e.message}`);
2600
+ }
2601
+ }
2602
+ }
2603
+ }
2604
+ return removed;
2605
+ }
2606
+ /** `<picture>` markup for generated images and the `<img>`'s attributes. */
2607
+ pictureHtml(meta, attrs) {
2608
+ return this.pictureMarkup(meta, attrs, false)[0];
2609
+ }
2610
+ /** `pictureHtml`, and with `preload`, its `<link rel="preload">`: the image loads eagerly with `fetchpriority="high"`, and `sizes="auto"` (lazy images only) is left out. */
2611
+ pictureMarkup(meta, attrs, preload) {
2612
+ const fallback = fallbackOf(meta);
2613
+ const low = fallback[0];
2614
+ const high = fallback.at(-1);
2615
+ if (!low || !high) return ["", void 0];
2616
+ const has = (name) => attrs.some(([a]) => a === name);
2617
+ let sizes;
2618
+ const img = [];
2619
+ for (const [k, v] of this.options.defaultAttributes) {
2620
+ if (k === "sizes") sizes = v;
2621
+ else if (preload && k === "loading") continue;
2622
+ else if (!has(k)) img.push([k, v]);
2623
+ }
2624
+ for (const [k, v] of attrs) {
2625
+ if (k === "width" || k === "height") continue;
2626
+ if (k === "sizes") sizes = v;
2627
+ else if (k === "src") img.push(["src", low.url]);
2628
+ else if (k === "loading" && preload && v.toLowerCase() === "lazy") continue;
2629
+ else img.push([k, v]);
2630
+ }
2631
+ if (preload) {
2632
+ sizes = sizes === void 0 ? void 0 : withoutAuto(sizes) || void 0;
2633
+ if (!has("fetchpriority")) img.push(["fetchpriority", "high"]);
2634
+ }
2635
+ if (fallback.length > 1) {
2636
+ img.push(["srcset", srcsetAttr(fallback)]);
2637
+ if (sizes !== void 0) img.push(["sizes", sizes]);
2638
+ }
2639
+ if (high.width > 0) img.push(["width", String(high.width)], ["height", String(high.height)]);
2640
+ const tag = `<img${img.map(([k, v]) => ` ${k}="${v.replaceAll('"', "&quot;")}"`).join("")}>`;
2641
+ let link;
2642
+ if (preload) {
2643
+ const [format, entries] = [...meta.formats.entries()][0];
2644
+ link = `<link rel="preload" as="image" type="${mime(format)}" fetchpriority="high"`;
2645
+ if (entries.length === 1) link += ` href="${escapeHtml(entries[0].url)}"`;
2646
+ else {
2647
+ link += ` imagesrcset="${escapeHtml(srcsetAttr(entries))}"`;
2648
+ if (sizes !== void 0) link += ` imagesizes="${sizes.replaceAll('"', "&quot;")}"`;
2649
+ }
2650
+ link += ">";
2651
+ }
2652
+ if (meta.formats.size < 2) return [tag, link];
2653
+ let html = "<picture>";
2654
+ const formats = [...meta.formats.entries()];
2655
+ for (const [format, entries] of formats.slice(0, -1)) {
2656
+ html += `<source type="${mime(format)}" srcset="${escapeHtml(srcsetAttr(entries))}"`;
2657
+ if (sizes !== void 0) html += ` sizes="${sizes.replaceAll('"', "&quot;")}"`;
2658
+ html += ">";
2659
+ }
2660
+ return [`${html}${tag}</picture>`, link];
2661
+ }
2662
+ /**
2663
+ * Some HTML made ready for a feed (what `feedHtml()` does before making URLs absolute): each
2664
+ * local `<img src>` points at one generated copy (`width` pixels wide at most, or less when the
2665
+ * tag's own `width` says so, in `format`), since feed readers drop `<picture>` and `srcset`; a
2666
+ * link to a local image points at the copy a page's link would; and `srcset`, `sizes`,
2667
+ * `loading`, `decoding`, `fetchpriority` and `ssqch:*` attributes go. `pageUrl` is the page
2668
+ * the HTML is from (a path or a whole URL), for relative image paths.
2669
+ */
2670
+ feedImages(html, pageUrl, width, format) {
2671
+ if (!html.includes("<img") && !html.includes("<a")) return html;
2672
+ const pagePath = pagePathOf(pageUrl);
2673
+ const by = { name: `feedHtml() for ${pageUrl}` };
2674
+ const sitePath = (src) => src.startsWith("/") || src.includes("://") || src.startsWith("data:") ? this.resolveSiteSrc(src) : this.resolveSiteSrc(joinUrlPath(pagePath, src));
2675
+ return rewriteHtml(html, {
2676
+ tag: (el) => {
2677
+ if (el.name === "img" && el.get("src") !== void 0) {
2678
+ const ignored = el.get("ssqch:ignore") !== void 0;
2679
+ for (const n of el.names().filter((n2) => n2.startsWith("ssqch:"))) el.remove(n);
2680
+ if (ignored) return;
2681
+ const src = el.get("src") ?? "";
2682
+ const file = sitePath(src);
2683
+ if (file === void 0) return;
2684
+ if (!this.isSource(file)) {
2685
+ this.warnOnce(`feedHtml(): image not found: ${src}`);
2686
+ return;
2687
+ }
2688
+ const own = parseU32(el.get("width"));
2689
+ const w = own !== void 0 && own > 0 && (width === 0 || own < width) ? own : width;
2690
+ let meta;
2691
+ try {
2692
+ meta = this.generate(file, [w], [format]);
2693
+ } catch (e2) {
2694
+ this.warnOnce(e2.message);
2695
+ return;
2696
+ }
2697
+ this.watch(meta, file, by);
2698
+ const resolved = format === "auto" ? meta.auto : format;
2699
+ const e = widest((resolved !== void 0 ? meta.formats.get(resolved) : void 0) ?? [...meta.formats.values()][0]);
2700
+ if (e) el.set("src", e.url);
2701
+ for (const attr of ["srcset", "sizes", "loading", "decoding", "fetchpriority"]) if (el.get(attr) !== void 0) el.remove(attr);
2702
+ } else if (el.name === "a" && el.get("href") !== void 0) {
2703
+ if (el.get("ssqch:ignore") !== void 0) {
2704
+ el.remove("ssqch:ignore");
2705
+ return;
2706
+ }
2707
+ const href = el.get("href") ?? "";
2708
+ const file = sitePath(href);
2709
+ if (file === void 0 || fromPath(file) === void 0 || !this.isSource(file)) return;
2710
+ try {
2711
+ el.set("href", this.linkTarget(file, by));
2712
+ } catch (e) {
2713
+ this.warnOnce(e.message);
2714
+ }
2715
+ }
2716
+ }
2717
+ });
2718
+ }
2719
+ /** Every local `<img>` in an HTML page made a `<picture>`, and links to local images pointed at a copy. `url` is the page's, for an error. */
2720
+ transformHtml(html, pageInput, url) {
2721
+ const links = this.options.linkedImages && mayLinkImages(html);
2722
+ if (!html.includes("<img") && !links) return html;
2723
+ const preloads = [];
2724
+ const by = { name: this.display(pageInput), url };
2725
+ const out = rewriteHtml(html, {
2726
+ tag: (el) => {
2727
+ if (el.name === "a" && el.get("href") !== void 0) {
2728
+ if (el.get("ssqch:ignore") !== void 0) {
2729
+ el.remove("ssqch:ignore");
2730
+ return;
2731
+ }
2732
+ if (!links) return;
2733
+ const href = el.get("href") ?? "";
2734
+ const file = this.resolveSrc(href, pageInput);
2735
+ if (file === void 0 || fromPath(file) === void 0) return;
2736
+ if (!this.isSource(file)) {
2737
+ this.warnOnce(`linked image not found: ${href} (in ${pageInput})`);
2738
+ return;
2739
+ }
2740
+ try {
2741
+ el.set("href", this.linkTarget(file, by));
2742
+ } catch (e) {
2743
+ this.warnOnce(e.message);
2744
+ }
2745
+ } else if (el.name === "img" && el.get("src") !== void 0) {
2746
+ if (el.get("ssqch:ignore") !== void 0) {
2747
+ el.remove("ssqch:ignore");
2748
+ if (el.get("ssqch:preload") !== void 0) el.remove("ssqch:preload");
2749
+ return;
2750
+ }
2751
+ const preload = el.get("ssqch:preload") !== void 0;
2752
+ const src = el.get("src") ?? "";
2753
+ const file = this.resolveSrc(src, pageInput);
2754
+ if (file === void 0) return;
2755
+ if (!this.isSource(file)) {
2756
+ this.warnOnce(`image not found: ${src} (in ${pageInput})`);
2757
+ return;
2758
+ }
2759
+ const listed = el.get("ssqch:widths");
2760
+ const own = parseU32(el.get("width"));
2761
+ const widths = listed !== void 0 ? listed.split(",").map(parseU32).filter((w) => w !== void 0) : own !== void 0 ? [own] : this.options.widths;
2762
+ let meta;
2763
+ try {
2764
+ meta = this.generate(file, widths, this.options.formats);
2765
+ } catch (e) {
2766
+ this.warnOnce(e.message);
2767
+ return;
2768
+ }
2769
+ this.watch(meta, file, by);
2770
+ const attrs = el.entries().filter(([name]) => !name.startsWith("ssqch:"));
2771
+ const [markup, link] = this.pictureMarkup(meta, attrs, preload);
2772
+ el.replaceWith(markup);
2773
+ if (link !== void 0) preloads.push(link);
2774
+ }
2775
+ }
2776
+ });
2777
+ if (!preloads.length) return out;
2778
+ const placed = insertPreloads(out, preloads.join(""));
2779
+ if (placed === void 0) throw new BuildError(`ssqch:preload in ${pageInput}: the page has no <head> to put the preload in`);
2780
+ return placed;
2781
+ }
2782
+ };
2783
+ var MAY_LINK_IMAGES = /\.(?:png|jpe?g|gif|svg|webp)|%[0-9a-f]{2}|ssqch:ignore/i;
2784
+ var mayLinkImages = (html) => html.includes("<a") && MAY_LINK_IMAGES.test(html);
2785
+ function parseU32(v) {
2786
+ if (v === void 0) return void 0;
2787
+ const t = v.trim();
2788
+ if (!/^\+?\d+$/.test(t)) return void 0;
2789
+ const n = Number(t.replace(/^\+/, ""));
2790
+ return n <= 4294967295 ? n : void 0;
2791
+ }
2792
+ function widest(entries) {
2793
+ let best;
2794
+ for (const e of entries ?? []) if (!best || e.width > best.width) best = e;
2795
+ return best;
2796
+ }
2797
+ function insertPreloads(html, links) {
2798
+ let inHead = false;
2799
+ let seen = false;
2800
+ let at = -1;
2801
+ rewriteHtml(html, {
2802
+ tag: (el) => {
2803
+ if (el.name === "head" && !seen) {
2804
+ seen = true;
2805
+ inHead = true;
2806
+ return;
2807
+ }
2808
+ if (!inHead || at !== -1) return;
2809
+ const type = el.get("type");
2810
+ const script = el.name === "script" && (type === void 0 || ((t) => t === "" || t === "module" || t.includes("javascript"))(type.trim().toLowerCase()));
2811
+ const rel = el.name === "link" ? el.get("rel") : void 0;
2812
+ if (script || rel !== void 0 && rel.toLowerCase().split(/\s+/).includes("stylesheet")) at = el.start;
2813
+ },
2814
+ endTag: (name, start) => {
2815
+ if (name === "head" && inHead) {
2816
+ inHead = false;
2817
+ if (at === -1) at = start;
2818
+ }
2819
+ }
2820
+ });
2821
+ if (!seen || at === -1) return void 0;
2822
+ return html.slice(0, at) + links + html.slice(at);
2823
+ }
2824
+ function imageOptionsFor(who, options, defaultWidth) {
2825
+ if (options === void 0 || options === null) return [defaultWidth, "auto"];
2826
+ if (typeof options !== "object" || Array.isArray(options) || options instanceof Date) throw new BuildError(`${who}: options must be an object like { width: 1200, format: "png" }`);
2827
+ for (const key of Object.keys(options)) {
2828
+ if (key !== "width" && key !== "format") throw new BuildError(`${who}: unknown option "${key}" (options: width, format)`);
2829
+ }
2830
+ const o = options;
2831
+ let width = defaultWidth;
2832
+ if (o.width !== void 0 && o.width !== null) {
2833
+ if (o.width === "auto") width = 0;
2834
+ else {
2835
+ const n = Number(o.width);
2836
+ if (!(Number.isFinite(n) && n >= 1 && Number.isInteger(n))) throw new BuildError(`${who}: width must be a whole number of pixels or "auto", got ${String(o.width)}`);
2837
+ width = Math.min(n, 4294967295);
2838
+ }
2839
+ }
2840
+ let format = "auto";
2841
+ if (o.format !== void 0 && o.format !== null) {
2842
+ const parsed = parseFormat(String(o.format));
2843
+ if (parsed === void 0) throw new BuildError(`${who}: unknown format "${String(o.format)}" (use avif, webp, jpeg, png, gif, svg or auto)`);
2844
+ format = parsed;
2845
+ }
2846
+ return [width, format];
2847
+ }
2848
+ var processors = /* @__PURE__ */ new WeakMap();
2849
+ var current;
2850
+ function currentProcessor() {
2851
+ if (!current) throw new BuildError("the image processor isn't set up");
2852
+ return current;
2853
+ }
2854
+ function addImagePlugin(config, options) {
2855
+ if (processors.has(config)) throw new BuildError("the ssqch/image plugin was added twice");
2856
+ const p = new ImageProcessor(options);
2857
+ processors.set(config, p);
2858
+ register(config, p, true);
2859
+ }
2860
+ function useImages(config) {
2861
+ let p = processors.get(config);
2862
+ if (!p) {
2863
+ p = new ImageProcessor(defaultImageOptions());
2864
+ processors.set(config, p);
2865
+ register(config, p, false);
2866
+ }
2867
+ current = p;
2868
+ }
2869
+ function register(config, p, transform) {
2870
+ p.quiet = config.quiet;
2871
+ config.beforeBuild.unshift({ label: "", fn: () => p.startBuild(config) });
2872
+ const unnamed = (e) => {
2873
+ if (e instanceof Error && e.message.startsWith("imageUrl(): ")) e.message = e.message.slice("imageUrl(): ".length);
2874
+ return e;
2875
+ };
2876
+ config.filters.set("imageUrl", (src, options) => {
2877
+ try {
2878
+ const [width, format] = imageOptionsFor("imageUrl()", options, 0);
2879
+ return p.imageUrl(src === void 0 || src === null ? "" : String(src), width, format);
2880
+ } catch (e) {
2881
+ throw unnamed(e);
2882
+ }
2883
+ });
2884
+ if (transform) {
2885
+ config.htmlTransforms.push(["image", (content, info) => path4.extname(info.outputPath) === ".html" ? p.transformHtml(content, path4.resolve(config.root, info.inputPath), info.url) : content]);
2886
+ }
2887
+ config.settle.push(() => p.settle());
2888
+ config.afterBuild.push({ label: "", fn: () => p.finishBuild() });
2889
+ config.summaries.push(["Images", () => p.summary()]);
2890
+ }
2891
+
2892
+ // src/rust-plugin.ts
2893
+ import fs5 from "node:fs";
2894
+ import path5 from "node:path";
2895
+ import { fileURLToPath } from "node:url";
2896
+ var ABI_VERSION = 1;
2897
+ var OK = 0;
2898
+ var UNCHANGED = 1;
2899
+ var ERROR = 2;
2900
+ var WASI_EBADF = 8;
2901
+ var WASI_ENOSYS = 52;
2902
+ var EXPORTS = ["memory", "ssqch_reserve", "ssqch_result", "ssqch_init", "ssqch_transform", "ssqch_filter", "ssqch_render"];
2903
+ function readManifest(module, file) {
2904
+ const sections = WebAssembly.Module.customSections(module, "ssqch_plugin");
2905
+ if (sections.length === 0) throw new BuildError(`${file}: not an ssqch plugin (it has no ssqch_plugin section; was it built with ssqch_plugin::export!?)`);
2906
+ let manifest;
2907
+ try {
2908
+ manifest = JSON.parse(Buffer.from(sections[0]).toString("utf8"));
2909
+ } catch (e) {
2910
+ throw new BuildError(`${file}: not an ssqch plugin (its ssqch_plugin section isn't JSON: ${messageOf(e)})`);
2911
+ }
2912
+ if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) throw new BuildError(`${file}: not an ssqch plugin (its ssqch_plugin section isn't a manifest object)`);
2913
+ if (typeof manifest.abi !== "number") throw new BuildError(`${file}: not an ssqch plugin (its manifest has no abi number)`);
2914
+ if (manifest.abi !== ABI_VERSION) {
2915
+ const hint = manifest.abi > ABI_VERSION ? `update ssqch, or use a version of the plugin built for ABI ${ABI_VERSION}` : "rebuild it with a current ssqch-plugin";
2916
+ throw new BuildError(`${file}: built for plugin ABI ${manifest.abi}, and this ssqch loads ABI ${ABI_VERSION}: ${hint}`);
2917
+ }
2918
+ for (const key of ["hooks", "filters", "engines"]) {
2919
+ if (!Array.isArray(manifest[key])) throw new BuildError(`${file}: not an ssqch plugin (its manifest has no ${key} list)`);
2920
+ if (!manifest[key].every((entry) => typeof entry === "string")) throw new BuildError(`${file}: not an ssqch plugin (its manifest's ${key} must all be names, as text)`);
2921
+ }
2922
+ if (typeof manifest.name !== "string" || manifest.name === "") throw new BuildError(`${file}: not an ssqch plugin (its manifest has no name)`);
2923
+ return manifest;
2924
+ }
2925
+ var PluginCallError = class extends BuildError {
2926
+ plugin;
2927
+ what;
2928
+ detail;
2929
+ constructor(plugin, what, detail) {
2930
+ super(what === "" ? `${plugin}: ${detail}` : `${plugin}: ${what}: ${detail}`);
2931
+ this.plugin = plugin;
2932
+ this.what = what;
2933
+ this.detail = detail;
2934
+ }
2935
+ };
2936
+ var compiled = /* @__PURE__ */ new Map();
2937
+ function compilePlugin(file, shown2) {
2938
+ let stat;
2939
+ try {
2940
+ stat = fs5.statSync(file);
2941
+ } catch {
2942
+ throw new BuildError(`${shown2} doesn't exist`);
2943
+ }
2944
+ if (!stat.isFile()) throw new BuildError(`${shown2} isn't a file`);
2945
+ const stamp2 = `${stat.size}:${stat.mtimeMs}`;
2946
+ const kept = compiled.get(file);
2947
+ if (kept?.stamp === stamp2) return kept.module;
2948
+ let module;
2949
+ try {
2950
+ module = new WebAssembly.Module(fs5.readFileSync(file));
2951
+ } catch (e) {
2952
+ throw new BuildError(`${shown2}: not an ssqch plugin (it isn't WebAssembly: ${messageOf(e).replace(/^WebAssembly\.Module\(\): /, "")})`);
2953
+ }
2954
+ compiled.set(file, { stamp: stamp2, module });
2955
+ return module;
2956
+ }
2957
+ var RustPlugin = class {
2958
+ manifest;
2959
+ file;
2960
+ #module;
2961
+ #options;
2962
+ #x = null;
2963
+ #bytes = Buffer.alloc(0);
2964
+ #slot = 0;
2965
+ #scratch = 0;
2966
+ #room = -1;
2967
+ /** Starts the plugin, so options it refuses fail now, before any page. */
2968
+ constructor(module, options, file) {
2969
+ this.#module = module;
2970
+ this.file = file;
2971
+ this.manifest = readManifest(module, file);
2972
+ for (const i of WebAssembly.Module.imports(module)) {
2973
+ if (i.module !== "wasi_snapshot_preview1") throw new BuildError(`${file}: it imports ${i.module}.${i.name}, which ssqch doesn't provide (plugins can use std; ssqch answers wasi_snapshot_preview1 calls without files or network)`);
2974
+ }
2975
+ let json;
2976
+ try {
2977
+ json = options === void 0 ? "" : JSON.stringify(options) ?? "";
2978
+ } catch (e) {
2979
+ throw new BuildError(`${this.name}: options: ${messageOf(e)}`);
2980
+ }
2981
+ this.#options = json;
2982
+ this.#start();
2983
+ }
2984
+ get name() {
2985
+ return this.manifest.name;
2986
+ }
2987
+ #start() {
2988
+ let memory;
2989
+ const instance = new WebAssembly.Instance(this.#module, { wasi_snapshot_preview1: wasi(() => memory) });
2990
+ const x = instance.exports;
2991
+ for (const name of EXPORTS) {
2992
+ if (x[name] === void 0) throw new BuildError(`${this.file}: not an ssqch plugin (no ${name} export)`);
2993
+ }
2994
+ memory = x.memory;
2995
+ this.#x = x;
2996
+ this.#bytes = Buffer.alloc(0);
2997
+ this.#room = -1;
2998
+ this.#scratch = 0;
2999
+ try {
3000
+ x._initialize?.();
3001
+ } catch (e) {
3002
+ this.#x = null;
3003
+ throw new BuildError(`${this.name}: crashed while starting (${messageOf(e)})`);
3004
+ }
3005
+ this.#slot = x.ssqch_result();
3006
+ const status = this.#call([this.#options], (l) => x.ssqch_init(l[0]), () => "");
3007
+ if (status !== OK && status !== UNCHANGED) {
3008
+ const message = status === ERROR ? this.#result() : `answered with status ${status}`;
3009
+ this.#x = null;
3010
+ throw new PluginCallError(this.name, "", message);
3011
+ }
3012
+ return x;
3013
+ }
3014
+ #view() {
3015
+ const memory = this.#x.memory.buffer;
3016
+ if (this.#bytes.buffer !== memory) this.#bytes = Buffer.from(memory);
3017
+ return this.#bytes;
3018
+ }
3019
+ #result() {
3020
+ const b = this.#view();
3021
+ const ptr = b.readUInt32LE(this.#slot);
3022
+ const len = b.readUInt32LE(this.#slot + 4);
3023
+ return b.toString("utf8", ptr, ptr + len);
3024
+ }
3025
+ /** Writes the inputs one after another into the plugin's buffer, then makes the call. `what` names the call for errors. */
3026
+ #call(inputs, call, what) {
3027
+ const x = this.#x ?? this.#start();
3028
+ let total = 0;
3029
+ const lens = inputs.map((s) => {
3030
+ const n = Buffer.byteLength(s, "utf8");
3031
+ total += n;
3032
+ return n;
3033
+ });
3034
+ try {
3035
+ if (total > this.#room) {
3036
+ this.#scratch = x.ssqch_reserve(total);
3037
+ this.#room = total;
3038
+ }
3039
+ const b = this.#view();
3040
+ let at = this.#scratch;
3041
+ for (let i = 0; i < inputs.length; i++) at += b.write(inputs[i], at, lens[i], "utf8");
3042
+ return call(lens);
3043
+ } catch (e) {
3044
+ if (e instanceof BuildError) throw e;
3045
+ let panicked = false;
3046
+ let message = "";
3047
+ try {
3048
+ panicked = this.#view().readUInt32LE(this.#slot + 8) === 1;
3049
+ if (panicked) message = this.#result().replace(/^panicked at /, "").replace(/\s*\n\s*/g, " ");
3050
+ } catch {
3051
+ }
3052
+ this.#x = null;
3053
+ throw new PluginCallError(this.name, what(), panicked ? `panicked at ${message}` : `crashed (${messageOf(e)})`);
3054
+ }
3055
+ }
3056
+ #finish(status, what) {
3057
+ if (status === OK) return this.#result();
3058
+ if (status === UNCHANGED) return null;
3059
+ throw new PluginCallError(this.name, what(), status === ERROR ? this.#result() : `answered with status ${status}`);
3060
+ }
3061
+ /** A page's HTML rewritten, or `null` when it's unchanged (or the plugin has no transform). */
3062
+ transform(html, page = {}) {
3063
+ if (!this.manifest.hooks.includes("transform")) return null;
3064
+ const what = () => `transform of ${page.url || page.outputPath || "a page"}`;
3065
+ return this.#finish(this.#call([html, pageText(page)], (l) => this.#x.ssqch_transform(l[0], l[1]), what), what);
3066
+ }
3067
+ /** A filter's answer, for arguments as JSON text, as JSON text. */
3068
+ filterJson(name, argsJson) {
3069
+ if (!this.manifest.filters.includes(name)) throw new BuildError(`${this.name}: no filter named ${name} (it provides ${this.manifest.filters.join(", ") || "none"})`);
3070
+ const what = () => `filter ${name}`;
3071
+ return this.#finish(this.#call([name, argsJson], (l) => this.#x.ssqch_filter(l[0], l[1]), what), what) ?? "null";
3072
+ }
3073
+ /** A filter's answer, for arguments JSON can carry. */
3074
+ filter(name, args) {
3075
+ return JSON.parse(this.filterJson(name, toJson(args)));
3076
+ }
3077
+ /** A file of an extension the plugin renders (without the dot), as HTML. */
3078
+ render(ext, source, page = {}) {
3079
+ if (!this.manifest.engines.includes(ext)) throw new BuildError(`${this.name}: doesn't render .${ext} files (it renders ${this.manifest.engines.map((e) => `.${e}`).join(", ") || "none"})`);
3080
+ const what = () => `render of ${page.inputPath || page.url || `a .${ext} file`}`;
3081
+ return this.#finish(this.#call([ext, source, pageText(page)], (l) => this.#x.ssqch_render(l[0], l[1], l[2]), what), what) ?? "";
3082
+ }
3083
+ };
3084
+ function pageText(page) {
3085
+ return `${page.url ?? ""}\0${page.inputPath ?? ""}\0${page.outputPath ?? ""}\0${page.dataJson ?? ""}`;
3086
+ }
3087
+ function toJson(value, skip) {
3088
+ const inside = /* @__PURE__ */ new Set();
3089
+ const walk = (v) => {
3090
+ if (v === null || typeof v !== "object") {
3091
+ if (typeof v === "bigint") return v.toString();
3092
+ return typeof v === "function" || typeof v === "symbol" ? void 0 : v;
3093
+ }
3094
+ if (typeof v.toJSON === "function") return walk(v.toJSON());
3095
+ if (inside.has(v)) return null;
3096
+ inside.add(v);
3097
+ try {
3098
+ if (Array.isArray(v)) return v.map((item) => walk(item) ?? null);
3099
+ const out = {};
3100
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(v))) {
3101
+ if (!descriptor.enumerable || !("value" in descriptor)) continue;
3102
+ const item = walk(descriptor.value);
3103
+ if (item !== void 0) out[key] = item;
3104
+ }
3105
+ return out;
3106
+ } finally {
3107
+ inside.delete(v);
3108
+ }
3109
+ };
3110
+ if (skip !== void 0 && value !== null && typeof value === "object" && !Array.isArray(value)) {
3111
+ const { [skip]: _, ...rest } = value;
3112
+ value = rest;
3113
+ }
3114
+ return JSON.stringify(walk(value) ?? null);
3115
+ }
3116
+ function wasi(memory) {
3117
+ let seed = 0x5eed5ca7c4edf007n;
3118
+ const mask = (1n << 64n) - 1n;
3119
+ const view = () => new DataView(memory().buffer);
3120
+ const known = {
3121
+ environ_sizes_get: (count2, size) => {
3122
+ view().setUint32(count2, 0, true);
3123
+ view().setUint32(size, 0, true);
3124
+ return 0;
3125
+ },
3126
+ environ_get: () => 0,
3127
+ args_sizes_get: (count2, size) => {
3128
+ view().setUint32(count2, 0, true);
3129
+ view().setUint32(size, 0, true);
3130
+ return 0;
3131
+ },
3132
+ args_get: () => 0,
3133
+ clock_time_get: (id, _precision, out) => {
3134
+ view().setBigUint64(out, id === 0 ? BigInt(Date.now()) * 1000000n : process.hrtime.bigint(), true);
3135
+ return 0;
3136
+ },
3137
+ fd_write: (fd, iovs, count2, written) => {
3138
+ const v = view();
3139
+ let total = 0;
3140
+ for (let i = 0; i < count2; i++) {
3141
+ const ptr = v.getUint32(iovs + i * 8, true);
3142
+ const len = v.getUint32(iovs + i * 8 + 4, true);
3143
+ if (fd === 1 || fd === 2) process.stderr.write(new Uint8Array(memory().buffer, ptr, len).slice());
3144
+ total += len;
3145
+ }
3146
+ v.setUint32(written, total, true);
3147
+ return 0;
3148
+ },
3149
+ random_get: (ptr, len) => {
3150
+ const bytes2 = new Uint8Array(memory().buffer, ptr, len);
3151
+ for (let at = 0; at < len; at += 8) {
3152
+ seed ^= seed >> 12n;
3153
+ seed = (seed ^ seed << 25n) & mask;
3154
+ seed ^= seed >> 27n;
3155
+ let v = seed * 0x2545f4914f6cdd1dn & mask;
3156
+ for (let i = 0; i < 8 && at + i < len; i++) {
3157
+ bytes2[at + i] = Number(v & 0xffn);
3158
+ v >>= 8n;
3159
+ }
3160
+ }
3161
+ return 0;
3162
+ },
3163
+ fd_prestat_get: () => WASI_EBADF,
3164
+ proc_exit: (code) => {
3165
+ throw new WebAssembly.RuntimeError(`the plugin called exit(${code})`);
3166
+ }
3167
+ };
3168
+ return new Proxy(known, { get: (target, name) => target[name] ?? (() => WASI_ENOSYS) });
3169
+ }
3170
+ function loadRustPart(rust, where, root) {
3171
+ if (rust === null || typeof rust !== "object" || Array.isArray(rust)) throw new BuildError(`${where}: rust must be an object, like { wasm: "/path/to/plugin.wasm", options: {} }`);
3172
+ const part = rust;
3173
+ for (const key of Object.keys(part)) {
3174
+ if (key !== "wasm" && key !== "options") throw new BuildError(`${where}: rust.${key} isn't an option (options: wasm, options)`);
3175
+ }
3176
+ if (typeof part.wasm !== "string" || part.wasm.trim() === "") throw new BuildError(`${where}: rust.wasm must be the path to the plugin's .wasm file`);
3177
+ const file = path5.resolve(root, part.wasm.startsWith("file:") ? fileURLToPath(part.wasm) : part.wasm);
3178
+ const shown2 = displayPath(root, file);
3179
+ let plugin;
3180
+ try {
3181
+ plugin = new RustPlugin(compilePlugin(file, shown2), part.options, shown2);
3182
+ } catch (e) {
3183
+ if (e instanceof PluginCallError && where.endsWith(`"${e.plugin}"`)) throw new BuildError(`${where}: ${e.what === "" ? "" : `${e.what}: `}${e.detail}`);
3184
+ throw new BuildError(`${where}: ${messageOf(e)}`);
3185
+ }
3186
+ const { manifest } = plugin;
3187
+ const loaded2 = { plugin, filters: [], engines: [] };
3188
+ const said = (call, words2) => {
3189
+ try {
3190
+ return call();
3191
+ } catch (e) {
3192
+ throw e instanceof PluginCallError ? new BuildError(words2(e)) : e;
3193
+ }
3194
+ };
3195
+ if (manifest.hooks.includes("transform")) {
3196
+ loaded2.transform = [manifest.name, (content, page) => page.outputPath.endsWith(".html") ? said(() => plugin.transform(content, page), (e) => e.detail) ?? content : content];
3197
+ }
3198
+ for (const name of manifest.filters) loaded2.filters.push([name, (...args) => said(() => plugin.filter(name, args), (e) => `${e.plugin}: ${e.detail}`)]);
3199
+ for (const ext of manifest.engines) {
3200
+ loaded2.engines.push([ext, (source, data, inputPath) => {
3201
+ const page = data?.page ?? {};
3202
+ const dataJson = toJson(data, "collections");
3203
+ return said(() => plugin.render(ext, source, { url: page.url ?? "", inputPath: page.inputPath ?? inputPath, outputPath: page.outputPath ?? "", dataJson }), (e) => `${e.plugin}: ${e.detail.replace(/^line (\d+): /, `${inputPath}:$1: `)}`);
3204
+ }]);
3205
+ }
3206
+ return loaded2;
3207
+ }
3208
+
3209
+ // src/theme.ts
3210
+ import fs6 from "node:fs";
3211
+ import path6 from "node:path";
3212
+ import { spawnSync } from "node:child_process";
3213
+ var isGitUrl = (s) => ["https://", "http://", "ssh://", "git://", "file://", "git@"].some((p) => s.startsWith(p));
3214
+ var q = (s) => JSON.stringify(s);
3215
+ function parseTheme(given) {
3216
+ const spec = given.trim();
3217
+ if (spec === "") bail('theme is empty: give a folder ("themes/docs") or a git URL with a commit or tag ("https://github.com/you/theme#v1.2.0")');
3218
+ if (!isGitUrl(spec)) return { folder: spec };
3219
+ const hash = spec.indexOf("#");
3220
+ const pin = hash === -1 ? "" : spec.slice(hash + 1);
3221
+ if (pin === "") bail(`theme ${q(spec)} isn't pinned: add the commit or tag to use, like "${spec.replace(/#+$/, "")}#v1.2.0"`);
3222
+ const colon = pin.indexOf(":");
3223
+ return gitTheme(spec.slice(0, hash), colon === -1 ? pin : pin.slice(0, colon), colon === -1 ? "" : pin.slice(colon + 1));
3224
+ }
3225
+ function gitTheme(url, reference, dir) {
3226
+ if (!isGitUrl(url)) bail(`theme: ${q(url)} isn't a git URL (https://, ssh://, git@ or file://)`);
3227
+ if (reference === "" || reference.startsWith("-") || /\s/.test(reference)) bail(`theme ${q(url)}: ${q(reference)} isn't a commit or tag`);
3228
+ const folder = dir.replace(/^\/+|\/+$/g, "");
3229
+ if (folder.split("/").includes("..") || /[\\:]/.test(folder)) bail(`theme ${q(url)}: the folder ${q(folder)} must be inside the repository`);
3230
+ return { url, reference, dir: folder };
3231
+ }
3232
+ function resolveTheme(root, theme, quiet) {
3233
+ const source = typeof theme === "string" ? parseTheme(theme) : gitTheme(theme.git, theme.ref, theme.dir);
3234
+ if ("folder" in source) {
3235
+ const dir2 = path6.resolve(root, source.folder);
3236
+ if (!fs6.statSync(dir2, { throwIfNoEntry: false })?.isDirectory()) bail(`theme folder ${dir2} doesn't exist`);
3237
+ return realPath(dir2);
3238
+ }
3239
+ const checkout = fetch(root, source.url, source.reference, quiet);
3240
+ const dir = path6.join(checkout, source.dir);
3241
+ if (!fs6.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) bail(`theme ${source.url}#${source.reference}: there's no folder ${q(source.dir)} in it`);
3242
+ return realPath(dir);
3243
+ }
3244
+ function cacheName(url, reference) {
3245
+ const last = url.replace(/\/+$/, "").replace(/\.git$/, "").split(/[/:]/).pop() ?? "theme";
3246
+ const name = last.replace(/[^A-Za-z0-9_-]/g, "");
3247
+ let hash = 0xcbf29ce484222325n;
3248
+ for (const b of Buffer.from(`${url}#${reference}`)) hash = (hash ^ BigInt(b)) * 0x100000001b3n & 0xffffffffffffffffn;
3249
+ return `${name === "" ? "theme" : name}-${hash.toString(16).padStart(16, "0")}`;
3250
+ }
3251
+ function fetch(root, url, reference, quiet) {
3252
+ const dir = path6.join(root, ".cache/ssqch/themes", cacheName(url, reference));
3253
+ const marker = path6.join(dir, ".ssqch-theme");
3254
+ const source = `${url}#${reference}`;
3255
+ try {
3256
+ if (fs6.readFileSync(marker, "utf8").trim() === source) return dir;
3257
+ } catch {
3258
+ }
3259
+ if (!quiet) progress(`[ssqch] Fetching theme ${source}`);
3260
+ fs6.rmSync(dir, { recursive: true, force: true });
3261
+ fs6.mkdirSync(dir, { recursive: true });
3262
+ const git = (args) => {
3263
+ const out = spawnSync("git", ["-C", dir, ...args], { encoding: "utf8" });
3264
+ if (out.error) bail(`theme ${source}: can't run git (${out.error.message}); install git, or use a theme folder`);
3265
+ if (out.status !== 0) {
3266
+ fs6.rmSync(dir, { recursive: true, force: true });
3267
+ const short = reference.length >= 7 && reference.length < 40 && /^[0-9a-fA-F]+$/.test(reference);
3268
+ bail(`theme ${source}: git ${args[0] ?? ""} failed: ${(out.stderr ?? "").trim()}${short ? " (if that's a commit, give all 40 characters of its hash)" : ""}`);
3269
+ }
3270
+ };
3271
+ git(["init", "--quiet"]);
3272
+ git(["fetch", "--quiet", "--depth", "1", "--", url, reference]);
3273
+ git(["-c", "advice.detachedHead=false", "checkout", "--quiet", "FETCH_HEAD"]);
3274
+ fs6.rmSync(path6.join(dir, ".git"), { recursive: true, force: true });
3275
+ fs6.writeFileSync(marker, source);
3276
+ return dir;
3277
+ }
3278
+
3279
+ // src/config.ts
3280
+ var DEFAULTS2 = { templateFormats: ["jinja", "md", "html"], markdownEngine: "jinja", htmlEngine: "jinja" };
3281
+ function emptyConfig(options) {
3282
+ return {
3283
+ root: realPath(path7.resolve(options.root)),
3284
+ rootGiven: options.rootGiven ?? options.root,
3285
+ file: null,
3286
+ env: options.env,
3287
+ serving: options.serving ?? false,
3288
+ quiet: options.quiet ?? false,
3289
+ verbose: options.verbose ?? false,
3290
+ input: ".",
3291
+ output: "_site",
3292
+ includes: "_includes",
3293
+ layouts: null,
3294
+ data: "_data",
3295
+ templateFormats: [...DEFAULTS2.templateFormats],
3296
+ markdownEngine: DEFAULTS2.markdownEngine,
3297
+ htmlEngine: DEFAULTS2.htmlEngine,
3298
+ markdown: defaultMarkdownOptions(),
3299
+ deepMerge: true,
3300
+ leaveNoTrace: false,
3301
+ ignore: [],
3302
+ bundles: false,
3303
+ strict: false,
3304
+ lastModified: null,
3305
+ base: "",
3306
+ serveRun: [],
3307
+ budgets: [],
3308
+ schemas: [],
3309
+ themes: [],
3310
+ passthrough: [],
3311
+ filters: /* @__PURE__ */ new Map(),
3312
+ globalData: [],
3313
+ dataExtensions: /* @__PURE__ */ new Map(),
3314
+ collections: [],
3315
+ transforms: [],
3316
+ htmlTransforms: [],
3317
+ engines: /* @__PURE__ */ new Map(),
3318
+ beforeBuild: [],
3319
+ afterBuild: [],
3320
+ watch: [],
3321
+ plugins: [],
3322
+ summaries: [],
3323
+ generators: [],
3324
+ fileBuilders: [],
3325
+ settle: []
3326
+ };
3327
+ }
3328
+ function findConfig(root) {
3329
+ return CONFIG_FILES.map((name) => path7.join(root, name)).find((file) => fs7.statSync(file, { throwIfNoEntry: false })?.isFile());
3330
+ }
3331
+ async function loadConfig(options) {
3332
+ const config = emptyConfig(options);
3333
+ hookModules();
3334
+ if (fs7.statSync(config.root, { throwIfNoEntry: false })?.isDirectory()) process.chdir(config.root);
3335
+ Object.assign(site, { root: config.root, input: null, markdown: null });
3336
+ installFetch(config.root);
3337
+ config.summaries.push(["Fetch", summary]);
3338
+ for (const ext of ["js", "mjs", "cjs", "ts", "mts"]) config.dataExtensions.set(ext, (file) => loadJsData(file, config.root));
3339
+ const toml = path7.join(config.root, "sitesquatch.toml");
3340
+ const hasToml = fs7.statSync(toml, { throwIfNoEntry: false })?.isFile() ?? false;
3341
+ const js = findConfig(config.root);
3342
+ if (js && hasToml) bail(`found both ${path7.basename(js)} and sitesquatch.toml; keep one of them`);
3343
+ if (js) {
3344
+ config.file = js;
3345
+ await loadJs(config, js);
3346
+ } else {
3347
+ if (!hasToml) {
3348
+ const message = otherGenerator(config.root);
3349
+ if (message) warn(warning("other-generator", message));
3350
+ } else {
3351
+ config.file = toml;
3352
+ applyToml(config, toml);
3353
+ }
3354
+ }
3355
+ if (options.output !== void 0) config.output = options.output;
3356
+ if (options.base !== void 0) {
3357
+ try {
3358
+ config.base = normalizeBase(options.base);
3359
+ } catch (e) {
3360
+ throw context(e, "--base");
3361
+ }
3362
+ }
3363
+ useImages(config);
3364
+ return config;
3365
+ }
3366
+ async function loadJsData(file, root) {
3367
+ const name = path7.relative(root, file).split(path7.sep).join("/");
3368
+ try {
3369
+ const module = await importFile(file);
3370
+ if (!("default" in module)) bail("a data file needs a default export: the data, or a function that returns it");
3371
+ const value = module.default;
3372
+ return typeof value === "function" ? await settle(value()) : value;
3373
+ } catch (e) {
3374
+ throw new BuildError(`${name}: ${describeThrown(e, root)}`);
3375
+ }
3376
+ }
3377
+ var SETTINGS = ["dirs", "templateFormats", "markdownEngine", "htmlEngine", "markdown", "deepMerge", "leaveNoTrace", "clean", "ignore", "bundles", "strict", "lastModified", "base", "schemas", "theme", "serve", "budgets"];
3378
+ var PARTS = ["data", "filters", "collections", "transforms", "engines", "passthrough", "watch", "beforeBuild", "afterBuild", "plugins"];
3379
+ var CORE_ENGINES = ["edge", "md", "html", "txt"];
3380
+ var DIRS = ["input", "output", "includes", "layouts", "data"];
3381
+ var configOptions = () => [...SETTINGS, ...PARTS];
3382
+ var isObject2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
3383
+ var list = (v) => v === void 0 ? [] : [].concat(v);
3384
+ function meant(key, options) {
3385
+ const distance = (a, b) => {
3386
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
3387
+ for (let i = 0; i < a.length; i++) {
3388
+ let previous = row[0];
3389
+ row[0] = i + 1;
3390
+ for (let j = 0; j < b.length; j++) {
3391
+ const current2 = row[j + 1];
3392
+ row[j + 1] = a[i] === b[j] ? previous : 1 + Math.min(previous, current2, row[j]);
3393
+ previous = current2;
3394
+ }
3395
+ }
3396
+ return row[b.length];
3397
+ };
3398
+ let best;
3399
+ for (const option of options) {
3400
+ const edits = distance(String(key).toLowerCase(), option.toLowerCase());
3401
+ if (edits <= 2 && edits < option.length && (!best || edits < best.edits)) best = { edits, option };
3402
+ }
3403
+ return best ? ` (did you mean "${best.option}"?)` : "";
3404
+ }
3405
+ var configWord = (key) => find(key, "config");
3406
+ var fail = (message) => {
3407
+ throw new TypeError(message);
3408
+ };
3409
+ function aliased(part, where) {
3410
+ const words2 = Object.keys(part).filter((key) => configWord(key)?.alias);
3411
+ if (!words2.length) return part;
3412
+ const out = { ...part };
3413
+ const dirs = isObject2(part.dirs) ? { ...part.dirs } : part.dirs;
3414
+ const named = {};
3415
+ const twice = (name, word) => fail(`${where}: ${word} and ${named[name] ?? name} are two names for one option; set one of them`);
3416
+ for (const word of words2) {
3417
+ const row = configWord(word);
3418
+ const name = row.ssqch;
3419
+ const value = part[word];
3420
+ delete out[word];
3421
+ if (name === "dirs") {
3422
+ if (!isObject2(value)) fail(`${where}: ${word} must be an object, like ${word}: { input: "src", output: "dist" }`);
3423
+ for (const [key, folder] of Object.entries(value)) {
3424
+ if (isObject2(dirs) && dirs[key] !== void 0 || named[`dirs.${key}`]) twice(`dirs.${key}`, `${word}.${key}`);
3425
+ out.dirs = isObject2(out.dirs) ? out.dirs : { ...isObject2(dirs) ? dirs : {} };
3426
+ out.dirs[key] = folder;
3427
+ named[`dirs.${key}`] = `${word}.${key}`;
3428
+ }
3429
+ } else if (name.startsWith("dirs.")) {
3430
+ const key = name.slice(5);
3431
+ if (isObject2(dirs) && dirs[key] !== void 0 || named[name]) twice(name, word);
3432
+ out.dirs = isObject2(out.dirs) ? out.dirs : { ...isObject2(dirs) ? dirs : {} };
3433
+ out.dirs[key] = value;
3434
+ named[name] = word;
3435
+ } else {
3436
+ if (part[name] !== void 0 || named[name]) twice(name, word);
3437
+ out[name] = value;
3438
+ named[name] = word;
3439
+ }
3440
+ aliasUsed(row);
3441
+ }
3442
+ return out;
3443
+ }
3444
+ var BUILTINS = /* @__PURE__ */ new Map();
3445
+ var BUILTIN_NAMES = ["ssqch/rss", "ssqch/image", "ssqch/minify", "ssqch/assets", "ssqch/links", "ssqch/sitemap", "ssqch/redirects", "ssqch/sass", "ssqch/elements"];
3446
+ async function loadJs(config, file) {
3447
+ const name = path7.basename(file);
3448
+ const { root, env, serving } = config;
3449
+ loadedFiles.add(file);
3450
+ const settings = {};
3451
+ const ops = [];
3452
+ const names = { data: /* @__PURE__ */ new Map(), filters: /* @__PURE__ */ new Map(), collections: /* @__PURE__ */ new Map(), transforms: /* @__PURE__ */ new Map(), engines: /* @__PURE__ */ new Map() };
3453
+ const argument = new Proxy(Object.freeze({ env, serving }), {
3454
+ get(target, key, receiver) {
3455
+ const equivalent = typeof key === "string" && !(key in target) ? configWord(key) : void 0;
3456
+ if (equivalent) fail(`the config function's argument has no ${String(key)}(): an ssqch config returns an object. ${equivalent.say}
3457
+ More: ${equivalent.more}`);
3458
+ return Reflect.get(target, key, receiver);
3459
+ }
3460
+ });
3461
+ const claim = (kind, singular, key, where) => {
3462
+ const earlier = names[kind].get(key);
3463
+ if (earlier) fail(`${where}: ${singular} "${key}" is already defined by ${earlier}`);
3464
+ names[kind].set(key, where);
3465
+ };
3466
+ const functions = (kind, singular, value, where, add) => {
3467
+ if (value === void 0) return;
3468
+ if (!isObject2(value)) fail(`${where}: ${kind} must be an object of { name: function }`);
3469
+ for (const [key, fn] of Object.entries(value)) {
3470
+ if (typeof fn !== "function") fail(`${where}: ${kind}.${key} must be a function`);
3471
+ claim(kind, singular, key, where);
3472
+ add(key, fn);
3473
+ }
3474
+ };
3475
+ const hooks = (event, value, where) => {
3476
+ for (const hook of list(value)) {
3477
+ if (isObject2(hook)) {
3478
+ for (const key of Object.keys(hook)) {
3479
+ if (key !== "run") fail(`${where}: ${event}: "${key}" isn't an option (use { run: "command" })`);
3480
+ }
3481
+ if (!(typeof hook.run === "string" && hook.run.trim())) fail(`${where}: ${event}: run must be a command, like { run: "pagefind --site dist" }`);
3482
+ const run = hook.run;
3483
+ ops.push(() => {
3484
+ config[event].push({ run });
3485
+ });
3486
+ continue;
3487
+ }
3488
+ if (typeof hook !== "function") fail(`${where}: ${event} must be a function or { run: "command" } (or an array of them)`);
3489
+ const fn = hook;
3490
+ ops.push(() => {
3491
+ config[event].push({ label: `${event} (${where})`, fn });
3492
+ });
3493
+ }
3494
+ };
3495
+ async function apply(part, where, top) {
3496
+ if (typeof part === "function") part = await settle(part(argument));
3497
+ if (part === void 0 || part === null || part === false) return;
3498
+ if (!isObject2(part)) fail(`${where} must be an object (or a function that returns one)`);
3499
+ if ("builtin" in part) {
3500
+ const builtin = String(part.builtin);
3501
+ const options = part.options ?? {};
3502
+ ops.push(async () => {
3503
+ const register2 = BUILTINS.get(builtin);
3504
+ if (!register2) {
3505
+ if (BUILTIN_NAMES.includes(builtin)) bail(`plugin "${builtin}": this plugin isn't in the Node build of ssqch yet (the move to Node, stage 5)`);
3506
+ bail(`unknown plugin "${builtin}" (built-in plugins: ${BUILTIN_NAMES.join(", ")})`);
3507
+ }
3508
+ config.plugins.push(builtin);
3509
+ try {
3510
+ await register2(config, options);
3511
+ } catch (e) {
3512
+ throw context(e, `plugin "${builtin}"`);
3513
+ }
3514
+ });
3515
+ return;
3516
+ }
3517
+ if (top) part = aliased(part, where);
3518
+ const unknown = [];
3519
+ let guessed = false;
3520
+ for (const key of Object.keys(part)) {
3521
+ if ((key === "name" || key === "rust") && !top) continue;
3522
+ if (SETTINGS.includes(key)) {
3523
+ if (!top) fail(`${where}: "${key}" can only be set in the config itself, not in a plugin`);
3524
+ } else if (!PARTS.includes(key)) {
3525
+ const options = top ? [...SETTINGS, ...PARTS] : PARTS;
3526
+ const equivalent = configWord(key);
3527
+ if (equivalent?.alias) {
3528
+ unknown.push(`${where}: "${key}" can only be set in the config itself, not in a plugin (ssqch calls it ${equivalent.ssqch})`);
3529
+ continue;
3530
+ }
3531
+ if (equivalent) {
3532
+ unknown.push(`${where}: "${key}" isn't a config option. ${equivalent.say}
3533
+ More: ${equivalent.more}`);
3534
+ continue;
3535
+ }
3536
+ const hint = top && DIRS.includes(key) ? ` (it goes in dirs: { ${key}: "..." })` : meant(key, options);
3537
+ unknown.push(`${where}: "${key}" isn't a config option${hint}`);
3538
+ guessed = true;
3539
+ }
3540
+ }
3541
+ if (unknown.length) {
3542
+ const options = top ? [...SETTINGS, ...PARTS] : PARTS;
3543
+ fail(unknown.join("\n") + (guessed ? ` (options: ${options.join(", ")})` : ""));
3544
+ }
3545
+ if (!top && part.rust !== void 0) {
3546
+ const rust = loadRustPart(part.rust, where, root);
3547
+ if (rust.transform) {
3548
+ const [key, fn] = rust.transform;
3549
+ claim("transforms", "transform", key, where);
3550
+ ops.push(() => {
3551
+ config.transforms.push([key, fn]);
3552
+ });
3553
+ }
3554
+ for (const [key, fn] of rust.filters) {
3555
+ claim("filters", "filter", key, where);
3556
+ ops.push(() => {
3557
+ config.filters.set(key, fn);
3558
+ });
3559
+ }
3560
+ for (const [key, run] of rust.engines) {
3561
+ if (!/^[A-Za-z0-9_-]+$/.test(key)) fail(`${where}: engines.${key}: an engine's name is a file extension (letters, digits, - and _)`);
3562
+ if (CORE_ENGINES.includes(key)) fail(`${where}: engines.${key}: "${key}" is built in and can't be replaced`);
3563
+ claim("engines", "engine", key, where);
3564
+ ops.push(() => {
3565
+ config.engines.set(key, run);
3566
+ });
3567
+ }
3568
+ }
3569
+ if (top) {
3570
+ if (part.dirs !== void 0) {
3571
+ if (!isObject2(part.dirs)) fail(`${where}: dirs must be an object`);
3572
+ for (const [key, value] of Object.entries(part.dirs)) {
3573
+ if (!DIRS.includes(key)) fail(`${where}: dirs.${key} isn't supported${meant(key, DIRS)} (use ${DIRS.join(", ")})`);
3574
+ if (typeof value !== "string") fail(`${where}: dirs.${key} must be a string`);
3575
+ settings[key] = value;
3576
+ }
3577
+ }
3578
+ for (const key of SETTINGS.filter((k) => k !== "dirs")) {
3579
+ if (part[key] !== void 0) settings[key] = part[key];
3580
+ }
3581
+ }
3582
+ if (part.data !== void 0) {
3583
+ if (!isObject2(part.data)) fail(`${where}: data must be an object of { name: value or function }`);
3584
+ for (const [key, value] of Object.entries(part.data)) {
3585
+ claim("data", "data", key, where);
3586
+ ops.push(() => {
3587
+ config.globalData.push(typeof value === "function" ? { name: key, fn: value } : { name: key, value });
3588
+ });
3589
+ }
3590
+ }
3591
+ functions("filters", "filter", part.filters, where, (key, fn) => ops.push(() => {
3592
+ config.filters.set(key, fn);
3593
+ }));
3594
+ functions("collections", "collection", part.collections, where, (key, fn) => ops.push(() => {
3595
+ config.collections.push([key, fn]);
3596
+ }));
3597
+ functions("transforms", "transform", part.transforms, where, (key, fn) => {
3598
+ const run = async (content, page) => {
3599
+ const out = await settle(fn(content, page));
3600
+ if (typeof out !== "string") {
3601
+ throw new TypeError(`transform "${key}" returned ${out === void 0 ? "undefined" : typeof out} for ${page.outputPath}; return the content (unchanged if there's nothing to do)`);
3602
+ }
3603
+ return out;
3604
+ };
3605
+ ops.push(() => {
3606
+ config.transforms.push([key, run]);
3607
+ });
3608
+ });
3609
+ if (part.engines !== void 0) {
3610
+ if (!isObject2(part.engines)) fail(`${where}: engines must be an object of { extension: function or { render } }`);
3611
+ for (const [key, engine] of Object.entries(part.engines)) {
3612
+ const render = typeof engine === "function" ? engine : engine?.render;
3613
+ if (typeof render !== "function") fail(`${where}: engines.${key} must be a function (source, data) or an object with a render(source, data) method`);
3614
+ if (!/^[A-Za-z0-9_-]+$/.test(key)) fail(`${where}: engines.${key}: an engine's name is a file extension (letters, digits, - and _)`);
3615
+ if (CORE_ENGINES.includes(key)) fail(`${where}: engines.${key}: "${key}" is built in and can't be replaced`);
3616
+ claim("engines", "engine", key, where);
3617
+ const checked = (out, inputPath) => {
3618
+ if (typeof out !== "string") throw new TypeError(`engine "${key}" returned ${out === void 0 ? "undefined" : typeof out} for ${inputPath}; return the rendered text`);
3619
+ return out;
3620
+ };
3621
+ const run = (source, data, inputPath) => {
3622
+ const out = render.call(engine, source, data);
3623
+ return out instanceof Promise ? watchSettle(out).then((v) => checked(v, inputPath)) : checked(out, inputPath);
3624
+ };
3625
+ ops.push(() => {
3626
+ config.engines.set(key, run);
3627
+ });
3628
+ }
3629
+ }
3630
+ for (const entry of list(part.passthrough)) {
3631
+ if (typeof entry === "string") {
3632
+ ops.push(() => {
3633
+ config.passthrough.push({ from: entry });
3634
+ });
3635
+ } else if (isObject2(entry)) {
3636
+ for (const [from, to] of Object.entries(entry)) {
3637
+ if (typeof to !== "string") fail(`${where}: passthrough destination for "${from}" must be a string`);
3638
+ ops.push(() => {
3639
+ config.passthrough.push({ from, to });
3640
+ });
3641
+ }
3642
+ } else {
3643
+ fail(`${where}: passthrough entries must be paths or { from: to } objects`);
3644
+ }
3645
+ }
3646
+ for (const target of list(part.watch)) {
3647
+ if (typeof target !== "string") fail(`${where}: watch must be a path or an array of paths`);
3648
+ ops.push(() => {
3649
+ config.watch.push(target);
3650
+ });
3651
+ }
3652
+ hooks("beforeBuild", part.beforeBuild, where);
3653
+ hooks("afterBuild", part.afterBuild, where);
3654
+ const plugins = list(part.plugins);
3655
+ for (let i = 0; i < plugins.length; i++) {
3656
+ const plugin = plugins[i];
3657
+ const label = plugin?.name ? `plugin "${plugin.name}"` : `plugins[${i}]`;
3658
+ await apply(plugin, top ? label : `${where} > ${label}`, false);
3659
+ }
3660
+ }
3661
+ const inFile = (e) => {
3662
+ const message = describeThrown(e, root);
3663
+ return new BuildError(message.startsWith(`${name}:`) || message.startsWith(`${name} `) ? message : `${name}: ${message}`);
3664
+ };
3665
+ try {
3666
+ const module = await importFile(file);
3667
+ if (!("default" in module)) fail(`${name} needs a default export: export default defineConfig({ ... })`);
3668
+ await apply(module.default, name, true);
3669
+ } catch (e) {
3670
+ throw inFile(e);
3671
+ }
3672
+ try {
3673
+ applySettings(config, settings);
3674
+ for (const op of ops) await op();
3675
+ } catch (e) {
3676
+ throw new BuildError(`${name}: ${e instanceof BuildError ? e.message : describeThrown(e, root)}`);
3677
+ }
3678
+ }
3679
+ function applySettings(config, settings) {
3680
+ for (const key of DIRS) {
3681
+ const value = settings[key];
3682
+ if (value === void 0 || value === null) continue;
3683
+ if (typeof value !== "string") bail(`dirs.${key} must be a string, not ${typeof value}`);
3684
+ config[key] = value;
3685
+ }
3686
+ const formats = settings.templateFormats;
3687
+ if (typeof formats === "string") config.templateFormats = formats.split(",").map((f) => f.trim()).filter(Boolean);
3688
+ else if (Array.isArray(formats)) config.templateFormats = formats.map(String);
3689
+ else if (formats !== void 0) bail(`templateFormats must be an array or a comma-separated string, not ${typeof formats}`);
3690
+ for (const key of ["markdownEngine", "htmlEngine"]) {
3691
+ const value = settings[key];
3692
+ if (value === void 0) continue;
3693
+ if (value === false || value === null) config[key] = null;
3694
+ else if (typeof value === "string") config[key] = value === "" ? null : value;
3695
+ else bail(`${key} must be a string or false, not ${typeof value}`);
3696
+ }
3697
+ if (settings.markdown !== void 0) applyMarkdownOptions(config.markdown, settings.markdown);
3698
+ checkLanguages(config.markdown, config.root);
3699
+ if (settings.deepMerge !== void 0) {
3700
+ if (typeof settings.deepMerge !== "boolean") bail(`deepMerge must be true or false, not ${typeof settings.deepMerge}`);
3701
+ config.deepMerge = settings.deepMerge;
3702
+ }
3703
+ let trace;
3704
+ for (const key of ["leaveNoTrace", "clean"]) {
3705
+ const value = settings[key];
3706
+ if (value === void 0) continue;
3707
+ if (typeof value !== "boolean") bail(`${key} must be true or false, not ${typeof value}`);
3708
+ if (trace !== void 0) bail("leaveNoTrace and clean are two names for one option; set one of them");
3709
+ trace = value;
3710
+ }
3711
+ if (trace !== void 0) config.leaveNoTrace = trace;
3712
+ for (const key of ["bundles", "strict"]) {
3713
+ const value = settings[key];
3714
+ if (value === void 0) continue;
3715
+ if (typeof value !== "boolean") bail(`${key} must be true or false, not ${typeof value}`);
3716
+ config[key] = value;
3717
+ }
3718
+ const modified = settings.lastModified;
3719
+ if (modified === true) config.lastModified = "git";
3720
+ else if (modified === "git" || modified === "file") config.lastModified = modified;
3721
+ else if (typeof modified === "string") bail(`lastModified must be "git", "file" or false, not "${modified}"`);
3722
+ else if (modified !== void 0 && modified !== null && modified !== false) bail(`lastModified must be "git", "file" or false, not ${typeof modified}`);
3723
+ if (typeof settings.base === "string") config.base = normalizeBase(settings.base);
3724
+ else if (settings.base !== void 0 && settings.base !== null) bail(`base must be a URL path like "/docs/", not ${typeof settings.base}`);
3725
+ const theme = settings.theme;
3726
+ const themes = theme === void 0 || theme === null || theme === false ? [] : Array.isArray(theme) ? theme : [theme];
3727
+ for (const one of themes) addTheme(config, one);
3728
+ if (isObject2(settings.schemas)) {
3729
+ for (const [name, spec] of Object.entries(settings.schemas)) {
3730
+ const schema = parseSchema(name, spec);
3731
+ config.schemas = config.schemas.filter((s) => s.name !== name);
3732
+ config.schemas.push(schema);
3733
+ }
3734
+ } else if (settings.schemas !== void 0 && settings.schemas !== null) bail(`schemas must be an object of { name: { fields } }, not ${typeof settings.schemas}`);
3735
+ if (isObject2(settings.budgets)) config.budgets = Object.entries(settings.budgets).map(([name, size]) => budget(name, size));
3736
+ else if (settings.budgets !== void 0 && settings.budgets !== null) bail(`budgets must be an object, like { pages: "150 KB", images: "1 MB" }, not ${typeof settings.budgets}`);
3737
+ const serve = settings.serve;
3738
+ if (isObject2(serve)) {
3739
+ const unknown = Object.keys(serve).find((k) => k !== "run");
3740
+ if (unknown !== void 0) bail(`serve: "${unknown}" isn't an option (options: run)`);
3741
+ const run = serve.run;
3742
+ if (run === void 0 || run === null) config.serveRun = [];
3743
+ else if (typeof run === "string") config.serveRun = [run];
3744
+ else if (Array.isArray(run)) {
3745
+ config.serveRun = run.map((c) => typeof c === "string" && c.trim() !== "" ? c : bail('serve.run must be a command or an array of commands, like ["npx postcss src/app.css -o dist/app.css --watch"]'));
3746
+ } else bail(`serve.run must be a command or an array of commands, not ${typeof run}`);
3747
+ } else if (serve !== void 0 && serve !== null) bail(`serve must be an object, like { run: ["npx postcss ... --watch"] }, not ${typeof serve}`);
3748
+ const ignore = settings.ignore;
3749
+ if (typeof ignore === "string") config.ignore = [ignore];
3750
+ else if (Array.isArray(ignore)) config.ignore = ignore.map((g) => typeof g === "string" ? g : bail(`ignore must be a glob or an array of globs, not an array with ${typeof g}`));
3751
+ else if (ignore !== void 0) bail(`ignore must be a glob or an array of globs, not ${typeof ignore}`);
3752
+ }
3753
+ function addTheme(config, theme) {
3754
+ let dir;
3755
+ if (typeof theme === "string") dir = resolveTheme(config.root, theme, config.quiet);
3756
+ else if (isObject2(theme)) {
3757
+ const unknown = Object.keys(theme).find((k) => !["git", "ref", "dir"].includes(k));
3758
+ if (unknown !== void 0) bail(`theme: "${unknown}" isn't an option (options: git, ref, dir)`);
3759
+ const text = (key) => typeof theme[key] === "string" ? theme[key] : "";
3760
+ if (text("git") === "" || text("ref") === "") bail("theme: an object needs `git` (the repository's URL) and `ref` (the commit or tag to use)");
3761
+ dir = resolveTheme(config.root, { git: text("git"), ref: text("ref"), dir: text("dir") }, config.quiet);
3762
+ } else bail(`theme must be a folder, a git URL with #commit, or { git, ref, dir }, not ${typeof theme}`);
3763
+ if (!config.themes.includes(dir)) {
3764
+ config.watch.push(dir);
3765
+ config.themes.push(dir);
3766
+ }
3767
+ }
3768
+ var TOML_KEYS = ["input", "output", "includes", "layouts", "data", "template_formats", "markdown_engine", "html_engine", "data_deep_merge", "clean", "leave_no_trace", "ignore", "bundles", "strict", "base", "last_modified", "before_build", "after_build", "budgets", "serve", "theme", "schemas", "markdown", "passthrough"];
3769
+ function byName(table) {
3770
+ const out = {};
3771
+ for (const key of Object.keys(table).sort(compareText)) {
3772
+ const value = table[key];
3773
+ out[key] = isPlainObject(value) ? byName(value) : Array.isArray(value) ? value.map((v) => isPlainObject(v) ? byName(v) : v) : value;
3774
+ }
3775
+ return out;
3776
+ }
3777
+ function tomlText(v) {
3778
+ if (Array.isArray(v)) return `[${v.map(tomlText).join(", ")}]`;
3779
+ if (isPlainObject(v)) {
3780
+ const keys = Object.keys(v);
3781
+ return keys.length ? `{ ${keys.map((k) => `${/^[A-Za-z0-9_-]+$/.test(k) ? k : JSON.stringify(k)} = ${tomlText(v[k])}`).join(", ")} }` : "{}";
3782
+ }
3783
+ if (typeof v === "string") return JSON.stringify(v);
3784
+ if (typeof v === "number" && !Number.isFinite(v)) return Number.isNaN(v) ? "nan" : v > 0 ? "inf" : "-inf";
3785
+ return String(v);
3786
+ }
3787
+ function tomlKeyLine(text, at) {
3788
+ const lines = text.split(/\r?\n/);
3789
+ const escaped = (k) => k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3790
+ const isKey = (line, k) => new RegExp(`^\\s*(?:${escaped(k)}|"${escaped(k)}"|'${escaped(k)}')\\s*[=.]`).test(line);
3791
+ const header = (line) => /^\s*\[\[?\s*([^\]]*?)\s*\]/.exec(line)?.[1].replace(/["'\s]/g, "");
3792
+ let table = "";
3793
+ let found;
3794
+ for (let i = 0; i < lines.length && found === void 0; i++) {
3795
+ const name = header(lines[i]);
3796
+ if (name !== void 0) {
3797
+ table = name;
3798
+ if (name === at[0] || name.startsWith(`${at[0]}.`)) found = i + 1;
3799
+ continue;
3800
+ }
3801
+ if (table === "" && isKey(lines[i], at[0])) found = i + 1;
3802
+ }
3803
+ if (found !== void 0 && at.length > 1) {
3804
+ for (let i = found; i < lines.length && header(lines[i]) === void 0; i++) if (isKey(lines[i], at[1])) return i + 1;
3805
+ }
3806
+ return found;
3807
+ }
3808
+ function applyToml(config, file) {
3809
+ loadedFiles.add(file);
3810
+ const shown2 = /[\\/]$/.test(config.rootGiven) ? config.rootGiven + "sitesquatch.toml" : config.rootGiven + path7.sep + "sitesquatch.toml";
3811
+ let source = "";
3812
+ let at = [];
3813
+ const invalid = (e) => {
3814
+ const message = `invalid ${shown2}: ${e instanceof TomlError ? tomlReason(e) : messageOf(e)}`;
3815
+ const line = e instanceof TomlError ? e.line : at.length ? tomlKeyLine(source, at) : void 0;
3816
+ throw new BuildError(message, [error("config", message, { file: path7.relative(config.root, file), line })]);
3817
+ };
3818
+ let site2;
3819
+ try {
3820
+ source = fs7.readFileSync(file, "utf8");
3821
+ site2 = readToml(source);
3822
+ } catch (e) {
3823
+ return invalid(e);
3824
+ }
3825
+ try {
3826
+ const unknown = Object.keys(site2).find((k) => !TOML_KEYS.includes(k));
3827
+ at = unknown === void 0 ? [] : [unknown];
3828
+ if (unknown !== void 0) bail(`unknown field \`${unknown}\`, expected one of ${TOML_KEYS.map((k) => `\`${k}\``).join(", ")}`);
3829
+ const text = (key) => (at = [key], site2[key] === void 0 ? void 0 : typeof site2[key] === "string" ? site2[key] : bail(`${key} must be a string`));
3830
+ const flag = (key) => (at = [key], site2[key] === void 0 ? void 0 : typeof site2[key] === "boolean" ? site2[key] : bail(`${key} must be true or false`));
3831
+ const texts = (key) => (at = [key], site2[key] === void 0 ? void 0 : Array.isArray(site2[key]) && site2[key].every((v) => typeof v === "string") ? site2[key] : bail(`${key} must be an array of strings`));
3832
+ config.input = text("input") ?? config.input;
3833
+ config.output = text("output") ?? config.output;
3834
+ config.includes = text("includes") ?? config.includes;
3835
+ config.layouts = text("layouts") ?? config.layouts;
3836
+ config.data = text("data") ?? config.data;
3837
+ config.templateFormats = texts("template_formats") ?? config.templateFormats;
3838
+ for (const [key, slot] of [["markdown_engine", "markdownEngine"], ["html_engine", "htmlEngine"]]) {
3839
+ const value = text(key);
3840
+ if (value !== void 0) config[slot] = value === "" ? null : value;
3841
+ }
3842
+ config.deepMerge = flag("data_deep_merge") ?? config.deepMerge;
3843
+ at = ["clean"];
3844
+ if (site2.leave_no_trace !== void 0 && site2.clean !== void 0) bail("duplicate field `leave_no_trace`");
3845
+ config.leaveNoTrace = flag("leave_no_trace") ?? flag("clean") ?? config.leaveNoTrace;
3846
+ config.ignore = texts("ignore") ?? config.ignore;
3847
+ config.bundles = flag("bundles") ?? config.bundles;
3848
+ config.strict = flag("strict") ?? config.strict;
3849
+ const base = text("base");
3850
+ if (base !== void 0) config.base = normalizeBase(base);
3851
+ if (site2.budgets !== void 0) {
3852
+ at = ["budgets"];
3853
+ if (!isPlainObject(site2.budgets)) bail("budgets must be a table");
3854
+ for (const [name, value] of Object.entries(byName(site2.budgets))) {
3855
+ at = ["budgets", name];
3856
+ config.budgets.push(budget(name, Number.isInteger(value) || typeof value === "string" ? value : tomlText(value)));
3857
+ }
3858
+ }
3859
+ if (site2.serve !== void 0) {
3860
+ at = ["serve"];
3861
+ if (!isPlainObject(site2.serve)) bail("serve must be a table");
3862
+ const unknownServe = Object.keys(site2.serve).find((k) => k !== "run");
3863
+ if (unknownServe !== void 0) bail(`unknown field \`${unknownServe}\`, expected \`run\``);
3864
+ const run = site2.serve.run ?? [];
3865
+ if (!Array.isArray(run) || !run.every((command) => typeof command === "string")) bail('serve.run must be an array of commands, like run = ["npx postcss src/app.css -o dist/app.css --watch"]');
3866
+ config.serveRun = run;
3867
+ }
3868
+ for (const command of texts("before_build") ?? []) config.beforeBuild.push({ run: command });
3869
+ for (const command of texts("after_build") ?? []) config.afterBuild.push({ run: command });
3870
+ const modified = text("last_modified");
3871
+ if (modified !== void 0) {
3872
+ if (modified !== "git" && modified !== "file") bail('last_modified must be "git" or "file"');
3873
+ config.lastModified = modified;
3874
+ }
3875
+ if (site2.markdown !== void 0) {
3876
+ at = ["markdown"];
3877
+ if (!isPlainObject(site2.markdown)) bail("markdown must be a table");
3878
+ const camel = {};
3879
+ for (const [key, value] of Object.entries(site2.markdown)) camel[key.replace(/_(.)/g, (_, c) => c.toUpperCase())] = value;
3880
+ applyMarkdownOptions(config.markdown, camel);
3881
+ checkLanguages(config.markdown, config.root);
3882
+ }
3883
+ for (const theme of texts("theme") ?? []) addTheme(config, theme);
3884
+ if (site2.schemas !== void 0) {
3885
+ at = ["schemas"];
3886
+ if (!isPlainObject(site2.schemas)) bail("schemas must be a table");
3887
+ for (const [name, spec] of Object.entries(byName(site2.schemas))) {
3888
+ at = ["schemas", name];
3889
+ const schema = parseSchema(name, spec);
3890
+ config.schemas = config.schemas.filter((s) => s.name !== name);
3891
+ config.schemas.push(schema);
3892
+ }
3893
+ }
3894
+ if (site2.passthrough !== void 0) {
3895
+ at = ["passthrough"];
3896
+ if (!isPlainObject(site2.passthrough)) bail("passthrough must be a table");
3897
+ for (const from of Object.keys(site2.passthrough).sort()) {
3898
+ at = ["passthrough", from];
3899
+ const to = site2.passthrough[from];
3900
+ if (typeof to !== "string") bail(`passthrough: the destination for "${from}" must be a string`);
3901
+ config.passthrough.push(to === "" ? { from } : { from, to });
3902
+ }
3903
+ }
3904
+ } catch (e) {
3905
+ invalid(e);
3906
+ }
3907
+ }
3908
+
3909
+ export {
3910
+ rewriteHtml,
3911
+ withBase,
3912
+ cssWithBase,
3913
+ rewriteBase,
3914
+ schemaTypes,
3915
+ checkPages,
3916
+ blake3Hex,
3917
+ escapeHtml,
3918
+ debugString,
3919
+ isoDay,
3920
+ parseFormat,
3921
+ defaultImageOptions,
3922
+ imageOptionsFor,
3923
+ currentProcessor,
3924
+ addImagePlugin,
3925
+ compilePlugin,
3926
+ RustPlugin,
3927
+ wasi,
3928
+ DEFAULTS2 as DEFAULTS,
3929
+ findConfig,
3930
+ loadConfig,
3931
+ configOptions,
3932
+ meant,
3933
+ BUILTINS,
3934
+ tomlKeyLine
3935
+ };