@litfamily/litclaude 1.0.34 → 1.0.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +59 -44
- package/README.md +8 -8
- package/README_ko-KR.md +8 -8
- package/bin/litclaude-ai.js +24 -11
- package/docs/agents.md +5 -0
- package/docs/assets/cover-motion-still.webp +0 -0
- package/docs/assets/cover-motion.webp +0 -0
- package/docs/assets/cover.webp +0 -0
- package/docs/assets/litfamily-machines.png +0 -0
- package/docs/assets/readme/ascii-readme.svg +1 -1
- package/docs/assets/readme/badge-version.svg +1 -1
- package/docs/assets/skills/lit-brainstorm.webp +0 -0
- package/docs/hooks.md +77 -14
- package/docs/migration.md +2 -2
- package/package.json +2 -1
- package/plugins/litclaude/.claude-plugin/plugin.json +1 -1
- package/plugins/litclaude/bin/litclaude-hook.js +166 -17
- package/plugins/litclaude/bin/litclaude-lsp-doctor.js +10 -3
- package/plugins/litclaude/bin/litclaude-mcp.js +1 -1
- package/plugins/litclaude/bundled-rules/lit-humanizer.md +1 -0
- package/plugins/litclaude/commands/deep-interview.md +4 -0
- package/plugins/litclaude/commands/lit-brainstorm.md +108 -0
- package/plugins/litclaude/commands/litgoal.md +1 -1
- package/plugins/litclaude/commands/review-work.md +13 -4
- package/plugins/litclaude/hooks/lit-band-client.mjs +7 -4
- package/plugins/litclaude/hooks/lit-mod.mjs +35 -10
- package/plugins/litclaude/lib/automatic-update.mjs +15 -4
- package/plugins/litclaude/lib/canonical-skill-catalog.mjs +1 -0
- package/plugins/litclaude/lib/canonical-skill-resources.mjs +72 -38
- package/plugins/litclaude/lib/deliverable-hedge-guard.mjs +173 -48
- package/plugins/litclaude/lib/lit-activation.mjs +60 -0
- package/plugins/litclaude/lib/lit-mark.mjs +1 -1
- package/plugins/litclaude/lib/mod/frame.mjs +24 -7
- package/plugins/litclaude/lib/mod/motion.mjs +2 -1
- package/plugins/litclaude/lib/mod/skills.mjs +1 -0
- package/plugins/litclaude/lib/mod/svg-card.mjs +2 -2
- package/plugins/litclaude/lib/mod/timeline.mjs +12 -0
- package/plugins/litclaude/lib/mod/toasts.mjs +89 -0
- package/plugins/litclaude/lib/mod/view.mjs +16 -10
- package/plugins/litclaude/lib/mod/workflow.mjs +1 -0
- package/plugins/litclaude/lib/motion-render-gate.mjs +9 -4
- package/plugins/litclaude/lib/npm-invocation.mjs +64 -0
- package/plugins/litclaude/lib/office-runtime.mjs +40 -14
- package/plugins/litclaude/lib/office_runtime_bootstrap.py +13 -1
- package/plugins/litclaude/lib/rules/engine.mjs +23 -5
- package/plugins/litclaude/lib/start-work-lifecycle.mjs +125 -9
- package/plugins/litclaude/skills/deep-interview/SKILL.md +1 -1
- package/plugins/litclaude/skills/lit-brainstorm/SKILL.md +430 -0
- package/plugins/litclaude/skills/lit-brainstorm/references/idea-lenses.md +192 -0
- package/plugins/litclaude/skills/lit-brainstorm/references/scoring-and-convergence.md +149 -0
- package/plugins/litclaude/skills/lit-brainstorm/references/session-notes-template.md +106 -0
- package/plugins/litclaude/skills/lit-diagram-drawer/scripts/export.mjs +3 -4
- package/plugins/litclaude/skills/lit-diagram-drawer/scripts/renderer.mjs +10 -2
- package/plugins/litclaude/skills/lit-docx/SKILL.md +1 -1
- package/plugins/litclaude/skills/lit-docx/scripts/convert_md_to_pdf.py +23 -0
- package/plugins/litclaude/skills/lit-docx/templates/latex/acs/template.tex +14 -0
- package/plugins/litclaude/skills/lit-docx/templates/latex/elsevier/template.tex +14 -0
- package/plugins/litclaude/skills/lit-docx/templates/latex/ieee/template.tex +14 -0
- package/plugins/litclaude/skills/lit-docx/templates/latex/korean-generic/template.tex +14 -0
- package/plugins/litclaude/skills/lit-docx/templates/latex/nature/template.tex +14 -0
- package/plugins/litclaude/skills/lit-humanizer/SKILL.md +4 -0
- package/plugins/litclaude/skills/lit-humanizer/scripts/core.mjs +94 -1
- package/plugins/litclaude/skills/lit-humanizer/scripts/detect.mjs +3 -2
- package/plugins/litclaude/skills/lit-humanizer/scripts/scan-input.mjs +15 -2
- package/plugins/litclaude/skills/lit-loop/SKILL.md +11 -0
- package/plugins/litclaude/skills/lit-plan/SKILL.md +2 -1
- package/plugins/litclaude/skills/lit-typographic-motion/SKILL.md +14 -5
- package/plugins/litclaude/skills/lit-typographic-motion/engine/THIRD_PARTY_NOTICES +6 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/core/constants.mjs +35 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/chrome.mjs +3 -7
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/cover-assets.mjs +102 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/cover-capture.mjs +210 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/cover-gate.mjs +346 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/cover-image.mjs +141 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/cover-sheet.mjs +76 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/cover-treatment.mjs +106 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/cover-worker.mjs +32 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/cover.mjs +373 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/done.mjs +68 -2
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/encode.mjs +3 -5
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/host.mjs +31 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/look.mjs +53 -17
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/runtime.mjs +42 -12
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/stage-capture.mjs +2 -1
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/stage-serve.mjs +6 -1
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/stage.mjs +2 -2
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/treatment.mjs +2 -1
- package/plugins/litclaude/skills/lit-typographic-motion/engine/node/webp.mjs +145 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/stage/cover-init.js +37 -0
- package/plugins/litclaude/skills/lit-typographic-motion/engine/stage/loop-kit.js +106 -0
- package/plugins/litclaude/skills/lit-typographic-motion/fonts/jetbrains-mono/JetBrainsMono-wght-latin.woff2 +0 -0
- package/plugins/litclaude/skills/lit-typographic-motion/fonts/jetbrains-mono/OFL.txt +93 -0
- package/plugins/litclaude/skills/lit-typographic-motion/fonts/manifest.json +18 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/negatives/card-scenes/expected.json +16 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/negatives/card-scenes/index.html +27 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/negatives/reset-sweep/expected.json +16 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/negatives/reset-sweep/index.html +17 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/negatives/still-glow/expected.json +17 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/negatives/still-glow/index.html +18 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/negatives/title-slam/expected.json +17 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/negatives/title-slam/index.html +30 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/orbit-loop/expected.json +67 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/orbit-loop/index.html +152 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/painted-light/expected.json +95 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/painted-light/index.html +202 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/weight-tide/expected.json +67 -0
- package/plugins/litclaude/skills/lit-typographic-motion/recipes/weight-tide/index.html +100 -0
- package/plugins/litclaude/skills/lit-typographic-motion/references/cover.md +372 -0
- package/plugins/litclaude/skills/lit-typographic-motion/references/look.md +2 -1
- package/plugins/litclaude/skills/lit-typographic-motion/references/runtime.md +4 -3
- package/plugins/litclaude/skills/lit-typographic-motion/references/stage.md +1 -0
- package/plugins/litclaude/skills/lit-typographic-motion/references/treatment.md +4 -0
- package/plugins/litclaude/skills/lit-typographic-motion/scripts/motion-doctor.mjs +26 -6
- package/plugins/litclaude/skills/lit-typographic-motion/scripts/motion.mjs +43 -10
- package/plugins/litclaude/skills/litgoal/SKILL.md +9 -1
- package/plugins/litclaude/skills/lsp-setup/scripts/verify-lsp.ts +47 -6
- package/plugins/litclaude/skills/review-work/SKILL.md +37 -1
- package/plugins/litclaude/skills/start-work/SKILL.md +5 -0
- package/scripts/doctor.mjs +2 -2
- package/scripts/qa-cover-recipes.mjs +172 -0
- package/scripts/validate-plugin.mjs +12 -2
|
@@ -92,6 +92,16 @@ When the request is still underspecified, pause execution and route to
|
|
|
92
92
|
before planning or editing. Lit-loop execution should not invent non-goals, decision
|
|
93
93
|
boundaries, or acceptance criteria.
|
|
94
94
|
|
|
95
|
+
## Repeating `lit` in one session
|
|
96
|
+
|
|
97
|
+
The prompt hook sends the full activation once per discipline and session. A later
|
|
98
|
+
`lit ...` for the same discipline arrives as a short "already active" note: carry on
|
|
99
|
+
under this contract, do not reload this file, and open no new run, plan or goal line.
|
|
100
|
+
`lit plan ...` or another discipline switches and brings its own full activation. A bare
|
|
101
|
+
`lit` or `lit continue` carries on whatever is active in this session (a start-work run,
|
|
102
|
+
the discipline last activated, or an open plan) and writes no new plan. `lit new ...` and `lit restart ...` start fresh. The
|
|
103
|
+
hook keeps this record per session; when it is missing the full activation comes again.
|
|
104
|
+
|
|
95
105
|
## Role
|
|
96
106
|
|
|
97
107
|
Deliver the user's objective end-to-end. Convert the objective into explicit
|
|
@@ -174,6 +184,7 @@ like this:
|
|
|
174
184
|
text or claim native activation without observed evidence.
|
|
175
185
|
- Forward-compat only: if a future Claude Code build exposes model-facing goal tools, prefer
|
|
176
186
|
them according to the no-clobber rule above.
|
|
187
|
+
- litgoal sets and keeps the finish line; lit-loop and start-work run toward it.
|
|
177
188
|
- While model-facing goal tools are not exposed, the local litgoal ledger is the
|
|
178
189
|
durable record; surface the degraded-mode note once for long-running goals and
|
|
179
190
|
don't spam fallback status.
|
|
@@ -524,7 +524,8 @@ them in the plan.
|
|
|
524
524
|
## Planner Restraints
|
|
525
525
|
|
|
526
526
|
Do not edit production files. Do not mark tasks complete. Do not publish. Do
|
|
527
|
-
not open-endedly brainstorm when the user asked for an executable plan
|
|
527
|
+
not open-endedly brainstorm when the user asked for an executable plan; open
|
|
528
|
+
ideation belongs to `lit-brainstorm`. If the
|
|
528
529
|
task is too vague, ask the smallest clarifying question or write assumptions
|
|
529
530
|
explicitly.
|
|
530
531
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: lit-typographic-motion
|
|
3
|
-
description: Film director for a finished short film from a one-line request — writes a treatment first (idea, audience, format, beats, a drawn subject, copy, sound), then takes the stage path for films that show things (a model-authored HTML/SVG/Canvas/WebGL page captured frame by frame by the bundled deterministic renderer, 16:9 or 9:16) or the type path for films whose words are the film (kinetic type, lyric or quote video, title sequence, through the bundled WebGL2 type engine), with a generated sound bed, look rounds on the rendered frames and a QA gate (flash audit, legibility, determinism, sound). Not for editing, trimming or captioning existing footage, a video embedded in a web page, a thumbnail, or slides.
|
|
3
|
+
description: Film director for a finished short film from a one-line request — writes a treatment first (idea, audience, format, beats, a drawn subject, copy, sound), then takes the stage path for films that show things (a model-authored HTML/SVG/Canvas/WebGL page captured frame by frame by the bundled deterministic renderer, 16:9 or 9:16) or the type path for films whose words are the film (kinetic type, lyric or quote video, title sequence, through the bundled WebGL2 type engine), with a generated sound bed, look rounds on the rendered frames and a QA gate (flash audit, legibility, determinism, sound). Cover mode makes a silent, seamless README cover loop. Not for editing, trimming or captioning existing footage, a video embedded in a web page, a thumbnail, or slides.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
## #contract.activation
|
|
@@ -17,13 +17,14 @@ host: Claude Code
|
|
|
17
17
|
verdicts: [PASS, FAIL, BLOCKED]
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
-
This skill is a film director. Every film starts with a treatment. Films that are the words themselves take the type path; every other film takes the stage path, where you author the visuals and the product's renderer captures them deterministically and runs the gate.
|
|
20
|
+
This skill is a film director. Every film starts with a treatment. Films that are the words themselves take the type path; every other film takes the stage path, where you author the visuals and the product's renderer captures them deterministically and runs the gate. A README cover loop is not a film: it takes cover mode (`references/cover.md`).
|
|
21
21
|
|
|
22
|
-
The UserPromptSubmit hook activates it for a prompt that starts with the token `lit-typographic-motion`, or for a bare `lit` prompt that asks to make something and names a film: a compound (모션그래픽, 타이포 모션, 키네틱 타이포, 가사 영상, 오프닝 타이틀, 타이틀 시퀀스, motion graphics, kinetic type, lyric video, title sequence, opening titles) or a bare 영상 / 비디오 / video / clip. It
|
|
22
|
+
The UserPromptSubmit hook activates it for a prompt that starts with the token `lit-typographic-motion`, or for a bare `lit` prompt that asks to make something and names a film: a compound (모션그래픽, 타이포 모션, 키네틱 타이포, 가사 영상, 오프닝 타이틀, 타이틀 시퀀스, motion graphics, kinetic type, lyric video, title sequence, opening titles) or a bare 영상 / 비디오 / video / clip. It does not fire for editing or captioning an existing clip, a video inside a page or slide, a script, thumbnail or summary about a video, UI motion (hover, motion tokens), or a bare 모션 / motion / 인트로 / intro.
|
|
23
23
|
|
|
24
24
|
| Request | Route |
|
|
25
25
|
| --- | --- |
|
|
26
26
|
| A film from a request, with or without its words | this skill |
|
|
27
|
+
| A README, hero, banner or cover loop | this skill, cover mode |
|
|
27
28
|
| Slides or a report, with no video noun | lit-pptx / lit-docx |
|
|
28
29
|
| A web page, a background video in a page, UI motion | frontend-ui-ux |
|
|
29
30
|
| Editing, trimming or captioning existing footage | not this skill; say so |
|
|
@@ -49,7 +50,8 @@ The UserPromptSubmit hook activates it for a prompt that starts with the token `
|
|
|
49
50
|
| treatment | exit 16 | Fix the named field of `treatment.json` and rerun. |
|
|
50
51
|
| stage contract | exit 17, 18 or 19 | Fix the page (element, API, raster, clock source or URL the message names) and rerun. |
|
|
51
52
|
| sound | exit 20 | Fix the bed or the track the message names and rerun. |
|
|
52
|
-
|
|
|
53
|
+
| cover | treatment `mode: cover` | Done by `references/cover.md`. |
|
|
54
|
+
| review-only | the user asks for a critique of a render | Look at the frames and run `gate` (`cover-gate` for a cover); write nothing else. |
|
|
53
55
|
|
|
54
56
|
## #contract.procedure
|
|
55
57
|
|
|
@@ -61,10 +63,14 @@ node "$SKILL_ROOT/scripts/motion.mjs" make <brief.json> --out <dir> --round <N>
|
|
|
61
63
|
node "$SKILL_ROOT/scripts/motion.mjs" sound --out <dir>
|
|
62
64
|
node "$SKILL_ROOT/scripts/motion.mjs" look --out <dir> --round <N> --answers <file>
|
|
63
65
|
node "$SKILL_ROOT/scripts/motion.mjs" gate <dir>
|
|
66
|
+
node "$SKILL_ROOT/scripts/motion.mjs" cover --out <dir> --round <N>
|
|
67
|
+
node "$SKILL_ROOT/scripts/motion.mjs" cover-gate <dir>/cover.webp --strict
|
|
64
68
|
```
|
|
65
69
|
|
|
66
70
|
Every frame and track passes through these renderers. A film encoded by hand with ffmpeg, Python, a raster flipbook or a screen recording is not the deliverable.
|
|
67
71
|
|
|
72
|
+
Cover mode replaces steps 1–6 with `references/cover.md`: a cover treatment, a page from a recipe in `recipes/`, then render and look rounds on the decoded cover.
|
|
73
|
+
|
|
68
74
|
1. **Treatment.** Load `references/treatment.md`. Write `<dir>/treatment.json` from it: idea, audience, channel, format, the genre arc's beats, the subject (invent one when the request names none), visual devices, type plan, palette, sound and copy. Set `path` by its path rule.
|
|
69
75
|
2. **Path references.** Stage path: `references/stage.md`. Type path: `references/brief-schema.md`, `references/style-bibles.md`, `references/type-craft.md` and `references/craft-loop.md` (`references/engine-contract.md` and `references/runtime.md` when you need the engine's internals). Both paths: `references/look.md` and `references/sound.md`.
|
|
70
76
|
3. **Build.** Stage path: write the page `index.html` and its local assets in the output directory's `stage` folder, with the kit. Type path: write `brief.json` for the engine.
|
|
@@ -85,6 +91,7 @@ Every frame and track passes through these renderers. A film encoded by hand wit
|
|
|
85
91
|
| `sound/`, `sound-cues.json` | The generated bed or the prepared track, and every cue against its cut |
|
|
86
92
|
| `manifest.json`, `render.jsonl`, `gate-report.txt` | Run manifest, per-frame log, QA gate report |
|
|
87
93
|
| `withheld/` | Only after a flash-audit FAIL: diagnostics, never deliverables |
|
|
94
|
+
| `cover.webp` | Cover mode: the loop (≤ 2 MiB); `stills/` holds the decoded sheet with its difference plot and the seam pair |
|
|
88
95
|
|
|
89
96
|
## #contract.output_channels
|
|
90
97
|
|
|
@@ -114,6 +121,8 @@ Done needs all of: a valid treatment; gate PASS; at least two look rounds, the f
|
|
|
114
121
|
| 18 | STAGE_NONDETERMINISTIC | The page read something the clock does not drive; seed it or drive it from `t`. |
|
|
115
122
|
| 19 | STAGE_NETWORK_REQUEST | Remove the named URL or connection; everything is local. |
|
|
116
123
|
| 20 | SOUND_INVALID | The planned sound is missing, silent at the start or out of limits; fix it. |
|
|
124
|
+
| 21 | BLOCKED_NO_COVER_ENCODER | Install libwebp (img2webp, dwebp) or gifski. |
|
|
125
|
+
| 22 | BLOCKED_ASSET_MISSING | Cover mode: a listed asset is missing; supply or generate it, never a stand-in. |
|
|
117
126
|
|
|
118
127
|
Never raise a gate number, never weaken the flash audit, never ship a withheld export as a draft.
|
|
119
128
|
|
|
@@ -128,4 +137,4 @@ Never raise a gate number, never weaken the flash audit, never ship a withheld e
|
|
|
128
137
|
- Outlined or haloed type, fake Hangul condensing, tracking or width motion on Hangul, glitch as constant texture.
|
|
129
138
|
- Quoting song lyrics or other text the user does not own as the film's content.
|
|
130
139
|
|
|
131
|
-
References: `references/treatment.md`, `references/stage.md`, `references/look.md`, `references/sound.md`, `references/brief-schema.md`, `references/style-bibles.md`, `references/type-craft.md`, `references/craft-loop.md`, `references/engine-contract.md`, `references/runtime.md`. Type engine credit: portions adapted from mexicat/pdoom-video (MIT), commit `ca251e3`; see `engine/NOTICE`.
|
|
140
|
+
References: `references/treatment.md`, `references/cover.md`, `references/stage.md`, `references/look.md`, `references/sound.md`, `references/brief-schema.md`, `references/style-bibles.md`, `references/type-craft.md`, `references/craft-loop.md`, `references/engine-contract.md`, `references/runtime.md`. Type engine credit: portions adapted from mexicat/pdoom-video (MIT), commit `ca251e3`; see `engine/NOTICE`.
|
|
@@ -30,6 +30,12 @@ ${XDG_CACHE_HOME:-~/.cache}/litclaude/motion-runtime.
|
|
|
30
30
|
font files: fonts/silkscreen/Silkscreen-Regular.ttf, fonts/silkscreen/Silkscreen-Bold.ttf
|
|
31
31
|
licence: fonts/silkscreen/OFL.txt
|
|
32
32
|
|
|
33
|
+
JetBrains Mono, variable wght 100-800, latin subset (bundled, unmodified; OFL 1.1, no Reserved
|
|
34
|
+
Font Name)
|
|
35
|
+
font file: fonts/jetbrains-mono/JetBrainsMono-wght-latin.woff2
|
|
36
|
+
licence: fonts/jetbrains-mono/OFL.txt
|
|
37
|
+
source: @fontsource-variable/jetbrains-mono 5.3.0, files/jetbrains-mono-latin-wght-normal.woff2
|
|
38
|
+
|
|
33
39
|
EMS Allure, EMS Felix, EMS Osmotron, EMS Readability, EMS Tech single-stroke SVG fonts
|
|
34
40
|
(bundled, unmodified; OFL 1.1)
|
|
35
41
|
font files: fonts/stroke/EMS*.svg
|
|
@@ -34,6 +34,9 @@ export const EXIT = Object.freeze({
|
|
|
34
34
|
STAGE_NONDETERMINISTIC: 18,
|
|
35
35
|
STAGE_NETWORK_REQUEST: 19,
|
|
36
36
|
SOUND_INVALID: 20,
|
|
37
|
+
// Cover mode.
|
|
38
|
+
BLOCKED_NO_COVER_ENCODER: 21,
|
|
39
|
+
BLOCKED_ASSET_MISSING: 22,
|
|
37
40
|
USAGE: 2,
|
|
38
41
|
});
|
|
39
42
|
export const EXIT_NAME = Object.freeze(Object.fromEntries(Object.entries(EXIT).map(([name, code]) => [code, name])));
|
|
@@ -209,3 +212,35 @@ export const FONT_BUDGET = Object.freeze({ perFileBytes: 1_000_000, totalBytes:
|
|
|
209
212
|
|
|
210
213
|
// ---- craft loop (MO-C-15/16) ----
|
|
211
214
|
export const MAX_ROUNDS = 3;
|
|
215
|
+
|
|
216
|
+
// ---- cover mode: the decoded-file gate (calibrated 2026-10-20 on 8 painted covers, 4 slide-like
|
|
217
|
+
// negatives and 3 pilot loops; change a number only with a new calibration table) ----
|
|
218
|
+
// FLOOR fails a cover: every calibration cover passes it, every slide-like negative fails it.
|
|
219
|
+
// TARGET is the cover-mode goal and `--strict` fails on it too; the calibration covers miss it on
|
|
220
|
+
// purpose, because they hold for about 2 s and flash at the seam.
|
|
221
|
+
export const COVER = Object.freeze({
|
|
222
|
+
maxBytes: 3 * 1024 * 1024,
|
|
223
|
+
targetBytes: 2 * 1024 * 1024,
|
|
224
|
+
minSec: 6,
|
|
225
|
+
maxSec: 12,
|
|
226
|
+
stepMs: 50, // metrics run on a fixed grid of max(stepMs, shortest source frame)
|
|
227
|
+
stillEps: 0.0005, // a grid step whose mean |dY| (luma 0..1, ~300 px wide) is below this is still
|
|
228
|
+
floor: Object.freeze({ medianD: 0.0004, movingFrac: 0.45, stillSec: 2.0, seamLocal: 8.0 }),
|
|
229
|
+
target: Object.freeze({ medianD: 0.0015, movingFrac: 0.95, stillSec: 0.5, spike: 6, seamLocal: 2.0, seamLo: 0.25 }),
|
|
230
|
+
minContrast: 4.5,
|
|
231
|
+
// G6: the title's cap height at the README display width (a full-width README image is about 830
|
|
232
|
+
// CSS px wide); a smaller title is not a title, whatever its contrast.
|
|
233
|
+
minGlyphPx: 24,
|
|
234
|
+
displayWidth: 830,
|
|
235
|
+
// Frame 0 shows the base art: SSIM of its check box against the source scaled into it.
|
|
236
|
+
artSsim: 0.9,
|
|
237
|
+
artMinShare: 0.1,
|
|
238
|
+
seekSamples: 16, // frames re-rendered in a fresh page in a seeded shuffled order
|
|
239
|
+
windowPadSec: 0.5, // a window re-render covers each defect's span plus this on each side
|
|
240
|
+
maxDefects: 3,
|
|
241
|
+
captureScale: 2,
|
|
242
|
+
fps: Object.freeze([16, 20, 25]),
|
|
243
|
+
// The page is laid out at `page` CSS px, captured at captureScale and downsampled to `out`.
|
|
244
|
+
aspects: Object.freeze({ "2:1": Object.freeze({ page: [1200, 600], out: [1000, 500] }), "3:2": Object.freeze({ page: [1200, 800], out: [960, 640] }) }),
|
|
245
|
+
encode: Object.freeze({ q: 86, edgeQ: 97, edgeFrames: 15, method: 4 }),
|
|
246
|
+
});
|
|
@@ -8,6 +8,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
|
|
|
8
8
|
import { homedir } from "node:os";
|
|
9
9
|
import path from "node:path";
|
|
10
10
|
import { CHROME_ALWAYS, CHROME_RUNGS, EXIT, UNKNOWN_RENDERER } from "../core/constants.mjs";
|
|
11
|
+
import { which } from "./host.mjs";
|
|
11
12
|
|
|
12
13
|
export class BlockedError extends Error {
|
|
13
14
|
constructor(code, message) {
|
|
@@ -30,11 +31,6 @@ const CANDIDATES = {
|
|
|
30
31
|
],
|
|
31
32
|
};
|
|
32
33
|
|
|
33
|
-
function onPath(name) {
|
|
34
|
-
const probe = spawnSync(process.platform === "win32" ? "where" : "which", [name], { encoding: "utf8" });
|
|
35
|
-
return probe.status === 0 ? probe.stdout.trim().split("\n")[0] : null;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
34
|
/** Resolve Chrome: $CHROME_PATH, then the platform's usual locations. Returns null when absent. */
|
|
39
35
|
export function findChrome(env = process.env) {
|
|
40
36
|
if (env.CHROME_PATH) return existsSync(env.CHROME_PATH) ? env.CHROME_PATH : null;
|
|
@@ -42,7 +38,7 @@ export function findChrome(env = process.env) {
|
|
|
42
38
|
if (path.isAbsolute(candidate)) {
|
|
43
39
|
if (existsSync(candidate)) return candidate;
|
|
44
40
|
} else {
|
|
45
|
-
const found =
|
|
41
|
+
const found = which(candidate);
|
|
46
42
|
if (found) return found;
|
|
47
43
|
}
|
|
48
44
|
}
|
|
@@ -51,7 +47,7 @@ export function findChrome(env = process.env) {
|
|
|
51
47
|
|
|
52
48
|
export function chromeVersion(chrome) {
|
|
53
49
|
const probe = spawnSync(chrome, ["--version"], { encoding: "utf8", timeout: 15000 });
|
|
54
|
-
return probe.status === 0 ? probe.stdout.trim() : `unknown (${(probe.stderr || probe.error?.message || "").trim().split(
|
|
50
|
+
return probe.status === 0 ? probe.stdout.trim() : `unknown (${(probe.stderr || probe.error?.message || "").trim().split(/\r?\n/u)[0]})`;
|
|
55
51
|
}
|
|
56
52
|
|
|
57
53
|
/**
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// Cover assets: every raster a cover page loads (base art, logo, wordmark, texture) is listed in
|
|
2
|
+
// `<out>/assets.json` with its path, role, source (user or generated) and SHA-256, and the renderer
|
|
3
|
+
// checks the list before any capture. A listed file that is missing is BLOCKED_ASSET_MISSING
|
|
4
|
+
// (exit 22): the art is supplied or generated, never replaced by a drawn stand-in. The painted-light
|
|
5
|
+
// recipe needs its base art listed. After the render, frame 0 must show that art: the SSIM of its
|
|
6
|
+
// check box in the decoded frame 0 against the source scaled into the art box.
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { COVER, EXIT } from "../core/constants.mjs";
|
|
11
|
+
import { BlockedError } from "./chrome.mjs";
|
|
12
|
+
import { crop, lanczosResize, ssim } from "./cover-image.mjs";
|
|
13
|
+
|
|
14
|
+
export const ASSETS_FILE = "assets.json";
|
|
15
|
+
export const ASSET_ROLES = Object.freeze(["base-art", "logo", "wordmark", "texture"]);
|
|
16
|
+
|
|
17
|
+
const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
18
|
+
const invalid = (field, message) => new BlockedError(EXIT.BLOCKED_TREATMENT_INVALID, `BLOCKED_TREATMENT_INVALID: assets.json: ${field}: ${message}`);
|
|
19
|
+
const isBox = (b) => Array.isArray(b) && b.length === 4 && b.every((v) => typeof v === "number" && v >= 0 && v <= 1) && b[2] > 0 && b[3] > 0 && b[0] + b[2] <= 1 + 1e-9 && b[1] + b[3] <= 1 + 1e-9;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Check `<out>/assets.json` against the cover folder before capture. `rasters` are the static scan's
|
|
23
|
+
* rasters (paths relative to the cover folder). Returns { assets } (empty when there is no list and
|
|
24
|
+
* the recipe needs none). Exit 22 for a missing listed file or a painted recipe without base art,
|
|
25
|
+
* exit 17 for an unlisted raster or a file that no longer matches its hash, exit 16 for a bad entry.
|
|
26
|
+
*/
|
|
27
|
+
export function checkAssets({ out, treatment, rasters, coverDir = "cover" }) {
|
|
28
|
+
const file = path.join(out, ASSETS_FILE);
|
|
29
|
+
const needsArt = treatment.recipe === "painted-light";
|
|
30
|
+
const blockedArt = new BlockedError(EXIT.BLOCKED_ASSET_MISSING, "BLOCKED_ASSET_MISSING: the painted-light recipe needs its base art listed in assets.json ({ path, role: base-art, source: user or generated, sha256, box }); supply or generate the art, never draw a stand-in");
|
|
31
|
+
let assets = [];
|
|
32
|
+
if (existsSync(file)) {
|
|
33
|
+
let doc;
|
|
34
|
+
try {
|
|
35
|
+
doc = JSON.parse(readFileSync(file, "utf8"));
|
|
36
|
+
} catch (error) {
|
|
37
|
+
throw invalid("assets.json", `not valid JSON (${error.message})`);
|
|
38
|
+
}
|
|
39
|
+
if (!doc || !Array.isArray(doc.assets)) throw invalid("assets", "must be an array of { path, role, source, sha256 }");
|
|
40
|
+
assets = doc.assets.map((a, i) => {
|
|
41
|
+
const f = `assets[${i}]`;
|
|
42
|
+
if (!a || typeof a !== "object") throw invalid(f, "must be an object");
|
|
43
|
+
if (typeof a.path !== "string" || !a.path.startsWith(`${coverDir}/`) || a.path.split("/").includes("..")) throw invalid(`${f}.path`, `must be a path inside ${coverDir}/, relative to the output directory`);
|
|
44
|
+
if (!ASSET_ROLES.includes(a.role)) throw invalid(`${f}.role`, `must be one of ${ASSET_ROLES.join(", ")}`);
|
|
45
|
+
if (!["user", "generated"].includes(a.source)) throw invalid(`${f}.source`, "must be user (supplied) or generated");
|
|
46
|
+
if (!/^[0-9a-f]{64}$/u.test(a.sha256 ?? "")) throw invalid(`${f}.sha256`, "must be the file's SHA-256 (64 hex)");
|
|
47
|
+
if ("box" in a && !isBox(a.box)) throw invalid(`${f}.box`, "must be [x, y, w, h], fractions of the cover, inside it");
|
|
48
|
+
if ("checkBox" in a) {
|
|
49
|
+
if (!isBox(a.checkBox)) throw invalid(`${f}.checkBox`, "must be [x, y, w, h], fractions of the cover, inside it");
|
|
50
|
+
if (!a.box) throw invalid(`${f}.checkBox`, "needs the art's box");
|
|
51
|
+
const [bx, by, bw, bh] = a.box;
|
|
52
|
+
const [cx, cy, cw, ch] = a.checkBox;
|
|
53
|
+
if (cx < bx - 1e-9 || cy < by - 1e-9 || cx + cw > bx + bw + 1e-9 || cy + ch > by + bh + 1e-9) throw invalid(`${f}.checkBox`, "must lie inside the art's box");
|
|
54
|
+
if (cw * ch < COVER.artMinShare * bw * bh) throw invalid(`${f}.checkBox`, `must cover at least ${COVER.artMinShare * 100} % of the art's box`);
|
|
55
|
+
}
|
|
56
|
+
if (a.role === "base-art" && !a.box) throw invalid(`${f}.box`, "base art needs the box it fills on the cover");
|
|
57
|
+
return { path: a.path, role: a.role, source: a.source, sha256: a.sha256, box: a.box ?? null, checkBox: a.checkBox ?? null, title: a.title === true };
|
|
58
|
+
});
|
|
59
|
+
for (const a of assets) {
|
|
60
|
+
const real = path.join(out, a.path);
|
|
61
|
+
if (!existsSync(real)) throw new BlockedError(EXIT.BLOCKED_ASSET_MISSING, `BLOCKED_ASSET_MISSING: ${a.path} is listed in assets.json and missing; supply it, never draw a stand-in`);
|
|
62
|
+
if (sha256(readFileSync(real)) !== a.sha256) throw new BlockedError(EXIT.STAGE_CONTRACT_ERROR, `STAGE_CONTRACT_ERROR: ${a.path} does not match its sha256 in assets.json; list it again after changing it`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (needsArt && !assets.some((a) => a.role === "base-art")) throw blockedArt;
|
|
66
|
+
const listed = new Set(assets.map((a) => a.path));
|
|
67
|
+
for (const r of rasters) {
|
|
68
|
+
const rel = `${coverDir}/${r.rel.split(path.sep).join("/")}`;
|
|
69
|
+
if (!listed.has(rel)) throw new BlockedError(EXIT.STAGE_CONTRACT_ERROR, `STAGE_CONTRACT_ERROR: ${rel} is a raster the page can load but assets.json does not list; list it with its role, source and sha256`);
|
|
70
|
+
}
|
|
71
|
+
return { assets };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const px = (box, W, H) => box.map((v, k) => Math.round(v * (k % 2 ? H : W)));
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Frame 0 shows the base art: crop the check box (default: the art box) out of decoded frame 0 and
|
|
78
|
+
* compare it with the same region of the source scaled into the art box. `art` is { rgba, width,
|
|
79
|
+
* height }; boxes are fractions of the cover.
|
|
80
|
+
*/
|
|
81
|
+
export function artCheck({ frame0, width, height, art, box, checkBox = null }) {
|
|
82
|
+
const [bx, by, bw, bh] = px(box, width, height);
|
|
83
|
+
const scaled = lanczosResize(art.rgba, art.width, art.height, bw, bh);
|
|
84
|
+
const [cx, cy, cw, ch] = px(checkBox ?? box, width, height);
|
|
85
|
+
const a = crop(frame0, width, [cx, cy, cw, ch]);
|
|
86
|
+
const b = crop(scaled, bw, [cx - bx, cy - by, cw, ch]);
|
|
87
|
+
const value = ssim(a, b, cw, ch);
|
|
88
|
+
return { ssim: value, pass: value >= COVER.artSsim, box: [bx, by, bw, bh], checked: [cx, cy, cw, ch] };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The reply labels a generated asset needs (the Stop hook's finished-cover notice carries them). */
|
|
92
|
+
export function generatedLabels(out) {
|
|
93
|
+
const file = path.join(out, ASSETS_FILE);
|
|
94
|
+
if (!existsSync(file)) return [];
|
|
95
|
+
try {
|
|
96
|
+
const doc = JSON.parse(readFileSync(file, "utf8"));
|
|
97
|
+
return (doc.assets ?? []).filter((a) => a?.source === "generated" && typeof a.path === "string")
|
|
98
|
+
.map((a) => `the ${String(a.role ?? "asset").replace("-", " ")} ${a.path} is generated, not supplied: label it as generated in the reply`);
|
|
99
|
+
} catch {
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
// Cover capture: one headless Chrome on the stage path's software rung, laid out at the cover's CSS
|
|
2
|
+
// size and captured at twice that (device scale 2), the page served from disk on the synthetic stage
|
|
3
|
+
// origin, the cover init script injected before any page script. The renderer SEEKS: it calls
|
|
4
|
+
// window.renderFrame(t, { mask }) for any t in [0, 1) in any order, captures, and a worker pool
|
|
5
|
+
// downsamples each capture to the cover size. The master, the determinism pass and the seek-order
|
|
6
|
+
// check each open their own CoverBrowser.
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
8
|
+
import { cpus } from "node:os";
|
|
9
|
+
import { Worker } from "node:worker_threads";
|
|
10
|
+
import { EXIT } from "../core/constants.mjs";
|
|
11
|
+
import { BlockedError, ChromeSession, findChrome, stageFlags } from "./chrome.mjs";
|
|
12
|
+
import { COVER_INIT_FILE, STAGE_ORIGIN, stageRouter } from "./stage-serve.mjs";
|
|
13
|
+
|
|
14
|
+
const withTimeout = (promise, ms, message) => Promise.race([
|
|
15
|
+
promise,
|
|
16
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms).unref()),
|
|
17
|
+
]);
|
|
18
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
19
|
+
|
|
20
|
+
/** The stage flag set at the cover's device scale. */
|
|
21
|
+
export const coverFlags = ({ width, height, scale }) => stageFlags({ width, height }).map((f) => (f === "--force-device-scale-factor=1" ? `--force-device-scale-factor=${scale}` : f));
|
|
22
|
+
|
|
23
|
+
export class CoverBrowser {
|
|
24
|
+
static async open({ stageDir, faces, width, height, scale, profileDir, env = process.env, log = () => {}, page = "index.html" }) {
|
|
25
|
+
const chrome = findChrome(env);
|
|
26
|
+
if (!chrome) throw new BlockedError(EXIT.BLOCKED_NO_CHROME, "BLOCKED_NO_CHROME: Chrome/Chromium not found (set CHROME_PATH or install Google Chrome)");
|
|
27
|
+
const session = await ChromeSession.launch({ chrome, flags: coverFlags({ width, height, scale }), profileDir, routes: () => null });
|
|
28
|
+
const browser = new CoverBrowser(session, { stageDir, faces, width, height, scale, log });
|
|
29
|
+
try {
|
|
30
|
+
await browser.#attach();
|
|
31
|
+
await browser.#load(page);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
await browser.close();
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
return browser;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
constructor(session, { stageDir, faces, width, height, scale, log }) {
|
|
40
|
+
this.session = session;
|
|
41
|
+
this.width = width;
|
|
42
|
+
this.height = height;
|
|
43
|
+
this.scale = scale;
|
|
44
|
+
this.log = log;
|
|
45
|
+
this.router = stageRouter({ stageDir, faces });
|
|
46
|
+
this.errors = [];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
send(method, params = {}) {
|
|
50
|
+
return this.session.pipe.send(method, params, this.sessionId);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async evaluate(expression, { timeoutMs = 120000 } = {}) {
|
|
54
|
+
const result = await withTimeout(this.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }), timeoutMs, `cover page evaluation timed out: ${expression.slice(0, 60)}`);
|
|
55
|
+
if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description?.split("\n")[0] ?? result.exceptionDetails.text);
|
|
56
|
+
return result.result.value;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async #attach() {
|
|
60
|
+
const pipe = this.session.pipe;
|
|
61
|
+
const { targetId } = await pipe.send("Target.createTarget", { url: "about:blank" });
|
|
62
|
+
const { sessionId } = await pipe.send("Target.attachToTarget", { targetId, flatten: true });
|
|
63
|
+
this.sessionId = sessionId;
|
|
64
|
+
pipe.on("Fetch.requestPaused", (p, sid) => {
|
|
65
|
+
if (sid === sessionId) this.#serve(p);
|
|
66
|
+
});
|
|
67
|
+
pipe.on("Runtime.exceptionThrown", (p, sid) => {
|
|
68
|
+
if (sid === sessionId) this.errors.push(p.exceptionDetails?.exception?.description?.split("\n")[0] ?? p.exceptionDetails?.text ?? "error");
|
|
69
|
+
});
|
|
70
|
+
await this.send("Page.enable");
|
|
71
|
+
await this.send("Runtime.enable");
|
|
72
|
+
await this.send("Emulation.setDeviceMetricsOverride", { width: this.width, height: this.height, deviceScaleFactor: this.scale, mobile: false });
|
|
73
|
+
await this.send("Fetch.enable", { patterns: [{ urlPattern: "*", requestStage: "Request" }] });
|
|
74
|
+
await this.send("Page.addScriptToEvaluateOnNewDocument", { source: readFileSync(COVER_INIT_FILE, "utf8") });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async #serve(params) {
|
|
78
|
+
const answer = this.router.route(params.request.url);
|
|
79
|
+
try {
|
|
80
|
+
if (answer.kind === "blocked") await this.send("Fetch.failRequest", { requestId: params.requestId, errorReason: "BlockedByClient" });
|
|
81
|
+
else if (answer.kind === "missing") await this.send("Fetch.fulfillRequest", { requestId: params.requestId, responseCode: 404, body: "" });
|
|
82
|
+
else {
|
|
83
|
+
const body = answer.kind === "file" ? readFileSync(answer.file) : Buffer.from(answer.body);
|
|
84
|
+
await this.send("Fetch.fulfillRequest", {
|
|
85
|
+
requestId: params.requestId, responseCode: 200,
|
|
86
|
+
responseHeaders: [{ name: "Content-Type", value: answer.type }, { name: "Cache-Control", value: "no-store" }],
|
|
87
|
+
body: body.toString("base64"),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
} catch (error) {
|
|
91
|
+
this.log(`cover serve ${params.request.url}: ${error.message}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Throw the named exit for anything the page did that a cover page may not do. */
|
|
96
|
+
async check(context) {
|
|
97
|
+
if (this.router.refused.length) {
|
|
98
|
+
const first = this.router.refused[0];
|
|
99
|
+
throw new BlockedError(EXIT.STAGE_NETWORK_REQUEST, `STAGE_NETWORK_REQUEST: the cover page requested ${first.url.slice(0, 160)} (${first.reason}); everything is local`);
|
|
100
|
+
}
|
|
101
|
+
const misuse = await this.evaluate("window.__litCoverMisuse ? window.__litCoverMisuse() : []").catch(() => []);
|
|
102
|
+
if (misuse.length) throw new BlockedError(EXIT.STAGE_NONDETERMINISTIC, `STAGE_NONDETERMINISTIC: the cover page called ${misuse.join(", ")}${context ? ` ${context}` : ""}; a cover frame is a function of t only (LitLoop.rng(seed) for layout)`);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async #load(page) {
|
|
106
|
+
await this.send("Page.navigate", { url: `${STAGE_ORIGIN}/${page}` });
|
|
107
|
+
const deadline = Date.now() + 60000;
|
|
108
|
+
for (;;) {
|
|
109
|
+
const state = await this.evaluate("[document.readyState, window.ready === true, typeof window.renderFrame]").catch(() => ["loading", false, "undefined"]);
|
|
110
|
+
if (state[0] === "complete" && state[1]) {
|
|
111
|
+
await this.check("while loading");
|
|
112
|
+
if (state[2] !== "function") throw new BlockedError(EXIT.STAGE_CONTRACT_ERROR, "STAGE_CONTRACT_ERROR: the cover page set window.ready but defines no window.renderFrame(t)");
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
// An uncaught error before window.ready is a stage-contract stop (a missing ART entry, a bad
|
|
116
|
+
// hero index): report it now instead of after the ready wait runs out.
|
|
117
|
+
if (this.errors.length) {
|
|
118
|
+
await this.check("while loading");
|
|
119
|
+
throw new BlockedError(EXIT.STAGE_CONTRACT_ERROR, `STAGE_CONTRACT_ERROR: the cover page stopped before it set window.ready; first page error: ${this.errors[0]}`);
|
|
120
|
+
}
|
|
121
|
+
if (Date.now() > deadline) {
|
|
122
|
+
await this.check("while loading");
|
|
123
|
+
const why = this.errors[0] ? `; first page error: ${this.errors[0]}` : state[0] === "complete" ? "; it never set window.ready = true" : "";
|
|
124
|
+
throw new BlockedError(EXIT.STAGE_CONTRACT_ERROR, `STAGE_CONTRACT_ERROR: the cover page was not ready within 60 s${why}`);
|
|
125
|
+
}
|
|
126
|
+
await sleep(50);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Draw loop time t (and the mask variant) and wait for the frame to settle. */
|
|
131
|
+
async frame(t, { mask = false } = {}) {
|
|
132
|
+
try {
|
|
133
|
+
await this.evaluate(`(async () => { await window.renderFrame(${t}, ${JSON.stringify({ mask })}); if (document.fonts) await document.fonts.ready; return true; })()`);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
await this.check(`at t = ${t.toFixed(4)}`);
|
|
136
|
+
throw new BlockedError(EXIT.STAGE_CONTRACT_ERROR, `STAGE_CONTRACT_ERROR: renderFrame(${t.toFixed(4)}${mask ? ", { mask: true }" : ""}) threw: ${error.message}`);
|
|
137
|
+
}
|
|
138
|
+
await this.check(`at t = ${t.toFixed(4)}`);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The viewport at device scale: a PNG of (width x scale) by (height x scale). */
|
|
142
|
+
async capture() {
|
|
143
|
+
const shot = await this.send("Page.captureScreenshot", {
|
|
144
|
+
format: "png", optimizeForSpeed: true, captureBeyondViewport: false, fromSurface: true,
|
|
145
|
+
clip: { x: 0, y: 0, width: this.width, height: this.height, scale: 1 },
|
|
146
|
+
});
|
|
147
|
+
return Buffer.from(shot.data, "base64");
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async close() {
|
|
151
|
+
await this.session.close();
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Workers that downsample and write captured frames; results come back per job. */
|
|
156
|
+
export class CoverPool {
|
|
157
|
+
constructor(size = Math.max(2, Math.min(6, cpus().length - 2))) {
|
|
158
|
+
this.workers = Array.from({ length: size }, () => new Worker(new URL("./cover-worker.mjs", import.meta.url)));
|
|
159
|
+
this.next = 0;
|
|
160
|
+
this.id = 0;
|
|
161
|
+
this.waiting = new Map();
|
|
162
|
+
for (const w of this.workers) {
|
|
163
|
+
w.on("message", (msg) => {
|
|
164
|
+
const done = this.waiting.get(msg.id);
|
|
165
|
+
this.waiting.delete(msg.id);
|
|
166
|
+
if (msg.error) done.reject(new Error(msg.error));
|
|
167
|
+
else done.resolve(msg);
|
|
168
|
+
});
|
|
169
|
+
w.on("error", (error) => {
|
|
170
|
+
for (const p of this.waiting.values()) p.reject(error);
|
|
171
|
+
this.waiting.clear();
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
process(png, width, height, file = null) {
|
|
177
|
+
const id = ++this.id;
|
|
178
|
+
const worker = this.workers[this.next++ % this.workers.length];
|
|
179
|
+
const copy = png.buffer.slice(png.byteOffset, png.byteOffset + png.byteLength);
|
|
180
|
+
return new Promise((resolve, reject) => {
|
|
181
|
+
this.waiting.set(id, { resolve, reject });
|
|
182
|
+
worker.postMessage({ id, png: copy, width, height, file }, [copy]);
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async close() {
|
|
187
|
+
await Promise.all(this.workers.map((w) => w.terminate()));
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Capture loop times `times` (an array of [index, t]) in the given order into `dir` as
|
|
193
|
+
* `<prefix><index>.png` at the cover size. Returns Map index -> sha256 of the written PNG.
|
|
194
|
+
*/
|
|
195
|
+
export async function capturePass({ browser, pool, times, dir, prefix = "f", mask = false, width, height }) {
|
|
196
|
+
const out = new Map();
|
|
197
|
+
const pending = [];
|
|
198
|
+
const expected = `${browser.width * browser.scale}x${browser.height * browser.scale}`;
|
|
199
|
+
for (const [index, t] of times) {
|
|
200
|
+
await browser.frame(t, { mask });
|
|
201
|
+
const png = await browser.capture();
|
|
202
|
+
const file = dir ? `${dir}/${prefix}${String(index).padStart(4, "0")}.png` : null;
|
|
203
|
+
pending.push(pool.process(png, width, height, file).then((r) => {
|
|
204
|
+
if (r.captured !== expected) throw new BlockedError(EXIT.STAGE_CONTRACT_ERROR, `STAGE_CONTRACT_ERROR: captured ${r.captured}, expected ${expected} (the page must not resize its viewport)`);
|
|
205
|
+
out.set(index, r.sha256);
|
|
206
|
+
}));
|
|
207
|
+
}
|
|
208
|
+
await Promise.all(pending);
|
|
209
|
+
return out;
|
|
210
|
+
}
|