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,631 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The routes that change how the deck LOOKS rather than what it says: the
5
+ // theme it opens in and whether the picker holds it to its brand's themes,
6
+ // and the three things a marketplace hands a deck to wear (themes, design
7
+ // systems, fonts), each listed from the cache and marked or dropped in the
8
+ // deck's config block (SPEC THEME_DISTRIBUTION, DESIGN_SYSTEMS, FONTS) — and
9
+ // the marketplaces themselves (SPEC MARKETPLACES_SCREEN): listed, checked,
10
+ // updated and added, every one of them through the `decklight marketplace`
11
+ // command it would be at a terminal.
12
+ //
13
+ // They came out of cli/edit.mjs because they are a family with one shape and
14
+ // one set of needs. Every one either lists what the cached catalogs offer
15
+ // against what the deck already references, or writes one entry into the
16
+ // config block as one undo entry; and between them they want six of editMain's
17
+ // bindings, none of them about git, agents, bridges or the export machinery
18
+ // that make up the rest of that server. The marketplace and reference modules
19
+ // they lean on are imported per request, as they always were, so the server
20
+ // still pays for none of them until somebody opens a picker.
21
+ //
22
+ // The import back to edit.mjs is avoided rather than repeated: nothing here
23
+ // needs edit.mjs's own transforms, so this module imports only leaf modules,
24
+ // and edit.mjs reaches it with a STATIC import for the reason
25
+ // cli/edit-slides.mjs gives (a dynamic one from inside editMain would wait on
26
+ // edit.mjs's top-level `await`).
27
+
28
+ import { readFileSync } from 'node:fs';
29
+ import { execFile } from 'node:child_process';
30
+ import { basename, dirname } from 'node:path';
31
+ import { fileURLToPath } from 'node:url';
32
+
33
+ import { oneline } from './git.mjs';
34
+ import { setDeckTheme, setDeckBrandThemesOnly } from './runtime-link.mjs';
35
+
36
+ /**
37
+ * Put the look routes into `routes`, the table cli/edit.mjs dispatches on, and
38
+ * hand it back.
39
+ *
40
+ * `ctx` is the whole of what these handlers may touch: `readDeck()` for the
41
+ * current file; `applyEdit()` for the routes that are one text transform;
42
+ * `writeDeck()` and `history` for the marks, which compute the next file
43
+ * themselves (a mark may fetch, validate and record an install first) and so
44
+ * record the undo entry and write it in two steps of their own; `broadcast`
45
+ * for the in-place theme and brand-theme picks; and `quiet(html)`, which
46
+ * tells the deck watcher that the next write of exactly these bytes updates
47
+ * the page itself and must not reload it. `quiet` is a setter, not the
48
+ * variable, because the watcher in editMain reads and clears it.
49
+ * `deckPath` is where a relative marketplace path is read from, and
50
+ * `marketplace(args)` runs `decklight marketplace <args…>` (a test hands in
51
+ * its own); `addMarketplace(spec, ref)` is its `add` (with `--branch ref` when
52
+ * one is given), kept apart because a test of the add door replaces only that.
53
+ */
54
+ export function registerLookRoutes(routes, {
55
+ readDeck, applyEdit, writeDeck, history, broadcast = () => {}, quiet = () => {},
56
+ deckPath = null, marketplace = runMarketplace,
57
+ addMarketplace = (spec, ref = null) => marketplace(['add', spec, ...(ref ? ['--branch', ref] : [])]),
58
+ }) {
59
+ // The deck's theme (PRESENTING): in write mode a pick is the deck's, not
60
+ // the viewer's — written the way this deck carries it (setDeckTheme), quiet
61
+ // and in place like a layout pick, with a `theme` event for every other
62
+ // page. One undo entry, so Z takes it back.
63
+ function themeRoute({ body, json }) {
64
+ const { theme, quiet: inPlace, from } = JSON.parse(body || '{}');
65
+ if (typeof theme !== 'string' || !/^[\w-]+$/.test(theme)) return json(400, { ok: false, error: 'theme is a name' });
66
+ let unwritable = false;
67
+ const changed = applyEdit((html) => { const next = setDeckTheme(html, theme); if (next === null) unwritable = true; return next ?? html; });
68
+ if (unwritable) return json(409, { ok: false, error: `this deck does not carry a theme the server can set to ${theme} — a bundle holds only the themes it embeds` });
69
+ if (changed) {
70
+ console.log(` theme saved: ${theme}`);
71
+ if (inPlace === true) {
72
+ quiet(readDeck());
73
+ broadcast('theme', { theme, from: typeof from === 'string' ? from.slice(0, 64) : null });
74
+ }
75
+ }
76
+ return json(200, { ok: true, changed, inPlace: changed && inPlace === true, ...history.counts() });
77
+ }
78
+ /**
79
+ * `POST /deck/edit/brand-themes` `{ only, quiet?, from? }`: whether the
80
+ * picker holds this deck to its design systems' own themes (SPEC
81
+ * BRAND_PALETTE) — the picker's *Show every theme* and *Only <brand>'s
82
+ * themes* rows. Quiet and in place like a theme pick; every other page reloads.
83
+ */
84
+ function brandThemesRoute({ body, json }) {
85
+ const { only, quiet: inPlace, from } = JSON.parse(body || '{}');
86
+ if (typeof only !== 'boolean') return json(400, { ok: false, error: 'only is true or false' });
87
+ let unwritable = false;
88
+ const changed = applyEdit((html) => { const next = setDeckBrandThemesOnly(html, only); if (next === null) unwritable = true; return next ?? html; });
89
+ if (unwritable) return json(409, { ok: false, error: 'this deck carries no configuration block to record it in — decklight upgrade --link <deck.html> gives it one' });
90
+ if (changed) {
91
+ console.log(` brand themes only: ${only}`);
92
+ if (inPlace === true) {
93
+ quiet(readDeck());
94
+ broadcast('styles', { slide: 1, index: 0, from: typeof from === 'string' ? from.slice(0, 64) : null });
95
+ }
96
+ }
97
+ return json(200, { ok: true, changed, inPlace: changed && inPlace === true, ...history.counts() });
98
+ }
99
+
100
+ // ── marketplace themes, and marking (THEME_BROWSE#UI) ─────────────────
101
+ // What the overlay lists while authoring: every theme of every registered
102
+ // marketplace, each saying whether this deck marks it. Cache-only by
103
+ // construction — the catalogs `marketplace update` already fetched — so a
104
+ // deck on a plane lists what it has and names what it could not read.
105
+ async function themeBrowseRoute({ json }) {
106
+ const { marketplaceThemes, markedRefs, markedSources, resolveThemeRef } = await import('./theme-refs.mjs');
107
+ const { themes, stale } = marketplaceThemes();
108
+ // what the deck marks, as THIS machine names it — the deck may call the
109
+ // same catalog something else (its recorded source says which it means)
110
+ const html = readDeck();
111
+ const sources = markedSources(html);
112
+ const marked = new Set(markedRefs(html).map((r) => {
113
+ const hit = resolveThemeRef(r, undefined, { source: sources[r.marketplace] ?? null });
114
+ return `${r.name}@${hit.local ?? r.marketplace}`;
115
+ }));
116
+ const out = themes.map((t) => ({
117
+ ...t, marked: marked.has(t.qualified),
118
+ ...(resolveThemeRef(t.qualified).remote ? { remote: true } : {}),
119
+ }));
120
+ return json(200, { ok: true, themes: out, stale, cacheOnly: true });
121
+ }
122
+
123
+ /**
124
+ * Mark a theme for this deck, or unmark it (SPEC THEME_DISTRIBUTION). The
125
+ * deck gains or loses one reference in its config block — never CSS — as
126
+ * one undo entry; the watcher's reload brings every browser back with the
127
+ * list as the file now says it is.
128
+ *
129
+ * Marking runs the theme through `theme add`'s own validator first, so a
130
+ * theme refused on the command line is refused here, by the same code, and
131
+ * a deck cannot be made to carry what the shipped set could not contain.
132
+ * An entry whose bytes live at a URL is read now — this is the explicit act
133
+ * — and kept, so no server ever has to reach for it again.
134
+ */
135
+ async function themeMarkRoute({ body, json }) {
136
+ const req = JSON.parse(body || '{}');
137
+ const ref = typeof req.ref === 'string' ? req.ref.trim() : '';
138
+ const on = req.marked !== false;
139
+ const { parseRef, parseShipped, resolveThemeRef, setMarked, cacheThemeCss, refForDeck } = await import('./theme-refs.mjs');
140
+ const { MarketplaceError, configHome } = await import('./marketplace.mjs');
141
+ const shipped = parseShipped(ref);
142
+ if (!shipped && !parseRef(ref)) return json(400, { ok: false, error: 'which theme? — a shipped name, or name@marketplace' });
143
+ const before = readDeck();
144
+ let deckRef = ref, source = null;
145
+ // A shipped theme needs no resolving and no check — it is decklight's own,
146
+ // and passed the contract when it shipped. Marking it says only that the
147
+ // deck carries it when it travels.
148
+ if (on && !shipped) {
149
+ const r = resolveThemeRef(ref);
150
+ let css;
151
+ if (r.file) css = readFileSync(r.file, 'utf8');
152
+ else if (r.remote) {
153
+ const { fetchTheme } = await import('./theme.mjs');
154
+ try { css = await fetchTheme(r.remote); }
155
+ catch (e) { return json(502, { ok: false, error: `could not read ${r.remote}: ${oneline(e)}` }); }
156
+ } else {
157
+ // An entry this machine knows but whose files are not here is a state
158
+ // `marketplace update` fixes (409); one it has never heard of is 404.
159
+ const status = r.entry && r.entry.type !== 'theme' ? 400 : r.entry ? 409 : 404;
160
+ return json(status, { ok: false, error: r.missing });
161
+ }
162
+ const { validateTheme } = await import('../tools/theme-check.mjs');
163
+ const check = validateTheme(css);
164
+ if (!check.ok) {
165
+ // The deck is left byte-for-byte unchanged.
166
+ return json(400, { ok: false, error: `${r.name} fails the theme contract`, problems: check.errors ?? [] });
167
+ }
168
+ if (r.remote) cacheThemeCss(configHome(), r.marketplace, r.name, css);
169
+ source = r.source ?? null;
170
+ deckRef = refForDeck(before, r.name, r.local, source);
171
+ }
172
+ let out;
173
+ try { out = setMarked(before, deckRef, on, { source }); }
174
+ catch (e) {
175
+ if (e instanceof MarketplaceError) return json(409, { ok: false, error: e.message });
176
+ throw e;
177
+ }
178
+ if (out.changed) {
179
+ history.record(before); // Z takes a mark back like any other edit
180
+ // The picker asks for `quiet`: it shows the new mark itself and stays
181
+ // open. Everyone else — the export card's "mark and carry on", which
182
+ // resumes across the reload — gets the reload.
183
+ if (req.quiet === true) quiet(out.html);
184
+ writeDeck(out.html);
185
+ console.log(` theme: ${on ? 'marked' : 'unmarked'} ${deckRef}`);
186
+ }
187
+ return json(200, { ok: true, ref: deckRef, marked: on, changed: out.changed, ...history.counts() });
188
+ }
189
+ // Every design system every registered marketplace offers, each saying
190
+ // whether this deck references it (SPEC DESIGN_SYSTEMS) — the palette's
191
+ // "Design systems…" list. Cache-only, like the theme browse above.
192
+ async function designSystemBrowseRoute({ json }) {
193
+ const { marketplaceDesignSystems, designSystemRefs, resolveDesignSystemRef } = await import('./design-system-refs.mjs');
194
+ const { markedSources } = await import('./theme-refs.mjs');
195
+ const { systems, stale, unfetched } = marketplaceDesignSystems();
196
+ const html = readDeck();
197
+ const sources = markedSources(html);
198
+ // what the deck references, as THIS machine names the catalog
199
+ const used = new Set(designSystemRefs(html).map((r) => {
200
+ const hit = resolveDesignSystemRef(r, undefined, { source: sources[r.marketplace] ?? null });
201
+ return `${r.name}@${hit.local ?? r.marketplace}`;
202
+ }));
203
+ return json(200, { ok: true, systems: systems.map((s) => ({ ...s, used: used.has(s.qualified) })), stale, unfetched, cacheOnly: true });
204
+ }
205
+
206
+ /**
207
+ * Reference a design system from this deck, or drop it (SPEC
208
+ * DESIGN_SYSTEMS) — the twin of the theme mark below it. The package runs
209
+ * through `decklight design-system gate` first, so the command line and
210
+ * this route refuse by the same code; the deck gains or loses one entry in
211
+ * its config block as one undo entry.
212
+ */
213
+ async function designSystemMarkRoute({ body, json }) {
214
+ const req = JSON.parse(body || '{}');
215
+ const ref = typeof req.ref === 'string' ? req.ref.trim() : '';
216
+ const on = req.used !== false && req.marked !== false;
217
+ const { parseRef, refForDeck } = await import('./theme-refs.mjs');
218
+ const { resolveDesignSystemRef, setDesignSystem, designSystemRefs } = await import('./design-system-refs.mjs');
219
+ const { checkDir } = await import('./design-system.mjs');
220
+ const { MarketplaceError, recordInstall, loadRegistry, configHome } = await import('./marketplace.mjs');
221
+ if (!parseRef(ref)) return json(400, { ok: false, error: 'which design system? — name@marketplace' });
222
+ const before = readDeck();
223
+ let deckRef = ref, source = null, manifest = null, local = null;
224
+ if (on) {
225
+ const r = resolveDesignSystemRef(ref);
226
+ if (!r.dir) {
227
+ const status = r.entry && r.entry.type !== 'design-system' ? 400 : r.entry ? 409 : 404;
228
+ return json(status, { ok: false, error: r.missing });
229
+ }
230
+ const verdict = checkDir(r.dir);
231
+ if (!verdict.ok) {
232
+ // the deck is left byte-for-byte unchanged
233
+ return json(400, { ok: false, error: `${r.ref} fails the design-system check`, problems: verdict.problems.map((p) => `${p.file}${p.line ? ` line ${p.line}` : ''}: ${p.msg}`) });
234
+ }
235
+ source = r.source ?? null;
236
+ manifest = verdict.manifest;
237
+ local = r.local;
238
+ deckRef = refForDeck(before, r.name, r.local, source);
239
+ if (!designSystemRefs(before).some((x) => x.ref === deckRef)) {
240
+ recordInstall({ type: 'design-system', name: r.name, marketplace: r.local, version: r.entry.version ?? null,
241
+ commit: loadRegistry(configHome()).marketplaces?.[r.local]?.commit ?? null });
242
+ }
243
+ } else {
244
+ // the deck's own spelling, whatever this machine calls the catalog
245
+ const p = parseRef(ref);
246
+ deckRef = designSystemRefs(before).find((x) => x.ref === ref || x.name === p.name)?.ref ?? ref;
247
+ }
248
+ let out;
249
+ try { out = setDesignSystem(before, deckRef, on, { source, version: manifest?.version ?? null }); }
250
+ catch (e) {
251
+ if (e instanceof MarketplaceError) return json(409, { ok: false, error: e.message });
252
+ throw e;
253
+ }
254
+ // Its themes and fonts come with it (SPEC DESIGN_SYSTEMS, #642) — in the
255
+ // same write, so the whole thing is ONE undo — unless the author held ⇧
256
+ // (recommended: false). The look is offered, and applied only when asked.
257
+ let html = out.html, plan = null, look = null;
258
+ if (on && manifest) {
259
+ const deps = await import('./design-system-deps.mjs');
260
+ plan = deps.planRecommended(html, { manifest, local });
261
+ if (req.recommended !== false) {
262
+ html = deps.writePlan(html, plan);
263
+ for (const inst of deps.plannedInstalls(plan)) recordInstall(inst);
264
+ }
265
+ look = deps.lookOf(html, req.recommended !== false ? plan
266
+ : { ...plan, items: plan.items.filter((it) => it.status === 'already' || it.status === 'stack') });
267
+ if (req.apply === true && look.differs) html = deps.applyLook(html, look);
268
+ look.phrase = deps.lookPhrase(look, plan);
269
+ }
270
+ const changed = html !== before;
271
+ if (changed) {
272
+ history.record(before); // Z takes it back like any other edit
273
+ if (req.quiet === true) quiet(html);
274
+ writeDeck(html);
275
+ console.log(` design system: ${on ? 'referenced' : 'dropped'} ${deckRef}`);
276
+ }
277
+ const pulled = plan && req.recommended !== false ? plan.items.map(({ kind, rec, ref: r2, status, why, cmd, family }) => ({ kind, rec, ref: r2, status, why, cmd, family })) : [];
278
+ return json(200, { ok: true, ref: deckRef, used: on, changed, pulled, look, ...history.counts() });
279
+ }
280
+
281
+ /**
282
+ * Give the deck the look a design system it uses was drawn for (SPEC
283
+ * DESIGN_SYSTEMS, #642): its first recommended theme and font, bringing any
284
+ * that are missing — one edit, one undo, so Z puts the old look back and
285
+ * keeps the design system. The twin of `decklight design-system apply`.
286
+ */
287
+ async function designSystemApplyRoute({ body, json }) {
288
+ const req = JSON.parse(body || '{}');
289
+ const { designSystemRefs, resolveDesignSystemRef, recordVersionIfCurrent } = await import('./design-system-refs.mjs');
290
+ const { markedSources, parseRef } = await import('./theme-refs.mjs');
291
+ const { checkDir } = await import('./design-system.mjs');
292
+ const { recordInstall } = await import('./marketplace.mjs');
293
+ const deps = await import('./design-system-deps.mjs');
294
+ const before = readDeck();
295
+ const p = parseRef(String(req.ref ?? ''));
296
+ const hit = designSystemRefs(before).find((x) => x.ref === req.ref || x.name === (p?.name ?? req.ref));
297
+ if (!hit) return json(404, { ok: false, error: `this deck does not use ${req.ref}` });
298
+ const r = resolveDesignSystemRef(hit, undefined, { source: markedSources(before)[hit.marketplace] ?? null });
299
+ if (!r.dir) return json(409, { ok: false, error: r.missing });
300
+ const verdict = checkDir(r.dir);
301
+ if (!verdict.ok) return json(409, { ok: false, error: `${hit.ref} no longer passes its check` });
302
+ const plan = deps.planRecommended(before, { manifest: verdict.manifest, local: r.local });
303
+ // a deck that records no version takes this one, as `design-system apply` does (SPEC DESIGN_SYSTEM_MIGRATIONS)
304
+ let html = deps.writePlan(recordVersionIfCurrent(before, hit.ref, verdict.manifest, deckPath ? dirname(deckPath) : process.cwd()), plan);
305
+ const look = deps.lookOf(html, plan);
306
+ if (look.differs) html = deps.applyLook(html, look);
307
+ look.phrase = deps.lookPhrase(look, plan);
308
+ // recorded even when the deck is unchanged: a dependency already there
309
+ // takes the catalog's version now, as `design-system apply` does (#653)
310
+ for (const inst of deps.plannedInstalls(plan)) recordInstall(inst);
311
+ if (html !== before) {
312
+ history.record(before);
313
+ writeDeck(html);
314
+ console.log(` design system: applied ${look.title}'s look — ${look.phrase || 'already worn'}`);
315
+ }
316
+ return json(200, { ok: true, ref: hit.ref, changed: html !== before, look, ...history.counts() });
317
+ }
318
+
319
+ // Every font every registered marketplace offers (SPEC FONTS), each saying
320
+ // whether this deck references it, with the faces a preview needs — the
321
+ // font picker's marketplace rows. Cache-only, like the theme browse.
322
+ async function fontBrowseRoute({ json }) {
323
+ const { marketplaceFonts, fontRefs, resolveFontRef } = await import('./font-refs.mjs');
324
+ const { markedSources } = await import('./theme-refs.mjs');
325
+ const { fonts, stale, unfetched } = marketplaceFonts();
326
+ const html = readDeck();
327
+ const sources = markedSources(html);
328
+ const used = new Set(fontRefs(html).map((r) => {
329
+ const hit = resolveFontRef(r, undefined, { source: sources[r.marketplace] ?? null });
330
+ return `${r.name}@${hit.local ?? r.marketplace}`;
331
+ }));
332
+ return json(200, { ok: true, fonts: fonts.map((f) => ({ ...f, used: used.has(f.qualified) })), stale, unfetched, cacheOnly: true });
333
+ }
334
+
335
+ /**
336
+ * Reference a font from this deck, or drop it (SPEC FONTS) — the twin of
337
+ * the design-system mark above: `font gate` first, one config entry, one
338
+ * undo. `use: true` also makes it the deck's default font. `quiet` writes
339
+ * without the reload: the picker previews the face itself, and stays open.
340
+ */
341
+ async function fontMarkRoute({ body, json }) {
342
+ const req = JSON.parse(body || '{}');
343
+ const ref = typeof req.ref === 'string' ? req.ref.trim() : '';
344
+ const on = req.used !== false && req.marked !== false;
345
+ const { parseRef, refForDeck } = await import('./theme-refs.mjs');
346
+ const { resolveFontRef, setFont, fontRefs } = await import('./font-refs.mjs');
347
+ const { checkFontDir } = await import('./font.mjs');
348
+ const { MarketplaceError, recordInstall, loadRegistry, configHome } = await import('./marketplace.mjs');
349
+ if (!parseRef(ref)) return json(400, { ok: false, error: 'which font? — name@marketplace' });
350
+ const before = readDeck();
351
+ let deckRef = ref, source = null;
352
+ if (on) {
353
+ const r = resolveFontRef(ref);
354
+ if (!r.dir) {
355
+ const status = r.entry && r.entry.type !== 'font' ? 400 : r.entry ? 409 : 404;
356
+ return json(status, { ok: false, error: r.missing });
357
+ }
358
+ const verdict = checkFontDir(r.dir);
359
+ if (!verdict.ok) {
360
+ return json(400, { ok: false, error: `${r.ref} fails the font check`, problems: verdict.problems.map((p) => `${p.file}${p.line ? ` line ${p.line}` : ''}: ${p.msg}`) });
361
+ }
362
+ source = r.source ?? null;
363
+ deckRef = refForDeck(before, r.name, r.local, source);
364
+ if (!fontRefs(before).some((x) => x.ref === deckRef)) {
365
+ recordInstall({ type: 'font', name: r.name, marketplace: r.local, version: r.entry.version ?? null,
366
+ commit: loadRegistry(configHome()).marketplaces?.[r.local]?.commit ?? null });
367
+ }
368
+ } else {
369
+ const p = parseRef(ref);
370
+ deckRef = fontRefs(before).find((x) => x.ref === ref || x.name === p.name)?.ref ?? ref;
371
+ }
372
+ let out;
373
+ try { out = setFont(before, deckRef, on, { source, use: req.use === true }); }
374
+ catch (e) {
375
+ if (e instanceof MarketplaceError) return json(409, { ok: false, error: e.message });
376
+ throw e;
377
+ }
378
+ if (out.changed) {
379
+ history.record(before);
380
+ if (req.quiet === true) quiet(out.html);
381
+ writeDeck(out.html);
382
+ console.log(` font: ${on ? 'referenced' : 'dropped'} ${deckRef}${on && req.use === true ? ' (the deck\'s default)' : ''}`);
383
+ }
384
+ return json(200, { ok: true, ref: deckRef, used: on, changed: out.changed, ...history.counts() });
385
+ }
386
+
387
+ // `/deck/edit/theme/add` was 0.9.0's name for installing from Browse. A deck that
388
+ // carries its OWN copy of the runtime still asks for it; it means "mark".
389
+ const themeAddRoute = ({ body, json }) =>
390
+ themeMarkRoute({ body: JSON.stringify({ ref: JSON.parse(body || '{}').ref, marked: true }), json });
391
+
392
+ /**
393
+ * `POST /deck/edit/marketplace/add` `{ spec, ref?, confirm? }`: register a
394
+ * marketplace from inside the deck (SPEC MARKETPLACES_SCREEN, PLATFORM
395
+ * MARKETPLACE_REGISTRY). `ref` is the command's `--branch`, a branch or a
396
+ * tag to pin the catalog to. Two steps, like publish. Without `confirm` it says
397
+ * what it is about to do (`planAdd`: which URL it would clone, or which
398
+ * directory it would read) and touches nothing. With it, it runs
399
+ * `decklight marketplace add` itself, as a child process: the same command,
400
+ * so the registry cannot tell the two doors apart, and a clone that takes
401
+ * thirty seconds holds up nobody but the person who asked for it. A relative
402
+ * path is the deck's directory's, and is registered absolute. Nothing in
403
+ * the deck changes, so there is no undo entry and no reload: the pickers ask
404
+ * again, and find it.
405
+ */
406
+ async function marketplaceAddRoute({ body, json }) {
407
+ const req = JSON.parse(body || '{}');
408
+ if (req.ref != null && typeof req.ref !== 'string') return json(400, { ok: false, error: '--branch takes a branch or tag name' });
409
+ const { planAdd, loadRegistry, loadCatalog, MarketplaceError, configHome } = await import('./marketplace.mjs');
410
+ let plan;
411
+ try { plan = planAdd(req.spec, { ref: req.ref?.trim() || null, base: deckPath ? dirname(deckPath) : process.cwd(), home: configHome() }); }
412
+ catch (e) {
413
+ if (e instanceof MarketplaceError) return json(400, { ok: false, error: e.message });
414
+ throw e;
415
+ }
416
+ if (req.confirm !== true) return json(200, { ok: true, confirm: true, plan });
417
+ const out = await addMarketplace(plan.spec, plan.ref);
418
+ if (!out.ok) return json(409, { ok: false, error: out.error, plan });
419
+ const reg = loadRegistry(configHome()).marketplaces ?? {};
420
+ const name = Object.keys(reg).find((n) => reg[n].source === plan.spec) ?? null;
421
+ const cat = name ? loadCatalog(name, configHome()) : null;
422
+ const counts = {};
423
+ for (const e of cat?.ok ? cat.manifest.entries ?? [] : []) counts[e.type] = (counts[e.type] ?? 0) + 1;
424
+ console.log(` marketplace: ${plan.registered ? 'refreshed' : 'registered'} ${name ?? plan.spec} from ${plan.spec}`);
425
+ return json(200, { ok: true, name, spec: plan.spec, refreshed: !!plan.registered, counts, said: out.said });
426
+ }
427
+
428
+ /**
429
+ * `GET /deck/edit/marketplaces`: every registered marketplace, from the
430
+ * registry and the cache alone (SPEC MARKETPLACES_SCREEN) — what
431
+ * `marketplace list` says, as data. Per marketplace: where it comes from
432
+ * and at which ref and commit, whether it was ever fetched (`state`), what
433
+ * its catalog offers per kind (`counts`), what its last update changed
434
+ * (`changes`, as `update` recorded it), and which installs the catalog now
435
+ * has newer (`newer`). No network: whether a source has MOVED is
436
+ * `/deck/edit/marketplace/check`'s question, asked only when somebody asks.
437
+ */
438
+ async function marketplacesRoute({ json }) {
439
+ const { loadRegistry, loadCatalog, newerThanInstalled, classifySource, configHome, MarketplaceError } = await import('./marketplace.mjs');
440
+ let reg;
441
+ try { reg = loadRegistry(configHome()).marketplaces ?? {}; } catch (e) {
442
+ if (e instanceof MarketplaceError) return json(409, { ok: false, error: e.message });
443
+ throw e;
444
+ }
445
+ const newer = newerThanInstalled(configHome());
446
+ const marketplaces = Object.keys(reg).sort().map((name) => {
447
+ const m = reg[name];
448
+ const cat = loadCatalog(name, configHome());
449
+ const counts = {};
450
+ for (const e of cat?.ok ? cat.manifest.entries : []) counts[e.type] = (counts[e.type] ?? 0) + 1;
451
+ return {
452
+ name, source: m.source, ref: m.ref ?? null, commit: m.commit ?? null, firstParty: !!m.firstParty,
453
+ local: classifySource(m.source).kind === 'local',
454
+ state: cat === null ? 'unfetched' : cat.ok ? 'fetched' : 'unreadable',
455
+ description: cat?.ok ? cat.manifest.description ?? null : null,
456
+ counts, changes: m.changes ?? null,
457
+ newer: newer.filter((n) => n.qualified.endsWith(`@${name}`)),
458
+ };
459
+ });
460
+ // the last check's answer, whoever asked (C, the command line, or the
461
+ // auto-check a starting server ran), so the list says it without a C;
462
+ // and whether that auto-check is on, and if not, whether to ask once
463
+ const { readCheckRecord, autoCheckOn, autoCheckOffered } = await import('./marketplace-autocheck.mjs');
464
+ const rec = readCheckRecord(configHome());
465
+ const on = autoCheckOn(configHome());
466
+ return json(200, {
467
+ ok: true, marketplaces, cacheOnly: true,
468
+ checked: rec ? { at: new Date(rec.checkedAt).toISOString(), marketplaces: rec.marketplaces } : null,
469
+ autoCheck: { on, ask: !on && !autoCheckOffered(configHome()) },
470
+ });
471
+ }
472
+
473
+ /**
474
+ * `GET /deck/edit/marketplace/auto-check`: what the auto-check found that
475
+ * the open deck should offer (SPEC MARKETPLACES_SCREEN) — every marketplace
476
+ * the last check found behind, not dismissed at that commit, with what this
477
+ * deck uses from it. Read from the record; asks nothing. Empty while the
478
+ * switch is off.
479
+ */
480
+ async function autoCheckGetRoute({ json }) {
481
+ const { configHome } = await import('./marketplace.mjs');
482
+ const { readCheckRecord, autoCheckOn, autoCheckOffers } = await import('./marketplace-autocheck.mjs');
483
+ let html = null;
484
+ try { html = readDeck(); } catch { /* no deck to say what it uses */ }
485
+ const rec = readCheckRecord(configHome());
486
+ return json(200, {
487
+ ok: true, on: autoCheckOn(configHome()),
488
+ checkedAt: rec ? new Date(rec.checkedAt).toISOString() : null,
489
+ offers: await autoCheckOffers(html, configHome()),
490
+ });
491
+ }
492
+
493
+ /**
494
+ * `POST /deck/edit/marketplace/auto-check` `{ on } | { asked: true } |
495
+ * { dismiss, remote }`: turn the auto-check on or off (O on the screen; the
496
+ * file `decklight marketplace auto-check` writes), say the screen has asked
497
+ * its one question, or dismiss an offer at the commit it was made for.
498
+ * Turning it on is the consent, so a check that is due runs then, in the
499
+ * background, and the pages are told when its answer lands.
500
+ */
501
+ async function autoCheckPostRoute({ body, json }) {
502
+ const req = JSON.parse(body || '{}');
503
+ const { configHome } = await import('./marketplace.mjs');
504
+ const ac = await import('./marketplace-autocheck.mjs');
505
+ if (typeof req.dismiss === 'string') {
506
+ if (!/^\w[\w-]*$/.test(req.dismiss)) return json(400, { ok: false, error: 'which marketplace? — its registered name' });
507
+ ac.dismissOffer(req.dismiss, typeof req.remote === 'string' ? req.remote : null, configHome());
508
+ return json(200, { ok: true, dismissed: req.dismiss });
509
+ }
510
+ if (req.asked === true) { ac.markAutoCheckOffered(configHome()); return json(200, { ok: true }); }
511
+ if (typeof req.on !== 'boolean') return json(400, { ok: false, error: 'on is true or false' });
512
+ const on = ac.setAutoCheck(req.on, configHome());
513
+ console.log(` marketplaces: auto-check ${on ? 'on' : 'off'}`);
514
+ if (on) autoCheckInBackground({ run: marketplace, broadcast });
515
+ return json(200, { ok: true, on });
516
+ }
517
+
518
+ /**
519
+ * `POST /deck/edit/marketplace/check` `{ name? }`: which marketplaces are
520
+ * behind their source — `decklight marketplace outdated --json`, run as a
521
+ * child like `add`. It ASKS each remote where its ref points (`git
522
+ * ls-remote`, the caller's credentials) and fetches nothing, so it is one
523
+ * explicit press, not a confirm; it never runs on its own.
524
+ */
525
+ async function marketplaceCheckRoute({ body, json }) {
526
+ const req = JSON.parse(body || '{}');
527
+ if (req.name != null && !/^\w[\w-]*$/.test(String(req.name))) return json(400, { ok: false, error: 'which marketplace? — its registered name' });
528
+ const out = await marketplace(['outdated', '--json', ...(req.name ? [String(req.name)] : [])]);
529
+ if (!out.ok) return json(409, { ok: false, error: out.error });
530
+ let parsed;
531
+ try { parsed = JSON.parse(out.stdout); } catch { return json(500, { ok: false, error: 'decklight marketplace outdated answered something that is not JSON' }); }
532
+ return json(200, { ok: true, marketplaces: parsed.marketplaces ?? [] });
533
+ }
534
+
535
+ /**
536
+ * `POST /deck/edit/marketplace/update` `{ name }`: `decklight marketplace
537
+ * update <name>`, run as a child — the same re-clone, at the same pinned
538
+ * ref, with the same refusals; a failed one leaves the cache and checkout
539
+ * as they were. Answers with what the update changed (the `changes` the
540
+ * command recorded: added, removed, versions moved) and which installs the
541
+ * catalog now has newer, with the command that takes each — the screen's
542
+ * what's new — and `behind`, the design systems the open deck is now
543
+ * behind (`deckBehind`), which the screen offers to migrate. Nothing in
544
+ * the deck changes, so no undo entry and no reload.
545
+ */
546
+ async function marketplaceUpdateRoute({ body, json }) {
547
+ const req = JSON.parse(body || '{}');
548
+ const name = typeof req.name === 'string' ? req.name : '';
549
+ if (!/^\w[\w-]*$/.test(name)) return json(400, { ok: false, error: 'which marketplace? — its registered name' });
550
+ const { loadRegistry, loadCatalog, newerThanInstalled, configHome } = await import('./marketplace.mjs');
551
+ if (!loadRegistry(configHome()).marketplaces?.[name]) return json(404, { ok: false, error: `no marketplace "${name}" is registered` });
552
+ const out = await marketplace(['update', name]);
553
+ if (!out.ok) return json(409, { ok: false, error: out.error });
554
+ const m = loadRegistry(configHome()).marketplaces?.[name] ?? {};
555
+ const cat = loadCatalog(name, configHome());
556
+ const counts = {};
557
+ for (const e of cat?.ok ? cat.manifest.entries : []) counts[e.type] = (counts[e.type] ?? 0) + 1;
558
+ console.log(` marketplace: updated ${name}${m.commit ? ` (${m.commit.slice(0, 7)})` : ''}`);
559
+ // What the update means for the deck that is open (SPEC
560
+ // DESIGN_SYSTEM_MIGRATIONS): the design systems it is now behind, read
561
+ // as `check` reads them — the page offers Migrate without a reload.
562
+ const { withMigrationHint, deckBehind } = await import('./design-system-refs.mjs');
563
+ const newer = newerThanInstalled(configHome(), name).map((n) => withMigrationHint(n, configHome()));
564
+ let behind = [];
565
+ try { if (deckPath) behind = deckBehind(readDeck(), dirname(deckPath), configHome(), { deck: basename(deckPath) }); } catch { /* the deck unreadable: nothing to offer */ }
566
+ for (const b of behind) console.log(` design system: ${b.ref} — ${b.message}`);
567
+ return json(200, { ok: true, name, commit: m.commit ?? null, changes: m.changes ?? null, counts, newer, behind, said: out.said });
568
+ }
569
+
570
+ routes.set('POST /deck/edit/theme', themeRoute);
571
+ routes.set('POST /deck/edit/brand-themes', brandThemesRoute);
572
+ routes.set('GET /deck/edit/theme/browse', themeBrowseRoute);
573
+ routes.set('POST /deck/edit/theme/add', themeAddRoute);
574
+ routes.set('POST /deck/edit/theme/mark', themeMarkRoute);
575
+ routes.set('GET /deck/edit/design-system/browse', designSystemBrowseRoute);
576
+ routes.set('POST /deck/edit/design-system/mark', designSystemMarkRoute);
577
+ routes.set('POST /deck/edit/design-system/apply', designSystemApplyRoute);
578
+ routes.set('GET /deck/edit/font/browse', fontBrowseRoute);
579
+ routes.set('POST /deck/edit/font/mark', fontMarkRoute);
580
+ routes.set('POST /deck/edit/marketplace/add', marketplaceAddRoute);
581
+ routes.set('GET /deck/edit/marketplaces', marketplacesRoute);
582
+ routes.set('POST /deck/edit/marketplace/check', marketplaceCheckRoute);
583
+ routes.set('POST /deck/edit/marketplace/update', marketplaceUpdateRoute);
584
+ routes.set('GET /deck/edit/marketplace/auto-check', autoCheckGetRoute);
585
+ routes.set('POST /deck/edit/marketplace/auto-check', autoCheckPostRoute);
586
+ return routes;
587
+ }
588
+
589
+ /**
590
+ * The auto-check, if it is due (SPEC MARKETPLACES_SCREEN): `run` is
591
+ * `decklight marketplace <args…>`, and `broadcast` tells every page when the
592
+ * answer lands, so the deck offers it without a reload. Never awaited by a
593
+ * caller that matters, and silent on failure: resolves to the record, or null.
594
+ * The edit server calls it once as it starts; turning the switch on calls it too.
595
+ */
596
+ export function autoCheckInBackground({ run = runMarketplace, broadcast = () => {} } = {}) {
597
+ return import('./marketplace-autocheck.mjs')
598
+ .then(({ runAutoCheck, checkSummary }) => runAutoCheck({ run }).then((rec) => {
599
+ if (!rec) return null;
600
+ broadcast('marketplaces', { checkedAt: rec.checkedAt, summary: checkSummary(rec) });
601
+ return rec;
602
+ }))
603
+ .catch(() => null);
604
+ }
605
+
606
+ const CLI = fileURLToPath(new URL('./decklight.mjs', import.meta.url));
607
+
608
+ /**
609
+ * Run `decklight marketplace <args…>` and say how it went: `{ ok, said,
610
+ * stdout }` with the command's own first line, or `{ ok: false, error }` with
611
+ * what it printed on the way out, prefix dropped. git is told never to prompt
612
+ * (the command does that too; a server has no terminal to prompt on), and the
613
+ * update notice is the command line's business, not this sentence's.
614
+ */
615
+ export function runMarketplace(args, { timeoutMs = 120000 } = {}) {
616
+ return new Promise((done) => {
617
+ execFile(process.execPath, [CLI, 'marketplace', ...args], {
618
+ encoding: 'utf8', timeout: timeoutMs,
619
+ // no version banner: the server already said which version this is,
620
+ // and on stderr it would open every refusal read back from there
621
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', DECKLIGHT_NO_UPDATE_CHECK: '1', DECKLIGHT_BANNER: '1' },
622
+ }, (err, stdout, stderr) => {
623
+ if (!err) return done({ ok: true, said: String(stdout).trim().split('\n')[0] ?? '', stdout: String(stdout) });
624
+ const said = String(stderr).trim().replace(new RegExp(`^decklight marketplace ${args[0]}: `), '');
625
+ done({ ok: false, error: said || (err.killed ? `gave up after ${Math.round(timeoutMs / 1000)}s` : oneline(err)) });
626
+ });
627
+ });
628
+ }
629
+
630
+ /** `decklight marketplace add <spec>` — the add door's one command. */
631
+ export const runMarketplaceAdd = (spec, opts) => runMarketplace(['add', spec], opts);