@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.
- package/.pi/skills/deck3d/SKILL.agent.md +78 -0
- package/.pi/skills/deck3d/SKILL.md +68 -0
- package/.pi/skills/deck3d/reference/effects.md +185 -2
- package/.pi/skills/deck3d/reference/ir-fields.md +26 -3
- package/.pi/skills/deck3d-from-pptx/SKILL.md +134 -0
- package/.pi/skills/deck3d-from-pptx/reference/steps.md +72 -0
- package/README.md +30 -2
- package/assets/preview/stub-chrome.png +0 -0
- package/assets/preview/stub-icon.json +59 -0
- package/assets/preview/stub-layout.json +195 -0
- package/assets/preview/stub-outline.json +48 -0
- package/dist/cli.js +11780 -5934
- package/dist/runtime.js +5916 -4007
- package/fixtures/business-2031/assets/stub-chrome.png +0 -0
- package/fixtures/business-2031/assets/stub-icon.json +59 -0
- package/fixtures/business-2031/assets/stub-layout.json +195 -0
- package/fixtures/business-2031/assets/stub-outline.json +48 -0
- package/fixtures/business-2031/build-overrides.mjs +58 -13
- package/fixtures/business-2031/deck.agent.md +60 -0
- package/fixtures/business-2031/deck.json +133 -8
- package/fixtures/business-2031/overrides.json +133 -8
- package/package.json +8 -4
- package/scripts/gen-stub-assets.ts +31 -0
- package/src/art/cutout.ts +97 -0
- package/src/art/decode.ts +169 -0
- package/src/art/icon.ts +380 -0
- package/src/art/png.ts +232 -0
- package/src/art/trace.ts +288 -0
- package/src/check/rules.ts +13 -8
- package/src/cli.ts +313 -51
- package/src/compare/index.ts +131 -0
- package/src/compare/ssim.ts +91 -0
- package/src/fx/art-geometry.ts +137 -0
- package/src/fx/art3d.meta.json +30 -0
- package/src/fx/art3d.ts +131 -0
- package/src/fx/bank.meta.json +26 -0
- package/src/fx/bank.ts +8 -0
- package/src/fx/compose.ts +5 -4
- package/src/fx/crane.meta.json +26 -0
- package/src/fx/crane.ts +8 -0
- package/src/fx/dolly.ts +5 -1
- package/src/fx/fade.ts +5 -1
- package/src/fx/flythrough.ts +5 -1
- package/src/fx/frame-chrome.meta.json +17 -0
- package/src/fx/frame-chrome.ts +134 -0
- package/src/fx/haze.meta.json +19 -0
- package/src/fx/haze.ts +91 -0
- package/src/fx/icon3d.meta.json +21 -0
- package/src/fx/icon3d.ts +167 -0
- package/src/fx/index.ts +96 -66
- package/src/fx/iris.ts +5 -1
- package/src/fx/meta.schema.json +10 -2
- package/src/fx/path.meta.json +25 -0
- package/src/fx/path.ts +8 -0
- package/src/fx/persistent.ts +11 -0
- package/src/fx/revolve.meta.json +26 -0
- package/src/fx/revolve.ts +8 -0
- package/src/fx/slide-layer.meta.json +26 -0
- package/src/fx/slide-layer.ts +557 -0
- package/src/fx/slide-space.ts +142 -0
- package/src/fx/stub-assets.ts +117 -0
- package/src/fx/swing.meta.json +26 -0
- package/src/fx/swing.ts +8 -0
- package/src/fx/types.ts +63 -2
- package/src/ir/merge.ts +5 -2
- package/src/ir/schema.json +140 -3
- package/src/ir/types.ts +54 -0
- package/src/ir/validate.ts +91 -3
- package/src/parse/harvest/index.ts +4 -1
- package/src/parse/markdown.ts +38 -7
- package/src/pptx/baseline.ts +183 -0
- package/src/pptx/extract.ts +161 -0
- package/src/pptx/fallback.ts +70 -0
- package/src/pptx/import.ts +256 -0
- package/src/pptx/master.ts +135 -0
- package/src/pptx/media.ts +81 -0
- package/src/pptx/package.ts +109 -0
- package/src/pptx/ref.ts +100 -0
- package/src/pptx/shapes.ts +276 -0
- package/src/pptx/stage.ts +82 -0
- package/src/pptx/text.ts +202 -0
- package/src/pptx/theme.ts +194 -0
- package/src/pptx/types.ts +159 -0
- package/src/pptx/xfrm.ts +93 -0
- package/src/pptx/xml.ts +106 -0
- package/src/pptx/zip.ts +239 -0
- package/src/render/assets.ts +57 -0
- package/src/render/build.ts +75 -0
- package/src/render/index.ts +7 -2
- package/src/render/template.html +1 -1
- package/src/runtime/assets.ts +75 -0
- package/src/runtime/fade.ts +110 -0
- package/src/runtime/hud.ts +37 -9
- package/src/runtime/index.ts +431 -67
- package/src/runtime/post.ts +11 -5
- package/src/runtime/scene.ts +25 -2
- package/src/runtime/transition.ts +222 -0
- package/src/runtime/types.ts +13 -2
- package/src/serve/index.ts +199 -16
- package/src/util/cleanup.ts +13 -0
- package/src/util/confine.ts +15 -0
- package/src/variants/pick.ts +282 -0
- package/src/variants/render.ts +179 -0
- package/src/variants/schema.json +48 -0
- package/src/variants/style.ts +318 -0
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `variants render` (spec deck3d-variant-loop "Variant contact sheet"): the
|
|
3
|
+
* deck is rendered once per variant with that variant's fragment deep-merged
|
|
4
|
+
* into the current overrides IN MEMORY — `deck.json` is never touched — each
|
|
5
|
+
* sample slide is snapshotted at rest, and a contact sheet is composed in
|
|
6
|
+
* chromium: a header row, then one row per sample slide with the reference
|
|
7
|
+
* render (when one exists) as the first column and one labelled column per
|
|
8
|
+
* variant. Temporary HTML is removed before returning.
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { dirname, join } from "node:path";
|
|
13
|
+
import { pathToFileURL } from "node:url";
|
|
14
|
+
import type { Page } from "playwright";
|
|
15
|
+
import { deepMerge } from "../ir/merge.js";
|
|
16
|
+
import type { DeckIR } from "../ir/types.js";
|
|
17
|
+
import { formatIssue, validate } from "../ir/validate.js";
|
|
18
|
+
import { renderIrToHtml } from "../render/build.js";
|
|
19
|
+
import { closeQuietly } from "../util/cleanup.js";
|
|
20
|
+
import { requireStyle } from "./pick.js";
|
|
21
|
+
|
|
22
|
+
export const CELL_W = 480;
|
|
23
|
+
export const HEADER_H = 32;
|
|
24
|
+
|
|
25
|
+
export class RenderUnavailableError extends Error {
|
|
26
|
+
constructor() {
|
|
27
|
+
super("chromium missing (npx playwright install chromium)");
|
|
28
|
+
this.name = "RenderUnavailableError";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface RenderStepOptions {
|
|
33
|
+
deckJson: string;
|
|
34
|
+
step: string;
|
|
35
|
+
viewport?: { width: number; height: number };
|
|
36
|
+
/** Output root; default the deck directory. */
|
|
37
|
+
outDir?: string;
|
|
38
|
+
/** Reference renders (`<slideId>.png`); default `<deck dir>/pptx/ref`. */
|
|
39
|
+
refDir?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface RenderStepResult {
|
|
43
|
+
dir: string;
|
|
44
|
+
contact: string;
|
|
45
|
+
columns: number;
|
|
46
|
+
rows: number;
|
|
47
|
+
warnings: string[];
|
|
48
|
+
files: string[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Merge `fragment` into the IR's overrides in memory (same rules as `overrides apply`). */
|
|
52
|
+
export function withFragment(ir: DeckIR, fragment: Record<string, unknown> | undefined): DeckIR {
|
|
53
|
+
return fragment ? { ...ir, overrides: deepMerge(ir.overrides ?? {}, fragment) as DeckIR["overrides"] } : ir;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** HTML of the deck with `fragment` merged in — shared by `variants render` and `serve ?variant=`. */
|
|
57
|
+
export async function renderWithFragment(deckJson: string, fragment: Record<string, unknown> | undefined): Promise<string> {
|
|
58
|
+
const ir = JSON.parse(readFileSync(deckJson, "utf8")) as DeckIR;
|
|
59
|
+
const merged = withFragment(ir, fragment);
|
|
60
|
+
const result = validate(merged, { deckDir: dirname(deckJson) });
|
|
61
|
+
if (!result.ok) throw new Error(result.errors.map((e) => formatIssue("error", e)).join("; "));
|
|
62
|
+
const errs: string[] = [];
|
|
63
|
+
const html = await renderIrToHtml(merged, deckJson, { stdout: () => {}, stderr: (l) => errs.push(l) });
|
|
64
|
+
if (html === undefined) throw new Error(errs.join("; ") || "render failed");
|
|
65
|
+
return html;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function openPage(browser: import("playwright").Browser, htmlPath: string, vp: { width: number; height: number }): Promise<Page> {
|
|
69
|
+
const page = await browser.newPage({ viewport: vp, deviceScaleFactor: 1 });
|
|
70
|
+
await page.goto(pathToFileURL(htmlPath).href);
|
|
71
|
+
await page.waitForFunction(() => window.__deck3d !== undefined, undefined, { timeout: 60_000 });
|
|
72
|
+
await page.evaluate(() => window.__deck3d?.ready());
|
|
73
|
+
return page;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const dataUri = (png: Buffer) => `data:image/png;base64,${png.toString("base64")}`;
|
|
77
|
+
|
|
78
|
+
export async function renderStep(opts: RenderStepOptions): Promise<RenderStepResult> {
|
|
79
|
+
const deckDir = dirname(opts.deckJson);
|
|
80
|
+
const { style } = requireStyle(opts.deckJson);
|
|
81
|
+
const step = style.steps.find((s) => s.id === opts.step);
|
|
82
|
+
if (!step) throw new Error(`unknown step '${opts.step}' (steps: ${style.steps.map((s) => s.id).join(", ") || "none"})`);
|
|
83
|
+
const vp = opts.viewport ?? { width: 1920, height: 1080 };
|
|
84
|
+
const ir = JSON.parse(readFileSync(opts.deckJson, "utf8")) as DeckIR;
|
|
85
|
+
const deckIds = new Set(ir.slides.map((s) => s.id));
|
|
86
|
+
const warnings: string[] = [];
|
|
87
|
+
const samples = step.slides.filter((id) => {
|
|
88
|
+
if (deckIds.has(id)) return true;
|
|
89
|
+
warnings.push(`warning step ${step.id}: sample slide '${id}' is not in the deck; skipped`);
|
|
90
|
+
return false;
|
|
91
|
+
});
|
|
92
|
+
const outRoot = opts.outDir ?? deckDir;
|
|
93
|
+
const dir = join(outRoot, "variants", step.id, `r${step.round}`);
|
|
94
|
+
mkdirSync(dir, { recursive: true });
|
|
95
|
+
const refDir = opts.refDir ?? join(deckDir, "pptx", "ref");
|
|
96
|
+
const refs = new Map<string, Buffer>();
|
|
97
|
+
for (const id of samples) {
|
|
98
|
+
const f = join(refDir, `${id}.png`);
|
|
99
|
+
if (existsSync(f)) refs.set(id, readFileSync(f));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let browser: import("playwright").Browser;
|
|
103
|
+
try {
|
|
104
|
+
const { chromium } = await import("playwright");
|
|
105
|
+
browser = await chromium.launch({ channel: "chromium" });
|
|
106
|
+
} catch {
|
|
107
|
+
throw new RenderUnavailableError();
|
|
108
|
+
}
|
|
109
|
+
let tmp: string | undefined;
|
|
110
|
+
const files: string[] = [];
|
|
111
|
+
const shots = new Map<string, Buffer>();
|
|
112
|
+
try {
|
|
113
|
+
// Created INSIDE the cleanup scope: a failure here must still close the browser.
|
|
114
|
+
const scratch = mkdtempSync(join(tmpdir(), "deck3d-variants-"));
|
|
115
|
+
tmp = scratch;
|
|
116
|
+
for (const variant of step.variants) {
|
|
117
|
+
const html = join(scratch, `${variant.name}.html`);
|
|
118
|
+
writeFileSync(html, await renderWithFragment(opts.deckJson, variant.overrides));
|
|
119
|
+
const page = await openPage(browser, html, vp);
|
|
120
|
+
try {
|
|
121
|
+
const ids = await page.evaluate(() => window.__DECK.slides.map((s) => s.id));
|
|
122
|
+
for (const id of samples) {
|
|
123
|
+
const n = ids.indexOf(id) + 1;
|
|
124
|
+
await page.evaluate(
|
|
125
|
+
([slide]) => {
|
|
126
|
+
window.__deck3d?.gotoSlide(slide);
|
|
127
|
+
window.__deck3d?.setTime(0);
|
|
128
|
+
},
|
|
129
|
+
[n] as [number],
|
|
130
|
+
);
|
|
131
|
+
await page.evaluate(() => window.__deck3d?.ready());
|
|
132
|
+
await page.waitForTimeout(150);
|
|
133
|
+
const png = await page.screenshot();
|
|
134
|
+
const file = join(dir, `${variant.name}-${id}.png`);
|
|
135
|
+
writeFileSync(file, png);
|
|
136
|
+
files.push(file);
|
|
137
|
+
shots.set(`${variant.name}|${id}`, png);
|
|
138
|
+
}
|
|
139
|
+
} finally {
|
|
140
|
+
await closeQuietly(page);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const cellH = Math.round((CELL_W * vp.height) / vp.width);
|
|
145
|
+
const cols = (refs.size ? 1 : 0) + step.variants.length;
|
|
146
|
+
const header = [...(refs.size ? ["reference"] : []), ...step.variants.map((v) => `${v.name} — ${v.label}`)];
|
|
147
|
+
const rows = samples.map((id) => {
|
|
148
|
+
const cells = [
|
|
149
|
+
...(refs.size ? [refs.has(id) ? `<img src="${dataUri(refs.get(id) as Buffer)}">` : `<i>no reference</i>`] : []),
|
|
150
|
+
...step.variants.map((v) => `<img src="${dataUri(shots.get(`${v.name}|${id}`) as Buffer)}">`),
|
|
151
|
+
];
|
|
152
|
+
return cells.map((c, k) => `<div class="c">${c}${k === 0 ? `<b>${id}</b>` : ""}</div>`).join("");
|
|
153
|
+
});
|
|
154
|
+
const sheet = `<!doctype html><meta charset="utf-8"><style>
|
|
155
|
+
html,body{margin:0;background:#101114;color:#e5e7eb;font:600 13px/${HEADER_H}px system-ui,sans-serif}
|
|
156
|
+
.g{display:grid;grid-template-columns:repeat(${cols},${CELL_W}px);gap:0}
|
|
157
|
+
.h{height:${HEADER_H}px;padding:0 10px;box-sizing:border-box;background:#1b1d23;white-space:nowrap;overflow:hidden}
|
|
158
|
+
.c{position:relative;width:${CELL_W}px;height:${cellH}px;overflow:hidden;background:#000;display:flex;align-items:center;justify-content:center}
|
|
159
|
+
.c img{width:100%;height:100%;object-fit:contain}.c i{opacity:.5;font-weight:400}
|
|
160
|
+
.c b{position:absolute;left:6px;top:4px;padding:0 6px;line-height:20px;background:rgba(0,0,0,.65);border-radius:4px;font-size:11px}
|
|
161
|
+
</style><div class="g">${header.map((h) => `<div class="h">${h.replace(/</g, "<")}</div>`).join("")}${rows.join("")}</div>`;
|
|
162
|
+
const sheetHtml = join(scratch, "contact.html");
|
|
163
|
+
writeFileSync(sheetHtml, sheet);
|
|
164
|
+
const page = await browser.newPage({ viewport: { width: cols * CELL_W, height: HEADER_H + samples.length * cellH }, deviceScaleFactor: 1 });
|
|
165
|
+
try {
|
|
166
|
+
await page.goto(pathToFileURL(sheetHtml).href);
|
|
167
|
+
await page.waitForFunction(() => [...document.images].every((i) => i.complete));
|
|
168
|
+
const contact = join(dir, "contact.png");
|
|
169
|
+
writeFileSync(contact, await page.screenshot());
|
|
170
|
+
files.push(contact);
|
|
171
|
+
return { dir, contact, columns: cols, rows: samples.length, warnings, files };
|
|
172
|
+
} finally {
|
|
173
|
+
await closeQuietly(page);
|
|
174
|
+
}
|
|
175
|
+
} finally {
|
|
176
|
+
await closeQuietly(browser);
|
|
177
|
+
if (tmp) rmSync(tmp, { recursive: true, force: true });
|
|
178
|
+
}
|
|
179
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
3
|
+
"title": "deck3d style.json",
|
|
4
|
+
"description": "The recorded creative decisions of a deck: ordered steps, each with 2-4 candidate override fragments, the pick, and the rounds taken.",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"additionalProperties": false,
|
|
7
|
+
"required": ["version", "steps"],
|
|
8
|
+
"properties": {
|
|
9
|
+
"version": { "const": 1 },
|
|
10
|
+
"source": { "type": "string", "description": "The pptx or brief the deck was built from." },
|
|
11
|
+
"steps": {
|
|
12
|
+
"type": "array",
|
|
13
|
+
"items": {
|
|
14
|
+
"type": "object",
|
|
15
|
+
"additionalProperties": false,
|
|
16
|
+
"required": ["id", "title", "question", "slides", "round", "variants"],
|
|
17
|
+
"properties": {
|
|
18
|
+
"id": { "type": "string", "pattern": "^[a-z][a-z0-9-]{0,63}$" },
|
|
19
|
+
"title": { "type": "string" },
|
|
20
|
+
"question": { "type": "string" },
|
|
21
|
+
"slides": { "type": "array", "items": { "type": "string" }, "description": "Sample slide ids shown on the contact sheet." },
|
|
22
|
+
"round": { "type": "integer", "minimum": 1 },
|
|
23
|
+
"variants": {
|
|
24
|
+
"type": "array",
|
|
25
|
+
"minItems": 2,
|
|
26
|
+
"maxItems": 4,
|
|
27
|
+
"items": {
|
|
28
|
+
"type": "object",
|
|
29
|
+
"additionalProperties": false,
|
|
30
|
+
"required": ["name", "label", "overrides"],
|
|
31
|
+
"properties": {
|
|
32
|
+
"name": { "type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$" },
|
|
33
|
+
"label": { "type": "string" },
|
|
34
|
+
"overrides": { "type": "object", "description": "Fragment in the deck overrides grammar (validated against it)." }
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"picked": { "type": ["string", "null"], "description": "Chosen variant name, or null when the answer was free text." },
|
|
39
|
+
"note": { "type": "string" },
|
|
40
|
+
"pickedAt": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}T" },
|
|
41
|
+
"pending": { "type": "boolean", "description": "True while a pick is half-written; any variants command then asks for a re-run." },
|
|
42
|
+
"drop": { "type": "array", "items": { "type": "string" }, "description": "Effect/prop ids the pick was allowed to remove (--drop), kept so `variants replay` repeats it." },
|
|
43
|
+
"replaceStep": { "type": "string", "description": "Earlier step whose effects the pick replaced (--replace-step), kept for replay." }
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `style.json` — types, validation and atomic I/O (spec deck3d-variant-loop
|
|
3
|
+
* "style.json grammar and validation"). Every finding names its JSON path.
|
|
4
|
+
*/
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import { closeSync, existsSync, linkSync, openSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import Ajv, { type ErrorObject } from "ajv";
|
|
9
|
+
import { formatPath, validateOverridesFragment } from "../ir/validate.js";
|
|
10
|
+
import { pkgRoot } from "../util/paths.js";
|
|
11
|
+
|
|
12
|
+
export interface Variant {
|
|
13
|
+
name: string;
|
|
14
|
+
label: string;
|
|
15
|
+
overrides: Record<string, unknown>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface Step {
|
|
19
|
+
id: string;
|
|
20
|
+
title: string;
|
|
21
|
+
question: string;
|
|
22
|
+
slides: string[];
|
|
23
|
+
round: number;
|
|
24
|
+
variants: Variant[];
|
|
25
|
+
picked?: string | null;
|
|
26
|
+
note?: string;
|
|
27
|
+
pickedAt?: string;
|
|
28
|
+
pending?: boolean;
|
|
29
|
+
drop?: string[];
|
|
30
|
+
replaceStep?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface Style {
|
|
34
|
+
version: 1;
|
|
35
|
+
source?: string;
|
|
36
|
+
steps: Step[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface StyleIssue {
|
|
40
|
+
path: string;
|
|
41
|
+
message: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const ajv = new Ajv({ allErrors: true, strict: false });
|
|
45
|
+
const check = ajv.compile(JSON.parse(readFileSync(join(pkgRoot(), "src", "variants", "schema.json"), "utf8")) as object);
|
|
46
|
+
|
|
47
|
+
function message(e: ErrorObject): string {
|
|
48
|
+
const p = e.params as Record<string, unknown>;
|
|
49
|
+
switch (e.keyword) {
|
|
50
|
+
case "minItems":
|
|
51
|
+
return `needs at least ${String(p.limit)} entries`;
|
|
52
|
+
case "maxItems":
|
|
53
|
+
return `allows at most ${String(p.limit)} entries`;
|
|
54
|
+
case "additionalProperties":
|
|
55
|
+
return `unknown key '${String(p.additionalProperty)}'`;
|
|
56
|
+
case "required":
|
|
57
|
+
return `missing required key '${String(p.missingProperty)}'`;
|
|
58
|
+
case "type":
|
|
59
|
+
return `expected ${String(p.type)}`;
|
|
60
|
+
case "pattern":
|
|
61
|
+
return `must match ${String(p.pattern)}`;
|
|
62
|
+
default:
|
|
63
|
+
return e.message ?? e.keyword;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const STYLE_FILE = "style.json";
|
|
68
|
+
|
|
69
|
+
/** Validate a parsed `style.json`; `slideIds` (when known) turns dangling samples into warnings. */
|
|
70
|
+
export function validateStyle(style: unknown, slideIds?: Set<string>): { errors: StyleIssue[]; warnings: StyleIssue[] } {
|
|
71
|
+
const errors: StyleIssue[] = [];
|
|
72
|
+
const warnings: StyleIssue[] = [];
|
|
73
|
+
if (!check(style)) {
|
|
74
|
+
for (const e of check.errors ?? []) errors.push({ path: formatPath(e.instancePath), message: message(e) });
|
|
75
|
+
return { errors, warnings };
|
|
76
|
+
}
|
|
77
|
+
const s = style as Style;
|
|
78
|
+
s.steps.forEach((step, i) => {
|
|
79
|
+
const names = new Set<string>();
|
|
80
|
+
step.variants.forEach((v, j) => {
|
|
81
|
+
if (names.has(v.name)) errors.push({ path: `steps[${i}].variants[${j}].name`, message: `duplicate variant name '${v.name}'` });
|
|
82
|
+
names.add(v.name);
|
|
83
|
+
for (const issue of validateOverridesFragment(v.overrides)) {
|
|
84
|
+
errors.push({ path: `steps[${i}].variants[${j}].overrides${issue.path === "(root)" ? "" : `.${issue.path}`}`, message: issue.message });
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
if (typeof step.picked === "string" && !names.has(step.picked)) {
|
|
88
|
+
errors.push({ path: `steps[${i}].picked`, message: `'${step.picked}' names no variant (one of ${[...names].join(", ")})` });
|
|
89
|
+
}
|
|
90
|
+
if (slideIds) {
|
|
91
|
+
for (const id of step.slides) {
|
|
92
|
+
if (!slideIds.has(id)) warnings.push({ path: `steps[${i}].slides`, message: `sample slide '${id}' is not in the deck (skipped)` });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
const ids = new Set<string>();
|
|
97
|
+
s.steps.forEach((step, i) => {
|
|
98
|
+
if (ids.has(step.id)) errors.push({ path: `steps[${i}].id`, message: `duplicate step id '${step.id}'` });
|
|
99
|
+
ids.add(step.id);
|
|
100
|
+
});
|
|
101
|
+
return { errors, warnings };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function stylePath(deckDir: string): string {
|
|
105
|
+
return join(deckDir, STYLE_FILE);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function readStyle(path: string): Style | undefined {
|
|
109
|
+
if (!existsSync(path)) return undefined;
|
|
110
|
+
return JSON.parse(readFileSync(path, "utf8")) as Style;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Write via a temp file + rename, so a reader never sees a half-written file.
|
|
115
|
+
* The temp name is unique per call: a PID alone collided between two writers
|
|
116
|
+
* (or two writes) in one process.
|
|
117
|
+
*/
|
|
118
|
+
export function writeAtomic(path: string, data: string): void {
|
|
119
|
+
const tmp = `${path}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
120
|
+
writeFileSync(tmp, data);
|
|
121
|
+
try {
|
|
122
|
+
renameSync(tmp, path);
|
|
123
|
+
} catch (err) {
|
|
124
|
+
// Do not leave the temp file behind when the swap fails.
|
|
125
|
+
rmSync(tmp, { force: true });
|
|
126
|
+
throw err;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export class LockError extends Error {
|
|
131
|
+
constructor(message: string) {
|
|
132
|
+
super(message);
|
|
133
|
+
this.name = "LockError";
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface LockOptions {
|
|
138
|
+
/** How long to wait for a LIVE holder before giving up (default: fail at once). */
|
|
139
|
+
waitMs?: number;
|
|
140
|
+
/** Test seams for forced interleavings. */
|
|
141
|
+
hooks?: {
|
|
142
|
+
/** After a stale lock was inspected, before the recovery lock is taken. */
|
|
143
|
+
afterInspect?: (lock: string) => void;
|
|
144
|
+
/** Holding the recovery lock, after re-reading the lock, right before removing it. */
|
|
145
|
+
beforeUnlink?: (lock: string) => void;
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const POLL_MS = 40;
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Liveness probe only: signal 0 delivers nothing and kills nothing. deck3d is a
|
|
153
|
+
* standalone package with no dependency edge on the dashboard's shared platform
|
|
154
|
+
* helpers (`isProcessAlive`), hence the per-line policy opt-out.
|
|
155
|
+
*/
|
|
156
|
+
function alive(pid: number): boolean {
|
|
157
|
+
try {
|
|
158
|
+
process.kill(pid, 0); // ban:process-kill-ok
|
|
159
|
+
return true;
|
|
160
|
+
} catch (err) {
|
|
161
|
+
return (err as NodeJS.ErrnoException).code === "EPERM";
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** `pid:token` → pid; undefined for anything else (empty, garbage). */
|
|
166
|
+
function ownerOf(content: string): number | undefined {
|
|
167
|
+
const m = /^(\d+):/.exec(content);
|
|
168
|
+
return m ? Number(m[1]) : undefined;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
type Attempt = { token: string } | { retry: true } | { busy: string };
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Create `path` atomically WITH its owner inside it: the content goes to a
|
|
175
|
+
* private temp file that is `link`ed to `path` (atomic, EEXIST when it already
|
|
176
|
+
* exists), so no other process can ever observe the file empty or half-written.
|
|
177
|
+
* Returns the owner token, or undefined when `path` already exists.
|
|
178
|
+
*/
|
|
179
|
+
function createWithOwner(path: string): string | undefined {
|
|
180
|
+
const token = `${process.pid}:${randomBytes(6).toString("hex")}`;
|
|
181
|
+
const tmp = `${path}.${token.replace(":", "-")}.tmp`;
|
|
182
|
+
writeFileSync(tmp, token);
|
|
183
|
+
try {
|
|
184
|
+
linkSync(tmp, path);
|
|
185
|
+
return token;
|
|
186
|
+
} catch (err) {
|
|
187
|
+
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
|
|
188
|
+
return undefined;
|
|
189
|
+
} finally {
|
|
190
|
+
try {
|
|
191
|
+
unlinkSync(tmp);
|
|
192
|
+
} catch {
|
|
193
|
+
// Already gone.
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Remove `path` only if it still holds `token` (never a lock that is not ours). */
|
|
199
|
+
function releaseOwned(path: string, token: string): void {
|
|
200
|
+
try {
|
|
201
|
+
if (readFileSync(path, "utf8") === token) unlinkSync(path);
|
|
202
|
+
} catch {
|
|
203
|
+
// Already gone: nothing left to release.
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* One acquisition attempt. A held lock is only taken over when its owner is
|
|
209
|
+
* provably dead, and only under a separate recovery lock, re-reading the lock
|
|
210
|
+
* first: if it is no longer the one we inspected we leave it alone and
|
|
211
|
+
* re-inspect. A lock we cannot identify is treated as live. The recovery lock
|
|
212
|
+
* is never expired by age — a recoverer that is merely slow is still the
|
|
213
|
+
* recoverer — so one left by a crash is reported with its pid for manual removal.
|
|
214
|
+
*/
|
|
215
|
+
function tryAcquire(lock: string, hooks: LockOptions["hooks"]): Attempt {
|
|
216
|
+
const token = createWithOwner(lock);
|
|
217
|
+
if (token) return { token };
|
|
218
|
+
let content: string;
|
|
219
|
+
try {
|
|
220
|
+
content = readFileSync(lock, "utf8");
|
|
221
|
+
} catch (err) {
|
|
222
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return { retry: true }; // released meanwhile
|
|
223
|
+
throw err;
|
|
224
|
+
}
|
|
225
|
+
const owner = ownerOf(content);
|
|
226
|
+
if (owner === undefined) return { busy: `unidentifiable lock ${lock}; if no other deck3d process is running, remove it` };
|
|
227
|
+
if (alive(owner)) return { busy: `another deck3d process is writing this deck (pid ${owner}); if it crashed, remove ${lock}` };
|
|
228
|
+
|
|
229
|
+
hooks?.afterInspect?.(lock);
|
|
230
|
+
const recover = `${lock}.recover`;
|
|
231
|
+
const rtoken = createWithOwner(recover);
|
|
232
|
+
if (!rtoken) {
|
|
233
|
+
let who = "unknown";
|
|
234
|
+
try {
|
|
235
|
+
who = String(ownerOf(readFileSync(recover, "utf8")) ?? "unknown");
|
|
236
|
+
} catch {
|
|
237
|
+
// Released meanwhile; the next attempt decides.
|
|
238
|
+
}
|
|
239
|
+
return { busy: `another process is recovering ${lock} (pid ${who}); if it crashed, remove ${recover}` };
|
|
240
|
+
}
|
|
241
|
+
try {
|
|
242
|
+
// Only the holder of the recovery lock may remove a lock, and only the one inspected.
|
|
243
|
+
if (readFileSync(lock, "utf8") === content) {
|
|
244
|
+
hooks?.beforeUnlink?.(lock);
|
|
245
|
+
unlinkSync(lock);
|
|
246
|
+
}
|
|
247
|
+
} catch (err) {
|
|
248
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
|
249
|
+
} finally {
|
|
250
|
+
releaseOwned(recover, rtoken);
|
|
251
|
+
}
|
|
252
|
+
return { retry: true };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function release(lock: string, token: string): void {
|
|
256
|
+
releaseOwned(lock, token);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function lockPathOf(deckDir: string): string {
|
|
260
|
+
return `${stylePath(deckDir)}.lock`;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function sleepSync(ms: number): void {
|
|
264
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Run `fn` holding the deck's exclusive lock. A pick is a read-validate step
|
|
269
|
+
* and three writes (style pending → deck.json → style final); two writers
|
|
270
|
+
* interleaving them can leave the deck and the recorded pick from different
|
|
271
|
+
* decisions. The lock is released on every path out, success or throw.
|
|
272
|
+
*/
|
|
273
|
+
export function withStyleLock<T>(deckDir: string, fn: () => T, opts: LockOptions = {}): T {
|
|
274
|
+
const lock = lockPathOf(deckDir);
|
|
275
|
+
const deadline = Date.now() + (opts.waitMs ?? 0);
|
|
276
|
+
for (;;) {
|
|
277
|
+
const got = tryAcquire(lock, opts.hooks);
|
|
278
|
+
if ("token" in got) {
|
|
279
|
+
try {
|
|
280
|
+
return fn();
|
|
281
|
+
} finally {
|
|
282
|
+
release(lock, got.token);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if ("busy" in got && Date.now() >= deadline) throw new LockError(got.busy);
|
|
286
|
+
if ("busy" in got) sleepSync(POLL_MS);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Async twin for callers that hold the lock across awaits (serve's rebuild). */
|
|
291
|
+
export async function withStyleLockAsync<T>(deckDir: string, fn: () => Promise<T>, opts: LockOptions = {}): Promise<T> {
|
|
292
|
+
const lock = lockPathOf(deckDir);
|
|
293
|
+
const deadline = Date.now() + (opts.waitMs ?? 0);
|
|
294
|
+
for (;;) {
|
|
295
|
+
const got = tryAcquire(lock, opts.hooks);
|
|
296
|
+
if ("token" in got) {
|
|
297
|
+
try {
|
|
298
|
+
return await fn();
|
|
299
|
+
} finally {
|
|
300
|
+
release(lock, got.token);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if ("busy" in got && Date.now() >= deadline) throw new LockError(got.busy);
|
|
304
|
+
if ("busy" in got) await new Promise((r) => setTimeout(r, POLL_MS));
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export const serialize = (v: unknown): string => `${JSON.stringify(v, null, 2)}\n`;
|
|
309
|
+
|
|
310
|
+
/** First step with `pending: true` (an interrupted pick), if any. */
|
|
311
|
+
export function pendingStep(style: Style): Step | undefined {
|
|
312
|
+
return style.steps.find((s) => s.pending === true);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export function interruptedMessage(step: Step): string {
|
|
316
|
+
const name = step.picked ?? step.variants[0]?.name ?? "<variant>";
|
|
317
|
+
return `an earlier pick of step '${step.id}' was interrupted (style.json has pending: true); re-run: deck3d variants pick ${step.id} ${name}`;
|
|
318
|
+
}
|