@blackbelt-technology/pi-dashboard-deck3d 0.9.0 → 0.10.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 (105) hide show
  1. package/.pi/skills/deck3d/SKILL.agent.md +78 -0
  2. package/.pi/skills/deck3d/SKILL.md +68 -0
  3. package/.pi/skills/deck3d/reference/effects.md +185 -2
  4. package/.pi/skills/deck3d/reference/ir-fields.md +26 -3
  5. package/.pi/skills/deck3d-from-pptx/SKILL.md +134 -0
  6. package/.pi/skills/deck3d-from-pptx/reference/steps.md +72 -0
  7. package/README.md +30 -2
  8. package/assets/preview/stub-chrome.png +0 -0
  9. package/assets/preview/stub-icon.json +59 -0
  10. package/assets/preview/stub-layout.json +195 -0
  11. package/assets/preview/stub-outline.json +48 -0
  12. package/dist/cli.js +11780 -5934
  13. package/dist/runtime.js +5916 -4007
  14. package/fixtures/business-2031/assets/stub-chrome.png +0 -0
  15. package/fixtures/business-2031/assets/stub-icon.json +59 -0
  16. package/fixtures/business-2031/assets/stub-layout.json +195 -0
  17. package/fixtures/business-2031/assets/stub-outline.json +48 -0
  18. package/fixtures/business-2031/build-overrides.mjs +58 -13
  19. package/fixtures/business-2031/deck.agent.md +60 -0
  20. package/fixtures/business-2031/deck.json +133 -8
  21. package/fixtures/business-2031/overrides.json +133 -8
  22. package/package.json +8 -4
  23. package/scripts/gen-stub-assets.ts +31 -0
  24. package/src/art/cutout.ts +97 -0
  25. package/src/art/decode.ts +169 -0
  26. package/src/art/icon.ts +380 -0
  27. package/src/art/png.ts +232 -0
  28. package/src/art/trace.ts +288 -0
  29. package/src/check/rules.ts +13 -8
  30. package/src/cli.ts +313 -51
  31. package/src/compare/index.ts +131 -0
  32. package/src/compare/ssim.ts +91 -0
  33. package/src/fx/art-geometry.ts +137 -0
  34. package/src/fx/art3d.meta.json +30 -0
  35. package/src/fx/art3d.ts +131 -0
  36. package/src/fx/bank.meta.json +26 -0
  37. package/src/fx/bank.ts +8 -0
  38. package/src/fx/compose.ts +5 -4
  39. package/src/fx/crane.meta.json +26 -0
  40. package/src/fx/crane.ts +8 -0
  41. package/src/fx/dolly.ts +5 -1
  42. package/src/fx/fade.ts +5 -1
  43. package/src/fx/flythrough.ts +5 -1
  44. package/src/fx/frame-chrome.meta.json +17 -0
  45. package/src/fx/frame-chrome.ts +134 -0
  46. package/src/fx/haze.meta.json +19 -0
  47. package/src/fx/haze.ts +91 -0
  48. package/src/fx/icon3d.meta.json +21 -0
  49. package/src/fx/icon3d.ts +167 -0
  50. package/src/fx/index.ts +96 -66
  51. package/src/fx/iris.ts +5 -1
  52. package/src/fx/meta.schema.json +10 -2
  53. package/src/fx/path.meta.json +25 -0
  54. package/src/fx/path.ts +8 -0
  55. package/src/fx/persistent.ts +11 -0
  56. package/src/fx/revolve.meta.json +26 -0
  57. package/src/fx/revolve.ts +8 -0
  58. package/src/fx/slide-layer.meta.json +26 -0
  59. package/src/fx/slide-layer.ts +557 -0
  60. package/src/fx/slide-space.ts +142 -0
  61. package/src/fx/stub-assets.ts +117 -0
  62. package/src/fx/swing.meta.json +26 -0
  63. package/src/fx/swing.ts +8 -0
  64. package/src/fx/types.ts +63 -2
  65. package/src/ir/merge.ts +5 -2
  66. package/src/ir/schema.json +140 -3
  67. package/src/ir/types.ts +54 -0
  68. package/src/ir/validate.ts +91 -3
  69. package/src/parse/harvest/index.ts +4 -1
  70. package/src/parse/markdown.ts +38 -7
  71. package/src/pptx/baseline.ts +183 -0
  72. package/src/pptx/extract.ts +161 -0
  73. package/src/pptx/fallback.ts +70 -0
  74. package/src/pptx/import.ts +256 -0
  75. package/src/pptx/master.ts +135 -0
  76. package/src/pptx/media.ts +81 -0
  77. package/src/pptx/package.ts +109 -0
  78. package/src/pptx/ref.ts +100 -0
  79. package/src/pptx/shapes.ts +276 -0
  80. package/src/pptx/stage.ts +82 -0
  81. package/src/pptx/text.ts +202 -0
  82. package/src/pptx/theme.ts +194 -0
  83. package/src/pptx/types.ts +159 -0
  84. package/src/pptx/xfrm.ts +93 -0
  85. package/src/pptx/xml.ts +106 -0
  86. package/src/pptx/zip.ts +239 -0
  87. package/src/render/assets.ts +57 -0
  88. package/src/render/build.ts +75 -0
  89. package/src/render/index.ts +7 -2
  90. package/src/render/template.html +1 -1
  91. package/src/runtime/assets.ts +75 -0
  92. package/src/runtime/fade.ts +110 -0
  93. package/src/runtime/hud.ts +37 -9
  94. package/src/runtime/index.ts +431 -67
  95. package/src/runtime/post.ts +11 -5
  96. package/src/runtime/scene.ts +25 -2
  97. package/src/runtime/transition.ts +222 -0
  98. package/src/runtime/types.ts +13 -2
  99. package/src/serve/index.ts +199 -16
  100. package/src/util/cleanup.ts +13 -0
  101. package/src/util/confine.ts +15 -0
  102. package/src/variants/pick.ts +282 -0
  103. package/src/variants/render.ts +179 -0
  104. package/src/variants/schema.json +48 -0
  105. package/src/variants/style.ts +318 -0
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Guarded OOXML zip reader (design D1, spec "Untrusted input is contained").
3
+ *
4
+ * 1. Sniff the container: an OLE compound file is "encrypted" when it holds
5
+ * an `EncryptionInfo` stream, else "not a .pptx (OOXML) file"; anything
6
+ * without a zip end-of-central-directory record is the latter too.
7
+ * 2. Read the central directory and reject on DECLARED entry count / sizes /
8
+ * ratio and on absolute or `..` entry names — before inflating a byte.
9
+ * 3. Inflate each entry in small input slices with fflate's streaming
10
+ * `Inflate`, counting ACTUAL output per entry and in total, and abort the
11
+ * moment a limit or the ratio is crossed. A bomb is never fully inflated.
12
+ * 4. Reject any XML part (by `[Content_Types].xml` type or `.xml`/`.rels`
13
+ * name) whose raw bytes contain `<!DOCTYPE`. Media are never scanned.
14
+ */
15
+ import { Inflate } from "fflate";
16
+ import { PptxImportError } from "./types.js";
17
+
18
+ export const ZIP_LIMITS = {
19
+ maxEntries: 4000,
20
+ maxEntryBytes: 128 * 1024 * 1024,
21
+ maxTotalBytes: 512 * 1024 * 1024,
22
+ /** Actual (and declared) uncompressed:compressed ratio above this is rejected, at any size. */
23
+ maxRatio: 200,
24
+ };
25
+
26
+ const MiB = 1024 * 1024;
27
+ /** Compressed bytes pushed per inflate step — bounds the output of one step. */
28
+ const SLICE = 4096;
29
+
30
+ export class ZipLimitError extends PptxImportError {
31
+ readonly inflated: number;
32
+
33
+ constructor(
34
+ message: string,
35
+ /** Actual bytes inflated for the offending entry when the stream stopped. */
36
+ inflated = 0,
37
+ ) {
38
+ super(message);
39
+ this.inflated = inflated;
40
+ this.name = "ZipLimitError";
41
+ }
42
+ }
43
+
44
+ interface CdEntry {
45
+ name: string;
46
+ method: number;
47
+ compressedSize: number;
48
+ size: number;
49
+ localOffset: number;
50
+ flags: number;
51
+ }
52
+
53
+ const OLE_MAGIC = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1];
54
+
55
+ function startsWith(bytes: Uint8Array, magic: number[]): boolean {
56
+ return magic.every((b, i) => bytes[i] === b);
57
+ }
58
+
59
+ /** UTF-16LE needle search — OLE directory entry names are stored that way. */
60
+ function containsUtf16(bytes: Uint8Array, text: string): boolean {
61
+ const needle = new Uint8Array(text.length * 2);
62
+ for (let i = 0; i < text.length; i++) needle[i * 2] = text.charCodeAt(i);
63
+ outer: for (let i = 0; i + needle.length <= bytes.length; i++) {
64
+ for (let j = 0; j < needle.length; j++) if (bytes[i + j] !== needle[j]) continue outer;
65
+ return true;
66
+ }
67
+ return false;
68
+ }
69
+
70
+ function notOoxml(): PptxImportError {
71
+ return new PptxImportError("not a .pptx (OOXML) file");
72
+ }
73
+
74
+ function findEocd(bytes: Uint8Array): number {
75
+ const min = Math.max(0, bytes.length - 22 - 0xffff);
76
+ for (let i = bytes.length - 22; i >= min; i--) {
77
+ if (bytes[i] === 0x50 && bytes[i + 1] === 0x4b && bytes[i + 2] === 0x05 && bytes[i + 3] === 0x06) return i;
78
+ }
79
+ return -1;
80
+ }
81
+
82
+ /** Absolute, drive-letter, backslash-rooted or `..`-segment names are rejected. */
83
+ export function unsafeEntryName(name: string): boolean {
84
+ if (name.startsWith("/") || name.startsWith("\\") || /^[A-Za-z]:/.test(name)) return true;
85
+ return name.split(/[\\/]/).some((seg) => seg === "..");
86
+ }
87
+
88
+ function readCentralDirectory(bytes: Uint8Array): CdEntry[] {
89
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
90
+ const eocd = findEocd(bytes);
91
+ if (eocd < 0) throw notOoxml();
92
+ const count = view.getUint16(eocd + 10, true);
93
+ const cdOffset = view.getUint32(eocd + 16, true);
94
+ if (count > ZIP_LIMITS.maxEntries) {
95
+ throw new ZipLimitError(`zip lists ${count} entries (limit ${ZIP_LIMITS.maxEntries})`);
96
+ }
97
+ const entries: CdEntry[] = [];
98
+ let p = cdOffset;
99
+ let declaredTotal = 0;
100
+ for (let i = 0; i < count; i++) {
101
+ if (p + 46 > bytes.length || view.getUint32(p, true) !== 0x02014b50) throw notOoxml();
102
+ const flags = view.getUint16(p + 8, true);
103
+ const method = view.getUint16(p + 10, true);
104
+ const compressedSize = view.getUint32(p + 20, true);
105
+ const size = view.getUint32(p + 24, true);
106
+ const nameLen = view.getUint16(p + 28, true);
107
+ const extraLen = view.getUint16(p + 30, true);
108
+ const commentLen = view.getUint16(p + 32, true);
109
+ const localOffset = view.getUint32(p + 42, true);
110
+ const name = new TextDecoder().decode(bytes.subarray(p + 46, p + 46 + nameLen));
111
+ p += 46 + nameLen + extraLen + commentLen;
112
+ if (unsafeEntryName(name)) throw new ZipLimitError(`unsafe entry name '${name}' (absolute or '..' segment)`);
113
+ if (size > ZIP_LIMITS.maxEntryBytes) {
114
+ throw new ZipLimitError(`entry '${name}' declares ${size} bytes (limit ${ZIP_LIMITS.maxEntryBytes / MiB} MiB per entry)`);
115
+ }
116
+ declaredTotal += size;
117
+ if (declaredTotal > ZIP_LIMITS.maxTotalBytes) {
118
+ throw new ZipLimitError(`zip declares more than ${ZIP_LIMITS.maxTotalBytes / MiB} MiB uncompressed (at entry '${name}')`);
119
+ }
120
+ if (size > ZIP_LIMITS.maxRatio * Math.max(1, compressedSize)) {
121
+ throw new ZipLimitError(`entry '${name}' declares a compression ratio above ${ZIP_LIMITS.maxRatio}:1`);
122
+ }
123
+ entries.push({ name, method, compressedSize, size, localOffset, flags });
124
+ }
125
+ return entries;
126
+ }
127
+
128
+ function entryData(bytes: Uint8Array, e: CdEntry): Uint8Array {
129
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
130
+ const p = e.localOffset;
131
+ if (p + 30 > bytes.length || view.getUint32(p, true) !== 0x04034b50) throw new PptxImportError(`corrupt zip entry '${e.name}'`);
132
+ const start = p + 30 + view.getUint16(p + 26, true) + view.getUint16(p + 28, true);
133
+ if (start + e.compressedSize > bytes.length) throw new PptxImportError(`truncated zip entry '${e.name}'`);
134
+ return bytes.subarray(start, start + e.compressedSize);
135
+ }
136
+
137
+ function inflateGuarded(name: string, data: Uint8Array, budget: { total: number }): Uint8Array {
138
+ const chunks: Uint8Array[] = [];
139
+ let produced = 0;
140
+ const check = (): void => {
141
+ if (produced > ZIP_LIMITS.maxEntryBytes) {
142
+ throw new ZipLimitError(`entry '${name}' inflates past ${ZIP_LIMITS.maxEntryBytes / MiB} MiB (limit per entry)`, produced);
143
+ }
144
+ if (budget.total + produced > ZIP_LIMITS.maxTotalBytes) {
145
+ throw new ZipLimitError(`zip inflates past ${ZIP_LIMITS.maxTotalBytes / MiB} MiB in total (at entry '${name}')`, produced);
146
+ }
147
+ if (produced > ZIP_LIMITS.maxRatio * Math.max(1, data.length)) {
148
+ throw new ZipLimitError(`entry '${name}' exceeds a compression ratio of ${ZIP_LIMITS.maxRatio}:1`, produced);
149
+ }
150
+ };
151
+ const inflater = new Inflate((chunk) => {
152
+ produced += chunk.length;
153
+ check();
154
+ chunks.push(chunk);
155
+ });
156
+ for (let off = 0; off < data.length; off += SLICE) {
157
+ const end = Math.min(data.length, off + SLICE);
158
+ inflater.push(data.subarray(off, end), end === data.length);
159
+ }
160
+ if (data.length === 0) inflater.push(new Uint8Array(0), true);
161
+ budget.total += produced;
162
+ const out = new Uint8Array(produced);
163
+ let o = 0;
164
+ for (const c of chunks) {
165
+ out.set(c, o);
166
+ o += c.length;
167
+ }
168
+ return out;
169
+ }
170
+
171
+ const DOCTYPE = [0x3c, 0x21, 0x64, 0x6f, 0x63, 0x74, 0x79, 0x70, 0x65]; // "<!doctype"
172
+
173
+ /** Case-insensitive raw-byte scan for `<!DOCTYPE`. */
174
+ export function hasDoctype(bytes: Uint8Array): boolean {
175
+ outer: for (let i = 0; i + DOCTYPE.length <= bytes.length; i++) {
176
+ for (let j = 0; j < DOCTYPE.length; j++) {
177
+ const b = bytes[i + j];
178
+ const lower = b >= 0x41 && b <= 0x5a ? b + 0x20 : b;
179
+ if (lower !== DOCTYPE[j]) continue outer;
180
+ }
181
+ return true;
182
+ }
183
+ return false;
184
+ }
185
+
186
+ /** Part names `[Content_Types].xml` declares with an XML content type. */
187
+ function xmlPartsFromContentTypes(ct: Uint8Array | undefined): { overrides: Set<string>; extensions: Set<string> } {
188
+ const overrides = new Set<string>();
189
+ const extensions = new Set<string>();
190
+ if (!ct) return { overrides, extensions };
191
+ const text = new TextDecoder().decode(ct);
192
+ for (const m of text.matchAll(/<Override\b[^>]*>/g)) {
193
+ const part = /PartName="([^"]+)"/.exec(m[0])?.[1];
194
+ const type = /ContentType="([^"]+)"/.exec(m[0])?.[1] ?? "";
195
+ if (part && /xml/i.test(type)) overrides.add(part.replace(/^\//, ""));
196
+ }
197
+ for (const m of text.matchAll(/<Default\b[^>]*>/g)) {
198
+ const ext = /Extension="([^"]+)"/.exec(m[0])?.[1];
199
+ const type = /ContentType="([^"]+)"/.exec(m[0])?.[1] ?? "";
200
+ if (ext && /xml/i.test(type)) extensions.add(ext.toLowerCase());
201
+ }
202
+ return { overrides, extensions };
203
+ }
204
+
205
+ /** Read every entry of a pptx zip into memory, under the D1 guards. */
206
+ export function readPptxZip(bytes: Uint8Array): Map<string, Uint8Array> {
207
+ if (startsWith(bytes, OLE_MAGIC)) {
208
+ if (containsUtf16(bytes, "EncryptionInfo")) {
209
+ throw new PptxImportError("the file is encrypted (password-protected pptx); remove the password and export again");
210
+ }
211
+ throw notOoxml();
212
+ }
213
+ const entries = readCentralDirectory(bytes);
214
+ const files = new Map<string, Uint8Array>();
215
+ const budget = { total: 0 };
216
+ for (const e of entries) {
217
+ if (e.name.endsWith("/")) continue;
218
+ if (e.flags & 1) throw new PptxImportError(`entry '${e.name}' is encrypted`);
219
+ const data = entryData(bytes, e);
220
+ let out: Uint8Array;
221
+ if (e.method === 0) {
222
+ out = data;
223
+ budget.total += out.length;
224
+ if (budget.total > ZIP_LIMITS.maxTotalBytes) throw new ZipLimitError(`zip exceeds ${ZIP_LIMITS.maxTotalBytes / MiB} MiB in total`);
225
+ } else if (e.method === 8) {
226
+ out = inflateGuarded(e.name, data, budget);
227
+ } else {
228
+ throw new PptxImportError(`entry '${e.name}' uses unsupported compression method ${e.method}`);
229
+ }
230
+ files.set(e.name, out);
231
+ }
232
+ const { overrides, extensions } = xmlPartsFromContentTypes(files.get("[Content_Types].xml"));
233
+ for (const [name, data] of files) {
234
+ const ext = name.slice(name.lastIndexOf(".") + 1).toLowerCase();
235
+ const isXml = ext === "xml" || ext === "rels" || overrides.has(name) || extensions.has(ext);
236
+ if (isXml && hasDoctype(data)) throw new ZipLimitError(`XML part '${name}' contains <!DOCTYPE (DTDs and entities are rejected)`);
237
+ }
238
+ return files;
239
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Deck asset bundle → embedded `data:` URIs (spec deck3d-slide-layers "Deck
3
+ * asset bundle", design D3). Every `overrides.assets` entry is embedded once,
4
+ * in ascending id order, so the HTML is byte-identical whatever the order of
5
+ * entries in `deck.json`. Sizes are budgeted from `stat` BEFORE any file is
6
+ * read: warn above 25 MiB, refuse above 200 MiB.
7
+ */
8
+ import { readFileSync, statSync } from "node:fs";
9
+ import { dirname, resolve } from "node:path";
10
+ import type { DeckIR } from "../ir/types.js";
11
+ import { realInside } from "../util/confine.js";
12
+
13
+ export const ASSET_WARN_BYTES = 25 * 1024 * 1024;
14
+ export const ASSET_MAX_BYTES = 200 * 1024 * 1024;
15
+
16
+ export interface EmbeddedAsset {
17
+ id: string;
18
+ mime: string;
19
+ /** `data:<mime>;base64,…` */
20
+ data: string;
21
+ }
22
+
23
+ export interface AssetBundle {
24
+ assets: EmbeddedAsset[];
25
+ total: number;
26
+ warnings: string[];
27
+ }
28
+
29
+ export class AssetBudgetError extends Error {
30
+ constructor(total: number) {
31
+ super(`overrides.assets total ${total} bytes exceeds the ${ASSET_MAX_BYTES / 1024 / 1024} MiB limit; no HTML written`);
32
+ this.name = "AssetBudgetError";
33
+ }
34
+ }
35
+
36
+ /** Embed `entries` (paths relative to `baseDir`), sorted by id, under the size budget. */
37
+ export function embedFiles(entries: Array<{ id: string; path: string; mime: string }>, baseDir: string): AssetBundle {
38
+ const sorted = [...entries].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
39
+ // `validate` already checked this; re-checked here so no caller can embed a file from outside.
40
+ for (const a of sorted) {
41
+ if (!realInside(baseDir, resolve(baseDir, a.path))) throw new Error(`asset '${a.id}': '${a.path}' is missing or resolves outside the deck directory`);
42
+ }
43
+ const total = sorted.reduce((sum, a) => sum + statSync(resolve(baseDir, a.path)).size, 0);
44
+ if (total > ASSET_MAX_BYTES) throw new AssetBudgetError(total);
45
+ const warnings = total > ASSET_WARN_BYTES ? [`warning overrides.assets total ${total} bytes exceeds ${ASSET_WARN_BYTES / 1024 / 1024} MiB (deck.html grows by ~4/3 of that)`] : [];
46
+ const assets = sorted.map((a) => ({
47
+ id: a.id,
48
+ mime: a.mime,
49
+ data: `data:${a.mime};base64,${readFileSync(resolve(baseDir, a.path)).toString("base64")}`,
50
+ }));
51
+ return { assets, total, warnings };
52
+ }
53
+
54
+ /** Read and encode the deck's assets (paths already validated by `validate`). */
55
+ export function loadAssets(ir: DeckIR, jsonPath: string): AssetBundle {
56
+ return embedFiles(ir.overrides.assets ?? [], dirname(jsonPath));
57
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * IR → `deck.html` (the body of `deck3d render`), usable with an in-memory IR:
3
+ * `variants render` and `serve ?variant=` render a deck with a candidate
4
+ * fragment merged in without touching `deck.json`. Lives here, not in
5
+ * `cli.ts`, so `variants/` and `serve/` never import the CLI (see `cli-io.ts`).
6
+ *
7
+ * Callers validate first. Returns `undefined` after reporting on `io` when a
8
+ * param is out of range or two effects conflict.
9
+ */
10
+ import { basename } from "node:path";
11
+ import type { CliIO } from "../cli-io.js";
12
+ import type { DeckIR } from "../ir/types.js";
13
+
14
+ export interface RenderIrOptions {
15
+ embedVideo?: boolean;
16
+ }
17
+
18
+ export async function renderIrToHtml(ir: DeckIR, jsonPath: string, io: CliIO, opts: RenderIrOptions = {}): Promise<string | undefined> {
19
+ const { composeEffects, validateEffectParams } = await import("../fx/compose.js");
20
+ const { ensureRuntime, renderDeck, fontBase64, loadLocalEffects } = await import("./index.js");
21
+ // Resolve the local effects first: their cards take part in param bounds,
22
+ // conflict, mode and budget gating exactly like corpus cards.
23
+ const localFx = loadLocalEffects(ir, jsonPath);
24
+ const localCards = Object.fromEntries(
25
+ Object.entries(localFx).map(([name, m]) => [name, m.card as import("../fx/types.js").FxCard]),
26
+ );
27
+ const violations = validateEffectParams(ir, localCards);
28
+ if (violations.length) {
29
+ for (const v of violations) io.stderr(`error ${v.path}: ${v.message}`);
30
+ return undefined;
31
+ }
32
+ // Compose the MERGED view: `overrides.effects` + `overrides.slides[id].effects`
33
+ // are already folded into each slide's effective list by `applyOverrides`.
34
+ const { applyOverrides } = await import("../ir/merge.js");
35
+ const merged = applyOverrides(ir);
36
+ for (const slide of merged.slides) {
37
+ const ov = ir.overrides.slides?.[slide.id];
38
+ const mode = ov?.mode ?? ir.overrides.deck?.mode ?? ir.defaults.mode ?? "dark";
39
+ const quality = ov?.quality ?? ir.overrides.deck?.quality ?? ir.defaults.quality ?? "high";
40
+ const comp = composeEffects(slide.effects, mode, quality, slide.id, localCards);
41
+ for (const warning of comp.warnings) io.stderr(warning);
42
+ if (comp.conflicts.length) {
43
+ for (const c of comp.conflicts) io.stderr(`error conflict ${c}`);
44
+ return undefined;
45
+ }
46
+ }
47
+ const { loadProps } = await import("../props/embed.js");
48
+ const runtime = await ensureRuntime();
49
+ const props = loadProps(ir, jsonPath);
50
+ // `--embed-video` inlines clips as `data:` URLs so the html stays ONE file.
51
+ // Without it the clip is fetched relative to the page, which `deck3d serve`
52
+ // answers from its asset route.
53
+ let renderIr = ir;
54
+ if (opts.embedVideo) {
55
+ const { embedVideo } = await import("./embed-video.js");
56
+ const result = embedVideo(ir, jsonPath);
57
+ for (const w of result.warnings) io.stderr(`warning ${w}`);
58
+ const total = Object.values(result.embedded).reduce((a, b) => a + b, 0);
59
+ if (total) io.stdout(`embedded ${Object.keys(result.embedded).length} clip(s), ${(total / 1024 / 1024).toFixed(1)} MiB`);
60
+ renderIr = result.ir;
61
+ }
62
+ const { loadAssets, AssetBudgetError } = await import("./assets.js");
63
+ let bundle: ReturnType<typeof loadAssets>;
64
+ try {
65
+ bundle = loadAssets(ir, jsonPath);
66
+ } catch (err) {
67
+ if (err instanceof AssetBudgetError) {
68
+ io.stderr(`error ${err.message}`);
69
+ return undefined;
70
+ }
71
+ throw err;
72
+ }
73
+ for (const w of bundle.warnings) io.stderr(w);
74
+ return renderDeck(renderIr, { runtime, font: fontBase64(), title: basename(jsonPath, ".json"), props, localFx, assets: bundle.assets });
75
+ }
@@ -9,8 +9,8 @@
9
9
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
10
  import { dirname, join } from "node:path";
11
11
  import opentype from "opentype.js";
12
- import { canonicalJson } from "../ir/hash.js";
13
12
  import { localRefs, resolveLocalEffect, toFactorySource } from "../fx/local.js";
13
+ import { canonicalJson } from "../ir/hash.js";
14
14
  import { applyOverrides } from "../ir/merge.js";
15
15
  import type { DeckIR } from "../ir/types.js";
16
16
  import { activeProps, creditsSlide } from "../props/embed.js";
@@ -89,6 +89,8 @@ export interface RenderOptions {
89
89
  props?: Record<string, string>;
90
90
  /** Local effect sources + cards keyed by `<name>` (from `loadLocalEffects`). */
91
91
  localFx?: Record<string, { card: unknown; src: string }>;
92
+ /** Deck assets as `data:` URIs, sorted by id (from `loadAssets`). */
93
+ assets?: Array<{ id: string; mime: string; data: string }>;
92
94
  }
93
95
 
94
96
  /**
@@ -113,7 +115,7 @@ export function loadLocalEffects(ir: DeckIR, jsonPath: string): Record<string, {
113
115
  * (e.g. a slide documenting deck3d's own `__FONT__` placeholder).
114
116
  */
115
117
  function substituteTokens(template: string, values: Record<string, string>): string {
116
- return template.replace(/__(?:DECK_LOCAL_FX|DECK_PROPS|DECK|FONT|RUNTIME|TITLE)__/g, (token) => values[token] ?? token);
118
+ return template.replace(/__(?:DECK_ASSETS|DECK_LOCAL_FX|DECK_PROPS|DECK|FONT|RUNTIME|TITLE)__/g, (token) => values[token] ?? token);
117
119
  }
118
120
 
119
121
  /** Deck IR → self-contained `deck.html` string. */
@@ -137,11 +139,14 @@ export function renderDeck(ir: DeckIR, opts: RenderOptions = {}): string {
137
139
  // `jsonForScript` escapes `<`, so a `</script>` inside a module source cannot
138
140
  // terminate the block it is embedded in.
139
141
  const localFxJson = jsonForScript(opts.localFx ?? {});
142
+ // One escaped JSON block; ascending id order regardless of the deck.json order.
143
+ const assetsJson = jsonForScript([...(opts.assets ?? [])].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)));
140
144
 
141
145
  return substituteTokens(template, {
142
146
  __DECK__: deckJson,
143
147
  __DECK_PROPS__: propsJson,
144
148
  __DECK_LOCAL_FX__: localFxJson,
149
+ __DECK_ASSETS__: assetsJson,
145
150
  __FONT__: font,
146
151
  __RUNTIME__: runtime.replace(/<\/script/gi, "<\\/script"),
147
152
  __TITLE__: title.replace(/</g, "&lt;"),
@@ -81,7 +81,7 @@
81
81
  <body>
82
82
  <button id="deck3d-hud-toggle" type="button" aria-label="Configurator">⚙</button>
83
83
  <aside id="deck3d-hud" aria-label="Deck configurator"></aside>
84
- <script>window.__DECK=__DECK__;window.__DECK_FONT="__FONT__";window.__DECK_PROPS=__DECK_PROPS__;window.__DECK_LOCAL_FX=__DECK_LOCAL_FX__;</script>
84
+ <script>window.__DECK=__DECK__;window.__DECK_FONT="__FONT__";window.__DECK_PROPS=__DECK_PROPS__;window.__DECK_LOCAL_FX=__DECK_LOCAL_FX__;window.__DECK_ASSETS=__DECK_ASSETS__;</script>
85
85
  <script>__RUNTIME__</script>
86
86
  </body>
87
87
  </html>
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Runtime deck-asset registry (design D3, spec deck3d-slide-layers "Assets
3
+ * are ready before the first frame"). Every embedded asset is decoded BEFORE
4
+ * slides are built: images to a decoded `HTMLImageElement` (SVG included),
5
+ * JSON parsed, text decoded, fonts registered as a `FontFace` whose family
6
+ * name `get` returns. `get` is synchronous and throws for an unknown id.
7
+ */
8
+
9
+ export interface EmbeddedAsset {
10
+ id: string;
11
+ mime: string;
12
+ data: string;
13
+ }
14
+
15
+ /** The read-only accessor effects receive as `ctx.assets`. */
16
+ export interface AssetAccessor {
17
+ get(id: string): unknown;
18
+ has(id: string): boolean;
19
+ ids(): string[];
20
+ }
21
+
22
+ function base64Bytes(dataUri: string): Uint8Array {
23
+ const b64 = dataUri.slice(dataUri.indexOf(",") + 1);
24
+ const bin = atob(b64);
25
+ const out = new Uint8Array(bin.length);
26
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
27
+ return out;
28
+ }
29
+
30
+ async function decodeOne(a: EmbeddedAsset): Promise<unknown> {
31
+ if (a.mime.startsWith("image/")) {
32
+ const img = new Image();
33
+ img.decoding = "sync";
34
+ img.src = a.data;
35
+ await img.decode();
36
+ return img;
37
+ }
38
+ if (a.mime === "font/ttf" || a.mime === "font/otf") {
39
+ const family = `deck3d-${a.id}`;
40
+ const face = new FontFace(family, base64Bytes(a.data).buffer as ArrayBuffer);
41
+ await face.load();
42
+ document.fonts.add(face);
43
+ return family;
44
+ }
45
+ const text = new TextDecoder().decode(base64Bytes(a.data));
46
+ return a.mime === "application/json" ? JSON.parse(text) : text;
47
+ }
48
+
49
+ export function makeAccessor(values: Map<string, unknown>): AssetAccessor {
50
+ return Object.freeze({
51
+ get(id: string): unknown {
52
+ if (!values.has(id)) throw new Error(`unknown asset '${id}'`);
53
+ return values.get(id);
54
+ },
55
+ has: (id: string) => values.has(id),
56
+ ids: () => [...values.keys()],
57
+ });
58
+ }
59
+
60
+ /** Decode every embedded asset; a failing asset is reported and left out. */
61
+ export async function loadDeckAssets(embedded: EmbeddedAsset[] | undefined): Promise<{ accessor: AssetAccessor; failed: string[] }> {
62
+ const values = new Map<string, unknown>();
63
+ const failed: string[] = [];
64
+ await Promise.all(
65
+ (embedded ?? []).map(async (a) => {
66
+ try {
67
+ values.set(a.id, await decodeOne(a));
68
+ } catch (err) {
69
+ failed.push(a.id);
70
+ console.error(`deck asset ${a.id} failed to decode:`, err);
71
+ }
72
+ }),
73
+ );
74
+ return { accessor: makeAccessor(values), failed: failed.sort() };
75
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Slide cross-fade: scale the opacity of everything under some roots by a
3
+ * weight `w ∈ [0,1]`, without cloning materials (local fx keep live refs to
4
+ * theirs and animate them).
5
+ *
6
+ * Per material we keep the author's base opacity / transparency. A material an
7
+ * effect re-writes between frames (its opacity no longer equals what we last
8
+ * wrote) is re-based on its new value, so effect-driven fades compose with
9
+ * this one. Materials shared by several faded roots take the LARGEST weight.
10
+ * `ShaderMaterial`s with an `opacity` uniform are scaled through the uniform.
11
+ * At w = 1 the base is restored and the material is released; at w ≈ 0 the
12
+ * root is hidden outright (covers shaders that ignore opacity).
13
+ */
14
+ import type * as THREE from "three";
15
+
16
+ interface Tracked {
17
+ base: number;
18
+ transparent: boolean;
19
+ written: number;
20
+ }
21
+
22
+ const HIDE_BELOW = 0.01;
23
+
24
+ type OpacityHost = { get: () => number; set: (v: number) => void };
25
+
26
+ function hostOf(m: THREE.Material): OpacityHost | null {
27
+ const u = (m as THREE.ShaderMaterial).uniforms?.opacity;
28
+ if (u && typeof u.value === "number") return { get: () => u.value as number, set: (v) => (u.value = v) };
29
+ if (typeof m.opacity === "number") return { get: () => m.opacity, set: (v) => (m.opacity = v) };
30
+ return null;
31
+ }
32
+
33
+ export interface Fader {
34
+ /** Weight per root for this frame; roots not listed are released (w = 1). */
35
+ apply: (weights: Map<THREE.Object3D, number>) => void;
36
+ /** Release everything (base opacity back, roots visible). */
37
+ clear: () => void;
38
+ }
39
+
40
+ export function createFader(): Fader {
41
+ const tracked = new Map<THREE.Material, Tracked>();
42
+ const hidden = new Set<THREE.Object3D>();
43
+
44
+ function release(m: THREE.Material, t: Tracked): void {
45
+ const h = hostOf(m);
46
+ if (h && h.get() === t.written) h.set(t.base);
47
+ if (m.transparent !== t.transparent) {
48
+ m.transparent = t.transparent;
49
+ m.needsUpdate = true;
50
+ }
51
+ tracked.delete(m);
52
+ }
53
+
54
+ function apply(weights: Map<THREE.Object3D, number>): void {
55
+ const want = new Map<THREE.Material, number>();
56
+ for (const [root, raw] of weights) {
57
+ const w = Math.min(1, Math.max(0, raw));
58
+ if (w < HIDE_BELOW) {
59
+ if (root.visible) {
60
+ root.visible = false;
61
+ hidden.add(root);
62
+ }
63
+ } else if (hidden.has(root)) {
64
+ root.visible = true;
65
+ hidden.delete(root);
66
+ }
67
+ root.traverse((o) => {
68
+ const mat = (o as THREE.Mesh).material as THREE.Material | THREE.Material[] | undefined;
69
+ if (!mat) return;
70
+ for (const m of Array.isArray(mat) ? mat : [mat]) want.set(m, Math.max(want.get(m) ?? 0, w));
71
+ });
72
+ }
73
+ for (const [root] of [...hidden].map((r) => [r] as const)) {
74
+ if (!weights.has(root)) {
75
+ root.visible = true;
76
+ hidden.delete(root);
77
+ }
78
+ }
79
+ for (const [m, t] of tracked) if (!want.has(m) || want.get(m)! >= 1) release(m, t);
80
+ for (const [m, w] of want) {
81
+ if (w >= 1) continue;
82
+ const h = hostOf(m);
83
+ if (!h) continue;
84
+ let t = tracked.get(m);
85
+ if (!t) {
86
+ t = { base: h.get(), transparent: m.transparent, written: Number.NaN };
87
+ tracked.set(m, t);
88
+ } else if (h.get() !== t.written) {
89
+ t.base = h.get(); // the effect animated it since our last write
90
+ }
91
+ t.written = t.base * w;
92
+ h.set(t.written);
93
+ if (!m.transparent) {
94
+ m.transparent = true;
95
+ m.needsUpdate = true;
96
+ }
97
+ }
98
+ }
99
+
100
+ return {
101
+ apply,
102
+ clear: () => apply(new Map()),
103
+ };
104
+ }
105
+
106
+ /** Ease for the cross-fade window `[a, b]` of the move. */
107
+ export function fadeWindow(u: number, a: number, b: number): number {
108
+ const x = Math.min(1, Math.max(0, (u - a) / (b - a)));
109
+ return x * x * (3 - 2 * x);
110
+ }