decklight 0.8.0 → 0.9.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 (133) hide show
  1. package/PLATFORM.md +666 -0
  2. package/README.md +224 -150
  3. package/SPEC.md +732 -886
  4. package/cli/agent-review.mjs +245 -0
  5. package/cli/agents.mjs +25 -5
  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 +183 -0
  10. package/cli/bundle.mjs +383 -31
  11. package/cli/cast.mjs +7 -7
  12. package/cli/check.mjs +961 -0
  13. package/cli/clone-deck.mjs +179 -0
  14. package/cli/commands.mjs +345 -0
  15. package/cli/comments.mjs +64 -18
  16. package/cli/commit-flow.mjs +44 -19
  17. package/cli/commit-message.mjs +51 -74
  18. package/cli/commit-split.mjs +601 -0
  19. package/cli/deck-refs.mjs +59 -0
  20. package/cli/deck-routes.mjs +67 -0
  21. package/cli/deckfile.mjs +3 -5
  22. package/cli/decklight.mjs +68 -289
  23. package/cli/design-system-deps.mjs +209 -0
  24. package/cli/design-system-edit.mjs +194 -0
  25. package/cli/design-system-refs.mjs +409 -0
  26. package/cli/design-system.mjs +429 -0
  27. package/cli/doctor.mjs +115 -0
  28. package/cli/edit-git.mjs +353 -0
  29. package/cli/edit-handover.mjs +445 -0
  30. package/cli/edit-look.mjs +388 -0
  31. package/cli/edit-slides.mjs +683 -0
  32. package/cli/edit.mjs +2126 -842
  33. package/cli/enhance.mjs +483 -0
  34. package/cli/extension.mjs +10 -10
  35. package/cli/font-refs.mjs +273 -0
  36. package/cli/font.mjs +246 -0
  37. package/cli/git-tree.mjs +1 -1
  38. package/cli/git.mjs +65 -11
  39. package/cli/import.mjs +56 -10
  40. package/cli/init.mjs +400 -234
  41. package/cli/library.mjs +127 -0
  42. package/cli/loader.mjs +3 -1
  43. package/cli/marketplace.mjs +215 -21
  44. package/cli/narrate.mjs +176 -0
  45. package/cli/open-browser.mjs +63 -0
  46. package/cli/open.mjs +943 -0
  47. package/cli/pdf.mjs +41 -13
  48. package/cli/pkg.mjs +44 -2
  49. package/cli/plugin.mjs +43 -41
  50. package/cli/port-conflict.mjs +53 -23
  51. package/cli/pptx-export.mjs +71 -26
  52. package/cli/publish.mjs +8 -4
  53. package/cli/qr.mjs +1 -1
  54. package/cli/record.mjs +14 -12
  55. package/cli/remote.mjs +11 -11
  56. package/cli/restore.mjs +11 -4
  57. package/cli/review-ref.mjs +125 -0
  58. package/cli/review-remote.mjs +92 -48
  59. package/cli/review-routes.mjs +254 -0
  60. package/cli/review-store.mjs +47 -7
  61. package/cli/review-submit.mjs +47 -57
  62. package/cli/runtime-link.mjs +560 -0
  63. package/cli/serve.mjs +235 -44
  64. package/cli/setup.mjs +112 -0
  65. package/cli/sign.mjs +1 -1
  66. package/cli/skill-content.mjs +190 -33
  67. package/cli/skills.mjs +107 -24
  68. package/cli/start.mjs +110 -0
  69. package/cli/supervise.mjs +6 -6
  70. package/cli/theme-refs.mjs +515 -0
  71. package/cli/theme.mjs +181 -137
  72. package/cli/trust.mjs +83 -0
  73. package/cli/units.mjs +39 -42
  74. package/cli/update-check.mjs +1 -5
  75. package/cli/upgrade.mjs +194 -28
  76. package/cli/upstream.mjs +4 -3
  77. package/cli/util.mjs +4 -4
  78. package/cli/wizard.mjs +6 -6
  79. package/dist/build-info.json +1 -1
  80. package/dist/decklight.css +1126 -49
  81. package/dist/decklight.js +212 -115
  82. package/dist/decklight.js.map +4 -4
  83. package/docs/GLOSSARY.md +141 -0
  84. package/docs/architecture.svg +17 -17
  85. package/package.json +4 -2
  86. package/themes/README.md +9 -8
  87. package/themes/reveal-solarized.css +10 -0
  88. package/tools/args.mjs +20 -0
  89. package/tools/atomic-write.mjs +48 -0
  90. package/tools/brand-palette.mjs +717 -0
  91. package/tools/bridge.mjs +1 -1
  92. package/tools/build-groups.mjs +42 -0
  93. package/tools/color.mjs +48 -0
  94. package/tools/deck-html.mjs +396 -11
  95. package/tools/design-system-format.mjs +753 -0
  96. package/tools/elevenlabs-tts.mjs +110 -17
  97. package/tools/exec.mjs +35 -2
  98. package/tools/extension-check.mjs +31 -7
  99. package/tools/font-format.mjs +190 -0
  100. package/tools/font-stacks.mjs +24 -0
  101. package/tools/gemini-tts.mjs +3 -0
  102. package/tools/lipsync-config.mjs +103 -0
  103. package/tools/lipsync-engines.mjs +205 -2
  104. package/tools/lipsync-server.mjs +264 -41
  105. package/tools/lipsync.mjs +37 -18
  106. package/tools/local-voice.mjs +32 -42
  107. package/tools/narration-manifest.mjs +196 -0
  108. package/tools/narration-synth.mjs +416 -0
  109. package/tools/pptx.mjs +776 -19
  110. package/tools/publish-targets.mjs +1 -1
  111. package/tools/publish-voices.mjs +3 -3
  112. package/tools/recording-impact.mjs +7 -3
  113. package/tools/render-theme.mjs +33 -0
  114. package/tools/review-anchor.mjs +28 -12
  115. package/tools/semver.mjs +40 -0
  116. package/tools/sentences.mjs +180 -0
  117. package/tools/shot.mjs +14 -7
  118. package/tools/site-voices.mjs +232 -0
  119. package/tools/template-theme.mjs +1 -1
  120. package/tools/test-impact.mjs +19 -10
  121. package/tools/theme-check.mjs +30 -3
  122. package/tools/tts-cache.mjs +4 -3
  123. package/tools/tts-engines.mjs +38 -20
  124. package/tools/tts-setup.mjs +7 -7
  125. package/tools/video-options.mjs +34 -0
  126. package/tools/video.mjs +461 -48
  127. package/tools/voiceover-server.mjs +185 -104
  128. package/tools/voiceover.mjs +119 -261
  129. package/tools/zip.mjs +1 -1
  130. package/cli/dev.mjs +0 -623
  131. package/cli/present.mjs +0 -853
  132. package/cli/review.mjs +0 -361
  133. package/tools/publish-site-voices.mjs +0 -75
