@litfamily/litcodex 1.0.28 → 1.0.30

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 (170) hide show
  1. package/README-Ko-KR.md +10 -10
  2. package/README.md +10 -10
  3. package/dist/cli.js +1 -1
  4. package/dist/config-migration/cli.js +11 -3
  5. package/dist/install/generated-skill-payload-hashes.d.ts +59 -31
  6. package/dist/install/generated-skill-payload-hashes.js +59 -31
  7. package/dist/install/index.js +1 -1
  8. package/dist/install/marketplace.js +10 -1
  9. package/dist/install/motion-runtime.d.ts +4 -1
  10. package/dist/install/motion-runtime.js +15 -4
  11. package/dist/install/office-runtime.d.ts +10 -11
  12. package/dist/install/office-runtime.js +8 -3
  13. package/dist/install/skill-catalog.d.ts +1 -1
  14. package/dist/install/skill-catalog.js +1 -0
  15. package/dist/postinstall.js +4 -2
  16. package/marketplace/.agents/plugins/marketplace.json +4 -1
  17. package/marketplace/plugins/litcodex/.codex-plugin/plugin.json +14 -2
  18. package/marketplace/plugins/litcodex/assets/screenshot-lit-ignited.png +0 -0
  19. package/marketplace/plugins/litcodex/components/auto-update/dist/auto-update.d.ts +12 -0
  20. package/marketplace/plugins/litcodex/components/auto-update/dist/auto-update.js +31 -2
  21. package/marketplace/plugins/litcodex/components/auto-update/package.json +1 -1
  22. package/marketplace/plugins/litcodex/components/comment-checker/package.json +1 -1
  23. package/marketplace/plugins/litcodex/components/git-bash/package.json +1 -1
  24. package/marketplace/plugins/litcodex/components/lit-loop/directive.md +2 -1
  25. package/marketplace/plugins/litcodex/components/lit-loop/directives/deep-interview.md +2 -0
  26. package/marketplace/plugins/litcodex/components/lit-loop/directives/lit-brainstorm.md +216 -0
  27. package/marketplace/plugins/litcodex/components/lit-loop/directives/litgoal.md +8 -1
  28. package/marketplace/plugins/litcodex/components/lit-loop/directives/review-work.md +12 -4
  29. package/marketplace/plugins/litcodex/components/lit-loop/dist/codex-hook.d.ts +6 -1
  30. package/marketplace/plugins/litcodex/components/lit-loop/dist/codex-hook.js +16 -5
  31. package/marketplace/plugins/litcodex/components/lit-loop/dist/guards.d.ts +3 -1
  32. package/marketplace/plugins/litcodex/components/lit-loop/dist/guards.js +5 -2
  33. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.d.ts +2 -0
  34. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.js +26 -8
  35. package/marketplace/plugins/litcodex/components/lit-loop/dist/markers.d.ts +2 -0
  36. package/marketplace/plugins/litcodex/components/lit-loop/dist/markers.js +2 -0
  37. package/marketplace/plugins/litcodex/components/lit-loop/dist/modes.d.ts +1 -1
  38. package/marketplace/plugins/litcodex/components/lit-loop/dist/modes.js +9 -1
  39. package/marketplace/plugins/litcodex/components/lit-loop/dist/motion-route.js +2 -0
  40. package/marketplace/plugins/litcodex/components/lit-loop/dist/plan-persistence.d.ts +2 -0
  41. package/marketplace/plugins/litcodex/components/lit-loop/dist/plan-persistence.js +8 -0
  42. package/marketplace/plugins/litcodex/components/lit-loop/dist/reentry.d.ts +56 -0
  43. package/marketplace/plugins/litcodex/components/lit-loop/dist/reentry.js +171 -0
  44. package/marketplace/plugins/litcodex/components/lit-loop/dist/route-context.js +5 -2
  45. package/marketplace/plugins/litcodex/components/lit-loop/dist/route-heads.js +35 -15
  46. package/marketplace/plugins/litcodex/components/lit-loop/dist/skill-mention-scope.js +2 -0
  47. package/marketplace/plugins/litcodex/components/lit-loop/dist/trigger.d.ts +2 -2
  48. package/marketplace/plugins/litcodex/components/lit-loop/dist/trigger.js +17 -6
  49. package/marketplace/plugins/litcodex/components/lit-loop/dist/workflow-map.js +1 -0
  50. package/marketplace/plugins/litcodex/components/lit-loop/package.json +1 -1
  51. package/marketplace/plugins/litcodex/components/lsp/package.json +1 -1
  52. package/marketplace/plugins/litcodex/components/rules/dist/model-metadata.d.ts +16 -0
  53. package/marketplace/plugins/litcodex/components/rules/dist/model-metadata.js +37 -1
  54. package/marketplace/plugins/litcodex/components/rules/node_modules/picomatch/README.md +15 -21
  55. package/marketplace/plugins/litcodex/components/rules/node_modules/picomatch/lib/parse.js +49 -10
  56. package/marketplace/plugins/litcodex/components/rules/node_modules/picomatch/lib/picomatch.js +14 -2
  57. package/marketplace/plugins/litcodex/components/rules/node_modules/picomatch/lib/scan.js +30 -18
  58. package/marketplace/plugins/litcodex/components/rules/node_modules/picomatch/package.json +3 -2
  59. package/marketplace/plugins/litcodex/components/rules/package.json +1 -1
  60. package/marketplace/plugins/litcodex/components/start-work-continuation/package.json +1 -1
  61. package/marketplace/plugins/litcodex/components/telemetry/package.json +1 -1
  62. package/marketplace/plugins/litcodex/components/wikify-knowledge/package.json +1 -1
  63. package/marketplace/plugins/litcodex/skills/browser-drive/scripts/capability-probe.mjs +24 -4
  64. package/marketplace/plugins/litcodex/skills/deep-interview/SKILL.md +3 -1
  65. package/marketplace/plugins/litcodex/skills/lit-brainstorm/SKILL.md +271 -0
  66. package/marketplace/plugins/litcodex/skills/lit-brainstorm/agents/openai.yaml +6 -0
  67. package/marketplace/plugins/litcodex/skills/lit-diagram-drawer/scripts/doctor.mjs +4 -3
  68. package/marketplace/plugins/litcodex/skills/lit-diagram-drawer/scripts/export.mjs +6 -5
  69. package/marketplace/plugins/litcodex/skills/lit-diagram-drawer/scripts/runtime-probes.mjs +25 -0
  70. package/marketplace/plugins/litcodex/skills/lit-docx/scripts/convert_md_to_pdf.py +31 -1
  71. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/acs/template.tex +2 -0
  72. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/elsevier/template.tex +2 -0
  73. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/ieee/template.tex +2 -0
  74. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/korean-generic/template.tex +2 -0
  75. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/nature/template.tex +2 -0
  76. package/marketplace/plugins/litcodex/skills/lit-loop/SKILL.md +8 -1
  77. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/office-run.mjs +42 -10
  78. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/SKILL.md +11 -9
  79. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/agents/openai.yaml +3 -0
  80. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/THIRD_PARTY_NOTICES +4 -0
  81. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/constants.mjs +38 -0
  82. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-assets.mjs +113 -0
  83. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-capture.mjs +161 -0
  84. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-gate.mjs +327 -0
  85. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-image.mjs +136 -0
  86. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-init.js +43 -0
  87. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-sheet.mjs +69 -0
  88. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-treatment.mjs +102 -0
  89. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-worker.mjs +21 -0
  90. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover.mjs +352 -0
  91. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/driver.mjs +19 -1
  92. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/fonts.mjs +11 -0
  93. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/look.mjs +128 -2
  94. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/loop-kit.js +104 -0
  95. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/runtime.mjs +92 -18
  96. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/stage.mjs +2 -0
  97. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/treatment.mjs +3 -2
  98. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/webp.mjs +140 -0
  99. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/fonts/jetbrains-mono/JetBrainsMono-wght-latin.woff2 +0 -0
  100. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/fonts/jetbrains-mono/OFL.txt +93 -0
  101. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/card-scenes/expected.json +16 -0
  102. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/card-scenes/index.html +42 -0
  103. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/reset-sweep/expected.json +16 -0
  104. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/reset-sweep/index.html +27 -0
  105. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/still-glow/expected.json +17 -0
  106. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/still-glow/index.html +29 -0
  107. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/title-slam/expected.json +17 -0
  108. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/title-slam/index.html +44 -0
  109. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/orbit-loop/expected.json +67 -0
  110. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/orbit-loop/index.html +182 -0
  111. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/painted-light/expected.json +95 -0
  112. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/painted-light/index.html +231 -0
  113. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/weight-tide/expected.json +67 -0
  114. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/weight-tide/index.html +103 -0
  115. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/cover.md +389 -0
  116. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/quality-gate.md +4 -0
  117. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/runtime.md +7 -6
  118. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/stage.md +3 -1
  119. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/treatment.md +2 -0
  120. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/runtime/requirements-audio.txt +3 -3
  121. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/scripts/render.mjs +37 -5
  122. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/scripts/runtime.mjs +1 -1
  123. package/marketplace/plugins/litcodex/skills/litgoal/SKILL.md +8 -3
  124. package/marketplace/plugins/litcodex/skills/lsp-setup/SKILL.md +2 -1
  125. package/marketplace/plugins/litcodex/skills/lsp-setup/scripts/verify-lsp.ts +43 -7
  126. package/marketplace/plugins/litcodex/skills/readme-studio/templates/hyperframes-cover/package-lock.json +3 -3
  127. package/marketplace/plugins/litcodex/skills/readme-studio/templates/remotion-cover/package-lock.json +3 -3
  128. package/marketplace/plugins/litcodex/skills/review-work/SKILL.md +21 -4
  129. package/node_modules/@litcodex/lit-loop/CHANGELOG.md +7 -0
  130. package/node_modules/@litcodex/lit-loop/README.md +6 -0
  131. package/node_modules/@litcodex/lit-loop/directive.md +2 -1
  132. package/node_modules/@litcodex/lit-loop/directives/deep-interview.md +2 -0
  133. package/node_modules/@litcodex/lit-loop/directives/lit-brainstorm.md +216 -0
  134. package/node_modules/@litcodex/lit-loop/directives/litgoal.md +8 -1
  135. package/node_modules/@litcodex/lit-loop/directives/review-work.md +12 -4
  136. package/node_modules/@litcodex/lit-loop/dist/codex-hook.d.ts +6 -1
  137. package/node_modules/@litcodex/lit-loop/dist/codex-hook.js +16 -5
  138. package/node_modules/@litcodex/lit-loop/dist/guards.d.ts +3 -1
  139. package/node_modules/@litcodex/lit-loop/dist/guards.js +5 -2
  140. package/node_modules/@litcodex/lit-loop/dist/hook-cli.d.ts +2 -0
  141. package/node_modules/@litcodex/lit-loop/dist/hook-cli.js +26 -8
  142. package/node_modules/@litcodex/lit-loop/dist/markers.d.ts +2 -0
  143. package/node_modules/@litcodex/lit-loop/dist/markers.js +2 -0
  144. package/node_modules/@litcodex/lit-loop/dist/modes.d.ts +1 -1
  145. package/node_modules/@litcodex/lit-loop/dist/modes.js +9 -1
  146. package/node_modules/@litcodex/lit-loop/dist/motion-route.js +2 -0
  147. package/node_modules/@litcodex/lit-loop/dist/plan-persistence.d.ts +2 -0
  148. package/node_modules/@litcodex/lit-loop/dist/plan-persistence.js +8 -0
  149. package/node_modules/@litcodex/lit-loop/dist/reentry.d.ts +56 -0
  150. package/node_modules/@litcodex/lit-loop/dist/reentry.js +171 -0
  151. package/node_modules/@litcodex/lit-loop/dist/route-context.js +5 -2
  152. package/node_modules/@litcodex/lit-loop/dist/route-heads.js +35 -15
  153. package/node_modules/@litcodex/lit-loop/dist/skill-mention-scope.js +2 -0
  154. package/node_modules/@litcodex/lit-loop/dist/trigger.d.ts +2 -2
  155. package/node_modules/@litcodex/lit-loop/dist/trigger.js +17 -6
  156. package/node_modules/@litcodex/lit-loop/dist/workflow-map.js +1 -0
  157. package/node_modules/@litcodex/lit-loop/package.json +1 -1
  158. package/node_modules/@litcodex/lit-loop/skills/browser-drive/scripts/capability-probe.mjs +24 -4
  159. package/node_modules/@litcodex/lit-loop/skills/deep-interview/SKILL.md +3 -1
  160. package/node_modules/@litcodex/lit-loop/skills/lit-brainstorm/SKILL.md +271 -0
  161. package/node_modules/@litcodex/lit-loop/skills/lit-loop/SKILL.md +8 -1
  162. package/node_modules/@litcodex/lit-loop/skills/litgoal/SKILL.md +8 -3
  163. package/node_modules/@litcodex/lit-loop/skills/review-work/SKILL.md +21 -4
  164. package/package.json +2 -2
  165. package/readme-assets/badge-version.svg +1 -1
  166. package/readme-assets/cover-motion-still.webp +0 -0
  167. package/readme-assets/cover-motion.webp +0 -0
  168. package/readme-assets/cover.webp +0 -0
  169. package/readme-assets/litfamily-machines.png +0 -0
  170. package/readme-assets/skills/lit-brainstorm.webp +0 -0
