iso-explainer 0.0.0-stage → 1.0.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 (38) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +110 -2
  3. package/README.pt-BR.md +88 -0
  4. package/bin/iso-explainer.mjs +75 -0
  5. package/package.json +37 -4
  6. package/skills/iso-explainer/SKILL.md +92 -0
  7. package/skills/iso-explainer/assets/fonts/OFL.txt +93 -0
  8. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-400-normal.woff2 +0 -0
  9. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-500-normal.woff2 +0 -0
  10. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-600-normal.woff2 +0 -0
  11. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-700-normal.woff2 +0 -0
  12. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-800-normal.woff2 +0 -0
  13. package/skills/iso-explainer/assets/runtime/LUCIDE-LICENSE.txt +43 -0
  14. package/skills/iso-explainer/assets/runtime/app.js +687 -0
  15. package/skills/iso-explainer/assets/runtime/engine.js +1177 -0
  16. package/skills/iso-explainer/assets/runtime/icons.js +205 -0
  17. package/skills/iso-explainer/assets/runtime/styles.css +447 -0
  18. package/skills/iso-explainer/assets/runtime/template.html +29 -0
  19. package/skills/iso-explainer/assets/templates/starter.course.json +134 -0
  20. package/skills/iso-explainer/examples/arquitetura-pedidos.docs.json +1743 -0
  21. package/skills/iso-explainer/examples/engenharia-na-pratica.course.json +2074 -0
  22. package/skills/iso-explainer/examples/figures/token-bucket.html +98 -0
  23. package/skills/iso-explainer/examples/historia-pedidos.story.json +1872 -0
  24. package/skills/iso-explainer/references/architecture-mode.md +82 -0
  25. package/skills/iso-explainer/references/design-system.md +58 -0
  26. package/skills/iso-explainer/references/engine.md +64 -0
  27. package/skills/iso-explainer/references/entities.md +70 -0
  28. package/skills/iso-explainer/references/flows.md +67 -0
  29. package/skills/iso-explainer/references/inside.md +64 -0
  30. package/skills/iso-explainer/references/layout.md +122 -0
  31. package/skills/iso-explainer/references/schema.md +157 -0
  32. package/skills/iso-explainer/references/story-mode.md +72 -0
  33. package/skills/iso-explainer/references/storytelling.md +56 -0
  34. package/skills/iso-explainer/scripts/build.mjs +80 -0
  35. package/skills/iso-explainer/scripts/harvest.mjs +240 -0
  36. package/skills/iso-explainer/scripts/lib/resolve.mjs +251 -0
  37. package/skills/iso-explainer/scripts/snapshot.mjs +97 -0
  38. package/skills/iso-explainer/scripts/validate.mjs +41 -0