package/cli/supervise.mjs CHANGED
@@ -4,22 +4,22 @@
4
4
  /**
5
5
  * Outliving your parent is the one way a decklight server leaks.
6
6
  *
7
- * `author` runs the deck server and the bridges as child processes and reaps
7
+ * `open` runs the deck server and the bridges as child processes and reaps
8
8
  * them on its way out — but only for the signals it can catch. SIGKILL it (a
9
- * test harness, the OOM killer, an impatient `kill -9`) and author vanishes
9
+ * test harness, the OOM killer, an impatient `kill -9`) and `open` vanishes
10
10
  * with no chance to pass the signal on: the servers are reparented to init and
11
- * go on holding their ports, and the next `decklight author` finds a port
11
+ * go on holding their ports, and the next `decklight <deck>` finds a port
12
12
  * taken by something nobody remembers starting.
13
13
  *
14
- * The fix is a channel the OS closes for us. author opens a pipe to each
14
+ * The fix is a channel the OS closes for us. `open` opens a pipe to each
15
15
  * child's stdin and never writes a byte to it; the child reads it and exits at
16
- * EOF. However author dies, the write end dies with it and every child hears
16
+ * EOF. However `open` dies, the write end dies with it and every child hears
17
17
  * about it at once — no polling, no pid to watch, no signal to catch, and
18
18
  * nothing for a dying parent to remember to do.
19
19
  *
20
20
  * Opt-in, because stdin means something else to a server you started
21
21
  * yourself: `node cli/edit.mjs deck.html < /dev/null` would EOF immediately,
22
- * and a terminal never EOFs at all. author sets LEASH in the child's
22
+ * and a terminal never EOFs at all. `open` sets LEASH in the child's
23
23
  * environment; only then does anything here read stdin.
24
24
  */
25
25
 
