@blackbelt-technology/pi-dashboard-deck3d 0.0.0-stage → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/.pi/skills/deck3d/SKILL.md +227 -0
  2. package/.pi/skills/deck3d/examples/deck.json +388 -0
  3. package/.pi/skills/deck3d/examples/fixture.md +18 -0
  4. package/.pi/skills/deck3d/examples/snapshot-after.png +0 -0
  5. package/.pi/skills/deck3d/examples/snapshot-before.png +0 -0
  6. package/.pi/skills/deck3d/reference/effects.agent.md +78 -0
  7. package/.pi/skills/deck3d/reference/effects.md +1217 -0
  8. package/.pi/skills/deck3d/reference/ir-fields.agent.md +30 -0
  9. package/.pi/skills/deck3d/reference/ir-fields.md +246 -0
  10. package/README.md +177 -2
  11. package/assets/LICENSE-Poppins.txt +99 -0
  12. package/assets/Poppins-Bold.ttf +0 -0
  13. package/assets/props/LICENSES.txt +4 -0
  14. package/assets/props/brain.glb +0 -0
  15. package/assets/props/cloud.glb +0 -0
  16. package/assets/props/cube.glb +0 -0
  17. package/assets/props/database.glb +0 -0
  18. package/assets/props/laptop.glb +0 -0
  19. package/assets/props/manifest.json +119 -0
  20. package/assets/props/robot.glb +0 -0
  21. package/assets/props/server.glb +0 -0
  22. package/assets/props/shield.glb +0 -0
  23. package/bin/deck3d +49 -0
  24. package/dist/cli.js +10228 -0
  25. package/dist/harvest/harness.js +185718 -0
  26. package/dist/runtime.js +64597 -0
  27. package/fixtures/business-2031/build-deck.mjs +60 -0
  28. package/fixtures/business-2031/build-overrides.mjs +154 -0
  29. package/fixtures/business-2031/deck.json +4220 -0
  30. package/fixtures/business-2031/deck.md +470 -0
  31. package/fixtures/business-2031/fx/closing-mark.js +43 -0
  32. package/fixtures/business-2031/fx/closing-mark.meta.json +26 -0
  33. package/fixtures/business-2031/overrides.json +903 -0
  34. package/fixtures/harvest.md +23 -0
  35. package/fixtures/strategy-lab.json +891 -0
  36. package/fixtures/strategy-lab.md +85 -0
  37. package/package.json +80 -4
  38. package/scripts/build-cli.mjs +29 -0
  39. package/scripts/build-harvest.ts +8 -0
  40. package/scripts/build-runtime.mjs +22 -0
  41. package/scripts/gen-effects.ts +14 -0
  42. package/scripts/gen-ir-fields.ts +34 -0
  43. package/src/check/index.ts +315 -0
  44. package/src/check/rules.ts +393 -0
  45. package/src/cli-io.ts +23 -0
  46. package/src/cli.ts +823 -0
  47. package/src/fx/accent-cycle.meta.json +26 -0
  48. package/src/fx/accent-cycle.ts +8 -0
  49. package/src/fx/agent-depth.meta.json +42 -0
  50. package/src/fx/agent-depth.ts +62 -0
  51. package/src/fx/ascii.meta.json +35 -0
  52. package/src/fx/ascii.ts +4 -0
  53. package/src/fx/aurora.meta.json +26 -0
  54. package/src/fx/aurora.ts +18 -0
  55. package/src/fx/billboards.meta.json +34 -0
  56. package/src/fx/billboards.ts +67 -0
  57. package/src/fx/bloom.meta.json +26 -0
  58. package/src/fx/bloom.ts +4 -0
  59. package/src/fx/camera-drift.meta.json +26 -0
  60. package/src/fx/camera-drift.ts +8 -0
  61. package/src/fx/capital-flows.meta.json +30 -0
  62. package/src/fx/capital-flows.ts +64 -0
  63. package/src/fx/catalogue.ts +89 -0
  64. package/src/fx/chromatic-aberration.meta.json +32 -0
  65. package/src/fx/chromatic-aberration.ts +4 -0
  66. package/src/fx/city-grid.meta.json +37 -0
  67. package/src/fx/city-grid.ts +51 -0
  68. package/src/fx/clipped-solids.meta.json +49 -0
  69. package/src/fx/clipped-solids.ts +171 -0
  70. package/src/fx/cohort-grid.meta.json +48 -0
  71. package/src/fx/cohort-grid.ts +63 -0
  72. package/src/fx/compose.ts +114 -0
  73. package/src/fx/constellation.meta.json +51 -0
  74. package/src/fx/constellation.ts +103 -0
  75. package/src/fx/curve-flow.meta.json +40 -0
  76. package/src/fx/curve-flow.ts +63 -0
  77. package/src/fx/dashed-flow.meta.json +27 -0
  78. package/src/fx/dashed-flow.ts +8 -0
  79. package/src/fx/data-columns.meta.json +30 -0
  80. package/src/fx/data-columns.ts +18 -0
  81. package/src/fx/defaults.ts +92 -0
  82. package/src/fx/depth-of-field.meta.json +40 -0
  83. package/src/fx/depth-of-field.ts +4 -0
  84. package/src/fx/dolly.meta.json +26 -0
  85. package/src/fx/dolly.ts +4 -0
  86. package/src/fx/dot-screen.meta.json +35 -0
  87. package/src/fx/dot-screen.ts +4 -0
  88. package/src/fx/dynamic-instances.meta.json +40 -0
  89. package/src/fx/dynamic-instances.ts +57 -0
  90. package/src/fx/emissive.meta.json +26 -0
  91. package/src/fx/emissive.ts +8 -0
  92. package/src/fx/extruded-shapes.meta.json +62 -0
  93. package/src/fx/extruded-shapes.ts +133 -0
  94. package/src/fx/fab-wafer.meta.json +42 -0
  95. package/src/fx/fab-wafer.ts +72 -0
  96. package/src/fx/fade.meta.json +26 -0
  97. package/src/fx/fade.ts +4 -0
  98. package/src/fx/film.meta.json +26 -0
  99. package/src/fx/film.ts +4 -0
  100. package/src/fx/float.meta.json +26 -0
  101. package/src/fx/float.ts +8 -0
  102. package/src/fx/flythrough.meta.json +26 -0
  103. package/src/fx/flythrough.ts +4 -0
  104. package/src/fx/fog.meta.json +26 -0
  105. package/src/fx/fog.ts +8 -0
  106. package/src/fx/geo-fragments.meta.json +48 -0
  107. package/src/fx/geo-fragments.ts +59 -0
  108. package/src/fx/glass.meta.json +26 -0
  109. package/src/fx/glass.ts +8 -0
  110. package/src/fx/globe-arcs.meta.json +36 -0
  111. package/src/fx/globe-arcs.ts +67 -0
  112. package/src/fx/glow-tube.meta.json +26 -0
  113. package/src/fx/glow-tube.ts +8 -0
  114. package/src/fx/glyph-rain.meta.json +30 -0
  115. package/src/fx/glyph-rain.ts +18 -0
  116. package/src/fx/god-rays.meta.json +40 -0
  117. package/src/fx/god-rays.ts +4 -0
  118. package/src/fx/grid-horizon.meta.json +30 -0
  119. package/src/fx/grid-horizon.ts +18 -0
  120. package/src/fx/hex-grid.meta.json +29 -0
  121. package/src/fx/hex-grid.ts +18 -0
  122. package/src/fx/holo-fresnel.meta.json +26 -0
  123. package/src/fx/holo-fresnel.ts +8 -0
  124. package/src/fx/horizon-gates.meta.json +36 -0
  125. package/src/fx/horizon-gates.ts +60 -0
  126. package/src/fx/index.ts +258 -0
  127. package/src/fx/iridescent.meta.json +26 -0
  128. package/src/fx/iridescent.ts +8 -0
  129. package/src/fx/iris.meta.json +26 -0
  130. package/src/fx/iris.ts +4 -0
  131. package/src/fx/lightformers.meta.json +26 -0
  132. package/src/fx/lightformers.ts +8 -0
  133. package/src/fx/local.ts +200 -0
  134. package/src/fx/market-tape.meta.json +53 -0
  135. package/src/fx/market-tape.ts +97 -0
  136. package/src/fx/matcap.meta.json +26 -0
  137. package/src/fx/matcap.ts +8 -0
  138. package/src/fx/meta.schema.json +49 -0
  139. package/src/fx/metal.meta.json +26 -0
  140. package/src/fx/metal.ts +8 -0
  141. package/src/fx/mirror-floor.meta.json +26 -0
  142. package/src/fx/mirror-floor.ts +8 -0
  143. package/src/fx/neural-mesh.meta.json +54 -0
  144. package/src/fx/neural-mesh.ts +110 -0
  145. package/src/fx/orbit-agents.meta.json +36 -0
  146. package/src/fx/orbit-agents.ts +63 -0
  147. package/src/fx/orbit.meta.json +27 -0
  148. package/src/fx/orbit.ts +8 -0
  149. package/src/fx/outline.meta.json +43 -0
  150. package/src/fx/outline.ts +4 -0
  151. package/src/fx/paper-stack.meta.json +36 -0
  152. package/src/fx/paper-stack.ts +61 -0
  153. package/src/fx/particle-stream.meta.json +27 -0
  154. package/src/fx/particle-stream.ts +8 -0
  155. package/src/fx/particles.meta.json +26 -0
  156. package/src/fx/particles.ts +8 -0
  157. package/src/fx/pixelate.meta.json +28 -0
  158. package/src/fx/pixelate.ts +4 -0
  159. package/src/fx/points-on-geometry.meta.json +61 -0
  160. package/src/fx/points-on-geometry.ts +71 -0
  161. package/src/fx/proof-gate.meta.json +30 -0
  162. package/src/fx/proof-gate.ts +67 -0
  163. package/src/fx/rings.meta.json +27 -0
  164. package/src/fx/rings.ts +8 -0
  165. package/src/fx/room-ibl.meta.json +26 -0
  166. package/src/fx/room-ibl.ts +8 -0
  167. package/src/fx/sao.meta.json +32 -0
  168. package/src/fx/sao.ts +4 -0
  169. package/src/fx/scaffold.ts +172 -0
  170. package/src/fx/scatter.meta.json +49 -0
  171. package/src/fx/scatter.ts +74 -0
  172. package/src/fx/selective-bloom.meta.json +36 -0
  173. package/src/fx/selective-bloom.ts +4 -0
  174. package/src/fx/server-racks.meta.json +36 -0
  175. package/src/fx/server-racks.ts +54 -0
  176. package/src/fx/shader-particles.meta.json +46 -0
  177. package/src/fx/shader-particles.ts +75 -0
  178. package/src/fx/signal-pulse.meta.json +27 -0
  179. package/src/fx/signal-pulse.ts +8 -0
  180. package/src/fx/smaa.meta.json +19 -0
  181. package/src/fx/smaa.ts +4 -0
  182. package/src/fx/sobel.meta.json +24 -0
  183. package/src/fx/sobel.ts +4 -0
  184. package/src/fx/soft-shadows.meta.json +26 -0
  185. package/src/fx/soft-shadows.ts +8 -0
  186. package/src/fx/sprites.meta.json +40 -0
  187. package/src/fx/sprites.ts +57 -0
  188. package/src/fx/stagger-reveal.meta.json +26 -0
  189. package/src/fx/stagger-reveal.ts +8 -0
  190. package/src/fx/starfield.meta.json +32 -0
  191. package/src/fx/starfield.ts +18 -0
  192. package/src/fx/swarm.meta.json +27 -0
  193. package/src/fx/swarm.ts +8 -0
  194. package/src/fx/tessellate.meta.json +39 -0
  195. package/src/fx/tessellate.ts +79 -0
  196. package/src/fx/tokens.meta.json +27 -0
  197. package/src/fx/tokens.ts +8 -0
  198. package/src/fx/trail.meta.json +27 -0
  199. package/src/fx/trail.ts +8 -0
  200. package/src/fx/trust-ledger.meta.json +30 -0
  201. package/src/fx/trust-ledger.ts +47 -0
  202. package/src/fx/types.ts +83 -0
  203. package/src/fx/util.ts +108 -0
  204. package/src/fx/vault-glyphs.meta.json +37 -0
  205. package/src/fx/vault-glyphs.ts +55 -0
  206. package/src/fx/video-screen.meta.json +57 -0
  207. package/src/fx/video-screen.ts +99 -0
  208. package/src/fx/vignette.meta.json +32 -0
  209. package/src/fx/vignette.ts +4 -0
  210. package/src/fx/volume-cloud.meta.json +58 -0
  211. package/src/fx/volume-cloud.ts +87 -0
  212. package/src/fx/volume-perlin.meta.json +46 -0
  213. package/src/fx/volume-perlin.ts +82 -0
  214. package/src/fx/volumetric-spot.meta.json +26 -0
  215. package/src/fx/volumetric-spot.ts +8 -0
  216. package/src/fx/wireframe-overlay.meta.json +27 -0
  217. package/src/fx/wireframe-overlay.ts +8 -0
  218. package/src/ir/defaults.ts +62 -0
  219. package/src/ir/field-reference.ts +96 -0
  220. package/src/ir/hash.ts +34 -0
  221. package/src/ir/ids.ts +65 -0
  222. package/src/ir/merge.ts +155 -0
  223. package/src/ir/schema.json +1211 -0
  224. package/src/ir/types.ts +333 -0
  225. package/src/ir/validate.ts +196 -0
  226. package/src/parse/derive.ts +205 -0
  227. package/src/parse/harvest/bundle.ts +56 -0
  228. package/src/parse/harvest/harness.html +22 -0
  229. package/src/parse/harvest/harness.ts +191 -0
  230. package/src/parse/harvest/index.ts +169 -0
  231. package/src/parse/harvest/shapes.ts +75 -0
  232. package/src/parse/markdown.ts +215 -0
  233. package/src/props/embed.ts +92 -0
  234. package/src/props/fetch.ts +97 -0
  235. package/src/props/generate.ts +152 -0
  236. package/src/props/key.ts +13 -0
  237. package/src/props/search.ts +180 -0
  238. package/src/render/embed-video.ts +80 -0
  239. package/src/render/font.ts +86 -0
  240. package/src/render/index.ts +149 -0
  241. package/src/render/template.html +87 -0
  242. package/src/runtime/backgrounds.ts +146 -0
  243. package/src/runtime/builders.ts +808 -0
  244. package/src/runtime/camera.ts +73 -0
  245. package/src/runtime/hud.ts +887 -0
  246. package/src/runtime/index.ts +1168 -0
  247. package/src/runtime/local-fx.ts +151 -0
  248. package/src/runtime/materials.ts +136 -0
  249. package/src/runtime/measure.ts +73 -0
  250. package/src/runtime/node-geometry.ts +26 -0
  251. package/src/runtime/palette.ts +111 -0
  252. package/src/runtime/post.ts +649 -0
  253. package/src/runtime/props.ts +292 -0
  254. package/src/runtime/quality.ts +20 -0
  255. package/src/runtime/rng.ts +8 -0
  256. package/src/runtime/scene.ts +644 -0
  257. package/src/runtime/text.ts +174 -0
  258. package/src/runtime/types.ts +118 -0
  259. package/src/serve/index.ts +376 -0
  260. package/src/util/paths.ts +35 -0
