decklight 0.8.1 → 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 (138) hide show
  1. package/PLATFORM.md +707 -0
  2. package/README.md +226 -150
  3. package/SPEC.md +803 -888
  4. package/cli/agent-review.mjs +246 -0
  5. package/cli/agents.mjs +35 -9
  6. package/cli/associate.mjs +12 -12
  7. package/cli/audit.mjs +42 -10
  8. package/cli/banner.mjs +41 -17
  9. package/cli/bundle-audio.mjs +190 -0
  10. package/cli/bundle-module.mjs +95 -0
  11. package/cli/bundle.mjs +439 -35
  12. package/cli/cast.mjs +48 -12
  13. package/cli/check-fixes.mjs +186 -0
  14. package/cli/check.mjs +988 -0
  15. package/cli/clone-deck.mjs +179 -0
  16. package/cli/commands.mjs +345 -0
  17. package/cli/comments.mjs +64 -18
  18. package/cli/commit-flow.mjs +51 -22
  19. package/cli/commit-message.mjs +51 -74
  20. package/cli/commit-split.mjs +601 -0
  21. package/cli/deck-refs.mjs +64 -0
  22. package/cli/deck-routes.mjs +67 -0
  23. package/cli/deckfile.mjs +3 -5
  24. package/cli/decklight.mjs +68 -289
  25. package/cli/design-system-deps.mjs +209 -0
  26. package/cli/design-system-edit.mjs +194 -0
  27. package/cli/design-system-refs.mjs +666 -0
  28. package/cli/design-system.mjs +497 -0
  29. package/cli/doctor.mjs +115 -0
  30. package/cli/edit-git.mjs +353 -0
  31. package/cli/edit-handover.mjs +551 -0
  32. package/cli/edit-look.mjs +631 -0
  33. package/cli/edit-slides.mjs +683 -0
  34. package/cli/edit.mjs +2585 -855
  35. package/cli/enhance.mjs +485 -0
  36. package/cli/extension.mjs +10 -10
  37. package/cli/font-refs.mjs +273 -0
  38. package/cli/font.mjs +246 -0
  39. package/cli/git-tree.mjs +1 -1
  40. package/cli/git.mjs +78 -11
  41. package/cli/import.mjs +56 -10
  42. package/cli/init.mjs +407 -236
  43. package/cli/library.mjs +127 -0
  44. package/cli/loader.mjs +3 -1
  45. package/cli/marketplace-autocheck.mjs +200 -0
  46. package/cli/marketplace.mjs +460 -29
  47. package/cli/narrate.mjs +251 -0
  48. package/cli/open-browser.mjs +63 -0
  49. package/cli/open.mjs +961 -0
  50. package/cli/pdf.mjs +64 -17
  51. package/cli/pkg.mjs +44 -2
  52. package/cli/plugin.mjs +43 -41
  53. package/cli/port-conflict.mjs +53 -23
  54. package/cli/pptx-export.mjs +63 -27
  55. package/cli/publish.mjs +8 -4
  56. package/cli/qr.mjs +1 -1
  57. package/cli/record.mjs +85 -23
  58. package/cli/remote.mjs +43 -17
  59. package/cli/restore.mjs +11 -4
  60. package/cli/review-ref.mjs +125 -0
  61. package/cli/review-remote.mjs +92 -48
  62. package/cli/review-routes.mjs +254 -0
  63. package/cli/review-store.mjs +47 -7
  64. package/cli/review-submit.mjs +47 -57
  65. package/cli/runtime-link.mjs +560 -0
  66. package/cli/serve.mjs +236 -45
  67. package/cli/setup.mjs +112 -0
  68. package/cli/sign.mjs +1 -1
  69. package/cli/skill-content.mjs +229 -35
  70. package/cli/skills.mjs +353 -26
  71. package/cli/start.mjs +110 -0
  72. package/cli/supervise.mjs +6 -6
  73. package/cli/theme-refs.mjs +527 -0
  74. package/cli/theme.mjs +181 -137
  75. package/cli/trust.mjs +83 -0
  76. package/cli/units.mjs +112 -47
  77. package/cli/update-check.mjs +1 -5
  78. package/cli/upgrade.mjs +194 -28
  79. package/cli/upstream.mjs +4 -3
  80. package/cli/util.mjs +4 -4
  81. package/cli/wizard.mjs +6 -6
  82. package/dist/build-info.json +1 -1
  83. package/dist/decklight.css +1533 -59
  84. package/dist/decklight.js +258 -115
  85. package/dist/decklight.js.map +4 -4
  86. package/docs/GLOSSARY.md +141 -0
  87. package/docs/architecture.svg +17 -17
  88. package/package.json +4 -2
  89. package/themes/README.md +9 -8
  90. package/themes/reveal-solarized.css +10 -0
  91. package/tools/args.mjs +20 -0
  92. package/tools/atomic-write.mjs +48 -0
  93. package/tools/brand-palette.mjs +717 -0
  94. package/tools/bridge.mjs +1 -1
  95. package/tools/build-groups.mjs +42 -0
  96. package/tools/color.mjs +48 -0
  97. package/tools/deck-html.mjs +396 -11
  98. package/tools/design-system-format.mjs +778 -0
  99. package/tools/design-system-migrations.mjs +207 -0
  100. package/tools/elevenlabs-tts.mjs +110 -17
  101. package/tools/exec.mjs +11 -3
  102. package/tools/extension-check.mjs +31 -7
  103. package/tools/font-format.mjs +190 -0
  104. package/tools/font-stacks.mjs +24 -0
  105. package/tools/gemini-tts.mjs +3 -0
  106. package/tools/lipsync-config.mjs +103 -0
  107. package/tools/lipsync-engines.mjs +205 -2
  108. package/tools/lipsync-server.mjs +264 -41
  109. package/tools/lipsync.mjs +37 -18
  110. package/tools/local-voice.mjs +32 -42
  111. package/tools/narration-manifest.mjs +270 -0
  112. package/tools/narration-synth.mjs +416 -0
  113. package/tools/pptx.mjs +776 -19
  114. package/tools/publish-targets.mjs +1 -1
  115. package/tools/publish-voices.mjs +3 -3
  116. package/tools/recording-impact.mjs +7 -3
  117. package/tools/render-theme.mjs +33 -0
  118. package/tools/review-anchor.mjs +28 -12
  119. package/tools/semver.mjs +40 -0
  120. package/tools/sentences.mjs +180 -0
  121. package/tools/shot.mjs +14 -7
  122. package/tools/site-clip.mjs +114 -0
  123. package/tools/site-voices.mjs +232 -0
  124. package/tools/template-theme.mjs +1 -1
  125. package/tools/test-impact.mjs +17 -10
  126. package/tools/theme-check.mjs +30 -3
  127. package/tools/tts-cache.mjs +4 -3
  128. package/tools/tts-engines.mjs +38 -20
  129. package/tools/tts-setup.mjs +7 -7
  130. package/tools/video-options.mjs +34 -0
  131. package/tools/video.mjs +530 -54
  132. package/tools/voiceover-server.mjs +185 -104
  133. package/tools/voiceover.mjs +119 -261
  134. package/tools/zip.mjs +1 -1
  135. package/cli/dev.mjs +0 -623
  136. package/cli/present.mjs +0 -853
  137. package/cli/review.mjs +0 -361
  138. package/tools/publish-site-voices.mjs +0 -75