@@ -0,0 +1,251 @@
1
+ // Load + resolve an authored course into the fully-expanded runtime shape.
2
+ // Authoring conveniences handled here (see references/schema.md):
3
+ // • defs (course- or lesson-level) + `use` / string references for entities & links
4
+ // • steps inherit the previous step's scene and metrics (null removes; scene.reset starts fresh)
5
+ // • `at: [col,row]` screen-aligned placement, `size` for zones/crowds
6
+ // • links without `pts` are auto-routed along iso axes (`via: "x" | "y" | "straight"`)
7
+ // • string shorthands: tags ["text"], label "A\nB", route "linkId", body "single paragraph"
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+
12
+ export async function loadCourse(file) {
13
+ const abs = path.resolve(file);
14
+ if (/\.(mjs|js)$/.test(abs)) return (await import(pathToFileURL(abs).href)).default;
15
+ return JSON.parse(fs.readFileSync(abs, 'utf8'));
16
+ }
17
+
18
+ const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
19
+ const clone = (v) => (v === undefined ? v : JSON.parse(JSON.stringify(v)));
20
+ export const fromColRow = (col, row) => [col + row, col - row];
21
+ export const ENTITY_TYPES = ['block', 'device', 'db', 'crowd', 'queue', 'zone', 'ghost', 'panel'];
22
+ export const PACKET_KINDS = ['req', 'res', 'slow', 'heavy', 'mine', 'write', 'kill', 'msg', 'poison', 'push', 'empty', 'ping', 'retry', 'event'];
23
+ export const CHAPTERS = ['setup', 'problem', 'technique', 'solution', 'tradeoff', 'insight', 'recap', 'case',
24
+ 'overview', 'component', 'flow', 'data', 'integration', 'failure', 'decision', 'risk', 'proposal',
25
+ 'context', 'motivation', 'alternative', 'consequence', 'incident', 'migration', 'milestone', 'learning'];
26
+ export const SOURCE_KINDS = ['adr', 'rfc', 'session', 'commit', 'pr', 'issue', 'incident', 'postmortem', 'doc', 'chat', 'meeting', 'metric', 'link'];
27
+ export const LINK_STYLES = ['solid', 'dashed', 'off', 'beat', 'cut', 'hot'];
28
+
29
+ function centerOf(e) {
30
+ if (e.type === 'crowd' || e.type === 'zone') return [(e.x0 + e.x1) / 2, (e.y0 + e.y1) / 2];
31
+ return [e.x, e.y];
32
+ }
33
+
34
+ export function resolveCourse(src, { baseDir = process.cwd() } = {}) {
35
+ const errors = [], warnings = [];
36
+ const err = (p, m) => errors.push(`${p}: ${m}`), warn = (p, m) => warnings.push(`${p}: ${m}`);
37
+ const course = clone(src);
38
+ course.meta ||= {};
39
+ course.meta.id ||= String(course.meta.title || 'course').toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
40
+ const gdefs = { entities: {}, links: {}, ...(course.defs || {}) };
41
+ const story = course.meta.mode === 'story';
42
+ const docs = course.meta.mode === 'docs' || story;
43
+ if (course.meta.mode && !['course', 'docs', 'story'].includes(course.meta.mode)) warn('meta.mode', `unknown mode "${course.meta.mode}" (use "course", "docs" or "story")`);
44
+ const chapters = [...CHAPTERS, ...Object.keys(course.meta.chapters || {})];
45
+
46
+ // lessons may be an array or a map
47
+ const lessonList = Array.isArray(course.lessons) ? course.lessons : Object.entries(course.lessons || {}).map(([id, l]) => ({ id, ...l }));
48
+ const lessons = {};
49
+ for (const l of lessonList) { if (!l.id) err('lessons[]', 'lesson without id'); else lessons[l.id] = l; }
50
+
51
+ // modules: lessons can be ids or {id,title}
52
+ if (!Array.isArray(course.modules) || !course.modules.length) {
53
+ course.modules = [{ id: 'main', num: '01', title: course.meta.title || 'Lessons', color: 'sand', lessons: Object.keys(lessons) }];
54
+ }
55
+ course.modules.forEach((m, mi) => {
56
+ m.id ||= `m${mi + 1}`; m.num ??= String(mi + 1).padStart(2, '0');
57
+ m.lessons = (m.lessons || []).map((x) => (typeof x === 'string' ? { id: x, title: lessons[x]?.title || x } : { title: lessons[x.id]?.title || x.id, ...x }));
58
+ });
59
+ const listed = new Set(course.modules.flatMap((m) => m.lessons.map((l) => l.id)));
60
+ for (const id of Object.keys(lessons)) if (!listed.has(id)) warn(`lessons.${id}`, 'not listed in any module — it will not appear in the sidebar');
61
+
62
+ // Steps resolution (shared by lessons and by native `inside` drill-downs).
63
+ function resolveSteps(stepList, defs, metricKeys, P, depth = 0) {
64
+ let prevScene = { entities: {}, links: {}, flows: [] }, prevMetrics = Object.fromEntries(metricKeys.map((k) => [k, null]));
65
+ return stepList.map((st, si) => {
66
+ const SP = `${P}.steps[${si}]`;
67
+ const s = { ...st };
68
+ if (typeof s.body === 'string') s.body = [s.body];
69
+ s.body ||= [];
70
+ if (!s.title) err(SP, 'missing title');
71
+ if (!s.short) warn(SP, 'missing `short` (timeline label) — using title');
72
+ s.short ||= String(s.title || '').replace(/<[^>]+>/g, '').slice(0, 14);
73
+ if (s.short.length > 14) warn(SP, `short "${s.short}" is ${s.short.length} chars — keep ≤ 14 so the timeline stays readable`);
74
+ if (s.chapter && !chapters.includes(s.chapter)) warn(SP, `unknown chapter "${s.chapter}" (use ${chapters.join(', ')} or declare it in meta.chapters)`);
75
+ const words = s.body.join(' ').replace(/<[^>]+>/g, '').split(/\s+/).filter(Boolean).length;
76
+ if (words > 90) warn(SP, `body has ${words} words — aim for ≤ 70 (two short paragraphs)`);
77
+ if (s.callout && !['insight', 'tip', 'warn', 'next'].includes(s.callout.kind || 'insight')) warn(SP, `callout.kind "${s.callout.kind}" unknown`);
78
+ if (s.sources) s.sources = s.sources.map((x) => (typeof x === 'string' ? { label: x } : x));
79
+ for (const [k, x] of (s.sources || []).entries()) if (x.kind && !SOURCE_KINDS.includes(x.kind)) warn(`${SP}.sources[${k}]`, `unknown kind "${x.kind}" (use ${SOURCE_KINDS.join(', ')})`);
80
+ if (s.decision) {
81
+ if (!s.decision.decision) err(`${SP}.decision`, 'needs `decision` (what was decided)');
82
+ if (!s.decision.context) warn(`${SP}.decision`, 'no `context` — say what motivated it');
83
+ if (typeof s.decision.alternatives === 'string') s.decision.alternatives = [s.decision.alternatives];
84
+ }
85
+ if (story && depth === 0 && (s.decision || ['decision', 'motivation', 'incident'].includes(s.chapter)) && !(s.sources || []).length)
86
+ warn(SP, 'story step without `sources` — cite where this comes from (ADR, RFC, PR, session…) or say in the text that it is inferred');
87
+ if (story && depth === 0 && !s.date) warn(SP, 'story step without `date` (shown under the timeline label)');
88
+
89
+ // metrics inherit
90
+ const m = { ...prevMetrics, ...(s.metrics || {}) };
91
+ for (const k of Object.keys(s.metrics || {})) if (!metricKeys.includes(k)) warn(`${SP}.metrics.${k}`, 'not listed in lesson.metrics — it will not be shown');
92
+ s.metrics = m; prevMetrics = m;
93
+
94
+ // scene inherit
95
+ const raw = s.scene || {};
96
+ const base = raw.reset || si === 0 ? { entities: {}, links: {}, flows: [] } : clone(prevScene);
97
+ const ents = { ...base.entities };
98
+ for (const [id, v] of Object.entries(raw.entities || {})) {
99
+ const EP = `${SP}.scene.entities.${id}`;
100
+ if (v === null) { delete ents[id]; continue; }
101
+ let e;
102
+ if (typeof v === 'string') { if (!defs.entities[v]) { err(EP, `unknown entity def "${v}"`); continue; } e = clone(defs.entities[v]); }
103
+ else if (v.use) { if (!defs.entities[v.use]) { err(EP, `unknown entity def "${v.use}"`); continue; } const { use, ...rest } = v; e = { ...clone(defs.entities[use]), ...rest }; }
104
+ else if (ents[id] && (v.patch || !v.type)) { const { patch, ...rest } = v; e = { ...ents[id], ...rest }; } // patch: tweak the inherited entity
105
+ else e = clone(v);
106
+ if (!e.type) e.type = 'block';
107
+ if (!ENTITY_TYPES.includes(e.type)) { err(EP, `unknown type "${e.type}" (use ${ENTITY_TYPES.join(', ')})`); continue; }
108
+ if (Array.isArray(e.at)) { const [x, y] = fromColRow(e.at[0], e.at[1]); e.x = x; e.y = y; delete e.at; }
109
+ if ((e.type === 'zone' || e.type === 'crowd') && e.x0 === undefined) {
110
+ if (e.x === undefined || !e.size) { err(EP, `${e.type} needs x0,x1,y0,y1 or at/x,y + size:[d,w]`); continue; }
111
+ const [d, w] = e.size; e.x0 = e.x - d / 2; e.x1 = e.x + d / 2; e.y0 = e.y - w / 2; e.y1 = e.y + w / 2; delete e.size; delete e.x; delete e.y;
112
+ }
113
+ if (e.type !== 'panel' && e.type !== 'zone' && e.type !== 'crowd' && (typeof e.x !== 'number' || typeof e.y !== 'number')) { err(EP, 'needs numeric x,y (or at:[col,row])'); continue; }
114
+ if (e.type === 'block' && typeof e.label === 'string') e.label = e.label.split('\n');
115
+ if (e.type === 'block') { // text is drawn on the block face: keep it inside
116
+ const size = Math.min(e.s ?? 4, e.d ?? e.s ?? 4, e.w ?? e.s ?? 4), maxL = Math.floor(size * 3.3), maxS = Math.floor(size * 4.2);
117
+ for (const line of e.label || []) if (String(line).length > maxL) warn(EP, `label line "${line}" is ${String(line).length} chars; a block of size ${size} fits ~${maxL} — shorten, split in 2 lines, or raise s`);
118
+ if (e.sub && String(e.sub).length > maxS) warn(EP, `sub "${e.sub}" is ${String(e.sub).length} chars; fits ~${maxS} on this block`);
119
+ }
120
+ if (e.tags) e.tags = e.tags.map((t) => (typeof t === 'string' ? { text: t } : t));
121
+ if (e.type === 'panel') { e.lines ||= []; e.bars ||= []; if (!e.title) warn(EP, 'panel without title'); }
122
+ if (e.inside != null) {
123
+ if (e.type === 'panel' || e.type === 'zone' || e.type === 'queue') { warn(EP, `inside is ignored on ${e.type}`); delete e.inside; }
124
+ else if (typeof e.inside === 'string') { if (!useInside(e.inside, `${EP}.inside`, depth)) delete e.inside; }
125
+ else e.inside = registerInside(e.inside, `${EP}.inside`, depth, e);
126
+ }
127
+ ents[id] = e;
128
+ }
129
+ const panels = Object.entries(ents).filter(([, e]) => e.type === 'panel');
130
+ if (panels.length > 1) warn(SP, `${panels.length} panels in one scene — only one card is docked; keep one`);
131
+
132
+ const links = { ...base.links };
133
+ for (const [id, v] of Object.entries(raw.links || {})) {
134
+ const LP = `${SP}.scene.links.${id}`;
135
+ if (v === null) { delete links[id]; continue; }
136
+ let l;
137
+ if (typeof v === 'string') { if (!defs.links[v]) { err(LP, `unknown link def "${v}"`); continue; } l = clone(defs.links[v]); }
138
+ else if (v.use) { if (!defs.links[v.use]) { err(LP, `unknown link def "${v.use}"`); continue; } const { use, ...rest } = v; l = { ...clone(defs.links[use]), ...rest }; }
139
+ else if (links[id] && (v.patch || !v.from)) { const { patch, ...rest } = v; l = { ...links[id], ...rest }; if (rest.to || rest.via) delete l.pts; }
140
+ else l = clone(v);
141
+ links[id] = l;
142
+ }
143
+ // validate & auto-route links against the final entity set
144
+ for (const [id, l] of Object.entries(links)) {
145
+ const LP = `${SP}.scene.links.${id}`;
146
+ if (!l.from || !ents[l.from]) { err(LP, `from "${l.from}" is not an entity in this step`); delete links[id]; continue; }
147
+ if (l.to && !ents[l.to]) { err(LP, `to "${l.to}" is not an entity in this step`); delete links[id]; continue; }
148
+ if (ents[l.from].type === 'panel' || (l.to && ents[l.to].type === 'panel')) { err(LP, 'links cannot attach to a panel'); delete links[id]; continue; }
149
+ l.heads ||= 'end';
150
+ if (l.style && !LINK_STYLES.includes(l.style)) warn(LP, `unknown style "${l.style}"`);
151
+ if (!l.pts) {
152
+ if (!l.to) { err(LP, 'needs `to` or explicit `pts`'); delete links[id]; continue; }
153
+ const a = centerOf(ents[l.from]), b = centerOf(ents[l.to]), via = l.via || 'x';
154
+ const aligned = Math.abs(a[0] - b[0]) < 1e-6 || Math.abs(a[1] - b[1]) < 1e-6;
155
+ l.pts = via === 'straight' || aligned ? [l.from, l.to] : via === 'y' ? [l.from, [l.from, l.to], l.to] : [l.from, [l.to, l.from], l.to];
156
+ }
157
+ delete l.via;
158
+ if (l.label && String(l.label).length > 30) warn(LP, `label is ${String(l.label).length} chars — keep ≤ 28 or use "\\n"`);
159
+ }
160
+
161
+ let flows = raw.flows !== undefined ? clone(raw.flows) : base.flows;
162
+ flows = (flows || []).map((f, fi) => {
163
+ const FP = `${SP}.scene.flows[${fi}]`;
164
+ if (typeof f.route === 'string') f.route = [f.route];
165
+ const paths = f.routes ? f.routes.map((r) => (typeof r.path === 'string' ? (r.path = [r.path]) : r.path)) : [f.route || []];
166
+ for (const p of paths) for (const seg of p) for (const lid2 of [].concat(seg)) if (!links[lid2]) err(FP, `route uses link "${lid2}" which does not exist in this step`);
167
+ if (f.kind && !PACKET_KINDS.includes(f.kind)) warn(FP, `unknown packet kind "${f.kind}"`);
168
+ return f;
169
+ });
170
+
171
+ const scene = { entities: ents, links, flows };
172
+ s.scene = scene; prevScene = scene;
173
+ return s;
174
+ });
175
+ }
176
+
177
+ // `inside`: what you see when clicking an entity. Native sub-diagram (steps/scene) or an embedded figure (html/svg file,
178
+ // e.g. built with the anatomy skill). Registered once in course.insides; entities keep only the key.
179
+ const authoredInsides = course.insides || {};
180
+ const insides = {}, insideByContent = new Map();
181
+ function resolveInside(obj, IP, depth) {
182
+ if (depth > 2) { err(IP, 'inside nested more than 2 levels'); return null; }
183
+ const out = { title: obj.title || '', summary: obj.summary || '' };
184
+ const read = (f, key) => {
185
+ const abs = path.resolve(baseDir, f);
186
+ if (!fs.existsSync(abs)) { err(`${IP}.${key}`, `file not found: ${f} (paths are relative to the course file)`); return null; }
187
+ return fs.readFileSync(abs, 'utf8');
188
+ };
189
+ if (obj.html) { out.kind = 'html'; out.html = read(obj.html, 'html'); if (obj.htmlDark) out.htmlDark = read(obj.htmlDark, 'htmlDark'); out.height = obj.height || null; if (out.html == null) return null; }
190
+ else if (obj.svg) { out.kind = 'svg'; out.svg = read(obj.svg, 'svg'); if (out.svg == null) return null; }
191
+ else if (obj.steps || obj.scene) {
192
+ out.kind = 'scene';
193
+ const idefs = { entities: { ...gdefs.entities, ...(obj.defs?.entities || {}) }, links: { ...gdefs.links, ...(obj.defs?.links || {}) } };
194
+ const raw = obj.steps || [{ title: obj.title || '', short: '1', scene: obj.scene, body: obj.body || [] }];
195
+ out.metrics = obj.metrics || [];
196
+ out.legend = obj.legend || null;
197
+ out.steps = resolveSteps(raw, idefs, out.metrics, IP, depth + 1);
198
+ if (raw.length > 8) warn(IP, `${raw.length} steps inside — keep a drill-down short (≤ 6)`);
199
+ } else { err(IP, 'needs one of: steps, scene, html, svg'); return null; }
200
+ return out;
201
+ }
202
+ function useInside(key, IP, depth) {
203
+ if (insides[key]) return true;
204
+ if (!authoredInsides[key]) { err(IP, `unknown inside "${key}" (define it in course.insides)`); return false; }
205
+ const r = resolveInside(authoredInsides[key], `insides.${key}`, depth);
206
+ if (r) insides[key] = r;
207
+ return !!r;
208
+ }
209
+ function registerInside(obj, IP, depth, e) {
210
+ const sig = JSON.stringify(obj);
211
+ if (insideByContent.has(sig)) return insideByContent.get(sig);
212
+ const base = String(obj.id || (Array.isArray(e.label) ? e.label.join('-') : e.label) || 'inside').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'inside';
213
+ let key = base, n = 2; while (insides[key] || authoredInsides[key]) key = `${base}-${n++}`;
214
+ insideByContent.set(sig, key);
215
+ const r = resolveInside(obj, IP, depth);
216
+ if (r) insides[key] = r;
217
+ return r ? key : undefined;
218
+ }
219
+
220
+ const out = {};
221
+ for (const [lid, L] of Object.entries(lessons)) {
222
+ const P = `lessons.${lid}`;
223
+ const defs = { entities: { ...gdefs.entities, ...(L.defs?.entities || {}) }, links: { ...gdefs.links, ...(L.defs?.links || {}) } };
224
+ if (!L.title) err(P, 'missing title');
225
+ if (!Array.isArray(L.steps) || !L.steps.length) { err(P, 'needs at least one step'); continue; }
226
+ if (L.steps.length < 4 && !docs) warn(P, `only ${L.steps.length} steps — lessons read best with 6–12`);
227
+ if (L.steps.length > 14) warn(P, `${L.steps.length} steps — consider splitting the lesson (max ~12)`);
228
+ const metricKeys = L.metrics || [];
229
+ const steps = resolveSteps(L.steps, defs, metricKeys, P);
230
+ (L.goals || []).forEach((g, gi) => { if (g.step >= steps.length || g.step < 0) err(`${P}.goals[${gi}]`, `step ${g.step} out of range (0-based, < ${steps.length})`); });
231
+ if (story) { /* chronological: any opening works */ }
232
+ else if (docs) {
233
+ if (steps[0].chapter && steps[0].chapter !== 'overview') warn(`${P}.steps[0]`, 'architecture tours read best when step 1 is an "overview" of the whole view');
234
+ } else {
235
+ if (steps[0].chapter && !['problem', 'setup', 'case'].includes(steps[0].chapter)) warn(`${P}.steps[0]`, 'lessons land best when step 1 states a problem (chapter "problem" or "setup")');
236
+ if (steps.at(-1).chapter && steps.at(-1).chapter !== 'recap') warn(`${P}.steps[${steps.length - 1}]`, 'consider ending with a "recap" step');
237
+ }
238
+ if (docs) { // architecture tours & stories: readers click every box, so every main component should open
239
+ const bare = new Set();
240
+ for (const st of steps) for (const [id, e] of Object.entries(st.scene.entities)) if (['block', 'db', 'device'].includes(e.type) && !e.inside && !e.dead) bare.add(id);
241
+ if (bare.size) warn(P, `components without \`inside\`: ${[...bare].join(', ')} — in docs/story mode give every main component a drill-down (references/inside.md)`);
242
+ }
243
+ const { defs: _d, ...rest } = L;
244
+ out[lid] = { ...rest, metrics: metricKeys, steps };
245
+ }
246
+ course.lessons = out;
247
+ course.insides = insides;
248
+ delete course.defs;
249
+ if (!Object.keys(out).length) err('lessons', 'no playable lessons');
250
+ return { course, errors, warnings };
251
+ }
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ // Visual QA: screenshot every step of a built course and audit the layout.
3
+ // node scripts/snapshot.mjs dist/index.html [--out shots] [--lesson id] [--step n]
4
+ // [--viewport desktop|tablet|mobile|all] [--theme light|dark|both] [--wait 2700]
5
+ // Writes PNGs + report.json. Exit 1 if there are console errors (layout issues are warnings).
6
+ // Needs Playwright + a Chromium (npm i -D playwright && npx playwright install chromium),
7
+ // or an installed Chrome/Edge, or set CHROME_PATH.
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+
12
+ let chromium;
13
+ for (const spec of ['playwright', 'playwright-core', ...(process.env.PLAYWRIGHT_PATH ? [process.env.PLAYWRIGHT_PATH] : [])]) {
14
+ try { ({ chromium } = await import(spec)); break; } catch {}
15
+ }
16
+ if (!chromium) { console.error('Playwright not found. Install it: npm i -D playwright && npx playwright install chromium'); process.exit(2); }
17
+
18
+ const args = process.argv.slice(2);
19
+ const opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; };
20
+ const file = args.find((a, i) => !a.startsWith('-') && !args[i - 1]?.startsWith('--') && args[i - 1] !== '-o');
21
+ if (!file) { console.error('usage: node scripts/snapshot.mjs <built.html> [--out dir] [--lesson id] [--step n] [--viewport desktop|tablet|mobile|all] [--theme light|dark|both]'); process.exit(2); }
22
+ const out = path.resolve(opt('--out', 'shots'));
23
+ const wait = +opt('--wait', 2700);
24
+ const VP = { desktop: [1440, 900, 1], tablet: [1024, 768, 1], mobile: [390, 844, 2] };
25
+ const vps = opt('--viewport', 'desktop') === 'all' ? Object.keys(VP) : [opt('--viewport', 'desktop')];
26
+ const themes = opt('--theme', 'light') === 'both' ? ['light', 'dark'] : [opt('--theme', 'light')];
27
+ fs.mkdirSync(out, { recursive: true });
28
+
29
+ // Browser: CHROME_PATH → Playwright's bundled Chromium → installed Chrome/Edge (any OS).
30
+ const launchOpts = [{ executablePath: process.env.CHROME_PATH }, {}, { channel: 'chrome' }, { channel: 'msedge' }]
31
+ .filter((o, i) => i > 0 || o.executablePath).map((o) => ({ ...o, args: ['--no-sandbox'] }));
32
+ let browser;
33
+ for (const o of launchOpts) { try { browser = await chromium.launch(o); break; } catch {} }
34
+ if (!browser) { console.error('No Chromium found. Run: npx playwright install chromium (or set CHROME_PATH).'); process.exit(2); }
35
+ const url = pathToFileURL(path.resolve(file)).href;
36
+ const report = { shots: [], consoleErrors: [], issues: [] };
37
+
38
+ // In-page audit: pills/labels that overlap each other, and things clipped by the stage edges.
39
+ const audit = () => {
40
+ const stage = document.querySelector('#canvas').getBoundingClientRect();
41
+ const hud = [...document.querySelectorAll('#hud .chip, .stage__tools .tool:not([hidden]), #legend span')].map((n) => n.getBoundingClientRect());
42
+ const items = [...document.querySelectorAll('.layer-over > g, .layer-hud > g')]
43
+ .flatMap((g) => [...g.querySelectorAll('.pill'), ...(g.closest('.layer-hud') ? [g] : [])])
44
+ .map((n) => ({ r: n.getBoundingClientRect(), text: n.textContent.trim().slice(0, 40), op: +getComputedStyle(n.closest('g[style], g') || n).opacity }))
45
+ .filter((x) => x.r.width > 2 && x.r.height > 2);
46
+ const issues = [];
47
+ const inter = (a, b) => Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left)) * Math.max(0, Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top));
48
+ for (let i = 0; i < items.length; i++) for (let j = i + 1; j < items.length; j++) {
49
+ const a = items[i], b = items[j], ov = inter(a.r, b.r);
50
+ if (ov > 40) issues.push({ level: 'warn', kind: 'overlap', msg: `"${a.text}" overlaps "${b.text}" (${Math.round(ov)} px²)` });
51
+ }
52
+ const card = document.querySelector('#stage').getBoundingClientRect();
53
+ for (const x of items) {
54
+ if (x.r.left < card.left - 1 || x.r.right > card.right + 1 || x.r.top < card.top - 1 || x.r.bottom > card.bottom + 1) issues.push({ level: 'warn', kind: 'clipped', msg: `"${x.text}" sticks out of the stage` });
55
+ for (const h of hud) if (inter(x.r, h) > 60) { issues.push({ level: 'warn', kind: 'hud', msg: `"${x.text}" is under the HUD/tools/legend` }); break; }
56
+ }
57
+ void stage;
58
+ return issues;
59
+ };
60
+
61
+ for (const vp of vps) for (const theme of themes) {
62
+ const [w, h, dpr] = VP[vp];
63
+ const ctx = await browser.newContext({ viewport: { width: w, height: h }, deviceScaleFactor: dpr, reducedMotion: 'no-preference' });
64
+ await ctx.addInitScript((th) => { try { for (const k of Object.keys(localStorage)) if (k.endsWith(':theme')) localStorage.removeItem(k); } catch {} void th; }, theme);
65
+ const page = await ctx.newPage();
66
+ page.on('console', (m) => { if (m.type() === 'error') report.consoleErrors.push(`[${vp}/${theme}] ${m.text()}`); });
67
+ page.on('pageerror', (e) => report.consoleErrors.push(`[${vp}/${theme}] ${e.message}`));
68
+ await page.goto(url);
69
+ await page.waitForTimeout(400);
70
+ const course = await page.evaluate(() => ({ lessons: Object.fromEntries(Object.entries(window.__COURSE__.lessons).map(([k, l]) => [k, l.steps.length])), id: window.__COURSE__.meta.id }));
71
+ if (theme === 'dark') await page.evaluate(() => { if (document.documentElement.dataset.theme !== 'dark') document.querySelector('#theme-btn').click(); });
72
+ for (const [lid, n] of Object.entries(course.lessons)) {
73
+ if (opt('--lesson') && opt('--lesson') !== lid) continue;
74
+ for (let s = 1; s <= n; s++) {
75
+ if (opt('--step') && +opt('--step') !== s) continue;
76
+ await page.evaluate((h) => { location.hash = h; }, `#/${lid}/${s}`);
77
+ await page.waitForTimeout(250);
78
+ await page.waitForFunction(() => window.__isx && !window.__isx.state.animating, null, { timeout: 15000 }).catch(() => {});
79
+ await page.waitForTimeout(Math.max(600, wait - 2000)); // let packets flow so the shot shows traffic
80
+ const name = `${lid}-${String(s).padStart(2, '0')}-${vp}-${theme}.png`;
81
+ await page.screenshot({ path: path.join(out, name) });
82
+ const issues = (await page.evaluate(audit)).map((x) => ({ ...x, shot: name }));
83
+ report.issues.push(...issues);
84
+ report.shots.push(name);
85
+ process.stdout.write(`${issues.length ? '!' : '·'}`);
86
+ }
87
+ }
88
+ await ctx.close();
89
+ }
90
+ await browser.close();
91
+ fs.writeFileSync(path.join(out, 'report.json'), JSON.stringify(report, null, 2));
92
+ console.log(`\n${report.shots.length} screenshots → ${path.relative(process.cwd(), out)}/`);
93
+ for (const e of report.consoleErrors) console.log(`console error ${e}`);
94
+ const byShot = {};
95
+ for (const i of report.issues) (byShot[i.shot] ||= []).push(`${i.kind}: ${i.msg}`);
96
+ for (const [s, l] of Object.entries(byShot)) console.log(`${s}\n ${[...new Set(l)].join('\n ')}`);
97
+ process.exit(report.consoleErrors.length ? 1 : 0);
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+ // Validate a course without building. Prints errors/warnings with JSON paths; exit 1 on errors.
3
+ // node scripts/validate.mjs course.json [--json]
4
+ // Also runs geometry checks: overlapping footprints, entities sharing a spot, very long walks for links.
5
+ import path from 'node:path';
6
+ import { loadCourse, resolveCourse } from './lib/resolve.mjs';
7
+
8
+ const file = process.argv[2];
9
+ if (!file) { console.error('usage: node scripts/validate.mjs <course.json|course.mjs> [--json]'); process.exit(2); }
10
+ const { course, errors, warnings } = resolveCourse(await loadCourse(file), { baseDir: path.dirname(path.resolve(file)) });
11
+
12
+ const fp = (e) => {
13
+ if (e.type === 'crowd' || e.type === 'zone') return [e.x0, e.x1, e.y0, e.y1];
14
+ if (e.type === 'device') return [e.x - (e.d ?? 6) / 2, e.x + (e.d ?? 6) / 2, e.y - (e.w ?? 6) / 2, e.y + (e.w ?? 6) / 2];
15
+ if (e.type === 'db') { const r = e.r ?? 1.7; return [e.x - r, e.x + r, e.y - r, e.y + r]; }
16
+ if (e.type === 'queue' || e.type === 'panel' || e.type === 'ghost') return null;
17
+ const hx = (e.d ?? e.s ?? 4) / 2, hy = (e.w ?? e.s ?? 4) / 2;
18
+ return [e.x - hx, e.x + hx, e.y - hy, e.y + hy];
19
+ };
20
+ for (const [lid, L] of Object.entries(course.lessons || {})) {
21
+ L.steps.forEach((s, si) => {
22
+ const ents = Object.entries(s.scene.entities).filter(([, e]) => e.type !== 'zone' && e.type !== 'panel');
23
+ for (let i = 0; i < ents.length; i++) for (let j = i + 1; j < ents.length; j++) {
24
+ const a = fp(ents[i][1]), b = fp(ents[j][1]);
25
+ if (!a || !b) continue;
26
+ const ox = Math.min(a[1], b[1]) - Math.max(a[0], b[0]), oy = Math.min(a[3], b[3]) - Math.max(a[2], b[2]);
27
+ if (ox > -1.5 && oy > -1.5) warnings.push(`lessons.${lid}.steps[${si}]: "${ents[i][0]}" and "${ents[j][0]}" are ${ox > 0 && oy > 0 ? 'overlapping' : 'touching'} — keep ≥ 3 grid units between footprints (≥ 6 when labels/pills sit between them)`);
28
+ }
29
+ const n = Object.keys(s.scene.entities).length;
30
+ if (n > 14) warnings.push(`lessons.${lid}.steps[${si}]: ${n} entities — a step should show ≤ 12 things`);
31
+ const tags = Object.values(s.scene.entities).reduce((a, e) => a + (e.tags?.length || 0), 0);
32
+ if (tags > 8) warnings.push(`lessons.${lid}.steps[${si}]: ${tags} tag pills — too much text on the diagram; move detail to the body`);
33
+ });
34
+ }
35
+
36
+ if (process.argv.includes('--json')) { console.log(JSON.stringify({ errors, warnings }, null, 2)); process.exit(errors.length ? 1 : 0); }
37
+ for (const w of warnings) console.warn(`warn ${w}`);
38
+ for (const e of errors) console.error(`error ${e}`);
39
+ const lessons = Object.keys(course.lessons || {}).length, steps = Object.values(course.lessons || {}).reduce((a, l) => a + l.steps.length, 0);
40
+ console.log(errors.length ? `✗ ${errors.length} error(s), ${warnings.length} warning(s)` : `✓ valid · ${lessons} lesson(s), ${steps} steps · ${warnings.length} warning(s)`);
41
+ process.exit(errors.length ? 1 : 0);