@@ -0,0 +1,161 @@
1
+ // Cover capture, the browser side. One headless Chrome per pass on the stage path's software rung, its
2
+ // viewport the cover page's CSS size at device scale 2, the cover folder served on the synthetic
3
+ // stage origin (kit, loop kit, faces, nothing else), and the cover init script injected before any page
4
+ // script. The renderer SEEKS: it calls window.renderFrame(t, { mask }) for any t in [0, 1) in any
5
+ // order, captures the surface, and a worker pool downsamples each capture to the cover size. The
6
+ // master, the replay (G0) and the seek-order check each open their own CoverSession.
7
+ import { readFileSync, rmSync } from "node:fs";
8
+ import { availableParallelism } from "node:os";
9
+ import { join } from "node:path";
10
+ import { Worker } from "node:worker_threads";
11
+ import { EXIT, Exit, STAGE_ORIGIN } from "./constants.mjs";
12
+ import { launchCover } from "./driver.mjs";
13
+ import { SKILL_ROOT } from "./fonts.mjs";
14
+ import { firstLine } from "./runtime.mjs";
15
+ import { stageRouter } from "./stage.mjs";
16
+
17
+ const COVER_INIT = () => readFileSync(join(SKILL_ROOT, "engine", "cover-init.js"), "utf8");
18
+ const pause = (ms) => new Promise((done) => setTimeout(done, ms));
19
+
20
+ export class CoverSession {
21
+ /** Open the cover page and wait until it sets window.ready and defines window.renderFrame. */
22
+ static async open({ runtime, scan, fonts, width, height, scale, profileDir, env = process.env }) {
23
+ const { context, page } = await launchCover({ runtime, width, height, scale, profileDir, env });
24
+ const session = new CoverSession({ context, page, width, height, scale, profileDir });
25
+ try {
26
+ await context.route("**/*", stageRouter({ root: scan.root, fonts, record: session.record }));
27
+ await context.addInitScript({ content: COVER_INIT() });
28
+ page.on("pageerror", (error) => session.record.pageErrors.push(firstLine(error.message)));
29
+ await page.goto(`${STAGE_ORIGIN}/index.html`, { waitUntil: "load", timeout: 60000 });
30
+ session.cdp = await context.newCDPSession(page);
31
+ await session.#waitReady();
32
+ return session;
33
+ } catch (error) {
34
+ await session.close();
35
+ throw error;
36
+ }
37
+ }
38
+
39
+ constructor({ context, page, width, height, scale, profileDir }) {
40
+ Object.assign(this, { context, page, width, height, scale, profileDir });
41
+ this.record = { blocked: [], rejected: [], missing: [], pageErrors: [] };
42
+ }
43
+
44
+ async #waitReady() {
45
+ const deadline = Date.now() + 60000;
46
+ for (;;) {
47
+ const state = await this.page.evaluate(() => [document.readyState, window.ready === true, typeof window.renderFrame]).catch(() => ["loading", false, "undefined"]);
48
+ if (state[0] === "complete" && state[1]) {
49
+ await this.check("while loading");
50
+ if (state[2] !== "function") throw new Exit(EXIT.STAGE_CONTRACT_ERROR, "STAGE_CONTRACT_ERROR: the cover page set window.ready but defines no window.renderFrame(t)");
51
+ return;
52
+ }
53
+ // A page that threw before it was ready never recovers; say why now, not after the 60 s wait.
54
+ if (this.record.pageErrors.length) {
55
+ await this.check("while loading");
56
+ throw new Exit(EXIT.STAGE_CONTRACT_ERROR, `STAGE_CONTRACT_ERROR: the cover page threw before it was ready; first page error: ${this.record.pageErrors[0]}`);
57
+ }
58
+ if (Date.now() > deadline) {
59
+ await this.check("while loading");
60
+ const why = this.record.pageErrors[0] ? `; first page error: ${this.record.pageErrors[0]}` : state[0] === "complete" ? "; it never set window.ready = true" : "";
61
+ throw new Exit(EXIT.STAGE_CONTRACT_ERROR, `STAGE_CONTRACT_ERROR: the cover page was not ready within 60 s${why}`);
62
+ }
63
+ await pause(50);
64
+ }
65
+ }
66
+
67
+ /** Raise the named exit for anything the page did that a cover page may not do. */
68
+ async check(context) {
69
+ if (this.record.blocked.length) throw new Exit(EXIT.STAGE_NETWORK_REQUEST, `STAGE_NETWORK_REQUEST: the cover page requested ${this.record.blocked[0].slice(0, 160)}; every asset is a local file in cover/`);
70
+ if (this.record.rejected.length) throw new Exit(EXIT.STAGE_CONTRACT_ERROR, `STAGE_CONTRACT_ERROR: the cover page requested ${this.record.rejected[0]}, which is outside the cover folder or not an allowed asset`);
71
+ const calls = await this.page.evaluate(() => (window.__litCoverCalls ? window.__litCoverCalls() : [])).catch(() => []);
72
+ if (calls.length) throw new Exit(EXIT.STAGE_NONDETERMINISTIC, `STAGE_NONDETERMINISTIC: the cover page called ${calls.join(", ")} ${context}; a cover frame is a function of t alone (LitLoop.rng(seed) for layout)`);
73
+ }
74
+
75
+ /** Draw loop time t (or its title mask) and let fonts settle. */
76
+ async frame(t, { mask = false } = {}) {
77
+ try {
78
+ await this.page.evaluate(
79
+ async ({ time, asMask }) => {
80
+ await window.renderFrame(time, { mask: asMask });
81
+ await document.fonts.ready;
82
+ },
83
+ { time: t, asMask: mask },
84
+ );
85
+ } catch (error) {
86
+ await this.check(`at t = ${t.toFixed(4)}`);
87
+ throw new Exit(EXIT.STAGE_CONTRACT_ERROR, `STAGE_CONTRACT_ERROR: renderFrame(${t.toFixed(4)}${mask ? ", { mask: true }" : ""}) threw: ${firstLine(error.message)}`);
88
+ }
89
+ await this.check(`at t = ${t.toFixed(4)}`);
90
+ }
91
+
92
+ /** The surface as composited: a PNG of (width x scale) by (height x scale). */
93
+ async capture() {
94
+ const shot = await this.cdp.send("Page.captureScreenshot", { format: "png", optimizeForSpeed: true, captureBeyondViewport: false, fromSurface: true, clip: { x: 0, y: 0, width: this.width, height: this.height, scale: 1 } });
95
+ return Buffer.from(shot.data, "base64");
96
+ }
97
+
98
+ async close() {
99
+ await this.context?.close().catch(() => {});
100
+ rmSync(this.profileDir, { recursive: true, force: true });
101
+ }
102
+ }
103
+
104
+ /** Worker threads that downsample and write captures; each job resolves with its PNG's hash. */
105
+ export class CoverPool {
106
+ constructor(size = Math.max(2, Math.min(6, availableParallelism() - 2))) {
107
+ this.workers = Array.from({ length: size }, () => new Worker(new URL("./cover-worker.mjs", import.meta.url)));
108
+ this.next = 0;
109
+ this.id = 0;
110
+ this.waiting = new Map();
111
+ for (const worker of this.workers) {
112
+ worker.on("message", (message) => {
113
+ const waiter = this.waiting.get(message.id);
114
+ this.waiting.delete(message.id);
115
+ if (message.error) waiter.reject(new Error(message.error));
116
+ else waiter.resolve(message);
117
+ });
118
+ worker.on("error", (error) => {
119
+ for (const waiter of this.waiting.values()) waiter.reject(error);
120
+ this.waiting.clear();
121
+ });
122
+ }
123
+ }
124
+
125
+ downsample(png, width, height, file) {
126
+ const id = this.id++;
127
+ const worker = this.workers[this.next++ % this.workers.length];
128
+ const copy = png.buffer.slice(png.byteOffset, png.byteOffset + png.byteLength);
129
+ return new Promise((resolve, reject) => {
130
+ this.waiting.set(id, { resolve, reject });
131
+ worker.postMessage({ id, png: copy, width, height, file }, [copy]);
132
+ });
133
+ }
134
+
135
+ async close() {
136
+ await Promise.all(this.workers.map((worker) => worker.terminate()));
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Capture `times` ([index, t] pairs, in the order given) into `dir` as `<prefix>NNNN.png` at the
142
+ * cover size. Returns Map index -> SHA-256 of the written PNG.
143
+ */
144
+ export async function capturePass({ session, pool, times, dir, prefix = "f", mask = false, size: [width, height] }) {
145
+ const hashes = new Map();
146
+ const pending = [];
147
+ const expected = `${session.width * session.scale}x${session.height * session.scale}`;
148
+ for (const [index, t] of times) {
149
+ await session.frame(t, { mask });
150
+ const png = await session.capture();
151
+ const job = pool.downsample(png, width, height, join(dir, `${prefix}${String(index).padStart(4, "0")}.png`)).then((done) => {
152
+ if (done.captured !== expected) throw new Exit(EXIT.STAGE_CONTRACT_ERROR, `STAGE_CONTRACT_ERROR: captured ${done.captured}, expected ${expected} (the page must not resize its viewport)`);
153
+ hashes.set(index, done.sha256);
154
+ });
155
+ job.catch(() => {});
156
+ pending.push(job);
157
+ while (pending.length > 8) await pending.shift();
158
+ }
159
+ await Promise.all(pending);
160
+ return hashes;
161
+ }
@@ -0,0 +1,327 @@
1
+ // The cover gate, measured on the DECODED cover (the animated WebP a browser will show, or the GIF
2
+ // fallback), never only on the frames that went into the encoder: G0 determinism, G1 budget and loop,
3
+ // G2 motion energy, G3 anti-slide, G4 seam, G5 title contrast and G6 title cap height. The encoder
4
+ // merges identical frames into one long frame, so every motion number runs on a fixed time grid and
5
+ // a slide film cannot look busy by frame count. Two tiers: FLOOR fails a cover; TARGET is what cover
6
+ // mode delivers, and the strict verdict needs it, the 2 MiB size included. Thresholds: COVER in
7
+ // constants.mjs.
8
+ import { spawnSync } from "node:child_process";
9
+ import { createHash } from "node:crypto";
10
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { COVER } from "./constants.mjs";
13
+ import { lumaGrid } from "./cover-image.mjs";
14
+ import { decodePng } from "./image.mjs";
15
+ import { which } from "./runtime.mjs";
16
+ import { decodeWebp } from "./webp.mjs";
17
+
18
+ const median = (xs) => {
19
+ const s = [...xs].sort((a, b) => a - b);
20
+ const m = s.length >> 1;
21
+ return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
22
+ };
23
+ const quantile = (xs, p) => {
24
+ const s = [...xs].sort((a, b) => a - b);
25
+ return s[Math.min(s.length - 1, Math.max(0, Math.round(p * (s.length - 1))))];
26
+ };
27
+ const meanStep = (a, b) => {
28
+ let sum = 0;
29
+ for (let i = 0; i < a.length; i++) sum += Math.abs(a[i] - b[i]);
30
+ return sum / a.length / 255;
31
+ };
32
+
33
+ /** A PNG on disk as { width, height, rgba } (grey PNGs expand to RGBA). */
34
+ export function readPngRgba(file) {
35
+ const png = decodePng(readFileSync(file));
36
+ if (png.channels === 4) return { width: png.width, height: png.height, rgba: png.pixels };
37
+ const rgba = Buffer.alloc(png.width * png.height * 4, 255);
38
+ for (let i = 0; i < png.width * png.height; i++) rgba.fill(png.pixels[i], i * 4, i * 4 + 3);
39
+ return { width: png.width, height: png.height, rgba };
40
+ }
41
+
42
+ /** The `<prefix>NNNN.png` frames of a folder, in order. */
43
+ export const frameFiles = (dir, prefix = "f") => (dir && existsSync(dir) ? readdirSync(dir).filter((n) => n.startsWith(prefix) && n.endsWith(".png")).sort().map((n) => join(dir, n)) : []);
44
+
45
+ /** What a GIF's container says that a decoder pipe drops: per-frame delays (ms) and the loop count. */
46
+ export function gifTiming(bytes) {
47
+ if (bytes.toString("latin1", 0, 3) !== "GIF") throw new Error("not a GIF file");
48
+ const delays = [];
49
+ let loop = null;
50
+ let delay = 100;
51
+ const table = (flags) => (flags & 0x80 ? 3 * (1 << ((flags & 0x07) + 1)) : 0);
52
+ const skipSubBlocks = (p) => {
53
+ while (p < bytes.length && bytes[p] !== 0) p += bytes[p] + 1;
54
+ return p + 1;
55
+ };
56
+ let o = 13 + table(bytes[10]);
57
+ while (o < bytes.length && bytes[o] !== 0x3b) {
58
+ if (bytes[o] === 0x21) {
59
+ if (bytes[o + 1] === 0xf9) delay = 10 * bytes.readUInt16LE(o + 4);
60
+ if (bytes[o + 1] === 0xff && bytes.toString("latin1", o + 3, o + 14) === "NETSCAPE2.0") loop = bytes.readUInt16LE(o + 16);
61
+ o = skipSubBlocks(o + 2);
62
+ } else if (bytes[o] === 0x2c) {
63
+ o = skipSubBlocks(o + 10 + table(bytes[o + 9]) + 1);
64
+ delays.push(delay > 0 ? delay : 100);
65
+ delay = 100;
66
+ } else break;
67
+ }
68
+ return { delays, loop, width: bytes.readUInt16LE(6), height: bytes.readUInt16LE(8) };
69
+ }
70
+
71
+ /**
72
+ * Read a cover for the gate: { lumas, delays, width, height, loop, bytes, format, kept }. `keep(i, ms)`
73
+ * runs once per decoded frame, in order, and picks the frames kept whole (RGBA) for the stills and the
74
+ * frame-0 checks. A folder of PNG frames is read at `fps` (no container, so no G1).
75
+ */
76
+ export function loadCover(input, { fps = 16, keep = () => false, env = process.env } = {}) {
77
+ const lumas = [];
78
+ const kept = new Map();
79
+ const take = (i, rgba, ms, width, height) => {
80
+ lumas.push(lumaGrid(rgba, width, height).luma);
81
+ if (keep(i, ms)) kept.set(i, Buffer.from(rgba));
82
+ };
83
+ if (statSync(input).isDirectory()) {
84
+ const files = frameFiles(input);
85
+ let size = [0, 0];
86
+ files.forEach((file, i) => {
87
+ const img = readPngRgba(file);
88
+ size = [img.width, img.height];
89
+ take(i, img.rgba, 1000 / fps, img.width, img.height);
90
+ });
91
+ return { lumas, delays: files.map(() => 1000 / fps), width: size[0], height: size[1], loop: 0, bytes: null, format: "png", kept };
92
+ }
93
+ if (input.toLowerCase().endsWith(".gif")) {
94
+ const bytes = readFileSync(input);
95
+ const timing = gifTiming(bytes);
96
+ const ffmpeg = which("ffmpeg", env);
97
+ if (!ffmpeg) throw new Error("ffmpeg is needed to decode a GIF cover");
98
+ const raw = spawnSync(ffmpeg, ["-v", "error", "-i", input, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "pipe:1"], { maxBuffer: 2 ** 31, env });
99
+ if (raw.status !== 0) throw new Error(`ffmpeg could not decode ${input}: ${String(raw.stderr).trim().split("\n")[0]}`);
100
+ const size = timing.width * timing.height * 4;
101
+ for (let i = 0; (i + 1) * size <= raw.stdout.length; i++) take(i, raw.stdout.subarray(i * size, (i + 1) * size), timing.delays[i] ?? 100, timing.width, timing.height);
102
+ return { lumas, delays: timing.delays.slice(0, lumas.length), width: timing.width, height: timing.height, loop: timing.loop, bytes: bytes.length, format: "gif", kept };
103
+ }
104
+ const info = decodeWebp(input, { env, onFrame: (i, rgba, ms, width, height) => take(i, rgba, ms > 0 ? ms : 100, width, height) });
105
+ return { lumas, delays: info.durations.map((d) => (d > 0 ? d : 100)), width: info.width, height: info.height, loop: info.loop, bytes: info.bytes, format: "webp", kept };
106
+ }
107
+
108
+ /** The frame on screen at each multiple of `step` ms, given per-frame durations. */
109
+ export function resample(frames, delays, step) {
110
+ const total = delays.reduce((a, b) => a + b, 0);
111
+ const out = [];
112
+ let i = 0;
113
+ let end = delays[0];
114
+ for (let ms = 0; ms < total - 1e-6; ms += step) {
115
+ while (ms >= end && i < frames.length - 1) end += delays[++i];
116
+ out.push(frames[i]);
117
+ }
118
+ return out;
119
+ }
120
+
121
+ /** Motion numbers on the fixed grid. The loop is a ring: the seam (last to first) is one more step. */
122
+ export function motionMetrics({ lumas, delays }) {
123
+ const step = Math.max(COVER.gridMs, Math.min(...delays));
124
+ const grid = resample(lumas, delays, step);
125
+ const n = grid.length;
126
+ const steps = [];
127
+ for (let i = 1; i < n; i++) steps.push(meanStep(grid[i], grid[i - 1]));
128
+ const seam = meanStep(grid[0], grid[n - 1]);
129
+ const ring = [...steps, seam];
130
+ const medianD = median(ring);
131
+ const still = ring.map((d) => d < COVER.stillEps);
132
+ let longest = 0;
133
+ if (still.every(Boolean)) longest = n * step;
134
+ else {
135
+ const start = still.findIndex((s) => !s);
136
+ let run = 0;
137
+ for (let j = 1; j <= n; j++) {
138
+ run = still[(start + j - 1) % n] ? run + step : step;
139
+ longest = Math.max(longest, run);
140
+ }
141
+ }
142
+ const neighbours = n >= 4 ? (ring[n - 3] + ring[n - 2] + ring[0] + ring[1]) / 4 : medianD;
143
+ return {
144
+ gridFrames: n,
145
+ stepMs: step,
146
+ durationSec: (n * step) / 1000,
147
+ sourceDurationSec: delays.reduce((a, b) => a + b, 0) / 1000,
148
+ medianD,
149
+ p10D: quantile(ring, 0.1),
150
+ p90D: quantile(ring, 0.9),
151
+ movingFrac: ring.filter((d) => d >= COVER.stillEps).length / ring.length,
152
+ longestStillSec: longest / 1000,
153
+ spike: Math.max(...ring) / Math.max(medianD, COVER.stillEps),
154
+ seam,
155
+ seamLocal: seam / Math.max(COVER.stillEps, neighbours),
156
+ diffs: ring,
157
+ };
158
+ }
159
+
160
+ const linear = (c) => {
161
+ const v = c / 255;
162
+ return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
163
+ };
164
+ const relativeLuminance = (r, g, b) => 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
165
+ const boxPx = (box, width, height) => box.map((v, k) => Math.round(v * (k % 2 ? height : width)));
166
+
167
+ /**
168
+ * G5 per frame: the median title pixel against the 90th-percentile background in the title box (or
169
+ * the 10th when the title is darker), where background is every box pixel at least 3 px from a title
170
+ * pixel. The title pixels come from the mask frame of the same time (white = title).
171
+ */
172
+ export function titleContrast({ framesDir, masksDir, box }) {
173
+ const frames = frameFiles(framesDir, "f");
174
+ const masks = frameFiles(masksDir, "m");
175
+ if (!frames.length || masks.length !== frames.length) return { measured: false, reason: `needs one mask per frame (${frames.length} frames, ${masks.length} masks)` };
176
+ const ratios = [];
177
+ for (let i = 0; i < frames.length; i++) {
178
+ const { width, height, rgba } = readPngRgba(frames[i]);
179
+ const mask = readPngRgba(masks[i]);
180
+ if (mask.width !== width || mask.height !== height) return { measured: false, reason: `mask ${i} is ${mask.width}x${mask.height}, the frame ${width}x${height}` };
181
+ const [bx, by, bw, bh] = boxPx(box, width, height);
182
+ const kind = new Uint8Array(width * height);
183
+ for (let p = 0; p < width * height; p++) if (mask.rgba[p * 4] > 127) kind[p] = 2;
184
+ for (let y = by; y < by + bh; y++)
185
+ for (let x = bx; x < bx + bw; x++) {
186
+ if (kind[y * width + x] !== 2) continue;
187
+ for (let dy = -3; dy <= 3; dy++)
188
+ for (let dx = -3; dx <= 3; dx++) {
189
+ const yy = y + dy;
190
+ const xx = x + dx;
191
+ if (yy >= 0 && yy < height && xx >= 0 && xx < width && kind[yy * width + xx] === 0) kind[yy * width + xx] = 1;
192
+ }
193
+ }
194
+ const title = [];
195
+ const ground = [];
196
+ for (let y = by; y < by + bh; y++)
197
+ for (let x = bx; x < bx + bw; x++) {
198
+ const p = (y * width + x) * 4;
199
+ const l = relativeLuminance(rgba[p], rgba[p + 1], rgba[p + 2]);
200
+ if (kind[y * width + x] === 2) title.push(l);
201
+ else if (kind[y * width + x] === 0) ground.push(l);
202
+ }
203
+ if (!title.length || !ground.length) return { measured: false, reason: `frame ${i}: the title box holds ${title.length} title and ${ground.length} background pixels` };
204
+ const t = median(title);
205
+ const g = t > median(ground) ? quantile(ground, 0.9) : quantile(ground, 0.1);
206
+ ratios.push((Math.max(t, g) + 0.05) / (Math.min(t, g) + 0.05));
207
+ }
208
+ return { measured: true, min: Math.min(...ratios), median: median(ratios), frames: ratios.length };
209
+ }
210
+
211
+ /**
212
+ * G6: the title's cap height at the README display width. In up to 12 mask frames, the white pixels
213
+ * inside the title box split into 4-connected glyphs; specks (under 1 % of the largest glyph's area)
214
+ * and dots or accents (under 30 % of the tallest) are dropped, and the median height of the rest is
215
+ * that frame's cap height. The smallest, scaled from the cover width to `displayWidth`, must reach
216
+ * COVER.minCapPx. A title painted into declared base art is `exempt`: still measured, reported as INFO.
217
+ */
218
+ export function glyphHeights({ masksDir, box, displayWidth = COVER.displayWidth, exempt = null, samples = 12 }) {
219
+ const masks = frameFiles(masksDir, "m");
220
+ if (!masks.length) return { pass: false, reason: "no mask frames to measure the title on" };
221
+ const count = Math.min(samples, masks.length);
222
+ const picks = [...new Set(Array.from({ length: count }, (_, k) => Math.floor((k * masks.length) / count)))];
223
+ let cap = Number.POSITIVE_INFINITY;
224
+ let glyphs = 0;
225
+ let coverWidth = 0;
226
+ for (const i of picks) {
227
+ const mask = readPngRgba(masks[i]);
228
+ coverWidth = mask.width;
229
+ const [bx, by, bw, bh] = boxPx(box, mask.width, mask.height);
230
+ const on = new Uint8Array(bw * bh);
231
+ for (let y = 0; y < bh; y++) for (let x = 0; x < bw; x++) on[y * bw + x] = mask.rgba[((by + y) * mask.width + bx + x) * 4] > 127 ? 1 : 0;
232
+ const parts = [];
233
+ for (let seed = 0; seed < on.length; seed++) {
234
+ if (on[seed] !== 1) continue;
235
+ on[seed] = 2;
236
+ const stack = [seed];
237
+ let area = 0;
238
+ let top = bh;
239
+ let bottom = -1;
240
+ while (stack.length) {
241
+ const q = stack.pop();
242
+ const y = Math.floor(q / bw);
243
+ const x = q - y * bw;
244
+ area++;
245
+ top = Math.min(top, y);
246
+ bottom = Math.max(bottom, y);
247
+ for (const next of [x > 0 ? q - 1 : -1, x < bw - 1 ? q + 1 : -1, y > 0 ? q - bw : -1, y < bh - 1 ? q + bw : -1])
248
+ if (next >= 0 && on[next] === 1) {
249
+ on[next] = 2;
250
+ stack.push(next);
251
+ }
252
+ }
253
+ parts.push({ area, height: bottom - top + 1 });
254
+ }
255
+ if (!parts.length) return { pass: false, reason: `mask ${i}: no title pixels in the title box` };
256
+ const biggest = Math.max(...parts.map((p) => p.area));
257
+ const tallest = Math.max(...parts.map((p) => p.height));
258
+ const letters = parts.filter((p) => p.area >= 0.01 * biggest && p.height >= 0.3 * tallest);
259
+ glyphs = Math.max(glyphs, letters.length);
260
+ cap = Math.min(cap, median(letters.map((p) => p.height)));
261
+ }
262
+ const capPx = Math.round(((cap * displayWidth) / coverWidth) * 10) / 10;
263
+ const result = { capPx, coverPx: cap, displayWidth, glyphs, sampled: picks.length };
264
+ if (exempt) return { pass: null, ...result, reason: exempt };
265
+ return { pass: capPx >= COVER.minCapPx, ...result };
266
+ }
267
+
268
+ /** G0: SHA-256 of every frame of two independent captures. */
269
+ export function determinism(dirA, dirB) {
270
+ const a = frameFiles(dirA, "f");
271
+ const b = frameFiles(dirB, "f");
272
+ const hash = (file) => createHash("sha256").update(readFileSync(file)).digest("hex");
273
+ const n = Math.min(a.length, b.length);
274
+ let identical = 0;
275
+ let firstDiffering = null;
276
+ for (let i = 0; i < n; i++) {
277
+ if (hash(a[i]) === hash(b[i])) identical++;
278
+ else firstDiffering ??= i;
279
+ }
280
+ return { compared: n, identical, countsMatch: a.length === b.length, firstDiffering };
281
+ }
282
+
283
+ /**
284
+ * Gate one cover file (or PNG folder). Options: frames + frames2 (two captures, G0), masks + title
285
+ * (G5, and G6 when `glyph` is given), fps (a PNG folder), keep (frames kept whole). Returns the metrics,
286
+ * the per-gate verdicts, `pass` (FLOOR) and `target` (TARGET).
287
+ */
288
+ export function coverGate(input, { frames = null, frames2 = null, masks = null, title = null, glyph = null, fps = 16, keep, env = process.env } = {}) {
289
+ const cover = loadCover(input, { fps, keep, env });
290
+ const m = motionMetrics(cover);
291
+ const F = COVER.floor;
292
+ const T = COVER.target;
293
+ const gates = {};
294
+ if (frames && frames2) {
295
+ const det = determinism(frames, frames2);
296
+ gates.G0 = { pass: det.countsMatch && det.compared > 0 && det.identical === det.compared, ...det };
297
+ }
298
+ if (cover.format !== "png")
299
+ gates.G1 = { pass: cover.bytes <= COVER.maxBytes && m.sourceDurationSec >= COVER.minSec && m.sourceDurationSec <= COVER.maxSec && cover.loop === 0, target: cover.bytes <= COVER.targetBytes, bytes: cover.bytes, durationSec: m.sourceDurationSec, loop: cover.loop, size: `${cover.width}x${cover.height}` };
300
+ gates.G2 = { pass: m.medianD >= F.medianD && m.movingFrac >= F.movingFrac, target: m.medianD >= T.medianD && m.movingFrac >= T.movingFrac, medianD: m.medianD, movingFrac: m.movingFrac };
301
+ gates.G3 = { pass: m.longestStillSec <= F.stillSec, target: m.longestStillSec <= T.stillSec && m.spike <= T.spike, longestStillSec: m.longestStillSec, spike: m.spike };
302
+ gates.G4 = { pass: m.seamLocal <= F.seamLocal, target: m.seamLocal >= T.seamLow && m.seamLocal <= T.seamHigh, seam: m.seam, seamLocal: m.seamLocal };
303
+ if (title && frames) {
304
+ const c = titleContrast({ framesDir: frames, masksDir: masks, box: title });
305
+ gates.G5 = c.measured ? { pass: c.min >= COVER.minContrast, min: c.min, median: c.median, frames: c.frames } : { pass: false, reason: c.reason };
306
+ }
307
+ if (title && masks && glyph) gates.G6 = glyphHeights({ masksDir: masks, box: title, displayWidth: glyph.displayWidth ?? COVER.displayWidth, exempt: glyph.exempt ?? null });
308
+ const pass = Object.values(gates).every((g) => g.pass !== false);
309
+ const target = pass && Object.values(gates).every((g) => g.target !== false);
310
+ return { input, format: cover.format, width: cover.width, height: cover.height, bytes: cover.bytes, loop: cover.loop, sourceFrames: cover.lumas.length, durations: cover.delays, ...m, gates, pass, target, kept: cover.kept };
311
+ }
312
+
313
+ const show = (x) => (typeof x === "number" && !Number.isInteger(x) ? Number(x.toPrecision(4)) : x);
314
+
315
+ /** The verdict word for a gate result. */
316
+ export const verdictOf = (r) => (r.pass ? (r.target ? "PASS+TARGET" : "PASS(floor)") : "FAIL");
317
+
318
+ /** The report: the verdict line, the size line and one line per gate. */
319
+ export function formatCoverReport(r, { strict = false } = {}) {
320
+ const lines = [`COVER gate${strict ? " --strict" : ""}: ${verdictOf(r)}`, ` ${r.width}x${r.height} ${r.format} frames=${r.sourceFrames} dur=${show(r.sourceDurationSec)}s bytes=${r.bytes ?? "-"} loop=${r.loop} grid=${r.stepMs}ms`];
321
+ for (const [name, gate] of Object.entries(r.gates)) {
322
+ const { pass, target, ...detail } = gate;
323
+ const word = pass === null ? "INFO" : pass === false ? "FAIL" : target === false ? "pass(floor)" : "pass";
324
+ lines.push(` ${name} ${word} ${Object.entries(detail).map(([k, v]) => `${k}=${show(v)}`).join(" ")}`);
325
+ }
326
+ return `${lines.join("\n")}\n`;
327
+ }
@@ -0,0 +1,136 @@
1
+ // Pixel helpers for cover mode, on RGBA8 buffers: the separable Lanczos-3 resize that takes the 2x
2
+ // seek capture down to the cover size, the gate's luma grid (Rec. 709 weights on the gamma values,
3
+ // box-averaged to about COVER.lumaWidth wide, so every motion number is a thumbnail-scale number), a
4
+ // rectangle crop, and a tile SSIM on luma for the frame-0 base-art check.
5
+ import { COVER } from "./constants.mjs";
6
+
7
+ const sinc3 = (x) => {
8
+ if (x === 0) return 1;
9
+ if (Math.abs(x) >= 3) return 0;
10
+ const px = Math.PI * x;
11
+ return (3 * Math.sin(px) * Math.sin(px / 3)) / (px * px);
12
+ };
13
+
14
+ /** For each output index, the first source index and the normalized taps (the support widens when shrinking). */
15
+ function taps(src, dst) {
16
+ const scale = src / dst;
17
+ const reach = 3 * Math.max(1, scale);
18
+ return Array.from({ length: dst }, (_, i) => {
19
+ const centre = (i + 0.5) * scale - 0.5;
20
+ const first = Math.max(0, Math.ceil(centre - reach));
21
+ const last = Math.min(src - 1, Math.floor(centre + reach));
22
+ const weights = [];
23
+ for (let j = first; j <= last; j++) weights.push(sinc3((j - centre) / Math.max(1, scale)));
24
+ const total = weights.reduce((a, b) => a + b, 0);
25
+ return { first, weights: weights.map((w) => w / total) };
26
+ });
27
+ }
28
+
29
+ const byte = (v) => (v <= 0 ? 0 : v >= 255 ? 255 : Math.round(v));
30
+
31
+ /** Lanczos-3 resize of an opaque RGBA8 frame; the output alpha is 255. */
32
+ export function lanczosResize(src, sw, sh, dw, dh) {
33
+ if (sw === dw && sh === dh) return Buffer.from(src);
34
+ const across = taps(sw, dw);
35
+ const down = taps(sh, dh);
36
+ const rows = new Float32Array(dw * sh * 3);
37
+ for (let y = 0; y < sh; y++)
38
+ for (let x = 0; x < dw; x++) {
39
+ const { first, weights } = across[x];
40
+ let r = 0;
41
+ let g = 0;
42
+ let b = 0;
43
+ for (let k = 0; k < weights.length; k++) {
44
+ const o = (y * sw + first + k) * 4;
45
+ r += src[o] * weights[k];
46
+ g += src[o + 1] * weights[k];
47
+ b += src[o + 2] * weights[k];
48
+ }
49
+ const o = (y * dw + x) * 3;
50
+ rows[o] = r;
51
+ rows[o + 1] = g;
52
+ rows[o + 2] = b;
53
+ }
54
+ const out = Buffer.alloc(dw * dh * 4);
55
+ for (let y = 0; y < dh; y++) {
56
+ const { first, weights } = down[y];
57
+ for (let x = 0; x < dw; x++) {
58
+ let r = 0;
59
+ let g = 0;
60
+ let b = 0;
61
+ for (let k = 0; k < weights.length; k++) {
62
+ const o = ((first + k) * dw + x) * 3;
63
+ r += rows[o] * weights[k];
64
+ g += rows[o + 1] * weights[k];
65
+ b += rows[o + 2] * weights[k];
66
+ }
67
+ const o = (y * dw + x) * 4;
68
+ out[o] = byte(r);
69
+ out[o + 1] = byte(g);
70
+ out[o + 2] = byte(b);
71
+ out[o + 3] = 255;
72
+ }
73
+ }
74
+ return out;
75
+ }
76
+
77
+ /** Box-averaged luma (0..255) about COVER.lumaWidth wide: { luma, w, h }. */
78
+ export function lumaGrid(rgba, width, height) {
79
+ const f = Math.max(1, Math.round(width / COVER.lumaWidth));
80
+ const w = Math.floor(width / f);
81
+ const h = Math.floor(height / f);
82
+ const luma = new Float32Array(w * h);
83
+ for (let y = 0; y < h * f; y++) {
84
+ const row = Math.floor(y / f) * w;
85
+ for (let x = 0; x < w * f; x++) {
86
+ const p = (y * width + x) * 4;
87
+ luma[row + Math.floor(x / f)] += 0.2126 * rgba[p] + 0.7152 * rgba[p + 1] + 0.0722 * rgba[p + 2];
88
+ }
89
+ }
90
+ for (let i = 0; i < luma.length; i++) luma[i] /= f * f;
91
+ return { luma, w, h };
92
+ }
93
+
94
+ /** The rectangle [x, y, w, h] of an RGBA8 frame as its own buffer. */
95
+ export function crop(rgba, width, [x, y, w, h]) {
96
+ const out = Buffer.alloc(w * h * 4);
97
+ for (let row = 0; row < h; row++) out.set(rgba.subarray(((y + row) * width + x) * 4, ((y + row) * width + x + w) * 4), row * w * 4);
98
+ return out;
99
+ }
100
+
101
+ /** SSIM of two same-size RGBA8 images on luma: the mean SSIM over 8x8 tiles. */
102
+ export function ssim(a, b, width, height) {
103
+ const lum = (img, i) => 0.2126 * img[i * 4] + 0.7152 * img[i * 4 + 1] + 0.0722 * img[i * 4 + 2];
104
+ const T = 8;
105
+ const c1 = (0.01 * 255) ** 2;
106
+ const c2 = (0.03 * 255) ** 2;
107
+ let sum = 0;
108
+ let tiles = 0;
109
+ for (let ty = 0; ty + T <= height; ty += T)
110
+ for (let tx = 0; tx + T <= width; tx += T) {
111
+ const xs = [];
112
+ const ys = [];
113
+ for (let y = ty; y < ty + T; y++)
114
+ for (let x = tx; x < tx + T; x++) {
115
+ xs.push(lum(a, y * width + x));
116
+ ys.push(lum(b, y * width + x));
117
+ }
118
+ const n = xs.length;
119
+ const mx = xs.reduce((s, v) => s + v, 0) / n;
120
+ const my = ys.reduce((s, v) => s + v, 0) / n;
121
+ let vx = 0;
122
+ let vy = 0;
123
+ let cov = 0;
124
+ for (let i = 0; i < n; i++) {
125
+ vx += (xs[i] - mx) ** 2;
126
+ vy += (ys[i] - my) ** 2;
127
+ cov += (xs[i] - mx) * (ys[i] - my);
128
+ }
129
+ vx /= n - 1;
130
+ vy /= n - 1;
131
+ cov /= n - 1;
132
+ sum += ((2 * mx * my + c1) * (2 * cov + c2)) / ((mx * mx + my * my + c1) * (vx + vy + c2));
133
+ tiles++;
134
+ }
135
+ return tiles ? sum / tiles : 0;
136
+ }
@@ -0,0 +1,43 @@
1
+ // Cover init script. Injected before any page script in every cover document. A cover frame is a pure
2
+ // function of loop time t, and the renderer seeks frames in any order and in fresh browsers, so every
3
+ // clock and every unseeded entropy source a page could read throws instead of answering. Each call is
4
+ // recorded by name, so the renderer can name it (exit 18) even when the page swallowed the error. CSS
5
+ // animations and transitions would run on the browser's own clock, so they are switched off.
6
+ (function litCoverInit() {
7
+ "use strict";
8
+ const w = window;
9
+ const calls = [];
10
+ const refuse = (name, fix) =>
11
+ function refused() {
12
+ if (!calls.includes(name)) calls.push(name);
13
+ throw new Error(`${name} is not allowed in a cover page; ${fix}`);
14
+ };
15
+ const fromT = "draw every frame from t";
16
+ const ownLoop = "the renderer calls renderFrame(t); never run your own loop";
17
+
18
+ w.Math.random = refuse("Math.random", "use LitLoop.rng(seed) for layout and t for motion");
19
+ const NativeDate = w.Date;
20
+ function CoverDate(...args) {
21
+ if (!new.target || args.length === 0) return refuse("Date", fromT)();
22
+ return new NativeDate(...args);
23
+ }
24
+ CoverDate.prototype = NativeDate.prototype;
25
+ CoverDate.now = refuse("Date.now", fromT);
26
+ CoverDate.UTC = NativeDate.UTC;
27
+ CoverDate.parse = NativeDate.parse;
28
+ Object.defineProperty(w, "Date", { value: CoverDate, configurable: true, writable: true });
29
+ Object.defineProperty(w.Performance.prototype, "now", { value: refuse("performance.now", fromT), configurable: true, writable: true });
30
+ w.requestAnimationFrame = refuse("requestAnimationFrame", ownLoop);
31
+ w.setInterval = refuse("setInterval", ownLoop);
32
+ if (w.crypto) Object.defineProperty(w.crypto, "getRandomValues", { value: refuse("crypto.getRandomValues", "use LitLoop.rng(seed)"), configurable: true });
33
+
34
+ const still = () => {
35
+ const style = w.document.createElement("style");
36
+ style.textContent = "*, *::before, *::after { animation: none !important; transition: none !important; }";
37
+ (w.document.head ?? w.document.documentElement).appendChild(style);
38
+ };
39
+ if (w.document.documentElement) still();
40
+ else w.document.addEventListener("readystatechange", still, { once: true });
41
+
42
+ w.__litCoverCalls = () => calls.slice();
43
+ })();