@@ -0,0 +1,666 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // A deck's design systems, as REFERENCES (SPEC DESIGN_SYSTEMS) — the second
5
+ // instance of what THEME_DISTRIBUTION built for themes:
6
+ //
7
+ // "designSystems": ["acme@acme-mkt"],
8
+ // "themeSources": { "acme-mkt": "acme/decklight-marketplace" }
9
+ //
10
+ // The deck records WHICH design system it uses; the package stays in its
11
+ // marketplace. Every server — write mode, --no-trust, and the render server behind
12
+ // shot/pdf/pptx/video — links it into the page from the checkouts on this
13
+ // machine (`linkDesignSystems`) and answers its files under
14
+ // `decklight-design-system/<marketplace>/<name>/…` (`designSystemAsset`).
15
+ // Nothing here fetches: a deck on a plane serves what this machine has and
16
+ // names what it has not (MARKETPLACE_REGISTRY — registered, not fetched).
17
+ //
18
+ // What differs from a marked theme, on purpose:
19
+ // - the stylesheet is ALWAYS ON (no `media="not all"`): a design system is
20
+ // not an alternative to choose between, so `T` leaves it applied;
21
+ // - a package is a DIRECTORY of somebody else's files, so serving it is held
22
+ // tighter than the deck root — plain segments, the asset allowlist, real
23
+ // paths inside the package, fixed MIME, nosniff, a script-free SVG policy,
24
+ // and one indistinguishable 404 for every refusal;
25
+ // - the page also carries the package's meta (palette, templates and slots)
26
+ // and its templates, inline in a <template>, so the engine expands them
27
+ // synchronously, identically for a served deck and a bundled one;
28
+ // - an https `source` has no cache to land in (the theme cache holds one
29
+ // file; a package is many), so it resolves as missing.
30
+ //
31
+ // Every package is re-checked where it is used, not only when it was added —
32
+ // `marketplace update` can change its bytes afterwards — remembered by a
33
+ // stat signature so a page load re-reads nothing that has not changed.
34
+
35
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
36
+ import { dirname, join, resolve, sep } from 'node:path';
37
+ import { escapeHtml } from '../tools/escape.mjs';
38
+ import { DESIGN_SYSTEM_API_VERSION, ASSET_EXTENSIONS, tokenPrefixOf } from '../tools/design-system-format.mjs';
39
+ import { pendingMigrations, composeRenames, findRenamed, majorOf, applyRenames, RENAME_KINDS } from '../tools/design-system-migrations.mjs';
40
+ import { configBlock, isDeck } from './runtime-link.mjs';
41
+ import { configHome, loadRegistry, loadCatalog, MarketplaceError, NAME_RE } from './marketplace.mjs';
42
+ import {
43
+ parseRef, resolveCatalogEntry, markedSources, withKey, referencedMarketplaces, DESIGN_SYSTEMS_KEY, FONTS_KEY, SOURCES_KEY, MARKED_KEY,
44
+ } from './theme-refs.mjs';
45
+ import { resolveSource } from './theme.mjs';
46
+ import { checkDir } from './design-system.mjs';
47
+
48
+ export { DESIGN_SYSTEMS_KEY };
49
+
50
+ /**
51
+ * The config key a deck records the version of each design system it took
52
+ * under (SPEC DESIGN_SYSTEM_MIGRATIONS): `{ "<ref>": "5.0.0" }`, keyed by the
53
+ * deck's own spelling of the reference. The deck's fact, not this machine's:
54
+ * the ledger in ~/.decklight/ says what one machine installed, for every deck
55
+ * at once, and says nothing on the next machine.
56
+ */
57
+ export const DESIGN_SYSTEM_VERSIONS_KEY = 'designSystemVersions';
58
+
59
+ /** The versions a deck records, `{ ref: version }` — strings only. */
60
+ export function deckDesignSystemVersions(html) {
61
+ const v = configBlock(html)?.config?.[DESIGN_SYSTEM_VERSIONS_KEY];
62
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return {};
63
+ return Object.fromEntries(Object.entries(v).filter(([, x]) => typeof x === 'string'));
64
+ }
65
+
66
+ /**
67
+ * Record (or, with null, forget) the version of one design system the deck
68
+ * took, editing only that key so the author's formatting survives. A deck
69
+ * with no configuration block is returned as it is.
70
+ */
71
+ export function setDesignSystemVersion(html, ref, version) {
72
+ const block = configBlock(html);
73
+ if (!block || block.error) return html;
74
+ const versions = deckDesignSystemVersions(html);
75
+ if (version) versions[ref] = String(version);
76
+ else delete versions[ref];
77
+ const inner = withKey(block.inner, DESIGN_SYSTEM_VERSIONS_KEY, Object.keys(versions).length ? versions : null);
78
+ return html.slice(0, block.innerStart) + inner + html.slice(block.innerEnd);
79
+ }
80
+
81
+ /**
82
+ * The stylesheets a deck links from its own folder (`<link rel="stylesheet"
83
+ * href="course.css">`), as `[{ href, path, text }]`: what a migration reads
84
+ * and rewrites beside the deck. A URL, a root-absolute path, a design
85
+ * system's or a theme's own link, and a file that is not there are left out.
86
+ */
87
+ export function linkedStylesheets(html, dir) {
88
+ const out = [];
89
+ const masked = String(html).replace(/<!--[\s\S]*?-->/g, '');
90
+ for (const tag of masked.match(/<link\b[^>]*>/gi) ?? []) {
91
+ if (!/\brel\s*=\s*["']?stylesheet/i.test(tag) || /\bdata-(?:design-system|theme)\b/i.test(tag)) continue;
92
+ const href = /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(tag);
93
+ const url = (href?.[1] ?? href?.[2] ?? href?.[3] ?? '').replace(/[?#].*$/, '');
94
+ if (!url || /^([a-z][a-z0-9+.-]*:|\/)/i.test(url) || url.includes('decklight-design-system/')) continue;
95
+ const path = resolve(dir, decodeURI(url));
96
+ if (out.some((s) => s.path === path)) continue;
97
+ try { if (existsSync(path) && statSync(path).isFile()) out.push({ href: url, path, text: readFileSync(path, 'utf8') }); } catch { /* unreadable: not ours to migrate */ }
98
+ }
99
+ return out;
100
+ }
101
+
102
+ /**
103
+ * Is a deck behind the design system this machine serves (SPEC
104
+ * DESIGN_SYSTEM_MIGRATIONS)? From the version the deck records and the
105
+ * names it, and the stylesheets it links, still use:
106
+ * `{ behind, recorded, current, major, found, skills, renames }`
107
+ * `behind` when the deck records an older major, or uses a name a migration
108
+ * since its version renamed; `found` is those names (`findRenamed`), `skills`
109
+ * the skills the pending migrations name. A deck that records no version is
110
+ * held to every migration the package declares.
111
+ */
112
+ export function migrationStatus(manifest, recorded, texts) {
113
+ const current = manifest?.version ?? null;
114
+ const pending = pendingMigrations(manifest, recorded);
115
+ const renames = composeRenames(pending);
116
+ const found = findRenamed(texts, renames, tokenPrefixOf(manifest));
117
+ const rm = majorOf(recorded), cm = majorOf(current);
118
+ const major = rm !== null && cm !== null && rm < cm;
119
+ return {
120
+ behind: major || found.length > 0, recorded: recorded ?? null, current, major, found,
121
+ skills: [...new Set(pending.map((m) => m.skill).filter(Boolean))], renames,
122
+ };
123
+ }
124
+
125
+ /**
126
+ * Every design system a deck is behind, from what `check` reads: the deck
127
+ * and the stylesheets it links from `dir` (SPEC DESIGN_SYSTEM_MIGRATIONS).
128
+ * `[{ ref, name, title, recorded, current, skills, message }]`, `message`
129
+ * the one sentence (`behindMessage`) with `deck` as the command's argument.
130
+ * A reference this machine cannot serve is not behind: it is missing, and
131
+ * said as that.
132
+ */
133
+ export function deckBehind(html, dir, home = configHome(), { deck = '<deck.html>' } = {}) {
134
+ const refs = designSystemRefs(html);
135
+ if (!refs.length) return [];
136
+ const sources = markedSources(html);
137
+ const versions = deckDesignSystemVersions(html);
138
+ let texts = null;
139
+ const out = [];
140
+ for (const ref of refs) {
141
+ const r = resolveDesignSystemRef(ref, home, { source: sources[ref.marketplace] ?? null });
142
+ const verdict = r.dir ? packageVerdict(r.dir) : null;
143
+ if (!verdict?.ok) continue;
144
+ texts ??= [html, ...(dir ? linkedStylesheets(html, dir).map((x) => x.text) : [])];
145
+ const status = migrationStatus(verdict.manifest, versions[ref.ref] ?? null, texts);
146
+ if (!status.behind) continue;
147
+ out.push({
148
+ ref: ref.ref, name: ref.name, title: verdict.manifest.title || ref.name,
149
+ recorded: status.recorded, current: status.current, skills: status.skills,
150
+ message: behindMessage(ref.name, status, { ref: ref.ref, deck }),
151
+ });
152
+ }
153
+ return out;
154
+ }
155
+
156
+ /**
157
+ * A newer design system the catalog offers, said as what it means for the
158
+ * decks on it (SPEC DESIGN_SYSTEM_MIGRATIONS): one `newerThanInstalled` row
159
+ * with `note` (*major: decks that use it need migrating, with the acme-migrate
160
+ * skill*) and `how` (where to find them and what moves one) when the package
161
+ * this machine now has declares migrations since the version installed. Any
162
+ * other row comes back as it was.
163
+ */
164
+ export function withMigrationHint(n, home = configHome()) {
165
+ if (n?.type !== 'design-system') return n;
166
+ const r = resolveDesignSystemRef(n.qualified, home);
167
+ const verdict = r.dir ? packageVerdict(r.dir) : null;
168
+ if (!verdict?.ok) return n;
169
+ const pending = pendingMigrations(verdict.manifest, n.from);
170
+ if (!pending.length) return n;
171
+ const skills = [...new Set(pending.map((m) => m.skill).filter(Boolean))];
172
+ const major = n.from === null || (majorOf(n.from) ?? 0) < (majorOf(n.to) ?? 0);
173
+ return {
174
+ ...n, migrations: pending.map((m) => m.version), skills,
175
+ note: `${major ? 'major: ' : ''}decks that use it need migrating${skills.length ? `, with the ${skills.join(' or ')} skill` : ''}`,
176
+ how: `decklight check finds them; decklight design-system migrate ${n.qualified} <deck.html> moves one`,
177
+ };
178
+ }
179
+
180
+ /**
181
+ * What `design-system migrate` does to a deck, worked out in memory and
182
+ * written by nobody (SPEC DESIGN_SYSTEM_MIGRATIONS): the command and the
183
+ * edit server's Migrate both apply it. `{ error }` when the deck does not
184
+ * use `ref` or this machine cannot serve it, else
185
+ * `{ ref, name, title, recorded, version, status, html, sheets, renamed, byKind, changed }`
186
+ * — `html` the deck renamed and its version recorded, `sheets` the linked
187
+ * stylesheets a rename touched (`{ href, path, text, count }`), `byKind`
188
+ * `[[kind, found]]` for the report.
189
+ */
190
+ export function planMigration(html, dir, ref, home = configHome()) {
191
+ const hit = designSystemRefs(html).find((r) => r.ref === ref || r.name === ref);
192
+ if (!hit) return { error: `the deck does not use ${ref}` };
193
+ const r = resolveDesignSystemRef(hit, home, { source: markedSources(html)[hit.marketplace] ?? null });
194
+ if (!r.dir) return { error: `${hit.ref} — ${r.missing}` };
195
+ const verdict = checkDir(r.dir);
196
+ if (!verdict.ok) return { error: `${hit.ref} no longer passes its check — decklight design-system gate ${r.dir}` };
197
+ const m = verdict.manifest;
198
+ const recorded = deckDesignSystemVersions(html)[hit.ref] ?? null;
199
+ const sheets = linkedStylesheets(html, dir);
200
+ const status = migrationStatus(m, recorded, [html, ...sheets.map((x) => x.text)]);
201
+ const prefix = tokenPrefixOf(m);
202
+ const deckOut = applyRenames(html, status.renames, prefix, { config: true });
203
+ const next = setDesignSystemVersion(deckOut.text, hit.ref, m.version);
204
+ const touched = sheets.map((x) => ({ ...x, ...applyRenames(x.text, status.renames, prefix) })).filter((x) => x.count);
205
+ const renamed = deckOut.count + touched.reduce((n, x) => n + x.count, 0);
206
+ return {
207
+ ref: hit.ref, name: hit.name, marketplace: hit.marketplace, title: m.title || hit.name, recorded, version: m.version, status,
208
+ html: next, sheets: touched, renamed,
209
+ byKind: RENAME_KINDS.map((k) => [k, status.found.filter((f) => f.kind === k)]).filter(([, l]) => l.length),
210
+ changed: next !== html || renamed > 0,
211
+ };
212
+ }
213
+
214
+ /**
215
+ * A migration said in lines — what `design-system migrate` prints and what
216
+ * the agent panel records when the edit server runs one: the versions, the
217
+ * renames by kind, the count and where, and the skill named for what a
218
+ * rename cannot decide. `placed(name)` says whether an agent already loads
219
+ * that skill (cli/skills.mjs `placedSkill`): the line then says so instead
220
+ * of how to install it.
221
+ */
222
+ export function migrationLines(plan, deck, { placed = () => null } = {}) {
223
+ const out = [`${deck}: ${plan.ref} ${plan.recorded ?? '(no version recorded)'} → ${plan.version}`];
224
+ if (plan.renamed) {
225
+ for (const [kind, list] of plan.byKind) out.push(` ${kind.padEnd(8)} ${list.map((f) => `${f.from} → ${f.to}`).join(', ')}`);
226
+ out.push(` ${plan.renamed} rename${plan.renamed === 1 ? '' : 's'} — in ${deck}${plan.sheets.map((x) => `, ${x.href}`).join('')}`);
227
+ } else out.push(' nothing it uses was renamed — recorded the new version');
228
+ const skills = plan.status.skills;
229
+ if (skills.length) {
230
+ // where the agent finds it, or how to put it there: every project first
231
+ const missing = skills.filter((s) => !placed(s));
232
+ out.push(` what a rename cannot decide (a name removed with no successor) is the ${skills.join(' and ')} skill's:`
233
+ + (missing.length
234
+ ? ` decklight library add skill ${missing[0]} --global (every project; --dir . for this one only), then ask your agent to finish the migration`
235
+ : ' your agent has it, ask it to finish the migration'));
236
+ }
237
+ return out;
238
+ }
239
+
240
+ /**
241
+ * Where a skill's SKILL.md already is on this machine, or null: the library's
242
+ * copy (`~/.decklight/skills/<name>/`) when one is installed, else the
243
+ * catalog entry's source in its marketplace's checkout, `marketplace` first.
244
+ * What a migration's prompt points the agent at, so running one never
245
+ * installs anything into the project (#893).
246
+ */
247
+ export function skillFile(name, marketplace = null, home = configHome()) {
248
+ const installed = join(home, 'skills', name, 'SKILL.md');
249
+ if (existsSync(installed)) return installed;
250
+ const markets = Object.keys(loadRegistry(home).marketplaces ?? {});
251
+ for (const market of [...(markets.includes(marketplace) ? [marketplace] : []), ...markets.filter((m) => m !== marketplace)]) {
252
+ let cat;
253
+ try { cat = loadCatalog(market, home); } catch { continue; }
254
+ const entry = cat?.ok ? cat.manifest.entries.find((e) => e.type === 'skill' && e.name === name) : null;
255
+ if (!entry?.source || /^https?:\/\//i.test(entry.source)) continue;
256
+ let base;
257
+ try { base = resolveSource(entry.source, { name: market, source: loadRegistry(home).marketplaces[market]?.source }, home); } catch { continue; }
258
+ const file = join(base, 'SKILL.md');
259
+ if (existsSync(file)) return file;
260
+ }
261
+ return null;
262
+ }
263
+
264
+ /**
265
+ * A deck that uses a design system but records no version takes `manifest`'s
266
+ * — unless it, or a stylesheet it links from `dir`, still uses a name a
267
+ * migration renamed: recording the new version then would hide that it is
268
+ * behind, and `migrate` moves it first. The html, recorded or as it was.
269
+ */
270
+ export function recordVersionIfCurrent(html, ref, manifest, dir) {
271
+ if (deckDesignSystemVersions(html)[ref] || !manifest?.version) return html;
272
+ const status = migrationStatus(manifest, null, [html, ...linkedStylesheets(html, dir).map((x) => x.text)]);
273
+ return status.found.length ? html : setDesignSystemVersion(html, ref, manifest.version);
274
+ }
275
+
276
+ /**
277
+ * The one sentence that says a deck is behind, with what to do — the same in
278
+ * `check`, the write-mode toast and `design-system migrate`'s refusal.
279
+ */
280
+ export function behindMessage(name, status, { ref = name, deck = '<deck.html>' } = {}) {
281
+ const was = status.recorded ? `${name} ${status.recorded}` : `an earlier ${name}`;
282
+ const n = status.found.length;
283
+ const shown = status.found.slice(0, 3).map((f) => `${f.from} → ${f.to}`).join(', ');
284
+ const what = n ? `: ${n} renamed name${n === 1 ? '' : 's'} (${shown}${n > 3 ? ', …' : ''})` : ', a new major version';
285
+ const how = status.skills.length
286
+ ? `Migrate with the ${status.skills.join(' or ')} skill, or decklight design-system migrate ${ref} ${deck}`
287
+ : `Migrate with decklight design-system migrate ${ref} ${deck}`;
288
+ return `written for ${was}, this machine serves ${status.current}${what}. ${how}`;
289
+ }
290
+
291
+ /** The design systems a deck references, parsed; anything else dropped, not guessed at. */
292
+ export function designSystemRefs(html) {
293
+ const list = configBlock(html)?.config?.[DESIGN_SYSTEMS_KEY];
294
+ if (!Array.isArray(list)) return [];
295
+ const seen = new Set();
296
+ return list.map((e) => parseRef(e)).filter((r) => r && !seen.has(r.ref) && seen.add(r.ref));
297
+ }
298
+
299
+ /**
300
+ * Resolve a reference to its package directory on this machine — registry,
301
+ * catalog cache and checkouts only — or `{ missing }` in words a presenter can
302
+ * act on. Returns `{ name, marketplace, ref, local, title, entry, dir, source }`.
303
+ */
304
+ export function resolveDesignSystemRef(ref, home = configHome(), { source = null } = {}) {
305
+ const parsed = typeof ref === 'string' ? parseRef(ref) : ref;
306
+ if (!parsed) return { ref: String(ref), missing: 'not a design-system reference (name@marketplace)' };
307
+ const hit = resolveCatalogEntry(parsed, home, { source });
308
+ if (hit.missing) return hit;
309
+ const { local, title, entry, registered, origin } = hit;
310
+ if (entry.type !== 'design-system') return { ...parsed, entry, missing: `"${parsed.ref}" is a ${entry.type}, not a design system` };
311
+ if (Number.isInteger(entry.apiVersion) && entry.apiVersion > DESIGN_SYSTEM_API_VERSION) {
312
+ return { ...parsed, entry, missing: `${parsed.ref} needs a newer decklight — it is written for design-system format ${entry.apiVersion}, this one reads up to ${DESIGN_SYSTEM_API_VERSION}` };
313
+ }
314
+ if (typeof entry.source !== 'string' || /^[a-z][a-z0-9+.-]*:/i.test(entry.source)) {
315
+ return { ...parsed, entry, missing: `${parsed.ref} names a URL as its source — a design system is a directory of files in its marketplace, and there is no cache for one` };
316
+ }
317
+ let dir;
318
+ try { dir = resolveSource(entry.source, { name: local, source: registered.source }, home); }
319
+ catch (e) {
320
+ if (e instanceof MarketplaceError) return { ...parsed, title, entry, missing: e.message.replace(/\n\s*/g, ' — ') };
321
+ throw e;
322
+ }
323
+ let isDir = false;
324
+ try { isDir = statSync(dir).isDirectory(); } catch { /* not here */ }
325
+ if (!isDir) return { ...parsed, title, entry, missing: `${parsed.ref}: ${entry.source} is not in the marketplace's files` };
326
+ return { ...parsed, local, title, entry, dir: resolve(dir), source: origin };
327
+ }
328
+
329
+ /** A cheap fingerprint of a package's files — names, sizes and mtimes — so nothing unchanged is re-read. */
330
+ export function signature(dir) {
331
+ const parts = [];
332
+ const walk = (abs, rel) => {
333
+ for (const name of readdirSync(abs).sort()) {
334
+ if (name === '.git') continue;
335
+ const full = join(abs, name);
336
+ let st;
337
+ try { st = statSync(full); } catch { parts.push(`${rel}${name}!`); continue; }
338
+ if (st.isDirectory()) walk(full, `${rel}${name}/`);
339
+ else parts.push(`${rel}${name}:${st.size}:${st.mtimeMs}`);
340
+ }
341
+ };
342
+ walk(dir, '');
343
+ return parts.join('|');
344
+ }
345
+
346
+ const verdicts = new Map();
347
+
348
+ /**
349
+ * Does the package STILL pass `decklight design-system gate`? It follows its
350
+ * marketplace, so it is re-checked wherever it is used. `{ ok, why, summary,
351
+ * manifest }`, remembered by its stat signature.
352
+ */
353
+ export function packageVerdict(dir) {
354
+ let sig;
355
+ try { sig = signature(dir); } catch { return { ok: false, why: 'its files are gone' }; }
356
+ const hit = verdicts.get(dir);
357
+ if (hit && hit.sig === sig) return hit.value;
358
+ const r = checkDir(dir);
359
+ const value = r.ok
360
+ ? { ok: true, summary: r.summary, manifest: r.manifest, templatesHtml: r.templatesHtml }
361
+ : { ok: false, why: `it no longer passes the design-system check — ${r.problems[0].file}${r.problems[0].line ? ` line ${r.problems[0].line}` : ''}: ${r.problems[0].msg} (decklight design-system gate)` };
362
+ verdicts.set(dir, { sig, value });
363
+ return value;
364
+ }
365
+
366
+ /** What the page is told about a package: the facts the engine and the palette read. */
367
+ export function designSystemMeta(verdict) {
368
+ const m = verdict.manifest ?? {};
369
+ const brand = verdict.summary?.brand ?? null;
370
+ return {
371
+ name: m.name, version: m.version, title: m.title,
372
+ // a palette of scales (SPEC BRAND_PALETTE) is told as one entry per swatch, a colour's ten in a row
373
+ palette: brand ? brand.palette : Array.isArray(m.palette) ? m.palette : [],
374
+ ...(brand ? { scales: true, themes: brand.themes.map(({ name, title, mode, refs, roleValues }) => ({ name, title, mode, refs, ...(roleValues ? { roles: roleValues } : {}) })) } : {}),
375
+ // its roles (SPEC DESIGN_SYSTEM_ROLES): what the Colors tab offers on a deck held to the brand, each theme's value above
376
+ // …and which contract tokens read which role: a fill role is that diagram slot (SVG_DIAGRAMS)
377
+ ...(brand?.roles ? { roles: brand.roles, contract: brand.contract ?? {} } : {}),
378
+ // the themes it is made to sit on — the theme picker lists them first
379
+ recommendedThemes: Array.isArray(m.recommendedThemes) ? m.recommendedThemes.filter((t) => typeof t === 'string') : [],
380
+ // …and the fonts (SPEC FONTS) — the font picker lists them first
381
+ recommendedFonts: Array.isArray(m.recommendedFonts) ? m.recommendedFonts.filter((t) => typeof t === 'string') : [],
382
+ templates: (verdict.summary?.templates ?? []).map(({ id, title, slots }) => ({ id, title, slots })),
383
+ };
384
+ }
385
+
386
+ /** Where a server answers a package's files, relative to the deck. */
387
+ export const designSystemHref = (marketplace, name, path) => `decklight-design-system/${marketplace}/${name}/${path}`;
388
+
389
+ /** JSON safe inside a <script> — the manifest is somebody else's file. */
390
+ const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
391
+
392
+ /**
393
+ * A design system's palette of scales and its brand themes, as the page gets
394
+ * them (SPEC BRAND_PALETTE) — the same tags from every server and from
395
+ * `bundle`: the swatches as tokens, defined from the manifest, and each theme
396
+ * as an added theme (`<style data-theme data-theme-added media="not all">`,
397
+ * the shape a bundle's marked theme has), tagged with the design system it
398
+ * belongs to so the picker can hold a deck to its brand. Nothing for a
399
+ * package without a scale palette.
400
+ */
401
+ export function brandTags(name, verdict) {
402
+ const brand = verdict.summary?.brand;
403
+ if (!brand) return [];
404
+ const sys = escapeHtml(name);
405
+ const title = escapeHtml(String(verdict.manifest?.title ?? name));
406
+ const lines = brand.palette.map((e) => ` ${e.token}: ${e.hex};`);
407
+ // every role at its value in the brand's first theme, always on (SPEC DESIGN_SYSTEM_ROLES):
408
+ // each theme block sets them again after this, so a role is never undefined
409
+ // while no brand theme is applied — an unlocked deck on another theme, a block gone
410
+ const first = brand.themes[0]?.css ?? '';
411
+ for (const r of brand.roles ?? []) {
412
+ const m = new RegExp(`^\\s*${r.token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}:\\s*([^;\\n]+);`, 'm').exec(first);
413
+ if (m) lines.push(` ${r.token}: ${m[1]};`);
414
+ }
415
+ const safe = (css) => css.replace(/<\/(style)/gi, '<\\/$1');
416
+ return [
417
+ `<style data-design-system-palette="${sys}">\n.decklight {\n${lines.join('\n')}\n}\n</style>`,
418
+ ...brand.themes.map((t) => `<style data-theme="${escapeHtml(t.name)}" data-theme-added data-design-system-theme="${sys}" data-theme-source="${title}" media="not all">\n${safe(t.css)}</style>`),
419
+ ];
420
+ }
421
+
422
+ /**
423
+ * A deck's design systems, linked into the page on its way out — what every
424
+ * server does after `linkAddedThemes`, never `bundle`. Per reference, after
425
+ * the theme links and before `</head>`:
426
+ * <link rel="stylesheet" href="decklight-design-system/…/design-system.css" data-design-system="<name>">
427
+ * <script type="application/json" data-design-system-meta="<name>">{…}</script>
428
+ * <template data-design-system-templates="<name>">…templates.html…</template>
429
+ * Nothing when the page already carries `<style data-design-system="<name>">`
430
+ * (a bundle's own copy). An unresolvable reference, or a package that no
431
+ * longer passes the check, becomes `<meta name="decklight-design-system-missing">`
432
+ * naming it and why — never a silently short page. A deck behind a
433
+ * package's major gets `<meta name="decklight-design-system-behind"
434
+ * data-ref data-version>`, its sentence the content; `dir` is the deck's
435
+ * folder, so the stylesheets it links are read as `check` reads them, and
436
+ * `deck` its file name, for the command the sentence ends on.
437
+ */
438
+ export function linkDesignSystems(html, home = configHome(), { log = null, dir = null, deck = '<deck.html>' } = {}) {
439
+ if (!isDeck(html)) return html;
440
+ const refs = designSystemRefs(html);
441
+ if (!refs.length) return html;
442
+ const sources = markedSources(html);
443
+ const tags = [];
444
+ let texts = null;
445
+ for (const ref of refs) {
446
+ // a bundle's own copy (<style>), or a link this page already got
447
+ const carried = new RegExp(`<(?:style|link)\\b[^>]*\\bdata-design-system\\s*=\\s*["']${ref.name}["']`, 'i');
448
+ if (carried.test(html)) continue;
449
+ const r = resolveDesignSystemRef(ref, home, { source: sources[ref.marketplace] ?? null });
450
+ const verdict = r.dir ? packageVerdict(r.dir) : null;
451
+ if (r.dir && !verdict.ok) r.missing = verdict.why;
452
+ if (r.dir && verdict.ok) {
453
+ const name = escapeHtml(ref.name);
454
+ tags.push(`<link rel="stylesheet" href="${designSystemHref(r.local, r.name, verdict.manifest.styles)}" data-design-system="${name}">`);
455
+ tags.push(`<script type="application/json" data-design-system-meta="${name}">${scriptJson(designSystemMeta(verdict))}</script>`);
456
+ tags.push(`<template data-design-system-templates="${name}">\n${verdict.templatesHtml.trim()}\n</template>`);
457
+ tags.push(...brandTags(ref.name, verdict));
458
+ // a deck behind the major this machine serves: said once, while authoring (SPEC DESIGN_SYSTEM_MIGRATIONS)
459
+ // — read as `check` reads it: the deck and the stylesheets it links from `dir`
460
+ texts ??= [html, ...(dir ? linkedStylesheets(html, dir).map((x) => x.text) : [])];
461
+ const status = migrationStatus(verdict.manifest, deckDesignSystemVersions(html)[ref.ref] ?? null, texts);
462
+ if (status.behind) {
463
+ tags.push(`<meta name="decklight-design-system-behind" data-ref="${escapeHtml(ref.ref)}" data-version="${escapeHtml(status.current)}"`
464
+ + ` content="${escapeHtml(`${verdict.manifest.title || ref.name}: ${behindMessage(ref.name, status, { ref: ref.ref, deck })}`)}">`);
465
+ }
466
+ } else {
467
+ tags.push(`<meta name="decklight-design-system-missing" content="${escapeHtml(`${ref.ref} — ${r.missing}`)}">`);
468
+ log?.(`design system ${ref.ref}: ${r.missing}`);
469
+ }
470
+ }
471
+ if (!tags.length) return html;
472
+ const masked = html.replace(/<!--[\s\S]*?-->/g, (m) => ' '.repeat(m.length));
473
+ const headEnd = masked.search(/<\/head>/i);
474
+ const at = headEnd !== -1 ? headEnd : Math.max(0, masked.search(/<body\b/i));
475
+ return `${html.slice(0, at)}${tags.join('\n')}\n${html.slice(at)}`;
476
+ }
477
+
478
+ /** A design system's `url()`s — quoted or not — and the address each names. */
479
+ const CSS_URL = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)"'\s]*))\s*\)/gi;
480
+
481
+ /** Bytes as a `data:` URI: an SVG as percent-encoded UTF-8 (readable, smaller), anything else base64. */
482
+ function dataUri(ext, bytes) {
483
+ if (ext === 'svg') {
484
+ const text = encodeURIComponent(bytes.toString('utf8')).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
485
+ return `data:image/svg+xml;charset=utf-8,${text}`;
486
+ }
487
+ return `data:${(DS_MIME[ext] ?? 'application/octet-stream').split(';')[0]};base64,${bytes.toString('base64')}`;
488
+ }
489
+
490
+ /**
491
+ * A design system's stylesheet with every RELATIVE `url()` inlined as a
492
+ * `data:` URI, resolved against the stylesheet's own location — and nothing
493
+ * else touched, byte for byte, so a font's licence header travels with its
494
+ * face. `data:` and `#fragment` urls are left; an outside one (http(s), `//`)
495
+ * is left and listed, because it will not show offline. A relative url whose
496
+ * file is not in the package throws: half a design system is worse than none.
497
+ * Returns `{ css, assets, bytes, external }`.
498
+ */
499
+ export function inlineDesignSystemCss(css, dir, stylesPath) {
500
+ const base = dirname(resolve(dir, stylesPath));
501
+ const root = resolve(dir);
502
+ const assets = new Set();
503
+ let bytes = 0;
504
+ const external = [];
505
+ const out = css.replace(CSS_URL, (whole, dq, sq, bare) => {
506
+ const url = (dq ?? sq ?? bare ?? '').trim();
507
+ if (!url || url.startsWith('#') || /^data:/i.test(url)) return whole;
508
+ if (/^([a-z][a-z0-9+.-]*:|\/\/)/i.test(url)) { external.push(url); return whole; }
509
+ const rel = url.replace(/[?#].*$/, '');
510
+ const file = resolve(base, rel);
511
+ let data;
512
+ try {
513
+ if (!file.startsWith(root + sep)) throw new Error('outside');
514
+ data = readFileSync(file);
515
+ } catch {
516
+ throw new MarketplaceError(`${stylesPath} names url(${url}), and the design system has no such file`);
517
+ }
518
+ assets.add(file);
519
+ bytes += data.length;
520
+ return `url("${dataUri(file.split('.').pop().toLowerCase(), data)}")`;
521
+ });
522
+ return { css: out, assets: assets.size, bytes, external: [...new Set(external)] };
523
+ }
524
+
525
+ /**
526
+ * What a bundle carries for one resolved, still-valid design system: the
527
+ * stylesheet INLINE (`<style data-design-system data-design-system-version>`
528
+ * — the block every server's `linkDesignSystems` sees and links no second
529
+ * copy of), then the meta `<script>` and the templates `<template>` exactly as
530
+ * the servers inject them, so the runtime finds them by the same selectors.
531
+ * Returns `{ tags, assets, bytes, external, templates }`.
532
+ */
533
+ export function bundleDesignSystem(r, verdict) {
534
+ const m = verdict.manifest;
535
+ const inlined = inlineDesignSystemCss(readFileSync(join(r.dir, m.styles), 'utf8'), r.dir, m.styles);
536
+ const name = escapeHtml(r.name);
537
+ const safe = inlined.css.replace(/<\/(style)/gi, '<\\/$1');
538
+ return {
539
+ tags: [
540
+ `<style data-design-system="${name}" data-design-system-version="${escapeHtml(String(m.version ?? ''))}">\n${safe}\n</style>`,
541
+ `<script type="application/json" data-design-system-meta="${name}">${scriptJson(designSystemMeta(verdict))}</script>`,
542
+ `<template data-design-system-templates="${name}">\n${verdict.templatesHtml.trim()}\n</template>`,
543
+ ...brandTags(r.name, verdict),
544
+ ],
545
+ assets: inlined.assets, bytes: inlined.bytes, external: inlined.external,
546
+ templates: verdict.summary?.templates?.length ?? 0,
547
+ // its own themes (SPEC BRAND_PALETTE): carried in `tags`, never looked up in themes/
548
+ brandThemes: (verdict.summary?.brand?.themes ?? []).map((t) => t.name),
549
+ };
550
+ }
551
+
552
+ /** The MIME a package file is answered as — fixed by extension, never sniffed. */
553
+ const DS_MIME = {
554
+ svg: 'image/svg+xml', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp',
555
+ woff2: 'font/woff2', woff: 'font/woff', css: 'text/css; charset=utf-8',
556
+ };
557
+ const NAMESPACE = /(?:^|\/)decklight-design-system\/(.*)$/;
558
+
559
+ /** Is this request path in the design-system namespace at all? */
560
+ export const inDesignSystemNamespace = (rel) => NAMESPACE.test(String(rel ?? '').split('\\').join('/'));
561
+
562
+ /**
563
+ * `staticFiles`' answer for a file of a referenced package — `{ file, type,
564
+ * headers }`, or null, which the caller answers as a plain 404 whatever the
565
+ * reason (a probe learns nothing). The path must be plain segments ending in
566
+ * an allowlisted asset, or the package's own stylesheet; the package must
567
+ * resolve and still pass its check; and the real path must stay inside the
568
+ * package's real directory, so a symlink cannot reach out.
569
+ */
570
+ export function designSystemAsset(rel, home = configHome()) {
571
+ const m = NAMESPACE.exec(String(rel ?? '').split('\\').join('/'));
572
+ if (!m) return null;
573
+ const segs = m[1].split('/');
574
+ if (segs.length < 3) return null;
575
+ const [marketplace, name, ...path] = segs;
576
+ if (!NAME_RE.test(marketplace) || !NAME_RE.test(name)) return null;
577
+ const last = path[path.length - 1];
578
+ if (!path.slice(0, -1).every((s) => /^[\w-]+$/.test(s))) return null;
579
+ const ext = /^[\w-]+\.([A-Za-z0-9]+)$/.exec(last)?.[1]?.toLowerCase();
580
+ if (!ext || !(ASSET_EXTENSIONS.includes(ext) || ext === 'css')) return null;
581
+ const r = resolveDesignSystemRef({ name, marketplace, ref: `${name}@${marketplace}` }, home);
582
+ if (!r.dir) return null;
583
+ const verdict = packageVerdict(r.dir);
584
+ if (!verdict.ok) return null;
585
+ const relPath = path.join('/');
586
+ // the one stylesheet is the package's own; any other .css is not served
587
+ if (ext === 'css' && relPath !== verdict.manifest.styles) return null;
588
+ let real, root;
589
+ try { real = realpathSync(join(r.dir, ...path)); root = realpathSync(r.dir); } catch { return null; }
590
+ if (!real.startsWith(root + sep)) return null;
591
+ try { if (!statSync(real).isFile()) return null; } catch { return null; }
592
+ const headers = { 'x-content-type-options': 'nosniff' };
593
+ // an SVG is a document; one served same-origin to the deck must not script
594
+ if (ext === 'svg') headers['content-security-policy'] = "default-src 'none'; style-src 'unsafe-inline'";
595
+ return { file: real, type: DS_MIME[ext], headers };
596
+ }
597
+
598
+ /**
599
+ * Reference (`on`) or drop a design system in the deck's configuration
600
+ * block, editing only its keys so the author's formatting survives. The
601
+ * source rides alongside in the shared `themeSources`, once per marketplace,
602
+ * and goes only with the last reference of EITHER kind. Returns `{ html,
603
+ * changed }`, or throws a MarketplaceError a command prints as-is.
604
+ */
605
+ export function setDesignSystem(html, ref, on, { source = null, version = null } = {}) {
606
+ const parsed = parseRef(ref);
607
+ if (!parsed) throw new MarketplaceError(`"${ref}" is not a design-system reference — name@marketplace`);
608
+ const block = configBlock(html);
609
+ if (!block) {
610
+ throw new MarketplaceError('the deck has no configuration block to record its design systems in'
611
+ + ' — decklight upgrade --link <deck.html> gives it one');
612
+ }
613
+ if (block.error) throw new MarketplaceError(block.error);
614
+ const current = designSystemRefs(html);
615
+ const has = current.some((r) => r.ref === parsed.ref);
616
+ if (on) {
617
+ if (has) return { html, changed: false };
618
+ // a slide names a design system by its name (data-template="acme/…"), so
619
+ // two of the same name from different catalogs would be ambiguous
620
+ const clash = current.find((r) => r.name === parsed.name);
621
+ if (clash) throw new MarketplaceError(`the deck already uses ${clash.ref} — two design systems called "${parsed.name}" cannot both be referenced`);
622
+ } else if (!has) return { html, changed: false };
623
+ const next = on ? [...current.map((r) => r.ref), parsed.ref] : current.map((r) => r.ref).filter((r) => r !== parsed.ref);
624
+ const sources = markedSources(html);
625
+ if (on && source) sources[parsed.marketplace] = source;
626
+ const others = referencedMarketplaces(html, [MARKED_KEY, FONTS_KEY]);
627
+ for (const m of Object.keys(sources)) {
628
+ if (!next.some((r) => r.endsWith(`@${m}`)) && !others.has(m)) delete sources[m];
629
+ }
630
+ let inner = withKey(block.inner, DESIGN_SYSTEMS_KEY, next.length ? next : null);
631
+ inner = withKey(inner, SOURCES_KEY, Object.keys(sources).length ? sources : null);
632
+ const out = html.slice(0, block.innerStart) + inner + html.slice(block.innerEnd);
633
+ // the version it took goes in with the reference, and out with it (SPEC DESIGN_SYSTEM_MIGRATIONS)
634
+ return { html: on ? (version ? setDesignSystemVersion(out, parsed.ref, version) : out) : setDesignSystemVersion(out, parsed.ref, null), changed: true };
635
+ }
636
+
637
+ /**
638
+ * Every design system every registered marketplace offers, from the cache —
639
+ * what `design-system list` and the "Design systems…" palette show — and the
640
+ * marketplaces it could not list, named so `marketplace update` can be said:
641
+ * `unfetched`, registered but never fetched (the first-party one, on every
642
+ * install that has not asked — nothing is fetched unasked), and `stale`, a
643
+ * cached catalog that no longer reads. The two are told apart because "could
644
+ * not be read" about a catalog nobody has fetched yet sounds like a fault.
645
+ */
646
+ export function marketplaceDesignSystems(home = configHome()) {
647
+ const systems = [];
648
+ const stale = [];
649
+ const unfetched = [];
650
+ for (const market of Object.keys(loadRegistry(home).marketplaces ?? {})) {
651
+ const catalog = loadCatalog(market, home);
652
+ if (!catalog) { unfetched.push(market); continue; }
653
+ if (!catalog.ok) { stale.push(market); continue; }
654
+ for (const entry of catalog.manifest.entries ?? []) {
655
+ if (entry.type !== 'design-system') continue;
656
+ const r = resolveDesignSystemRef({ name: entry.name, marketplace: market, ref: `${entry.name}@${market}` }, home);
657
+ systems.push({
658
+ name: entry.name, marketplace: market, qualified: `${entry.name}@${market}`,
659
+ group: catalog.manifest.title?.trim() || market,
660
+ description: entry.description ?? '', version: entry.version ?? null,
661
+ ...(r.missing ? { missing: r.missing } : {}),
662
+ });
663
+ }
664
+ }
665
+ return { systems, stale, unfetched };
666
+ }