decklight 0.2.0 → 0.4.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 (137) hide show
  1. package/README.md +69 -31
  2. package/SPEC.md +881 -80
  3. package/cli/agents.mjs +116 -10
  4. package/cli/associate.mjs +286 -0
  5. package/cli/audit.mjs +424 -0
  6. package/cli/bundle.mjs +174 -46
  7. package/cli/deckfile.mjs +233 -0
  8. package/cli/decklight.mjs +201 -8
  9. package/cli/dev.mjs +244 -55
  10. package/cli/edit.mjs +577 -107
  11. package/cli/extension.mjs +108 -0
  12. package/cli/git.mjs +141 -0
  13. package/cli/import.mjs +398 -0
  14. package/cli/init.mjs +421 -116
  15. package/cli/loader.mjs +263 -0
  16. package/cli/marketplace.mjs +911 -0
  17. package/cli/pdf.mjs +156 -0
  18. package/cli/pkg.mjs +69 -0
  19. package/cli/plugin.mjs +654 -0
  20. package/cli/port-conflict.mjs +94 -0
  21. package/cli/present.mjs +564 -0
  22. package/cli/publish.mjs +342 -0
  23. package/cli/qr.mjs +334 -0
  24. package/cli/rec.mjs +5 -8
  25. package/cli/remote.mjs +149 -0
  26. package/cli/report-bug.mjs +97 -0
  27. package/cli/restore.mjs +174 -0
  28. package/cli/serve.mjs +247 -0
  29. package/cli/sign.mjs +216 -0
  30. package/cli/skill-content.mjs +222 -0
  31. package/cli/skills.mjs +338 -0
  32. package/cli/supervise.mjs +57 -0
  33. package/cli/theme.mjs +219 -0
  34. package/cli/units.mjs +500 -0
  35. package/cli/upgrade.mjs +250 -0
  36. package/cli/util.mjs +90 -0
  37. package/cli/wizard.mjs +432 -0
  38. package/cli/zip.mjs +121 -0
  39. package/dist/decklight.css +716 -29
  40. package/dist/decklight.js +198 -125
  41. package/dist/decklight.js.map +4 -4
  42. package/docs/architecture.svg +1 -1
  43. package/package.json +7 -5
  44. package/themes/README.md +6 -4
  45. package/themes/aurora.css +1 -1
  46. package/themes/berry.css +1 -1
  47. package/themes/carbon.css +1 -1
  48. package/themes/citrus.css +1 -1
  49. package/themes/coastal.css +1 -1
  50. package/themes/cosmos.css +1 -1
  51. package/themes/dune.css +1 -1
  52. package/themes/eclipse.css +1 -1
  53. package/themes/ember.css +1 -1
  54. package/themes/fjord.css +1 -1
  55. package/themes/gallery.html +3 -11
  56. package/themes/glacier.css +1 -1
  57. package/themes/graphite.css +1 -1
  58. package/themes/harvest.css +1 -1
  59. package/themes/ibm-modern.css +1 -1
  60. package/themes/ink.css +1 -1
  61. package/themes/latte.css +1 -1
  62. package/themes/linen.css +1 -1
  63. package/themes/meadow.css +1 -1
  64. package/themes/metropolis.css +1 -1
  65. package/themes/midnight.css +1 -1
  66. package/themes/mint.css +1 -1
  67. package/themes/moss.css +1 -1
  68. package/themes/obsidian.css +1 -1
  69. package/themes/orchid.css +1 -1
  70. package/themes/packs.json +2 -30
  71. package/themes/paper.css +1 -1
  72. package/themes/peony.css +1 -1
  73. package/themes/porcelain.css +1 -1
  74. package/themes/reveal-beige.css +1 -1
  75. package/themes/reveal-black.css +1 -1
  76. package/themes/reveal-blood.css +1 -1
  77. package/themes/reveal-dracula.css +1 -1
  78. package/themes/reveal-league.css +1 -1
  79. package/themes/reveal-moon.css +1 -1
  80. package/themes/reveal-night.css +1 -1
  81. package/themes/reveal-serif.css +1 -1
  82. package/themes/reveal-simple.css +1 -1
  83. package/themes/reveal-sky.css +1 -1
  84. package/themes/reveal-solarized.css +1 -1
  85. package/themes/reveal-white.css +1 -1
  86. package/themes/sepia.css +1 -1
  87. package/themes/seriph.css +1 -1
  88. package/themes/slate.css +1 -1
  89. package/themes/storm.css +1 -1
  90. package/themes/synthwave.css +1 -1
  91. package/themes/velvet.css +1 -1
  92. package/themes/yamabuki.css +1 -1
  93. package/tools/args.mjs +32 -0
  94. package/tools/bridge.mjs +30 -0
  95. package/tools/chrome.mjs +46 -11
  96. package/tools/color.mjs +110 -0
  97. package/tools/deck-html.mjs +138 -0
  98. package/tools/elevenlabs-tts.mjs +248 -0
  99. package/tools/escape.mjs +40 -0
  100. package/tools/extension-check-runner.mjs +41 -0
  101. package/tools/extension-check.mjs +266 -0
  102. package/tools/gemini-tts.mjs +25 -3
  103. package/tools/lipsync-engines.mjs +81 -0
  104. package/tools/lipsync-server.mjs +78 -37
  105. package/tools/lipsync.mjs +36 -21
  106. package/tools/local-voice.mjs +209 -0
  107. package/tools/ooxml.mjs +151 -0
  108. package/tools/pptx.mjs +320 -0
  109. package/tools/publish-site-voices.mjs +2 -1
  110. package/tools/publish-targets.mjs +143 -0
  111. package/tools/publish-voices.mjs +230 -0
  112. package/tools/shot.mjs +91 -47
  113. package/tools/theme-check.mjs +144 -0
  114. package/tools/tts-engines.mjs +270 -41
  115. package/tools/tts-setup.mjs +257 -0
  116. package/tools/veo.mjs +204 -0
  117. package/tools/video.mjs +440 -0
  118. package/tools/voiceover-server.mjs +163 -54
  119. package/tools/voiceover.mjs +24 -7
  120. package/tools/zip.mjs +143 -0
  121. package/docs/demo.svg +0 -124
  122. package/themes/aliens.css +0 -87
  123. package/themes/apple2.css +0 -129
  124. package/themes/blade-runner.css +0 -86
  125. package/themes/c64.css +0 -88
  126. package/themes/friends.css +0 -85
  127. package/themes/gameboy.css +0 -121
  128. package/themes/genesis.css +0 -87
  129. package/themes/godfather.css +0 -85
  130. package/themes/ibm-oldschool.css +0 -87
  131. package/themes/miami-vice.css +0 -87
  132. package/themes/pulp-fiction.css +0 -87
  133. package/themes/severance.css +0 -85
  134. package/themes/snes.css +0 -85
  135. package/themes/star-wars.css +0 -88
  136. package/themes/stranger-things.css +0 -87
  137. package/themes/terminator.css +0 -87