@@ -0,0 +1,515 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // A deck's added themes, as REFERENCES (SPEC THEME_DISTRIBUTION).
5
+ //
6
+ // A source deck is data (DECK_ANATOMY): slides and one configuration block.
7
+ // A theme from a marketplace used to break that — `theme add` pasted the whole
8
+ // stylesheet into the deck as a <style data-theme-added> block, kilobytes of
9
+ // somebody else's CSS in the file an author diffs and reviews. Now the deck
10
+ // records WHICH theme it uses, and nothing else:
11
+ //
12
+ // { "theme": "acme", "markedThemes": ["acme@acme-themes"] }
13
+ //
14
+ // A theme in that list is MARKED: it will be part of the deck's bundle. The servers link it
15
+ // from the marketplace already on this machine, the no-trust mode lists it, and
16
+ // `bundle` inlines it at hand-over, where the reference would mean nothing to
17
+ // whoever opens the file. A theme that is not marked is still listed while
18
+ // authoring (every registered marketplace's themes are), and can be looked at
19
+ // and applied — it simply does not go anywhere the deck goes.
20
+ //
21
+ // Everything here reads the catalog CACHE and the checkouts `marketplace
22
+ // add`/`update` left on disk. Nothing fetches: a deck on a plane links what
23
+ // this machine has and names what it has not (MARKETPLACES — registered, not
24
+ // fetched). The one exception is a catalog entry whose `source` is an https
25
+ // URL rather than a file in its repo: its bytes arrive when it is marked, or
26
+ // looked at while authoring, and are kept in `theme-cache/` from then on —
27
+ // see `themeCachePath`.
28
+
29
+ import { existsSync, readFileSync, readdirSync, mkdirSync, statSync } from 'node:fs';
30
+ import { join } from 'node:path';
31
+ import { escapeHtml } from '../tools/escape.mjs';
32
+ import { writeFileAtomic } from '../tools/atomic-write.mjs';
33
+ import { THEMES_DIR } from './pkg.mjs';
34
+ import { validateTheme } from '../tools/theme-check.mjs';
35
+ import { configBlock, isDeck } from './runtime-link.mjs';
36
+ import {
37
+ configHome, loadRegistry, saveRegistry, loadCatalog, writeCache, validateManifest,
38
+ classifySource, MarketplaceError, NAME_RE,
39
+ } from './marketplace.mjs';
40
+ import { resolveSource } from './theme.mjs';
41
+
42
+ /** The config key a deck lists its marked themes under. */
43
+ export const MARKED_KEY = 'markedThemes';
44
+
45
+ /** The config key a deck records where each of its marketplaces comes from. */
46
+ export const SOURCES_KEY = 'themeSources';
47
+
48
+ /**
49
+ * The config key a deck lists its design systems under (SPEC DESIGN_SYSTEMS).
50
+ * Here rather than in design-system-refs.mjs because the source sweep below
51
+ * has to count them: `themeSources` is keyed by MARKETPLACE, shared by both
52
+ * kinds of mark, and a source goes only with the last mark of either.
53
+ */
54
+ export const DESIGN_SYSTEMS_KEY = 'designSystems';
55
+ /** …and the fonts it references (SPEC FONTS) — the third kind that shares `themeSources`. */
56
+ export const FONTS_KEY = 'fonts';
57
+
58
+ /** Every marketplace reference a deck holds, of any kind — what a recorded source is still needed for. */
59
+ export function referencedMarketplaces(html, keys = [MARKED_KEY, DESIGN_SYSTEMS_KEY, FONTS_KEY]) {
60
+ const config = configBlock(html)?.config ?? {};
61
+ const out = new Set();
62
+ for (const key of keys) {
63
+ for (const e of Array.isArray(config[key]) ? config[key] : []) {
64
+ const r = parseRef(e);
65
+ if (r) out.add(r.marketplace);
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+
71
+ /** The personal marketplace `theme add <file|url>` copies into. */
72
+ export const LOCAL_MARKETPLACE = 'local';
73
+
74
+ /** `acme@acme-themes` → `{ name, marketplace }`, or null for anything else. */
75
+ export function parseRef(ref) {
76
+ const m = /^([^@\s]+)@([^@\s]+)$/.exec(String(ref ?? ''));
77
+ if (!m || !NAME_RE.test(m[1]) || !NAME_RE.test(m[2])) return null;
78
+ return { name: m[1], marketplace: m[2], ref: `${m[1]}@${m[2]}` };
79
+ }
80
+
81
+ /**
82
+ * A theme decklight SHIPS, marked by its bare name — `"ember"` — or null. It
83
+ * needs no reference: every install has it. Marking one says the deck carries
84
+ * it when it travels, since a bundle holds only the themes put in it.
85
+ */
86
+ export function parseShipped(entry) {
87
+ if (typeof entry !== 'string' || !NAME_RE.test(entry) || !shippedThemes().includes(entry)) return null;
88
+ return { name: entry, marketplace: null, ref: entry, shipped: true };
89
+ }
90
+
91
+ /** Every theme the deck marks — shipped names and marketplace references — parsed; anything else dropped, not guessed at. */
92
+ export function markedEntries(html) {
93
+ const list = configBlock(html)?.config?.[MARKED_KEY];
94
+ return Array.isArray(list) ? list.map((e) => parseRef(e) ?? parseShipped(e)).filter(Boolean) : [];
95
+ }
96
+
97
+ /** The deck's marked MARKETPLACE references — what is resolved, linked and cached. */
98
+ export const markedRefs = (html) => markedEntries(html).filter((r) => !r.shipped);
99
+
100
+ /** The shipped themes the deck marks, by name. */
101
+ export const markedShipped = (html) => markedEntries(html).filter((r) => r.shipped).map((r) => r.name);
102
+
103
+ /**
104
+ * A marketplace's source as a deck records it — the form `marketplace add`
105
+ * takes, so it is also the command that brings it — or null when there is
106
+ * nothing portable to record.
107
+ *
108
+ * The name a marketplace is registered under is this machine's (`--name`
109
+ * renames it), so it cannot say which catalog a deck means: the same catalog
110
+ * can be `acme` here and `acme-themes` there, and two different catalogs can
111
+ * share a name. The source can. A LOCAL marketplace has none worth writing: its
112
+ * source is a path on the author's disk, meaningless anywhere else and a
113
+ * disclosure of their home directory — the personal one included. Credentials
114
+ * a URL carries (`https://user:token@host/…`) are removed before anything is
115
+ * written; a deck is a file that gets sent to people.
116
+ */
117
+ export function portableSource(source) {
118
+ if (typeof source !== 'string' || !source) return null;
119
+ const bare = source.replace(/^(https?:\/\/|ssh:\/\/|git:\/\/)[^/@]*@/i, '$1');
120
+ const src = classifySource(bare, { exists: () => false });
121
+ if (src.kind === 'github') return `${src.owner}/${src.repo}`;
122
+ if (src.kind === 'git' && !/^file:\/\//i.test(bare)) return bare.replace(/\.git\/?$/, '').replace(/\/$/, '');
123
+ return null;
124
+ }
125
+
126
+ /** The deck's recorded sources, by the marketplace name its references use. */
127
+ export function markedSources(html) {
128
+ const map = configBlock(html)?.config?.[SOURCES_KEY];
129
+ if (!map || typeof map !== 'object' || Array.isArray(map)) return {};
130
+ return Object.fromEntries(Object.entries(map).filter(([k, v]) => NAME_RE.test(k) && typeof v === 'string' && v));
131
+ }
132
+
133
+ /** The theme names shipped with this install. */
134
+ export const shippedThemes = () =>
135
+ readdirSync(THEMES_DIR).filter((f) => f.endsWith('.css')).map((f) => f.slice(0, -4));
136
+
137
+ /**
138
+ * Where an https-sourced entry's bytes are kept once read.
139
+ *
140
+ * Every other entry is a file in a checkout, which is already on disk; this is
141
+ * the one kind that is not. Keeping it is what lets every server link it with
142
+ * no network — a marked theme must look the same on a plane as it did at the
143
+ * desk. Filled only by an explicit act (marking it, or looking at it while
144
+ * authoring), never by serving a deck.
145
+ */
146
+ export const themeCachePath = (home, marketplace, name) => join(home, 'theme-cache', marketplace, `${name}.css`);
147
+
148
+ /** Keep an https-sourced entry's bytes for later offline serving. */
149
+ export function cacheThemeCss(home, marketplace, name, css) {
150
+ mkdirSync(join(home, 'theme-cache', marketplace), { recursive: true });
151
+ writeFileAtomic(themeCachePath(home, marketplace, name), css);
152
+ }
153
+
154
+ /**
155
+ * The catalog entry a reference means on THIS machine — the half of resolving
156
+ * every by-reference kind shares (a marked theme, a design system, SPEC
157
+ * DESIGN_SYSTEMS): which registered marketplace the reference names (with a
158
+ * recorded source, the source decides, not the name), and its entry in that
159
+ * marketplace's cached catalog. Registry and cache only; it never fetches.
160
+ *
161
+ * Returns `{ name, marketplace, ref, local, title, entry, registered, origin }`
162
+ * — `local` what this machine calls the catalog, `origin` its portable source
163
+ * — or `{ ...parsed, missing }` in words a presenter can act on. The kind is
164
+ * the caller's to check: the entry comes back whatever its type.
165
+ */
166
+ export function resolveCatalogEntry(parsed, home = configHome(), { source = null } = {}) {
167
+ const { name } = parsed;
168
+ // Which marketplace HERE the reference means. With a recorded source, the
169
+ // source decides: whatever this machine calls that catalog is the one, and
170
+ // a marketplace that merely shares the name is not it.
171
+ const registry = loadRegistry(home).marketplaces ?? {};
172
+ let marketplace = parsed.marketplace;
173
+ if (source) {
174
+ const same = Object.entries(registry).find(([, m]) => portableSource(m.source) === source)?.[0];
175
+ if (same) marketplace = same;
176
+ else if (registry[marketplace]) {
177
+ return { ...parsed, missing: `"${marketplace}" here is a different catalog (${portableSource(registry[marketplace].source) ?? 'a local one'}) — the deck's comes from ${source}` };
178
+ } else {
179
+ return { ...parsed, missing: `its marketplace is not registered on this machine — decklight marketplace add ${source}` };
180
+ }
181
+ }
182
+ const registered = registry[marketplace];
183
+ if (!registered) {
184
+ return { ...parsed, missing: `marketplace "${marketplace}" is not registered on this machine`
185
+ + ' — it was local to whoever marked it, or never recorded where it came from' };
186
+ }
187
+ const catalog = loadCatalog(marketplace, home);
188
+ if (!catalog?.ok) {
189
+ return { ...parsed, missing: `marketplace "${marketplace}" has never been fetched — decklight marketplace update ${marketplace}` };
190
+ }
191
+ const entry = (catalog.manifest.entries ?? []).find((e) => e.name === name);
192
+ if (!entry) return { ...parsed, missing: `"${name}" is not in ${marketplace} any more` };
193
+ return {
194
+ ...parsed, local: marketplace, title: catalog.manifest.title?.trim() || null, entry, registered,
195
+ origin: portableSource(registered.source),
196
+ };
197
+ }
198
+
199
+ /**
200
+ * Resolve a reference to the file on disk that holds its CSS, reading only
201
+ * the registry, the catalog cache, the checkouts and the theme cache.
202
+ *
203
+ * Returns `{ name, marketplace, ref, title, entry, file }`, or
204
+ * `{ ...parsed, missing }` with `missing` saying, in words a presenter can act
205
+ * on, why this machine cannot show it. `remote` is set on an https-sourced
206
+ * entry that has not been read yet — the caller that is allowed to fetch
207
+ * (an explicit mark, an author looking at it) knows to.
208
+ */
209
+ export function resolveThemeRef(ref, home = configHome(), { source = null } = {}) {
210
+ const parsed = typeof ref === 'string' ? parseRef(ref) : ref;
211
+ if (!parsed) return { ref: String(ref), missing: 'not a theme reference (name@marketplace)' };
212
+ const hit = resolveCatalogEntry(parsed, home, { source });
213
+ if (hit.missing) return hit;
214
+ const { name, local, title, entry, registered, origin } = hit;
215
+ const marketplace = local;
216
+ if (entry.type !== 'theme') return { ...parsed, entry, missing: `"${parsed.ref}" is a ${entry.type}, not a theme` };
217
+ if (/^https?:\/\//i.test(entry.source)) {
218
+ const cached = themeCachePath(home, marketplace, name);
219
+ if (existsSync(cached)) return { ...parsed, local, title, entry, file: cached, source: origin };
220
+ return { ...parsed, local, title, entry, remote: entry.source, missing: `${parsed.ref} lives at ${entry.source} and has not been read on this machine` };
221
+ }
222
+ let file;
223
+ try { file = resolveSource(entry.source, { name: marketplace, source: registered.source }, home); }
224
+ catch (e) {
225
+ if (e instanceof MarketplaceError) return { ...parsed, title, entry, missing: e.message.replace(/\n\s*/g, ' — ') };
226
+ throw e;
227
+ }
228
+ if (!existsSync(file)) return { ...parsed, title, entry, missing: `${parsed.ref}: ${entry.source} is not in the marketplace's files` };
229
+ return { ...parsed, local, title, entry, file, source: origin };
230
+ }
231
+
232
+ /**
233
+ * Does the file a marked theme resolves to STILL pass the THEMING contract?
234
+ *
235
+ * A marked theme follows its marketplace: `marketplace update` can change its
236
+ * bytes after it was marked and checked. A deck must never be made to show —
237
+ * or a bundle to carry — what the shipped set could not contain, so the
238
+ * contract is re-run wherever the file is used, not only when it was marked.
239
+ * Remembered by path, mtime and size, so a page load re-reads nothing that
240
+ * has not changed.
241
+ */
242
+ const verdicts = new Map();
243
+ export function stillValid(file) {
244
+ let st;
245
+ try { st = statSync(file); } catch { return { ok: false, why: 'its file is gone' }; }
246
+ const hit = verdicts.get(file);
247
+ if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.value;
248
+ const r = validateTheme(readFileSync(file, 'utf8'));
249
+ const value = r.ok ? { ok: true } : { ok: false, why: `it no longer passes the theme contract — ${r.errors[0] ?? 'see decklight theme gate'}` };
250
+ verdicts.set(file, { mtimeMs: st.mtimeMs, size: st.size, value });
251
+ return value;
252
+ }
253
+
254
+ /**
255
+ * Every theme every registered marketplace offers, from the cache — what the
256
+ * overlay lists while authoring — and the marketplaces it could not read.
257
+ *
258
+ * A marketplace that is registered but never fetched is the FIRST-RUN state
259
+ * (the first-party one is deliberately in it), so it is reported, by name, as
260
+ * something `marketplace update` fixes rather than as an empty list that looks
261
+ * like an empty marketplace.
262
+ */
263
+ export function marketplaceThemes(home = configHome()) {
264
+ const themes = [];
265
+ const stale = [];
266
+ for (const market of Object.keys(loadRegistry(home).marketplaces ?? {})) {
267
+ const catalog = loadCatalog(market, home);
268
+ if (!catalog?.ok) { stale.push(market); continue; }
269
+ let readable = 0;
270
+ for (const entry of catalog.manifest.entries ?? []) {
271
+ if (entry.type !== 'theme') continue;
272
+ const r = resolveThemeRef({ name: entry.name, marketplace: market, ref: `${entry.name}@${market}` }, home);
273
+ // An entry whose files are not here — a remote marketplace never cloned —
274
+ // would only be a row that fails. An https entry not read yet is fine:
275
+ // looking at it is the explicit act that reads it.
276
+ if (r.missing && !r.remote) continue;
277
+ readable++;
278
+ themes.push({
279
+ name: entry.name, marketplace: market, qualified: r.ref,
280
+ title: r.title, description: entry.description ?? '',
281
+ });
282
+ }
283
+ if (!readable && (catalog.manifest.entries ?? []).some((e) => e.type === 'theme')) stale.push(market);
284
+ }
285
+ return { themes, stale };
286
+ }
287
+
288
+ /** Where a server answers a reference's CSS, relative to the deck. */
289
+ export const themeRefHref = (marketplace, name) => `decklight-theme/${marketplace}/${name}.css`;
290
+
291
+ const REF_ASSET = /(?:^|\/)decklight-theme\/([\w-]+)\/([\w-]+)\.css$/;
292
+
293
+ /**
294
+ * `staticFiles`' answer for a reference's CSS — `{ file, type }`, or null.
295
+ * Matched on the path's tail like `packageAsset`, so a deck in `slides/`
296
+ * resolves too. Cache and checkout only: this is on every server's path,
297
+ * `--no-trust` included, and it never fetches.
298
+ */
299
+ export function themeRefAsset(rel, home = configHome()) {
300
+ const m = REF_ASSET.exec(String(rel ?? '').split('\\').join('/'));
301
+ if (!m) return null;
302
+ const r = resolveThemeRef({ name: m[2], marketplace: m[1], ref: `${m[2]}@${m[1]}` }, home);
303
+ return r.file && stillValid(r.file).ok ? { file: r.file, type: 'text/css; charset=utf-8' } : null;
304
+ }
305
+
306
+ /**
307
+ * The element a resolved reference is linked as. The same attributes an
308
+ * inline added block has always carried, so the runtime lists, groups and
309
+ * applies it by the code it already had: `data-theme-added` keeps it apart
310
+ * from the deck's own themes, `media="not all"` keeps it off until chosen,
311
+ * and provenance names its marketplace heading. Both provenance values come
312
+ * from a manifest somebody else wrote and land in double-quoted attributes —
313
+ * escaped, never trusted.
314
+ */
315
+ export function addedThemeLink({ name, marketplace, local = marketplace, title }) {
316
+ // `href` is where THIS server answers it (the catalog's name here); the
317
+ // marketplace attribute is the deck's own name for it, which is what the
318
+ // picker groups by and what a mark toggle writes back
319
+ const label = title ? ` data-theme-source="${escapeHtml(title)}"` : '';
320
+ return `<link rel="stylesheet" href="${themeRefHref(local, name)}" data-theme="${escapeHtml(name)}"`
321
+ + ` data-theme-added data-theme-marketplace="${escapeHtml(marketplace)}"${label} media="not all">`;
322
+ }
323
+
324
+ /**
325
+ * A marked theme as a bundle carries it: the same attributes as its link, so
326
+ * the picker in a file opened on a machine with no registry still draws the
327
+ * marketplace heading — provenance travels in the file or not at all. A
328
+ * `</style` inside the CSS would end the block early; it is somebody else's
329
+ * file, which is exactly when to check.
330
+ */
331
+ export function addedThemeStyle({ name, marketplace, title }, css, { active = false } = {}) {
332
+ const label = title ? ` data-theme-source="${escapeHtml(title)}"` : '';
333
+ const safe = css.replace(/<\/(style)/gi, '<\\/$1');
334
+ return `<style data-theme="${escapeHtml(name)}" data-theme-added data-theme-marketplace="${escapeHtml(marketplace)}"`
335
+ + `${label}${active ? '' : ' media="not all"'}>\n${safe.trim()}\n</style>`;
336
+ }
337
+
338
+ /**
339
+ * The marked themes of a deck, linked into the page on its way out — what
340
+ * every server does after `linkRuntime`, never `bundle` (a hand-over carries
341
+ * the CSS itself, not a link to this machine's marketplaces).
342
+ *
343
+ * A reference this machine cannot resolve is not linked; the page carries a
344
+ * `<meta name="decklight-theme-missing">` instead, so the runtime can say which
345
+ * theme is absent and what brings it, rather than a list that is silently
346
+ * short by one. A theme the deck already carries a block for — a bundle's
347
+ * inlined copy — is left to that block.
348
+ */
349
+ export function linkAddedThemes(html, home = configHome(), { log = null } = {}) {
350
+ if (!isDeck(html)) return html;
351
+ const refs = markedRefs(html);
352
+ if (!refs.length) return html;
353
+ const sources = markedSources(html);
354
+ const tags = [];
355
+ for (const ref of refs) {
356
+ const carried = new RegExp(`<(?:style|link)\\b[^>]*\\bdata-theme\\s*=\\s*["']${ref.name}["']`, 'i');
357
+ if (carried.test(html)) continue;
358
+ const r = resolveThemeRef(ref, home, { source: sources[ref.marketplace] ?? null });
359
+ const valid = r.file ? stillValid(r.file) : null;
360
+ if (r.file && !valid.ok) r.missing = valid.why;
361
+ if (r.file && valid.ok) tags.push(addedThemeLink(r));
362
+ else {
363
+ tags.push(`<meta name="decklight-theme-missing" content="${escapeHtml(`${ref.ref} — ${r.missing}`)}">`);
364
+ log?.(`theme ${ref.ref}: ${r.missing}`);
365
+ }
366
+ }
367
+ if (!tags.length) return html;
368
+ const masked = html.replace(/<!--[\s\S]*?-->/g, (m) => ' '.repeat(m.length));
369
+ const headEnd = masked.search(/<\/head>/i);
370
+ const at = headEnd !== -1 ? headEnd : Math.max(0, masked.search(/<body\b/i));
371
+ return `${html.slice(0, at)}${tags.join('\n')}\n${html.slice(at)}`;
372
+ }
373
+
374
+ /**
375
+ * Mark (`on`) or unmark a reference in the deck's configuration block, editing
376
+ * only the `markedThemes` value so the author's own formatting of the rest
377
+ * survives. Returns `{ html, changed }`, or throws a MarketplaceError a
378
+ * command prints as-is.
379
+ *
380
+ * The rules are the ones the overlay needs to stay unambiguous: a marked name
381
+ * is never a shipped theme's (the picker would show two `aurora`s and apply
382
+ * whichever it met first), never another marketplace's theme of the same name,
383
+ * and the theme the deck OPENS on cannot be unmarked out from under it.
384
+ */
385
+ export function setMarked(html, ref, on, { source = null } = {}) {
386
+ const parsed = parseShipped(ref) ?? parseRef(ref);
387
+ if (!parsed) {
388
+ throw new MarketplaceError(`"${ref}" is neither a theme decklight ships nor a marketplace theme (name@marketplace)`);
389
+ }
390
+ const block = configBlock(html);
391
+ if (!block) {
392
+ throw new MarketplaceError('the deck has no configuration block to record its themes in'
393
+ + ' — decklight upgrade --link <deck.html> gives it one');
394
+ }
395
+ if (block.error) throw new MarketplaceError(block.error);
396
+ const current = markedEntries(html);
397
+ const has = current.some((r) => r.ref === parsed.ref);
398
+ if (on) {
399
+ if (has) return { html, changed: false };
400
+ if (!parsed.shipped && shippedThemes().includes(parsed.name)) {
401
+ throw new MarketplaceError(`"${parsed.name}" is the name of a theme decklight ships — ${parsed.ref} cannot sit beside it`);
402
+ }
403
+ const clash = current.find((r) => r.name === parsed.name);
404
+ if (clash) throw new MarketplaceError(`the deck already marks ${clash.ref} — two themes called "${parsed.name}" cannot both be listed`);
405
+ } else {
406
+ if (!has) return { html, changed: false };
407
+ // A marketplace theme the deck opens on would leave it opening on nothing.
408
+ // A shipped one is never missing — every bundle carries the theme it opens
409
+ // on — so unmarking it only stops it travelling as an extra.
410
+ if (!parsed.shipped && block.config.theme === parsed.name) {
411
+ throw new MarketplaceError(`${parsed.ref} is the theme the deck opens on — set another "theme" first`);
412
+ }
413
+ }
414
+ const next = on ? [...current.map((r) => r.ref), parsed.ref] : current.map((r) => r.ref).filter((r) => r !== parsed.ref);
415
+ // Where each marketplace comes from rides alongside, once per marketplace:
416
+ // written when its first theme is marked, gone with its last. A theme from a
417
+ // marketplace with nothing portable to record (a local one) records nothing.
418
+ const sources = markedSources(html);
419
+ if (on && source) sources[parsed.marketplace] = source;
420
+ // gone with the last reference of ANY kind — a design system or a font the
421
+ // deck still uses keeps its marketplace's source when a theme from it is unmarked
422
+ const others = referencedMarketplaces(html, [DESIGN_SYSTEMS_KEY, FONTS_KEY]);
423
+ for (const m of Object.keys(sources)) {
424
+ if (!next.some((r) => r.endsWith(`@${m}`)) && !others.has(m)) delete sources[m];
425
+ }
426
+ let inner = withKey(block.inner, MARKED_KEY, next.length ? next : null);
427
+ inner = withKey(inner, SOURCES_KEY, Object.keys(sources).length ? sources : null);
428
+ return { html: html.slice(0, block.innerStart) + inner + html.slice(block.innerEnd), changed: true };
429
+ }
430
+
431
+ // The block's text with `key` set to `value` (an array of refs, or a flat map
432
+ // of names to sources) — the value swapped, the key appended last, or the key
433
+ // removed when `value` is null. Both are flat, so a bracket match finds the
434
+ // whole value; their strings are refs and sources, JSON-escaped, and a
435
+ // `</script` cannot survive `portableSource` or a ref's shape to reach here.
436
+ export function withKey(inner, key, value) {
437
+ const json = value === null ? null
438
+ : typeof value === 'string' ? JSON.stringify(value).replace(/<\//g, '<\\/')
439
+ : Array.isArray(value) ? `[${value.map((r) => JSON.stringify(r)).join(', ')}]`
440
+ : `{ ${Object.entries(value).map(([k, v]) => `${JSON.stringify(k)}: ${JSON.stringify(v).replace(/<\//g, '<\\/')}`).join(', ')} }`;
441
+ // an array, an object, or a string (the deck's default `font`)
442
+ const val = '(?:\\[[^\\]]*\\]|\\{[^{}]*\\}|"(?:[^"\\\\]|\\\\.)*")';
443
+ const keyRe = new RegExp(`"${key}"\\s*:\\s*${val}`);
444
+ if (keyRe.test(inner)) {
445
+ if (json !== null) return inner.replace(keyRe, () => `"${key}": ${json}`);
446
+ const withComma = new RegExp(`\\s*,\\s*"${key}"\\s*:\\s*${val}|"${key}"\\s*:\\s*${val}\\s*,?\\s*`);
447
+ return inner.replace(withComma, '');
448
+ }
449
+ if (json === null) return inner;
450
+ const close = inner.lastIndexOf('}');
451
+ const before = inner.slice(0, close);
452
+ const empty = /\{\s*$/.test(before);
453
+ const trailing = before.match(/\s*$/)[0];
454
+ // a pretty-printed block gets the new key on a line of its own, at the
455
+ // indent its first key has; a one-line block stays on one line
456
+ const indent = /\{[ \t]*\n([ \t]*)"/.exec(before)?.[1];
457
+ const sep = empty ? ' ' : indent !== undefined ? `,\n${indent}` : ', ';
458
+ return `${before.slice(0, before.length - trailing.length)}${sep}"${key}": ${json}${trailing || (empty ? ' ' : '')}${inner.slice(close)}`;
459
+ }
460
+
461
+ /**
462
+ * The reference a deck should record for `name` from the marketplace called
463
+ * `local` here. A deck that already records that marketplace's source under
464
+ * its own name keeps its name — the same catalog is one entry in the deck,
465
+ * whatever each machine that marks from it happens to call it.
466
+ */
467
+ export function refForDeck(html, name, local, source) {
468
+ const known = source ? Object.entries(markedSources(html)).find(([, v]) => v === source)?.[0] : null;
469
+ return `${name}@${known ?? local}`;
470
+ }
471
+
472
+ /**
473
+ * Copy a theme that came from a file or a URL into the personal marketplace,
474
+ * so it can be referenced like any other: `house@local`.
475
+ *
476
+ * The personal marketplace is an ordinary LOCAL marketplace, registered the
477
+ * first time it is needed: a directory with `.decklight/marketplace.json` and
478
+ * the themes beside it. It lives at `~/.decklight/local/`, deliberately NOT
479
+ * under `marketplaces/` — that is where `marketplace remove` deletes clones
480
+ * from, and removing the registration must never take somebody's themes with
481
+ * it. Re-adding a name replaces its file (there is no auto-update; re-adding
482
+ * IS the update).
483
+ */
484
+ export function addToLocalMarketplace(css, name, from, home = configHome()) {
485
+ if (!NAME_RE.test(name)) throw new MarketplaceError(`"${name}" is not a usable theme name — letters, digits, - and _`);
486
+ const dir = join(home, LOCAL_MARKETPLACE);
487
+ const reg = loadRegistry(home);
488
+ const existing = reg.marketplaces?.[LOCAL_MARKETPLACE];
489
+ if (existing && existing.source !== dir) {
490
+ throw new MarketplaceError(`a marketplace called "${LOCAL_MARKETPLACE}" is already registered from ${existing.source}`
491
+ + ` — the personal marketplace needs that name (decklight marketplace remove ${LOCAL_MARKETPLACE})`);
492
+ }
493
+ const manifestPath = join(dir, '.decklight', 'marketplace.json');
494
+ let manifest = { name: LOCAL_MARKETPLACE, title: 'Local', entries: [] };
495
+ if (existsSync(manifestPath)) {
496
+ const v = validateManifest(readFileSync(manifestPath, 'utf8'));
497
+ if (!v.ok) throw new MarketplaceError(`${manifestPath} does not validate — fix or delete it`);
498
+ manifest = v.manifest;
499
+ }
500
+ mkdirSync(join(dir, 'themes'), { recursive: true });
501
+ mkdirSync(join(dir, '.decklight'), { recursive: true });
502
+ writeFileAtomic(join(dir, 'themes', `${name}.css`), css);
503
+ const entry = { name, type: 'theme', source: `themes/${name}.css`, description: `added from ${from}` };
504
+ const at = manifest.entries.findIndex((e) => e.name === name);
505
+ const replaced = at !== -1;
506
+ if (replaced) manifest.entries[at] = entry; else manifest.entries.push(entry);
507
+ const raw = JSON.stringify(manifest, null, 2) + '\n';
508
+ writeFileAtomic(manifestPath, raw);
509
+ if (!existing) {
510
+ reg.marketplaces = { ...(reg.marketplaces ?? {}), [LOCAL_MARKETPLACE]: { source: dir } };
511
+ saveRegistry(reg, home);
512
+ }
513
+ writeCache(home, LOCAL_MARKETPLACE, raw);
514
+ return { ref: `${name}@${LOCAL_MARKETPLACE}`, replaced, registered: !existing, file: join(dir, 'themes', `${name}.css`) };
515
+ }