package/src/cli.ts ADDED
@@ -0,0 +1,823 @@
1
+ /**
2
+ * deck3d CLI entry — `parse | validate | render | build | check | snapshot`,
3
+ * plus the `fx` and `props` sub-trees.
4
+ *
5
+ * Exit codes: 0 success, 1 failure (with a one-line reason on stderr), 2 usage.
6
+ */
7
+ import { spawnSync } from "node:child_process";
8
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { basename, dirname, join } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import type { DeckIR, Palette } from "./ir/types.js";
13
+ import { formatIssue, validate } from "./ir/validate.js";
14
+ import { type DeriveOptions, parseDeck } from "./parse/derive.js";
15
+ import { pkgRoot } from "./util/paths.js";
16
+
17
+ export const VERSION = "0.1.0";
18
+
19
+ /** Named palettes accepted by `--palette`; mirrors the schema enum. */
20
+ const PALETTE_IDS: Palette[] = ["blackbelt", "zenit", "dapp", "midnight", "ember", "arctic", "forest", "mono", "neon", "custom"];
21
+
22
+ export type { CliIO, CliRun } from "./cli-io.js";
23
+ import type { CliIO } from "./cli-io.js";
24
+
25
+ export const defaultIO: CliIO = {
26
+ stdout: (line) => process.stdout.write(`${line}\n`),
27
+ stderr: (line) => process.stderr.write(`${line}\n`),
28
+ };
29
+
30
+ export const HELP = `deck3d — deterministic markdown → self-contained 3D presentation
31
+
32
+ Usage: deck3d <command> [options]
33
+
34
+ Commands:
35
+ parse <deck.md> [-o deck.json] [--fresh] Markdown (+ mermaid) → Deck IR
36
+ validate <deck.json> Schema + derived-edit checks
37
+ render <deck.json> -o deck.html Deck IR → self-contained HTML
38
+ build <deck.md> -o deck.html parse → render (writes .json beside it)
39
+ serve <deck.md> [--port n] [--check] Watch + rebuild + live reload; panel saves overrides to disk
40
+ check <deck.html> [--style] Measure fit/legibility in headless chromium
41
+ snapshot <deck.html> [--slide n] [-o png] Screenshot a slide to PNG
42
+ fx <list|preview> Inspect the effects corpus
43
+ props <search|fetch|generate> Illustrate slides with glTF models
44
+ overrides apply <deck.json> <file> Merge an overrides-grammar file into the deck
45
+
46
+ fx options:
47
+ fx list [--kind k] [--tag t] [--topic p] List effects (optionally filtered)
48
+ fx preview <id> [--palette p] [-o out.png] Render one effect to a PNG (accepts local:<name>)
49
+ fx scaffold <name> [--kind k] [--for id] Write fx/<name>.js + card, print the override entry
50
+ fx hash <name> Print the sha256 of fx/<name>.js
51
+ fx promote <name> --source u --licence l Move a local effect into the corpus
52
+ props options:
53
+ props search <kw> [--role ambient] Candidates (ambient = low-tri + entry template)
54
+ props generate --from-image <img> --name <n> Geometry-only GLB via Hunyuan3D-2
55
+ props generate --prompt <text> --name <n> Text → image → GLB (DECK3D_T2I_URL)
56
+
57
+ Options:
58
+ -h, --help Show this help
59
+ -v, --version Print the version
60
+ `;
61
+
62
+ interface Flags {
63
+ positional: string[];
64
+ bool: Set<string>;
65
+ value: Record<string, string>;
66
+ }
67
+
68
+ /** Flags that consume the next argument as their value. */
69
+ const VALUE_FLAGS = new Set([
70
+ "-o",
71
+ "--out",
72
+ "--viewport",
73
+ "--slide",
74
+ "--kind",
75
+ "--tag",
76
+ "--topic",
77
+ "--palette",
78
+ "--from-image",
79
+ "--prompt",
80
+ "--name",
81
+ "--role",
82
+ "--for",
83
+ "--source",
84
+ "--licence",
85
+ "--port",
86
+ ]);
87
+
88
+ function parseArgs(args: string[]): Flags {
89
+ const flags: Flags = { positional: [], bool: new Set(), value: {} };
90
+ for (let i = 0; i < args.length; i++) {
91
+ const arg = args[i];
92
+ if (VALUE_FLAGS.has(arg)) {
93
+ const key = arg === "-o" ? "out" : arg.replace(/^--?/, "");
94
+ flags.value[key] = args[++i] ?? "";
95
+ } else if (arg.startsWith("-")) {
96
+ flags.bool.add(arg.replace(/^--?/, ""));
97
+ } else {
98
+ flags.positional.push(arg);
99
+ }
100
+ }
101
+ return flags;
102
+ }
103
+
104
+ function writeJson(path: string, value: unknown): void {
105
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
106
+ }
107
+
108
+ function defaultJsonPath(mdPath: string): string {
109
+ return `${mdPath.replace(/\.md$/i, "")}.json`;
110
+ }
111
+
112
+ /** Shared parse: markdown (+ mermaid harvest when present) → IR on disk. */
113
+ async function parseToFile(mdPath: string, outPath: string, flags: Flags, io: CliIO): Promise<number> {
114
+ const source = readFileSync(mdPath, "utf8");
115
+ const opts: DeriveOptions = { source: mdPath };
116
+ if (flags.bool.has("fresh")) opts.fresh = true;
117
+ else if (existsSync(outPath)) {
118
+ try {
119
+ opts.previous = JSON.parse(readFileSync(outPath, "utf8"));
120
+ } catch {
121
+ // A corrupt prior file is not fatal for parse — start fresh.
122
+ }
123
+ }
124
+ if (source.includes("```mermaid")) {
125
+ const { harvestDiagram } = await import("./parse/harvest/index.js");
126
+ opts.harvest = (mermaidSource, slideId) => harvestDiagram(mermaidSource, slideId);
127
+ }
128
+ const { defaultEffectsFor, defaultSceneFor } = await import("./fx/defaults.js");
129
+ opts.effectsForSlide = (slide, autoStyle) => defaultEffectsFor(slide, autoStyle);
130
+ opts.sceneForSlide = (slide, autoStyle) => defaultSceneFor(slide, autoStyle);
131
+ const { ir, warnings } = await parseDeck(source, opts);
132
+ for (const warning of warnings) io.stderr(warning);
133
+ writeJson(outPath, ir);
134
+ return 0;
135
+ }
136
+
137
+ async function cmdParse(args: string[], io: CliIO): Promise<number> {
138
+ const flags = parseArgs(args);
139
+ const mdPath = flags.positional[0];
140
+ if (!mdPath) {
141
+ io.stderr("deck3d parse: missing <deck.md>");
142
+ return 2;
143
+ }
144
+ const outPath = flags.value.out ?? defaultJsonPath(mdPath);
145
+ try {
146
+ const code = await parseToFile(mdPath, outPath, flags, io);
147
+ io.stdout(`wrote ${outPath}`);
148
+ return code;
149
+ } catch (err) {
150
+ io.stderr(`deck3d parse: ${(err as Error).message}`);
151
+ return 1;
152
+ }
153
+ }
154
+
155
+ async function cmdValidate(args: string[], io: CliIO): Promise<number> {
156
+ const file = parseArgs(args).positional[0];
157
+ if (!file) {
158
+ io.stderr("deck3d validate: missing <deck.json>");
159
+ return 2;
160
+ }
161
+ let parsed: unknown;
162
+ try {
163
+ parsed = JSON.parse(readFileSync(file, "utf8"));
164
+ } catch (err) {
165
+ io.stderr(`deck3d validate: invalid JSON in ${file}: ${(err as Error).message}`);
166
+ return 1;
167
+ }
168
+ const result = validate(parsed, { propBytes: cachedPropBytes(file), deckDir: dirname(file) });
169
+ for (const issue of result.errors) io.stderr(formatIssue("error", issue));
170
+ for (const warning of result.warnings) io.stderr(formatIssue("warn", warning));
171
+ if (result.ok) {
172
+ const { validateEffectParams } = await import("./fx/compose.js");
173
+ const violations = validateEffectParams(parsed as Parameters<typeof validateEffectParams>[0]);
174
+ for (const v of violations) io.stderr(`error ${v.path}: ${v.message}`);
175
+ if (violations.length) return 1;
176
+ }
177
+ if (result.errors.length === 0) io.stdout(`${file}: valid`);
178
+ return result.ok ? 0 : 1;
179
+ }
180
+
181
+ /** Load + validate a deck.json; returns undefined on failure (already reported). */
182
+ function loadValidated(file: string, io: CliIO): DeckIR | undefined {
183
+ let parsed: unknown;
184
+ try {
185
+ parsed = JSON.parse(readFileSync(file, "utf8"));
186
+ } catch (err) {
187
+ io.stderr(`deck3d: invalid JSON in ${file}: ${(err as Error).message}`);
188
+ return undefined;
189
+ }
190
+ // `render` re-checks the local referents it is about to embed.
191
+ const result = validate(parsed, { deckDir: dirname(file) });
192
+ if (!result.ok) {
193
+ for (const issue of result.errors) io.stderr(formatIssue("error", issue));
194
+ return undefined;
195
+ }
196
+ return parsed as DeckIR;
197
+ }
198
+
199
+ async function renderFile(jsonPath: string, outPath: string, io: CliIO, embedVideoFlag = false): Promise<number> {
200
+ const ir = loadValidated(jsonPath, io);
201
+ if (!ir) return 1;
202
+ const { composeEffects, validateEffectParams } = await import("./fx/compose.js");
203
+ const { ensureRuntime, renderDeck, fontBase64, loadLocalEffects } = await import("./render/index.js");
204
+ // Resolve the local effects first: their cards take part in param bounds,
205
+ // conflict, mode and budget gating exactly like corpus cards.
206
+ const localFx = loadLocalEffects(ir, jsonPath);
207
+ const localCards = Object.fromEntries(
208
+ Object.entries(localFx).map(([name, m]) => [name, m.card as import("./fx/types.js").FxCard]),
209
+ );
210
+ const violations = validateEffectParams(ir, localCards);
211
+ if (violations.length) {
212
+ for (const v of violations) io.stderr(`error ${v.path}: ${v.message}`);
213
+ return 1;
214
+ }
215
+ // Compose the MERGED view: `overrides.effects` + `overrides.slides[id].effects`
216
+ // are already folded into each slide's effective list by `applyOverrides`.
217
+ const { applyOverrides } = await import("./ir/merge.js");
218
+ const merged = applyOverrides(ir);
219
+ for (const slide of merged.slides) {
220
+ const ov = ir.overrides.slides?.[slide.id];
221
+ const mode = ov?.mode ?? ir.overrides.deck?.mode ?? ir.defaults.mode ?? "dark";
222
+ const quality = ov?.quality ?? ir.overrides.deck?.quality ?? ir.defaults.quality ?? "high";
223
+ const comp = composeEffects(slide.effects, mode, quality, slide.id, localCards);
224
+ for (const warning of comp.warnings) io.stderr(warning);
225
+ if (comp.conflicts.length) {
226
+ for (const c of comp.conflicts) io.stderr(`error conflict ${c}`);
227
+ return 1;
228
+ }
229
+ }
230
+ const { loadProps } = await import("./props/embed.js");
231
+ const runtime = await ensureRuntime();
232
+ const props = loadProps(ir, jsonPath);
233
+ // `--embed-video` inlines clips as `data:` URLs so the html stays ONE file.
234
+ // Without it the clip is fetched relative to the page, which `deck3d serve`
235
+ // answers from its asset route.
236
+ let renderIr = ir;
237
+ if (embedVideoFlag) {
238
+ const { embedVideo } = await import("./render/embed-video.js");
239
+ const result = embedVideo(ir, jsonPath);
240
+ for (const w of result.warnings) io.stderr(`warning ${w}`);
241
+ const total = Object.values(result.embedded).reduce((a, b) => a + b, 0);
242
+ if (total) io.stdout(`embedded ${Object.keys(result.embedded).length} clip(s), ${(total / 1024 / 1024).toFixed(1)} MiB`);
243
+ renderIr = result.ir;
244
+ }
245
+ const html = renderDeck(renderIr, { runtime, font: fontBase64(), title: basename(jsonPath, ".json"), props, localFx });
246
+ writeFileSync(outPath, html);
247
+ return 0;
248
+ }
249
+
250
+ async function cmdRender(args: string[], io: CliIO): Promise<number> {
251
+ const flags = parseArgs(args);
252
+ const jsonPath = flags.positional[0];
253
+ if (!jsonPath) {
254
+ io.stderr("deck3d render: missing <deck.json>");
255
+ return 2;
256
+ }
257
+ const outPath = flags.value.out ?? jsonPath.replace(/\.json$/i, ".html");
258
+ try {
259
+ const code = await renderFile(jsonPath, outPath, io, flags.bool.has("embed-video"));
260
+ if (code === 0) io.stdout(`wrote ${outPath}`);
261
+ return code;
262
+ } catch (err) {
263
+ io.stderr(`deck3d render: ${(err as Error).message}`);
264
+ return 1;
265
+ }
266
+ }
267
+
268
+ async function loadReport(htmlPath: string, flags: Flags, io: CliIO, strict: boolean, failOnFinding: boolean): Promise<{ code: number; report?: import("./check/index.js").CheckReport }> {
269
+ const { parseViewports, runCheck, CheckUnavailableError } = await import("./check/index.js");
270
+ try {
271
+ const report = await runCheck(htmlPath, {
272
+ viewports: parseViewports(flags.value.viewport),
273
+ ...(flags.value.slide ? { slides: [Number.parseInt(flags.value.slide, 10)] } : {}),
274
+ ...(flags.bool.has("style") ? { style: true } : {}),
275
+ });
276
+ return { code: 0, report };
277
+ } catch (err) {
278
+ if (err instanceof CheckUnavailableError) {
279
+ io.stderr("check skipped: chromium missing (npx playwright install chromium)");
280
+ // `--strict` makes an unrunnable check a failure even for `build`
281
+ // (which otherwise ignores findings). See spec deck3d-render: Build runs check.
282
+ return { code: strict ? 1 : 0 };
283
+ }
284
+ io.stderr(`check failed: ${(err as Error).message}`);
285
+ return { code: failOnFinding ? 1 : 0 };
286
+ }
287
+ }
288
+
289
+ function reportFindings(
290
+ report: import("./check/index.js").CheckReport,
291
+ io: CliIO,
292
+ strict: boolean,
293
+ formatFinding: (f: import("./check/index.js").Finding) => string,
294
+ reportOut?: string,
295
+ failOnFinding = true,
296
+ ): number {
297
+ if (reportOut) writeFileSync(reportOut, `${JSON.stringify(report, null, 2)}\n`);
298
+ const findings = report.viewports.flatMap((v) => v.findings);
299
+ for (const f of findings) io.stderr(formatFinding(f));
300
+ const errors = findings.filter((f) => f.severity === "error").length;
301
+ if (failOnFinding && errors > 0) return 1;
302
+ if (strict && findings.length) return 1;
303
+ io.stdout(findings.length ? `check: ${errors} error(s), ${findings.length - errors} warning(s)` : "check: clean");
304
+ return 0;
305
+ }
306
+
307
+ async function runCheckAndReport(htmlPath: string, flags: Flags, io: CliIO, failOnFinding: boolean, reportOut?: string): Promise<number> {
308
+ const { formatFinding } = await import("./check/index.js");
309
+ const strict = flags.bool.has("strict");
310
+ const { code, report } = await loadReport(htmlPath, flags, io, strict, failOnFinding);
311
+ if (!report) return code;
312
+ return reportFindings(report, io, strict, formatFinding, reportOut, failOnFinding);
313
+ }
314
+
315
+ async function cmdFx(args: string[], io: CliIO): Promise<number> {
316
+ const flags = parseArgs(args);
317
+ const sub = flags.positional[0];
318
+ if (sub === "preview") return fxPreview(flags, io);
319
+ if (sub === "scaffold") return fxScaffold(flags, io);
320
+ if (sub === "hash") return fxHash(flags, io);
321
+ if (sub === "promote") return fxPromote(flags, io);
322
+ if (sub !== "list") {
323
+ io.stderr(`deck3d fx: unknown subcommand '${sub ?? ""}' (try list|preview|scaffold|hash|promote)`);
324
+ return 2;
325
+ }
326
+ const { catalogue } = await import("./fx/catalogue.js");
327
+ const { FX_TOPICS } = await import("./fx/types.js");
328
+ let rows = catalogue();
329
+ if (flags.value.kind) rows = rows.filter((r) => r.kind === flags.value.kind);
330
+ if (flags.value.tag) rows = rows.filter((r) => r.content.includes(flags.value.tag) || r.mood.includes(flags.value.tag));
331
+ if (flags.value.topic) {
332
+ const topic = flags.value.topic;
333
+ // A typo must fail loudly: an unknown topic silently matching nothing looks
334
+ // like "the corpus has no effect for this", which is a different problem.
335
+ if (!(FX_TOPICS as readonly string[]).includes(topic)) {
336
+ io.stderr(`deck3d fx list: unknown topic '${topic}' (one of ${FX_TOPICS.join(", ")})`);
337
+ return 1;
338
+ }
339
+ rows = rows.filter((r) => (r.topic as string[] | undefined)?.includes(topic));
340
+ }
341
+ if (flags.bool.has("json")) {
342
+ io.stdout(JSON.stringify(rows, null, 2));
343
+ return 0;
344
+ }
345
+ for (const r of rows) io.stdout(`${r.id}\t${r.kind}\tcost ${r.cost}\t${r.modes}`);
346
+ return 0;
347
+ }
348
+
349
+ /** One-slide deck whose only effect is `id` (design D9 / 7d.3 preview). */
350
+ async function previewDeck(id: string, palette?: Palette, sha?: string): Promise<DeckIR> {
351
+ const { resolveDefaults } = await import("./ir/defaults.js");
352
+ const ref = sha ? { id, sha256: sha } : { id };
353
+ return {
354
+ meta: { engine: VERSION, mermaid: "11.17.2" },
355
+ defaults: resolveDefaults(palette ? { palette } : {}),
356
+ slides: [
357
+ {
358
+ index: 0,
359
+ id: "fx-preview",
360
+ kind: "title",
361
+ title: `fx ${id}`,
362
+ subtitle: "preview",
363
+ bullets: [],
364
+ scene: "tokens",
365
+ diagram: { kind: "none" },
366
+ effects: [ref],
367
+ },
368
+ ],
369
+ // The preview deck is rendered from a temp dir, so the local reference has
370
+ // to live in `overrides` for `loadLocalEffects` to find and embed it.
371
+ overrides: sha ? { slides: { "fx-preview": { effects: [ref] } } } : {},
372
+ };
373
+ }
374
+
375
+ /** `fx scaffold|hash|promote` — authoring a per-deck effect (design D1). */
376
+ async function fxScaffold(flags: Flags, io: CliIO): Promise<number> {
377
+ const name = flags.positional[1];
378
+ if (!name) {
379
+ io.stderr("deck3d fx scaffold: missing <name>");
380
+ return 2;
381
+ }
382
+ const { scaffoldLocalEffect } = await import("./fx/scaffold.js");
383
+ const r = scaffoldLocalEffect(process.cwd(), name, flags.value.kind ?? "background", flags.value.for);
384
+ if (!r.ok) {
385
+ io.stderr(`deck3d fx scaffold: ${r.message}`);
386
+ return 1;
387
+ }
388
+ io.stdout(r.message);
389
+ if (r.entry) io.stdout(r.entry);
390
+ return 0;
391
+ }
392
+
393
+ async function fxHash(flags: Flags, io: CliIO): Promise<number> {
394
+ const name = flags.positional[1];
395
+ if (!name) {
396
+ io.stderr("deck3d fx hash: missing <name>");
397
+ return 2;
398
+ }
399
+ const { hashLocalEffect } = await import("./fx/scaffold.js");
400
+ const r = hashLocalEffect(process.cwd(), name);
401
+ if (!r.ok) {
402
+ io.stderr(`deck3d fx hash: ${r.message}`);
403
+ return 1;
404
+ }
405
+ io.stdout(r.message);
406
+ return 0;
407
+ }
408
+
409
+ async function fxPromote(flags: Flags, io: CliIO): Promise<number> {
410
+ const name = flags.positional[1];
411
+ if (!name) {
412
+ io.stderr("deck3d fx promote: missing <name>");
413
+ return 2;
414
+ }
415
+ const { promoteLocalEffect } = await import("./fx/scaffold.js");
416
+ const corpusDir = process.env.DECK3D_CORPUS_DIR ?? join(pkgRoot(), "src", "fx");
417
+ const r = promoteLocalEffect(process.cwd(), name, {
418
+ source: flags.value.source,
419
+ licence: flags.value.licence,
420
+ corpusDir,
421
+ // The corpus gate is the real test suite: a module that will not construct
422
+ // must never land in the shipped corpus.
423
+ verify: () => {
424
+ const run = spawnSync("npx", ["vitest", "run", "src/fx/__tests__/corpus.test.ts"], {
425
+ cwd: pkgRoot(),
426
+ encoding: "utf8",
427
+ });
428
+ return { ok: run.status === 0, detail: `${run.stdout ?? ""}${run.stderr ?? ""}`.slice(-400) };
429
+ },
430
+ });
431
+ if (!r.ok) {
432
+ io.stderr(`deck3d fx promote: ${r.message}`);
433
+ return 1;
434
+ }
435
+ io.stdout(r.message);
436
+ return 0;
437
+ }
438
+
439
+ /** `fx preview <id> [-o png]` — render one effect and screenshot it (7d.7). */
440
+ async function fxPreview(flags: Flags, io: CliIO): Promise<number> {
441
+ const id = flags.positional[1];
442
+ if (!id) {
443
+ io.stderr("deck3d fx preview: missing <id>");
444
+ return 2;
445
+ }
446
+ const { isLocalId, localName, sha256 } = await import("./fx/local.js");
447
+ const local = isLocalId(id);
448
+ if (!local) {
449
+ const { REGISTRY } = await import("./fx/index.js");
450
+ if (!REGISTRY[id]) {
451
+ io.stderr(`deck3d fx preview: unknown effect '${id}' (try fx list)`);
452
+ return 1;
453
+ }
454
+ }
455
+ const modulePath = local ? join(process.cwd(), "fx", `${localName(id)}.js`) : "";
456
+ if (local && !existsSync(modulePath)) {
457
+ io.stderr(`deck3d fx preview: missing fx/${localName(id)}.js`);
458
+ return 1;
459
+ }
460
+ const palette = flags.value.palette as Palette | undefined;
461
+ if (palette && !PALETTE_IDS.includes(palette)) {
462
+ io.stderr(`deck3d fx preview: unknown palette '${palette}' (one of ${PALETTE_IDS.join(", ")})`);
463
+ return 1;
464
+ }
465
+ const out = flags.value.out ?? `${id}.png`;
466
+ try {
467
+ const { ensureRuntime, renderDeck, fontBase64, loadLocalEffects } = await import("./render/index.js");
468
+ const deck = await previewDeck(id, palette, local ? sha256(readFileSync(modulePath)) : undefined);
469
+ // Resolve against the deck dir (cwd), then render from a temp dir.
470
+ const localFx = local ? loadLocalEffects(deck, join(process.cwd(), "deck.json")) : {};
471
+ const html = renderDeck(deck, { runtime: await ensureRuntime(), font: fontBase64(), title: `fx ${id}`, localFx });
472
+ const htmlPath = join(mkdtempSync(join(tmpdir(), "deck3d-fx-")), "fx.html");
473
+ writeFileSync(htmlPath, html);
474
+ const { chromium } = await import("playwright");
475
+ const browser = await chromium.launch({ channel: "chromium" });
476
+ try {
477
+ const page = await browser.newPage({ viewport: { width: 1920, height: 1080 }, deviceScaleFactor: 1 });
478
+ await page.goto(pathToFileURL(htmlPath).href);
479
+ await page.waitForFunction(() => window.__deck3d !== undefined, undefined, { timeout: 30_000 });
480
+ await page.evaluate(() => window.__deck3d?.ready());
481
+ await page.evaluate(() => window.__deck3d?.setTime(0));
482
+ await page.waitForTimeout(200);
483
+ await page.screenshot({ path: out });
484
+ } finally {
485
+ await browser.close();
486
+ }
487
+ io.stdout(`wrote ${out}`);
488
+ return 0;
489
+ } catch (err) {
490
+ io.stderr(`deck3d fx preview: ${(err as Error).message}`);
491
+ return 1;
492
+ }
493
+ }
494
+
495
+ /** Cached `.glb` byte counts beside a deck.json, keyed `<source>-<id>`. */
496
+ function cachedPropBytes(jsonFile: string): Record<string, number> {
497
+ const dir = join(dirname(jsonFile), ".deck3d", "props");
498
+ const out: Record<string, number> = {};
499
+ if (!existsSync(dir)) return out;
500
+ for (const file of readdirSync(dir)) {
501
+ if (file.endsWith(".glb")) out[file.replace(/\.glb$/, "")] = statSync(join(dir, file)).size;
502
+ }
503
+ return out;
504
+ }
505
+
506
+ async function propsFetch(rest: string[], flags: Flags, io: CliIO): Promise<number> {
507
+ const [source, id] = rest;
508
+ if (!source || !id) {
509
+ io.stderr("deck3d props fetch: missing <source> <id>");
510
+ return 2;
511
+ }
512
+ const { searchPolyPizza, vendoredCandidates } = await import("./props/search.js");
513
+ const candidate =
514
+ source === "vendored"
515
+ ? vendoredCandidates(id).find((c) => c.id === id)
516
+ : (await searchPolyPizza(id)).candidates.find((c) => c.id === id);
517
+ if (!candidate) {
518
+ io.stderr(`deck3d props fetch: unknown ${source} prop '${id}'`);
519
+ return 1;
520
+ }
521
+ const { fetchProp } = await import("./props/fetch.js");
522
+ try {
523
+ const result = await fetchProp(candidate, { destDir: join(process.cwd(), ".deck3d", "props") });
524
+ io.stdout(
525
+ JSON.stringify(
526
+ {
527
+ source: candidate.source,
528
+ id: candidate.id,
529
+ licence: candidate.licence,
530
+ author: candidate.author,
531
+ sha256: result.sha256,
532
+ slide: flags.value.slide ?? "",
533
+ role: flags.value.role ?? "illustration",
534
+ },
535
+ null,
536
+ 2,
537
+ ),
538
+ );
539
+ return 0;
540
+ } catch (err) {
541
+ io.stderr(`deck3d props fetch: ${(err as Error).message}`);
542
+ return 1;
543
+ }
544
+ }
545
+
546
+ async function cmdProps(args: string[], io: CliIO): Promise<number> {
547
+ const flags = parseArgs(args);
548
+ const [sub, ...rest] = flags.positional;
549
+ if (sub === "search") {
550
+ const { searchProps, ambientCandidates, ambientTemplate } = await import("./props/search.js");
551
+ const result = await searchProps(rest.join(" "));
552
+ for (const notice of result.notices) io.stderr(notice);
553
+ const ambient = flags.value.role === "ambient";
554
+ const rows = ambient ? ambientCandidates(result.candidates) : result.candidates;
555
+ for (const c of rows) {
556
+ io.stdout(`${c.source}\t${c.id}\t${c.name}\t${c.licence}\t${c.bytes}b`);
557
+ // Ambient placement needs count/anim/size, which are easy to get wrong;
558
+ // print the entry rather than making the agent recall the shape.
559
+ if (ambient) io.stdout(JSON.stringify(ambientTemplate(c)));
560
+ }
561
+ return 0;
562
+ }
563
+ if (sub === "fetch") return propsFetch(rest, flags, io);
564
+ if (sub === "generate") return propsGenerate(flags, io);
565
+ io.stderr(`deck3d props: unknown subcommand '${sub ?? ""}' (try search|fetch|generate)`);
566
+ return 2;
567
+ }
568
+
569
+ /** `props generate --from-image <img> --name <n>` (7b.7). */
570
+ async function propsGenerate(flags: Flags, io: CliIO): Promise<number> {
571
+ const name = flags.value.name;
572
+ const prompt = flags.value.prompt;
573
+ if ((!flags.value["from-image"] && !prompt) || !name) {
574
+ io.stderr("deck3d props generate: missing --from-image <img> | --prompt <text>, and --name <n>");
575
+ return 2;
576
+ }
577
+ const { generateProp, textToImage } = await import("./props/generate.js");
578
+ const destDir = join(process.cwd(), ".deck3d", "props");
579
+ try {
580
+ // `--prompt` is a hop in FRONT of the existing image path: text → PNG → GLB.
581
+ const fromImage = prompt ? await textToImage({ prompt, name, destDir }) : (flags.value["from-image"] as string);
582
+ const result = await generateProp({ fromImage, name, destDir });
583
+ io.stdout(JSON.stringify(result.entry, null, 2));
584
+ return 0;
585
+ } catch (err) {
586
+ io.stderr(`deck3d props generate: ${(err as Error).message}`);
587
+ return 1;
588
+ }
589
+ }
590
+
591
+ async function cmdCheck(args: string[], io: CliIO): Promise<number> {
592
+ const flags = parseArgs(args);
593
+ const html = flags.positional[0];
594
+ if (!html) {
595
+ io.stderr("deck3d check: missing <deck.html>");
596
+ return 2;
597
+ }
598
+ return runCheckAndReport(html, flags, io, true, flags.value.out);
599
+ }
600
+
601
+ /** `style: <n>/<N> slides styled` — slides carrying an authored choice (D7). */
602
+ async function styleSummary(jsonPath: string): Promise<string> {
603
+ const ir = JSON.parse(readFileSync(jsonPath, "utf8")) as DeckIR;
604
+ const { defaultEffectsFor } = await import("./fx/defaults.js");
605
+ const { builtKindFor } = await import("./parse/derive.js");
606
+ const { applyOverrides } = await import("./ir/merge.js");
607
+ const merged = applyOverrides(ir);
608
+ const autoStyle = ir.overrides.deck?.autoStyle ?? ir.defaults.autoStyle ?? true;
609
+ const propSlides = new Set((ir.overrides.props ?? []).map((p) => p.slide));
610
+
611
+ let styled = 0;
612
+ for (const slide of merged.slides) {
613
+ const effects = (slide.effects ?? []).map((e) => e.id);
614
+ const defaults = defaultEffectsFor(
615
+ { id: slide.id, title: slide.title, bullets: slide.bullets, diagram: slide.diagram },
616
+ autoStyle,
617
+ ).map((e) => e.id);
618
+ const derivedKind =
619
+ slide.diagram.kind === "flowchart" || slide.diagram.kind === "sequence"
620
+ ? slide.diagram.kind
621
+ : autoStyle
622
+ ? builtKindFor({ title: slide.title, bullets: slide.bullets })
623
+ : "none";
624
+ const onDefaults = effects.join("\u0000") === defaults.join("\u0000") && slide.diagram.kind === derivedKind;
625
+ if (!onDefaults || propSlides.has(slide.id)) styled++;
626
+ }
627
+ return `style: ${styled}/${merged.slides.length} slides styled`;
628
+ }
629
+
630
+ async function cmdBuild(args: string[], io: CliIO): Promise<number> {
631
+ const flags = parseArgs(args);
632
+ const mdPath = flags.positional[0];
633
+ if (!mdPath) {
634
+ io.stderr("deck3d build: missing <deck.md>");
635
+ return 2;
636
+ }
637
+ const outPath = flags.value.out ?? mdPath.replace(/\.md$/i, ".html");
638
+ try {
639
+ await parseToFile(mdPath, defaultJsonPath(mdPath), flags, io);
640
+ const code = await renderFile(defaultJsonPath(mdPath), outPath, io);
641
+ if (code !== 0) return code;
642
+ io.stdout(`wrote ${outPath}`);
643
+ // `build` runs check, but only `--strict` fails on findings.
644
+ const checkCode = await runCheckAndReport(outPath, flags, io, false);
645
+ // A clean check says nothing about whether the deck was ever styled, so the
646
+ // style ratio is printed last, where the agent reads it.
647
+ io.stdout(await styleSummary(defaultJsonPath(mdPath)));
648
+ return checkCode;
649
+ } catch (err) {
650
+ io.stderr(`deck3d build: ${(err as Error).message}`);
651
+ return 1;
652
+ }
653
+ }
654
+
655
+ /**
656
+ * `serve <deck.md>` — authoring loop. Runs until interrupted; loopback only,
657
+ * because the panel can write `overrides.json` / `deck.json` through it.
658
+ */
659
+ async function cmdServe(args: string[], io: CliIO): Promise<number> {
660
+ const flags = parseArgs(args);
661
+ const mdPath = flags.positional[0];
662
+ if (!mdPath) {
663
+ io.stderr("deck3d serve: missing <deck.md>");
664
+ return 2;
665
+ }
666
+ const { startServe } = await import("./serve/index.js");
667
+ try {
668
+ const handle = await startServe(mdPath, {
669
+ port: flags.value.port ? Number.parseInt(flags.value.port, 10) : 0,
670
+ check: flags.bool.has("check"),
671
+ io,
672
+ // Injected, never imported back: see `cli-io.ts` for the cycle this avoids.
673
+ run,
674
+ });
675
+ io.stdout(`serving ${mdPath} on ${handle.url}`);
676
+ io.stdout("watching deck.md, fx/ and deck.json — edit and the browser reloads");
677
+ await new Promise<void>((resolve) => {
678
+ const stop = (): void => {
679
+ void handle.close().then(resolve);
680
+ };
681
+ process.once("SIGINT", stop);
682
+ process.once("SIGTERM", stop);
683
+ });
684
+ return 0;
685
+ } catch (err) {
686
+ io.stderr(`deck3d serve: ${(err as Error).message}`);
687
+ return 1;
688
+ }
689
+ }
690
+
691
+ async function cmdSnapshot(args: string[], io: CliIO): Promise<number> {
692
+ const flags = parseArgs(args);
693
+ const html = flags.positional[0];
694
+ if (!html) {
695
+ io.stderr("deck3d snapshot: missing <deck.html>");
696
+ return 2;
697
+ }
698
+ const out = flags.value.out ?? "snapshot.png";
699
+ const slide = flags.value.slide ? Number.parseInt(flags.value.slide, 10) : 1;
700
+ try {
701
+ const { chromium } = await import("playwright");
702
+ const browser = await chromium.launch({ channel: "chromium" });
703
+ try {
704
+ const page = await browser.newPage({ viewport: { width: 1920, height: 1080 }, deviceScaleFactor: 1 });
705
+ await page.goto(`${pathToFileURL(html).href}#${slide}`);
706
+ await page.waitForFunction(() => window.__deck3d !== undefined, undefined, { timeout: 30_000 });
707
+ await page.evaluate(() => window.__deck3d?.ready());
708
+ await page.waitForTimeout(400);
709
+ await page.screenshot({ path: out });
710
+ } finally {
711
+ await browser.close();
712
+ }
713
+ io.stdout(`wrote ${out}`);
714
+ return 0;
715
+ } catch (err) {
716
+ io.stderr(`deck3d snapshot: ${(err as Error).message}`);
717
+ return 1;
718
+ }
719
+ }
720
+
721
+ /**
722
+ * `overrides apply <deck.json> <file>` — merge a file written in the D1
723
+ * `overrides` grammar into `deck.json`'s `overrides` block (objects deep-merge,
724
+ * arrays and `diagram.data` replace), re-validate, and only then write. A
725
+ * validation failure leaves `deck.json` byte-unchanged.
726
+ */
727
+ async function overridesApply(rest: string[], io: CliIO): Promise<number> {
728
+ const [jsonPath, patchPath] = rest;
729
+ if (!jsonPath || !patchPath) {
730
+ io.stderr("deck3d overrides apply: missing <deck.json> <file>");
731
+ return 2;
732
+ }
733
+ let deck: DeckIR;
734
+ let patch: unknown;
735
+ try {
736
+ deck = JSON.parse(readFileSync(jsonPath, "utf8")) as DeckIR;
737
+ } catch (err) {
738
+ io.stderr(`deck3d overrides apply: invalid JSON in ${jsonPath}: ${(err as Error).message}`);
739
+ return 1;
740
+ }
741
+ try {
742
+ patch = JSON.parse(readFileSync(patchPath, "utf8"));
743
+ } catch (err) {
744
+ io.stderr(`deck3d overrides apply: invalid JSON in ${patchPath}: ${(err as Error).message}`);
745
+ return 1;
746
+ }
747
+
748
+ const { deepMerge } = await import("./ir/merge.js");
749
+ const merged = { ...deck, overrides: deepMerge(deck.overrides ?? {}, patch) as DeckIR["overrides"] };
750
+
751
+ const result = validate(merged, { propBytes: cachedPropBytes(jsonPath) });
752
+ for (const issue of result.errors) io.stderr(formatIssue("error", issue));
753
+ if (!result.ok) return 1;
754
+ for (const warning of result.warnings) io.stderr(formatIssue("warn", warning));
755
+
756
+ writeJson(jsonPath, merged);
757
+ io.stdout(JSON.stringify(merged.overrides, null, 2));
758
+ return 0;
759
+ }
760
+
761
+ async function cmdOverrides(args: string[], io: CliIO): Promise<number> {
762
+ const [sub, ...rest] = args;
763
+ if (sub === "apply") return overridesApply(rest, io);
764
+ io.stderr(`deck3d overrides: unknown subcommand '${sub ?? ""}' (try apply)`);
765
+ return 2;
766
+ }
767
+
768
+ export async function run(argv: string[], io: CliIO = defaultIO): Promise<number> {
769
+ const [command, ...rest] = argv;
770
+ switch (command) {
771
+ case undefined:
772
+ case "-h":
773
+ case "--help":
774
+ case "help":
775
+ io.stdout(HELP);
776
+ return 0;
777
+ case "-v":
778
+ case "--version":
779
+ case "version":
780
+ io.stdout(VERSION);
781
+ return 0;
782
+ case "parse":
783
+ return cmdParse(rest, io);
784
+ case "validate":
785
+ return await cmdValidate(rest, io);
786
+ case "render":
787
+ return cmdRender(rest, io);
788
+ case "build":
789
+ return cmdBuild(rest, io);
790
+ case "serve":
791
+ return cmdServe(rest, io);
792
+ case "check":
793
+ return cmdCheck(rest, io);
794
+ case "fx":
795
+ return cmdFx(rest, io);
796
+ case "props":
797
+ return cmdProps(rest, io);
798
+ case "snapshot":
799
+ return cmdSnapshot(rest, io);
800
+ case "overrides":
801
+ return cmdOverrides(rest, io);
802
+ default:
803
+ io.stderr(`deck3d: unknown command '${command}' (try --help)`);
804
+ return 2;
805
+ }
806
+ }
807
+
808
+ const entry = process.argv[1];
809
+ if (entry && import.meta.url === pathToFileURL(entry).href) {
810
+ // NOT `process.exit(await run(...))`. A top-level await here keeps this
811
+ // module's evaluation pending for the whole command, and `serve/index.ts`
812
+ // imports `run` from this file — so `serve`'s own `await import()` would
813
+ // wait on a module that is waiting on `serve`, and the process would exit 13
814
+ // before ever listening (#S10). Settling the promise in a callback lets
815
+ // evaluation finish immediately, which breaks the cycle.
816
+ void run(process.argv.slice(2)).then(
817
+ (code) => process.exit(code),
818
+ (err) => {
819
+ console.error(`deck3d: ${(err as Error).stack ?? err}`);
820
+ process.exit(1);
821
+ },
822
+ );
823
+ }