package/cli/units.mjs ADDED
@@ -0,0 +1,500 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * The unit library — one install seam for everything a marketplace
6
+ * distributes that is not a theme or a plugin (MARKETPLACE.md `UNITS`).
7
+ *
8
+ * `MARKETPLACES#CORE` registers catalogs and resolves a name to an entry;
9
+ * `THEME_BROWSE#UI` and `PRESENT#PLUGINS` each installed one kind of thing on
10
+ * top of it. This is the rest — deck templates, agent skills, import adapters
11
+ * — and it is deliberately ONE implementation with a type table rather than
12
+ * three commands that each grew their own copy of resolve-fetch-validate-write.
13
+ * `decklight template add` and `decklight importer add` are the same function
14
+ * with a different row.
15
+ *
16
+ * THE INVARIANT THAT OUTRANKS CONVENIENCE (SPEC MARKETPLACE_REGISTRY):
17
+ * registering is not fetching. Everything here reads the catalog CACHE; the
18
+ * only network call is `fetchArtifact`, reached only from an explicit `add`.
19
+ * `unitFor` and `listUnits` — the lookups on the `init` and `import` paths —
20
+ * cannot reach the network at all, so a deck on a plane behaves exactly like a
21
+ * deck at a desk.
22
+ *
23
+ * WHAT IS DELIBERATELY NOT HERE: running an installed unit. A template is
24
+ * HTML and a skill is Markdown, so both are just files. An import adapter and
25
+ * a build-time transform are both **Node code**, and executing either is one
26
+ * shared capability rather than two copies of resolve-fetch-validate-load —
27
+ * `cli/loader.mjs` (`EXTENSIONS#LOADER`) is that shared loader. `bundle
28
+ * --transform <name>` calls it once a transform is installed by the seam
29
+ * below, and `cli/import.mjs` calls the same loader's `runImporter` the
30
+ * moment an installed adapter matches the extension in hand
31
+ * (`EXTENSIONS#ADAPTEREXEC`, SPEC `EXTENSIONS_ADAPTERS`).
32
+ */
33
+
34
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
35
+ import { createHash } from 'node:crypto';
36
+ import { join, resolve } from 'node:path';
37
+ import { configHome, loadRegistry, loadCatalog, resolveEntry, MarketplaceError } from './marketplace.mjs';
38
+
39
+ /** A failure with a message for a human — the mains print it, never a stack. */
40
+ export class UnitError extends Error {}
41
+
42
+ /**
43
+ * The unit types this decklight installs, and the shape each one takes.
44
+ *
45
+ * `files` is what an entry's `source` must yield. A single-file unit names its
46
+ * one file and `source` points straight at it; a multi-file unit's `source` is
47
+ * a DIRECTORY and each name is fetched from inside it. `required` names the
48
+ * catalog fields beyond the universal `{name, type, source}` — `extensions`
49
+ * for an importer is not decoration: it is what lets `decklight import` find
50
+ * the adapter for a `.marp` file **offline**, from the cache alone.
51
+ */
52
+ export const UNIT_TYPES = {
53
+ template: {
54
+ dir: 'templates',
55
+ single: 'html',
56
+ label: 'deck template',
57
+ use: 'decklight init --from <name>',
58
+ example: 'startup-pitch',
59
+ required: [],
60
+ },
61
+ skill: {
62
+ dir: 'skills',
63
+ files: ['SKILL.md'],
64
+ optional: ['reference.md'],
65
+ label: 'agent skill',
66
+ use: 'decklight skills add <name>',
67
+ example: 'conference-cfp',
68
+ required: [],
69
+ },
70
+ // `pinned` marks the kinds that are Node code the loader runs unsandboxed
71
+ // at author privilege (EXTENSIONS#LOADER): their `source` resolves into a
72
+ // checkout cloned at whatever the marketplace's default branch pointed to
73
+ // when it was last added or updated — later than the admission that screened
74
+ // the code — so an entry installs only against the `sha256` its catalog
75
+ // admitted: refused before any read without one, refused before any write on
76
+ // a mismatch (SPEC UNIT_PINNING). Data kinds stay unpinned: a theme
77
+ // re-passes its whole contract at `theme add`, and nothing in a template or
78
+ // skill executes.
79
+ importer: {
80
+ dir: 'importers',
81
+ files: ['importer.mjs'],
82
+ label: 'import adapter',
83
+ use: 'decklight import <file>',
84
+ example: 'marp-import',
85
+ required: ['extensions'],
86
+ pinned: true,
87
+ },
88
+ // Node code, like an importer — but this one DOES run (EXTENSIONS#LOADER):
89
+ // `bundle --transform <name>` loads it through cli/loader.mjs. `apiVersion`
90
+ // is not persisted onto the installed file (there is nowhere on an .mjs to
91
+ // put it); the loader re-reads it from the catalog cache at run time, the
92
+ // same way `adapterFor` re-reads an importer's `extensions` rather than
93
+ // duplicating it into the library.
94
+ transform: {
95
+ dir: 'transforms',
96
+ single: 'mjs',
97
+ label: 'build-time transform',
98
+ use: 'decklight bundle --transform <name>',
99
+ example: 'grammar-check',
100
+ required: ['apiVersion'],
101
+ pinned: true,
102
+ },
103
+ // Node code that runs at AUTHOR time like a transform, and pinned for the
104
+ // same reason — but it is the first unit whose module is a FACTORY rather
105
+ // than a `(input) → string` pass (SPEC ENGINE_UNITS). What it returns is
106
+ // spoken with, so a malformed one has to be caught on the way out of the
107
+ // import rather than at the first sentence, mid-talk. Like a transform,
108
+ // `apiVersion` is not persisted onto the installed .mjs — the loader
109
+ // re-reads it, and `capability`, from the catalog cache.
110
+ engine: {
111
+ dir: 'engines',
112
+ single: 'mjs',
113
+ label: 'speech engine',
114
+ use: 'decklight tts --engine <name>, then the N picker',
115
+ example: 'azure-tts',
116
+ required: ['apiVersion', 'capability'],
117
+ pinned: true,
118
+ },
119
+ // A reference kind like `voice` below, but for a different reason: not
120
+ // consent, blast radius (SPEC AGENT_UNITS). An agent descriptor names a
121
+ // binary the user installed THEMSELVES and the argv of its headless mode,
122
+ // so teaching decklight a new agent downloads nothing and runs nothing of
123
+ // the catalog's — which is what keeps an open roster out of UNIT_PINNING's
124
+ // risk class entirely, unlike the engine directly above.
125
+ agent: {
126
+ dir: 'agents',
127
+ single: 'json',
128
+ reference: true,
129
+ label: 'AI agent',
130
+ use: 'A, author mode',
131
+ example: 'my-agent',
132
+ note: 'An agent unit is a DESCRIPTOR — which command to run and how to run it\n headlessly. Installing one fetches nothing; you install the agent itself the\n way its own docs say, and this only teaches decklight how to call it.',
133
+ required: ['bin', 'args'],
134
+ },
135
+ // The one kind that carries NOTHING. `reference: true` means the install is
136
+ // the catalog entry itself, written to disk as a pointer — no source to
137
+ // resolve, no bytes to fetch (SPEC VOICE_UNITS). Two consequences fall out
138
+ // of that and both are the point: `voice add` is the only add that works
139
+ // OFFLINE, and there is no code path by which a voice model could land in
140
+ // the library, because the fetch is not skipped conditionally — it is not
141
+ // reachable.
142
+ voice: {
143
+ dir: 'voices',
144
+ single: 'json',
145
+ reference: true,
146
+ label: 'voice',
147
+ use: 'the N picker, author mode',
148
+ example: 'narrator-anna',
149
+ note: 'A voice is a REFERENCE — which engine, which of its voices. Installing\n one writes a pointer and fetches nothing, so this is the one add that works\n offline; speaking through it still needs that engine and your own credential.',
150
+ required: ['engine', 'voiceId'],
151
+ },
152
+ };
153
+
154
+ const typeOf = (type) => {
155
+ const t = UNIT_TYPES[type];
156
+ if (!t) throw new UnitError(`"${type}" is not a unit type this decklight installs`);
157
+ return t;
158
+ };
159
+
160
+ /** Where a type's units live: `~/.decklight/templates/`, `…/skills/`, … */
161
+ export const unitDir = (type, home = configHome()) => join(home, typeOf(type).dir);
162
+
163
+ /** Where ONE unit lives — a file for a single-file type, a directory otherwise. */
164
+ export const unitPath = (type, name, home = configHome()) => {
165
+ const t = typeOf(type);
166
+ return join(unitDir(type, home), t.single ? `${name}.${t.single}` : name);
167
+ };
168
+
169
+ // ── reading the library, always offline ────────────────────────────────────
170
+
171
+ /** Installed units of a type, by name. Never touches the network. */
172
+ export function listUnits(type, home = configHome()) {
173
+ const t = typeOf(type);
174
+ const dir = unitDir(type, home);
175
+ if (!existsSync(dir)) return [];
176
+ const out = [];
177
+ for (const entry of readdirSync(dir).sort()) {
178
+ const full = join(dir, entry);
179
+ if (t.single) {
180
+ const suffix = `.${t.single}`;
181
+ if (!entry.endsWith(suffix) || !statSync(full).isFile()) continue;
182
+ out.push({ name: entry.slice(0, -suffix.length), path: full });
183
+ } else {
184
+ if (!statSync(full).isDirectory()) continue;
185
+ out.push({ name: entry, path: full });
186
+ }
187
+ }
188
+ return out;
189
+ }
190
+
191
+ /** One installed unit, or null. Never touches the network. */
192
+ export function findUnit(type, name, home = configHome()) {
193
+ const p = unitPath(type, name, home);
194
+ return existsSync(p) ? { name, path: p } : null;
195
+ }
196
+
197
+ /**
198
+ * Every entry in every CACHED catalog, flattened. The lookup that `init` and
199
+ * `import` use to name something they cannot find installed — reading a JSON
200
+ * file that is already on disk, which is exactly as offline-identical as not
201
+ * reading it at all.
202
+ */
203
+ export function catalogEntries(home = configHome()) {
204
+ const reg = loadRegistry(home);
205
+ const out = [];
206
+ for (const marketplace of Object.keys(reg.marketplaces).sort()) {
207
+ const cached = loadCatalog(marketplace, home);
208
+ if (!cached?.ok) continue;
209
+ for (const entry of cached.manifest.entries) {
210
+ out.push({ ...entry, marketplace, qualified: `${entry.name}@${marketplace}` });
211
+ }
212
+ }
213
+ return out;
214
+ }
215
+
216
+ /** Catalog entries of one type, cache-only — "what templates could I install?" */
217
+ export const catalogEntriesOfType = (type, home = configHome()) =>
218
+ catalogEntries(home).filter((e) => e.type === type);
219
+
220
+ /**
221
+ * The import adapter a file extension would need, from the cache alone.
222
+ *
223
+ * This is what makes the offer at the point of failure possible without a
224
+ * setup step nobody performs in advance (the ENGINES pattern): `import
225
+ * talk.marp` can name `marp-import` because the catalog it already fetched
226
+ * said which extensions that adapter handles. With no catalog cached it
227
+ * returns nothing and `import` says what it always said — never a hang, never
228
+ * a fetch.
229
+ */
230
+ export function adapterFor(ext, home = configHome()) {
231
+ const want = String(ext ?? '').toLowerCase();
232
+ if (!want) return null;
233
+ return catalogEntriesOfType('importer', home).find((e) =>
234
+ (e.extensions ?? []).some((x) => String(x).toLowerCase().replace(/^\.?/, '.') === want)) ?? null;
235
+ }
236
+
237
+ /**
238
+ * Installed voice references for one engine (SPEC VOICE_UNITS).
239
+ *
240
+ * Filtered by engine because a reference is only an answer on the engine it
241
+ * names: an ElevenLabs voice id means nothing to piper, and offering it while
242
+ * piper is live would put a row in the picker that can only fail. Unreadable
243
+ * or half-written files are skipped rather than thrown — one bad pointer must
244
+ * not cost the roster the bridge is otherwise able to report.
245
+ */
246
+ export function installedVoices(engine, home = configHome()) {
247
+ const want = String(engine ?? '').toLowerCase();
248
+ if (!want) return [];
249
+ const out = [];
250
+ for (const { name, path } of listUnits('voice', home)) {
251
+ let ref;
252
+ try { ref = JSON.parse(readFileSync(path, 'utf8')); } catch { continue; }
253
+ if (String(ref?.engine ?? '').toLowerCase() !== want) continue;
254
+ if (!ref.voiceId) continue;
255
+ out.push({ name, voiceId: String(ref.voiceId), label: ref.label || name, marketplace: ref.marketplace });
256
+ }
257
+ return out;
258
+ }
259
+
260
+ // ── installing, the one place that reaches the network ─────────────────────
261
+
262
+ /** Read one artifact file from a resolved source (a URL or a local path). */
263
+ async function fetchArtifact(at, { fetchImpl = fetch, timeoutMs = 8000 } = {}) {
264
+ if (/^https?:\/\//i.test(at)) {
265
+ let r;
266
+ try { r = await fetchImpl(at, { signal: AbortSignal.timeout(timeoutMs), redirect: 'follow' }); } catch (e) {
267
+ const why = e.name === 'TimeoutError' || e.code === 'ABORT_ERR'
268
+ ? `no response after ${timeoutMs / 1000}s` : String(e.cause?.code ?? e.message);
269
+ throw new UnitError(`could not fetch ${at} — ${why}`);
270
+ }
271
+ if (!r.ok) throw new UnitError(`${at} — HTTP ${r.status}`);
272
+ return await r.text();
273
+ }
274
+ if (!existsSync(at)) throw new UnitError(`no such file: ${at}`);
275
+ return readFileSync(at, 'utf8');
276
+ }
277
+
278
+ const joinSource = (base, file) => (/^https?:\/\//i.test(base)
279
+ ? `${base.replace(/\/$/, '')}/${file}`
280
+ : join(resolve(base), file));
281
+
282
+ /**
283
+ * Install one unit by catalog reference (`name` or `name@marketplace`).
284
+ *
285
+ * Everything is fetched and checked BEFORE anything is written, so a refusal
286
+ * or a dropped connection leaves the library exactly as it was — the rule
287
+ * `theme add` keeps, for the same reason: a half-installed unit is worse than
288
+ * an uninstalled one, because it looks present.
289
+ */
290
+ export async function installUnit(type, ref, home = configHome(), { fetchImpl = fetch } = {}) {
291
+ const t = typeOf(type);
292
+ const reg = loadRegistry(home);
293
+ const catalogs = {};
294
+ for (const name of Object.keys(reg.marketplaces)) {
295
+ const c = loadCatalog(name, home);
296
+ if (c?.ok) catalogs[name] = c.manifest;
297
+ }
298
+ if (!Object.keys(catalogs).length) {
299
+ throw new UnitError('no marketplace has been fetched yet'
300
+ + ' — decklight marketplace update <name> (registering is not fetching)');
301
+ }
302
+
303
+ let hit;
304
+ try { hit = resolveEntry(ref, catalogs); } catch (e) {
305
+ if (e instanceof MarketplaceError) throw new UnitError(e.message);
306
+ throw e;
307
+ }
308
+ if (hit.entry.type !== type) {
309
+ throw new UnitError(`${hit.qualified} is a ${hit.entry.type}, not a ${type}`
310
+ + `${UNIT_TYPES[hit.entry.type] ? ` — try: decklight ${hit.entry.type} add ${ref}` : ''}`);
311
+ }
312
+
313
+ // A reference-only kind is fully installed by the catalog entry it resolved
314
+ // to: write the pointer and return, before anything can be fetched.
315
+ if (t.reference) {
316
+ const dest = unitPath(type, hit.entry.name, home);
317
+ const { name, type: _t, source: _s, ...rest } = hit.entry;
318
+ mkdirSync(unitDir(type, home), { recursive: true });
319
+ writeFileSync(dest, `${JSON.stringify({ name, ...rest, marketplace: hit.marketplace }, null, 2)}\n`);
320
+ return { name, qualified: hit.qualified, entry: hit.entry, path: dest, files: [] };
321
+ }
322
+
323
+ // A pinned kind with no pin is refused HERE, before the network is touched:
324
+ // its source resolves against a moving ref, so without a digest there is no
325
+ // fact to hold the fetched bytes to (SPEC UNIT_PINNING).
326
+ if (t.pinned && !hit.entry.sha256) {
327
+ throw new UnitError(`${hit.qualified} carries no sha256 — a ${t.label} is Node code decklight`
328
+ + ` runs unsandboxed, so it installs only pinned to the digest its catalog admitted`
329
+ + ` (SPEC UNIT_PINNING). Ask the marketplace to pin the entry; decklight extension check`
330
+ + ` prints the digest to use`);
331
+ }
332
+
333
+ // Same placement, same reason: an `engine` entry may legitimately carry
334
+ // neither field, because the type is also how a catalog declares a wizard
335
+ // for an engine decklight already SHIPS (ENGINES#WIZARD) — no module, no
336
+ // contract version, nothing installed. Only an entry actually being
337
+ // installed as a unit has to answer for both (SPEC ENGINE_UNITS).
338
+ for (const field of t.required ?? []) {
339
+ if (t.reference || hit.entry[field] !== undefined) continue;
340
+ throw new UnitError(`${hit.qualified} declares no ${field}, which installing a ${t.label} needs`
341
+ + (type === 'engine'
342
+ ? ' (SPEC ENGINE_UNITS). An entry that only declares a wizard for an engine decklight'
343
+ + ' already ships carries neither field, and is not installed this way — the wizard'
344
+ + ' reaches it through the palette instead'
345
+ : ''));
346
+ }
347
+
348
+ // An entry's `source` is relative to its marketplace, which by now is a
349
+ // CHECKOUT on disk (MARKETPLACES#CLONE) — so for everything but an absolute
350
+ // URL, installing a unit reads files rather than reaching the network.
351
+ const { resolveSource } = await import('./theme.mjs');
352
+ let base;
353
+ try {
354
+ base = resolveSource(hit.entry.source,
355
+ { name: hit.marketplace, source: reg.marketplaces[hit.marketplace]?.source }, home);
356
+ } catch (e) {
357
+ if (e instanceof MarketplaceError) throw new UnitError(e.message);
358
+ throw e;
359
+ }
360
+
361
+ // Fetch first, write second.
362
+ const fetched = [];
363
+ if (t.single) {
364
+ fetched.push(['', await fetchArtifact(base, { fetchImpl })]);
365
+ } else {
366
+ for (const file of t.files) fetched.push([file, await fetchArtifact(joinSource(base, file), { fetchImpl })]);
367
+ for (const file of t.optional ?? []) {
368
+ try { fetched.push([file, await fetchArtifact(joinSource(base, file), { fetchImpl })]); } catch { /* optional */ }
369
+ }
370
+ }
371
+
372
+ // The pin covers the MODULE — the file the loader will import() — and it is
373
+ // checked between fetch and write, so a mismatch leaves the library exactly
374
+ // as it was, like every other refusal here.
375
+ if (hit.entry.sha256) {
376
+ const moduleFile = t.single ? '' : t.files[0];
377
+ const got = createHash('sha256').update(fetched.find(([f]) => f === moduleFile)[1]).digest('hex');
378
+ const want = String(hit.entry.sha256).toLowerCase();
379
+ if (got !== want) {
380
+ throw new UnitError(`${hit.qualified}: the fetched ${t.single ? `.${t.single} file` : t.files[0]}`
381
+ + ` does not match the catalog's pin (SPEC UNIT_PINNING)\n`
382
+ + ` pinned sha256 ${want}\n`
383
+ + ` fetched sha256 ${got}\n`
384
+ + ` the file changed since this catalog was cached — nothing was installed. If the`
385
+ + ` marketplace re-pinned it, decklight marketplace update ${hit.marketplace} and try again`);
386
+ }
387
+ }
388
+
389
+ const dest = unitPath(type, hit.entry.name, home);
390
+ if (t.single) {
391
+ mkdirSync(unitDir(type, home), { recursive: true });
392
+ writeFileSync(dest, fetched[0][1]);
393
+ } else {
394
+ mkdirSync(dest, { recursive: true });
395
+ for (const [file, text] of fetched) writeFileSync(join(dest, file), text);
396
+ }
397
+ return { name: hit.entry.name, qualified: hit.qualified, entry: hit.entry, path: dest, files: fetched.map(([f]) => f).filter(Boolean) };
398
+ }
399
+
400
+ /** Delete an installed unit. */
401
+ export function removeUnit(type, name, home = configHome()) {
402
+ const p = unitPath(type, name, home);
403
+ if (!existsSync(p)) throw new UnitError(`no ${type} "${name}" installed (decklight ${type} list)`);
404
+ rmSync(p, { recursive: true, force: true });
405
+ return p;
406
+ }
407
+
408
+ // ── the command every unit type shares ─────────────────────────────────────
409
+
410
+ export const unitUsage = (type) => {
411
+ const t = typeOf(type);
412
+ return `usage: decklight ${type} <add|list|remove> …
413
+
414
+ decklight ${type} add <name[@marketplace]>
415
+ install a ${t.label} from a registered marketplace into ~/.decklight/${t.dir}/
416
+ EXAMPLE: decklight ${type} add ${t.example}${t.note ? `\n\n ${t.note}` : ''}
417
+
418
+ decklight ${type} list
419
+ what is installed, and what the registered catalogs offer that is not
420
+
421
+ decklight ${type} remove <name>
422
+ delete it from your library
423
+
424
+ used by: ${t.use}
425
+
426
+ Registering a marketplace is not fetching it (SPEC MARKETPLACE_REGISTRY):
427
+ \`list\` reads only the cache and works on a plane, and the network is touched
428
+ only by an explicit \`add\`. DECKLIGHT_HOME overrides ~/.decklight/.`;
429
+ };
430
+
431
+ async function addMain(type, args, home) {
432
+ const [ref] = args.filter((a) => !a.startsWith('-'));
433
+ if (!ref) { console.error(`decklight ${type} add: needs a name\n\n${unitUsage(type)}`); return 1; }
434
+ let done;
435
+ try { done = await installUnit(type, ref, home); } catch (e) {
436
+ if (!(e instanceof UnitError)) throw e;
437
+ console.error(`decklight ${type} add: ${e.message}`);
438
+ return 1;
439
+ }
440
+ console.log(`installed ${done.name} from ${done.qualified} — ${UNIT_TYPES[type].use}`);
441
+ if (done.entry.description) console.log(` ${done.entry.description}`);
442
+ return 0;
443
+ }
444
+
445
+ function listMain(type, home) {
446
+ const t = UNIT_TYPES[type];
447
+ const installed = listUnits(type, home);
448
+ const offered = catalogEntriesOfType(type, home);
449
+ const have = new Set(installed.map((u) => u.name));
450
+
451
+ if (!installed.length && !offered.length) {
452
+ console.log(`no ${t.label}s installed, and no registered marketplace offers one`);
453
+ console.log(' decklight marketplace add <owner/repo>, then decklight marketplace update <name>');
454
+ return 0;
455
+ }
456
+ for (const u of installed) {
457
+ const from = offered.find((e) => e.name === u.name);
458
+ console.log(`${u.name}${from ? ` ${from.qualified}` : ''}${from?.description ? ` — ${from.description}` : ''}`);
459
+ }
460
+ const rest = offered.filter((e) => !have.has(e.name));
461
+ if (rest.length) {
462
+ console.log(installed.length ? `\navailable (decklight ${type} add <name>):` : `available (decklight ${type} add <name>):`);
463
+ for (const e of rest) console.log(` ${e.qualified}${e.description ? ` — ${e.description}` : ''}`);
464
+ }
465
+ return 0;
466
+ }
467
+
468
+ function removeMain(type, args, home) {
469
+ const [name] = args.filter((a) => !a.startsWith('-'));
470
+ if (!name) { console.error(`decklight ${type} remove: which one?\n\n${unitUsage(type)}`); return 1; }
471
+ try { removeUnit(type, name, home); } catch (e) {
472
+ if (!(e instanceof UnitError)) throw e;
473
+ console.error(`decklight ${type} remove: ${e.message}`);
474
+ return 1;
475
+ }
476
+ console.log(`removed ${name}`);
477
+ return 0;
478
+ }
479
+
480
+ /** `decklight <type> <add|list|remove>` — one implementation, three commands. */
481
+ export async function unitMain(type, args = []) {
482
+ const sub = args[0];
483
+ if (!sub || sub === '--help' || sub === '-h' || sub === 'help') { console.log(unitUsage(type)); return sub ? 0 : 1; }
484
+ const rest = args.slice(1);
485
+ if (rest.includes('--help') || rest.includes('-h')) { console.log(unitUsage(type)); return 0; }
486
+ const home = configHome();
487
+ try {
488
+ if (sub === 'add') return await addMain(type, rest, home);
489
+ if (sub === 'list') return listMain(type, home);
490
+ if (sub === 'remove') return removeMain(type, rest, home);
491
+ } catch (e) {
492
+ if (e instanceof UnitError || e instanceof MarketplaceError) {
493
+ console.error(`decklight ${type} ${sub}: ${e.message}`);
494
+ return 1;
495
+ }
496
+ throw e;
497
+ }
498
+ console.error(`decklight ${type}: unknown subcommand "${sub}"\n\n${unitUsage(type)}`);
499
+ return 1;
500
+ }