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/wizard.mjs ADDED
@@ -0,0 +1,432 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * The engine wizard framework (MARKETPLACE.md `ENGINES#WIZARD`).
6
+ *
7
+ * TTS ships with no configuration and no bundled provider, but `V`/`N` and the
8
+ * palette entries are always there. First use opens a wizard: pick a provider,
9
+ * answer what it needs, and the answers land under the config home. There is
10
+ * nothing to start if nothing is installed, which is what this replaces — eager
11
+ * bridge startup, and any lazy-loading scheme that would have grown out of it.
12
+ *
13
+ * ## The rule this file exists to enforce
14
+ *
15
+ * **Core renders; a plugin only declares.** A plugin supplies a schema —
16
+ * questions, field types, a validation endpoint — and never paints UI into the
17
+ * deck. That is not a stylistic preference. "The wizard only appears in author
18
+ * mode" has to be *enforceable*, and it stops being enforceable the moment a
19
+ * plugin can put arbitrary markup on a slide: whatever rule core writes, the
20
+ * plugin's own HTML is the thing that would have to honour it. So the field
21
+ * vocabulary below is closed, and a schema asking for anything outside it is
22
+ * refused by name rather than rendered as a best guess.
23
+ *
24
+ * ## Credentials
25
+ *
26
+ * Pasted in the player, posted to the author server, written `0600` under the
27
+ * config home. Loopback-only by construction rather than by check: the author
28
+ * server refuses every `/edit/*` mutation off-loopback unconditionally
29
+ * (`allowRemote`), flag or no flag. Never logged, never written into the deck,
30
+ * never picked up by `bundle` — a key that reached a deck would travel with it.
31
+ *
32
+ * A credential prompt in a deck you were *emailed* is a phishing primitive, so
33
+ * `present` registers none of this and a bundled deck has nothing to post to.
34
+ *
35
+ * And the prompt itself names its asker and its destination (#232): every
36
+ * string a schema puts on screen — the title, each field's label — was written
37
+ * by the plugin, so `provenance` below derives the one line the plugin cannot
38
+ * write, and the player refuses to render a schema that arrives without it.
39
+ */
40
+
41
+ import { readFileSync, writeFileSync, mkdirSync, chmodSync, statSync, existsSync } from 'node:fs';
42
+ import path, { delimiter } from 'node:path';
43
+ import { homedir } from 'node:os';
44
+ import { configHome } from './marketplace.mjs';
45
+
46
+ /** Where credentials live. Beside `marketplaces.json`, same config home. */
47
+ export const credentialsPath = (home = configHome()) => path.join(home, 'credentials.json');
48
+
49
+ /**
50
+ * The closed field vocabulary. A plugin picks from these and nothing else.
51
+ *
52
+ * `secret` is the only one that is redacted and the only one that may be
53
+ * written to the credentials file; the rest are ordinary configuration and are
54
+ * safe to print back. Adding a type here is a deliberate act — it widens what
55
+ * every plugin in every marketplace can ask a presenter for.
56
+ */
57
+ export const FIELD_TYPES = Object.freeze(['secret', 'text', 'choice', 'path', 'boolean']);
58
+
59
+ /** Thrown for a schema core will not render. Distinct so callers can name it. */
60
+ export class SchemaError extends Error {}
61
+
62
+ const NAME_RE = /^[A-Za-z][\w-]{0,63}$/;
63
+
64
+ /**
65
+ * Validate a plugin's declared wizard, returning a normalized copy.
66
+ *
67
+ * Deliberately strict, and deliberately explicit about *why* each rejection
68
+ * happens: a plugin author reading the error should be able to fix the schema
69
+ * without reading this file. Unknown keys are refused rather than ignored —
70
+ * silently dropping a key a plugin thought was doing something is how a plugin
71
+ * ends up shipping a wizard that asks for less than its author believed.
72
+ */
73
+ export function validateSchema(raw) {
74
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
75
+ throw new SchemaError('a wizard schema must be a JSON object');
76
+ }
77
+ const allowed = new Set(['engine', 'title', 'fields', 'validate', 'install', 'requires']);
78
+ for (const key of Object.keys(raw)) {
79
+ if (!allowed.has(key)) {
80
+ throw new SchemaError(`unknown key "${key}" — a schema may declare only: ${[...allowed].join(', ')}`);
81
+ }
82
+ }
83
+ if (typeof raw.engine !== 'string' || !NAME_RE.test(raw.engine)) {
84
+ throw new SchemaError('engine must be a name like "elevenlabs" (letters, digits, - and _)');
85
+ }
86
+ if (raw.title !== undefined && typeof raw.title !== 'string') {
87
+ throw new SchemaError('title must be a string');
88
+ }
89
+ if (!Array.isArray(raw.fields) || !raw.fields.length) {
90
+ throw new SchemaError('fields must be a non-empty array — a wizard with nothing to ask is not a wizard');
91
+ }
92
+ if (raw.fields.length > 12) {
93
+ throw new SchemaError(`${raw.fields.length} fields is more than a first-run wizard should ask; 12 is the ceiling`);
94
+ }
95
+
96
+ const seen = new Set();
97
+ const fields = raw.fields.map((f, i) => {
98
+ const at = `fields[${i}]`;
99
+ if (!f || typeof f !== 'object' || Array.isArray(f)) throw new SchemaError(`${at} must be an object`);
100
+ for (const key of Object.keys(f)) {
101
+ if (!['name', 'label', 'type', 'required', 'options', 'default'].includes(key)) {
102
+ throw new SchemaError(`${at}: unknown key "${key}"`);
103
+ }
104
+ }
105
+ if (typeof f.name !== 'string' || !NAME_RE.test(f.name)) throw new SchemaError(`${at}.name must be a plain name`);
106
+ if (seen.has(f.name)) throw new SchemaError(`${at}: duplicate field name "${f.name}"`);
107
+ seen.add(f.name);
108
+ if (!FIELD_TYPES.includes(f.type)) {
109
+ // The refusal that carries the whole design: no `html`, no `script`, no
110
+ // `markdown`, no `iframe`. Core renders a known set of inputs, so there
111
+ // is no path by which a plugin's own markup reaches a slide.
112
+ throw new SchemaError(`${at}.type "${f.type}" is not a field type core renders — pick one of: ${FIELD_TYPES.join(', ')}`);
113
+ }
114
+ if (f.label !== undefined && typeof f.label !== 'string') throw new SchemaError(`${at}.label must be a string`);
115
+ if (f.type === 'choice') {
116
+ if (!Array.isArray(f.options) || !f.options.length) {
117
+ throw new SchemaError(`${at}: a choice field needs options`);
118
+ }
119
+ if (f.options.some((o) => typeof o !== 'string')) throw new SchemaError(`${at}.options must be strings`);
120
+ } else if (f.options !== undefined) {
121
+ throw new SchemaError(`${at}: options only mean something for a choice field`);
122
+ }
123
+ if (f.type === 'secret' && f.default !== undefined) {
124
+ // A default secret is either a placeholder that will be pasted over or a
125
+ // key baked into a catalog. The second is bad enough to refuse the first.
126
+ throw new SchemaError(`${at}: a secret cannot carry a default`);
127
+ }
128
+ return {
129
+ name: f.name,
130
+ label: typeof f.label === 'string' ? f.label : f.name,
131
+ type: f.type,
132
+ required: f.required === true,
133
+ ...(f.type === 'choice' ? { options: [...f.options] } : {}),
134
+ ...(f.default !== undefined ? { default: f.default } : {}),
135
+ };
136
+ });
137
+
138
+ const requires = validateRequires(raw);
139
+
140
+ for (const key of ['validate', 'install']) {
141
+ if (raw[key] === undefined) continue;
142
+ if (typeof raw[key] !== 'string' || !raw[key].startsWith('/')) {
143
+ throw new SchemaError(`${key} must be a path on the plugin's own bridge, like "/validate"`);
144
+ }
145
+ }
146
+
147
+ return {
148
+ engine: raw.engine,
149
+ title: raw.title ?? raw.engine,
150
+ fields,
151
+ ...(raw.validate ? { validate: raw.validate } : {}),
152
+ ...(raw.install ? { install: raw.install } : {}),
153
+ ...(requires.length ? { requires } : {}),
154
+ };
155
+ }
156
+
157
+ /** What a prerequisite may BE — closed, like `FIELD_TYPES` and for the same reason. */
158
+ export const REQUIRE_KINDS = Object.freeze(['binary', 'file']);
159
+
160
+ /**
161
+ * Validate a schema's `requires` block — the NON-CREDENTIAL prerequisites an
162
+ * engine needs before it can run at all (SPEC `ENGINE_PREREQUISITES`,
163
+ * `ENGINES#LIPSYNC`). Lipsync is what forced this: rhubarb is a binary,
164
+ * Wav2Lip is a python checkout plus model weights, and only Veo is the
165
+ * paste-a-key shape TTS made look universal.
166
+ *
167
+ * Two kinds, and deliberately no third: `binary` (a command that must be on
168
+ * PATH) and `file` (a path that must exist — a checkout, a checkpoint, a
169
+ * model). Everything a talking-head engine needs is one of those two, and a
170
+ * vocabulary that grew past them would stop being a declaration and start
171
+ * being a build script.
172
+ *
173
+ * **`hint` is displayed, never executed.** It is the line a human would type,
174
+ * shown so they can copy it. Decklight does not run it, and that is the whole
175
+ * reason this can be catalog-supplied at all: a plugin able to get a shell
176
+ * command run at author privilege merely by declaring a "prerequisite" would
177
+ * make the wizard a remote-code-execution primitive with a config file for a
178
+ * delivery mechanism — the exact inversion MARKETPLACE.md `WHY` exists to
179
+ * refuse. The piper offer-to-fetch (#159) looks similar and is not: that
180
+ * command is chosen by decklight's own code (`tools/tts-engines.mjs`), against
181
+ * a package decklight names, and nobody else can put a string in it.
182
+ */
183
+ function validateRequires(raw) {
184
+ if (raw.requires === undefined) return [];
185
+ if (!Array.isArray(raw.requires)) throw new SchemaError('requires must be an array');
186
+ if (raw.requires.length > 8) {
187
+ throw new SchemaError(`${raw.requires.length} prerequisites is more than a wizard should gate on; 8 is the ceiling`);
188
+ }
189
+ return raw.requires.map((r, i) => {
190
+ const at = `requires[${i}]`;
191
+ if (!r || typeof r !== 'object' || Array.isArray(r)) throw new SchemaError(`${at} must be an object`);
192
+ for (const key of Object.keys(r)) {
193
+ if (!['kind', 'name', 'hint'].includes(key)) {
194
+ throw new SchemaError(`${at}.${key} is not part of a prerequisite — only: kind, name, hint`);
195
+ }
196
+ }
197
+ if (!REQUIRE_KINDS.includes(r.kind)) {
198
+ throw new SchemaError(`${at}.kind "${r.kind}" is not a prerequisite core can check — pick one of: ${REQUIRE_KINDS.join(', ')}`);
199
+ }
200
+ if (typeof r.name !== 'string' || !r.name.trim()) {
201
+ throw new SchemaError(`${at}.name must be the command or path to look for`);
202
+ }
203
+ // A hint is prose shown to a human. It is never run, so it is not
204
+ // constrained to a command shape — but it IS length-capped, because a
205
+ // catalog should not be able to paste a wall of text into the player.
206
+ if (r.hint !== undefined && (typeof r.hint !== 'string' || r.hint.length > 200)) {
207
+ throw new SchemaError(`${at}.hint must be a short string (≤200 chars) — the line a human would type`);
208
+ }
209
+ return { kind: r.kind, name: r.name.trim(), ...(r.hint ? { hint: r.hint } : {}) };
210
+ });
211
+ }
212
+
213
+ /**
214
+ * Which of a schema's prerequisites are NOT satisfied on this machine.
215
+ *
216
+ * Pure and probe-injected (the `needsDevMode`/`detectAgents` idiom), so the
217
+ * whole gate is node-testable without a rhubarb on PATH. Returns the unmet
218
+ * entries in declaration order; an empty array means the engine can run.
219
+ */
220
+ export function unmetRequirements(schema, { hasBin = binOnPath, exists = existsSync } = {}) {
221
+ return (schema?.requires ?? []).filter((r) => (r.kind === 'binary'
222
+ ? !hasBin(r.name)
223
+ : !exists(expandHome(r.name))));
224
+ }
225
+
226
+ /** `~/x` → `$HOME/x`; a model path is the one prerequisite people write that way. */
227
+ const expandHome = (p) => (p.startsWith('~/') ? path.join(homedir(), p.slice(2)) : p);
228
+
229
+ /** Is `bin` on $PATH? The wizard only ever probes bare command names. */
230
+ function binOnPath(bin, env = process.env) {
231
+ const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
232
+ return (env.PATH || '').split(delimiter)
233
+ .some((dir) => dir && exts.some((ext) => existsSync(path.join(dir, bin + ext))));
234
+ }
235
+
236
+ /** One unmet prerequisite as a line for a human, naming the fix when declared. */
237
+ export const requirementLine = (r) => `${r.kind === 'binary' ? 'command' : 'file'} "${r.name}" is missing`
238
+ + (r.hint ? ` — ${r.hint}` : '');
239
+
240
+ /**
241
+ * Where a declared `validate`/`install` path actually resolves: the plugin's
242
+ * own bridge on this machine. One constant, exported, so the code that POSTs
243
+ * answers there (cli/edit.mjs) and the provenance the player shows can never
244
+ * name two different places.
245
+ */
246
+ export const BRIDGE_ADDR = '127.0.0.1:8787';
247
+
248
+ /**
249
+ * The provenance a wizard prompt must carry before a single answer is typed
250
+ * (#232). A field labelled "OpenAI API key" backed by an `install` endpoint is
251
+ * a phishing form when the label is the only thing on screen — the same
252
+ * untrusted party chose the question and the recipient. So the card also says
253
+ * who is asking and where the answer goes, in words the plugin did not write:
254
+ * `qualified` is the entry's registry name (`name@marketplace`, resolved by
255
+ * the author server from the catalog, never read from the schema), and the
256
+ * destination is derived from the *vetted* schema's endpoint declarations.
257
+ * One function so the wording exists once; the player prints both strings
258
+ * verbatim (as text, never markup) and refuses a schema that lacks them.
259
+ */
260
+ export function provenance(schema, qualified) {
261
+ if (typeof qualified !== 'string' || !/^[^@\s]+@[^@\s]+$/.test(qualified)) {
262
+ throw new SchemaError('provenance needs the entry\'s qualified registry name, like "elevenlabs@voices"');
263
+ }
264
+ const endpoints = [...new Set([schema.validate, schema.install].filter(Boolean))];
265
+ return {
266
+ askedBy: `asked by ${qualified}`,
267
+ sentTo: endpoints.length
268
+ ? `answers go to its own bridge on this machine (${endpoints.map((p) => BRIDGE_ADDR + p).join(' and ')}), then ~/.decklight/credentials.json (0600)`
269
+ : 'answers stay on this machine: ~/.decklight/credentials.json (0600)',
270
+ };
271
+ }
272
+
273
+ /** Which of a schema's fields are secrets — the only ones that get hidden. */
274
+ export const secretNames = (schema) =>
275
+ new Set(schema.fields.filter((f) => f.type === 'secret').map((f) => f.name));
276
+
277
+ /**
278
+ * Check answers against the schema before anything is stored.
279
+ *
280
+ * Returns `{ ok, errors }` rather than throwing: a presenter filling in a form
281
+ * should see every field that needs attention at once, not the first one.
282
+ */
283
+ export function checkAnswers(schema, answers) {
284
+ const errors = [];
285
+ const given = answers && typeof answers === 'object' && !Array.isArray(answers) ? answers : {};
286
+ for (const key of Object.keys(given)) {
287
+ if (!schema.fields.some((f) => f.name === key)) errors.push(`${key}: not a field this engine asks for`);
288
+ }
289
+ for (const f of schema.fields) {
290
+ const v = given[f.name];
291
+ const missing = v === undefined || v === null || v === '';
292
+ if (missing) {
293
+ if (f.required) errors.push(`${f.label}: required`);
294
+ continue;
295
+ }
296
+ if (f.type === 'boolean' ? typeof v !== 'boolean' : typeof v !== 'string') {
297
+ errors.push(`${f.label}: expected ${f.type === 'boolean' ? 'true or false' : 'text'}`);
298
+ } else if (f.type === 'choice' && !f.options.includes(v)) {
299
+ errors.push(`${f.label}: not one of ${f.options.join(', ')}`);
300
+ }
301
+ }
302
+ return { ok: !errors.length, errors };
303
+ }
304
+
305
+ /** Everything stored, or `{}` — a missing file is first run, not an error. */
306
+ export function loadCredentials(home = configHome()) {
307
+ try { return JSON.parse(readFileSync(credentialsPath(home), 'utf8')); }
308
+ catch { return {}; }
309
+ }
310
+
311
+ /**
312
+ * Store one engine's answers, `0600`.
313
+ *
314
+ * The mode is set on every write, not only on create: a file that was
315
+ * world-readable before this call must not stay world-readable after it, and
316
+ * `writeFileSync`'s mode argument is ignored for a path that already exists.
317
+ */
318
+ export function saveCredentials(engine, answers, home = configHome()) {
319
+ const file = credentialsPath(home);
320
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
321
+ const all = loadCredentials(home);
322
+ all[engine] = { ...answers };
323
+ writeFileSync(file, `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 });
324
+ chmodSync(file, 0o600);
325
+ return file;
326
+ }
327
+
328
+ /** Forget an engine's answers. Returns whether there was anything to forget. */
329
+ export function forgetCredentials(engine, home = configHome()) {
330
+ if (!existsSync(credentialsPath(home))) return false;
331
+ const all = loadCredentials(home);
332
+ if (!(engine in all)) return false;
333
+ delete all[engine];
334
+ writeFileSync(credentialsPath(home), `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 });
335
+ chmodSync(credentialsPath(home), 0o600);
336
+ return true;
337
+ }
338
+
339
+ /** The file's mode, for the test that this is actually `0600` on disk. */
340
+ export const credentialsMode = (home = configHome()) =>
341
+ existsSync(credentialsPath(home)) ? statSync(credentialsPath(home)).mode & 0o777 : null;
342
+
343
+ /**
344
+ * A stored answer set with every secret replaced by its shape, never its value.
345
+ *
346
+ * The one function anything that logs, prints, pings or reports must go
347
+ * through. Redacting at each call site is how a key ends up in a debug panel
348
+ * two features later, so there is exactly one place that decides.
349
+ */
350
+ export function redactAnswers(schema, answers) {
351
+ const secrets = secretNames(schema);
352
+ const out = {};
353
+ for (const [k, v] of Object.entries(answers ?? {})) {
354
+ out[k] = secrets.has(k) ? (v ? `set (${String(v).length} chars)` : 'unset') : v;
355
+ }
356
+ return out;
357
+ }
358
+
359
+ /**
360
+ * The two failures this flow is allowed to have, and they are not the same one.
361
+ *
362
+ * "Couldn't reach the marketplace" and "that key didn't authenticate" are
363
+ * different problems with different fixes, and a wizard that prints one line for
364
+ * both sends people to check their network when their key is wrong. `ENGINES#WIZARD`
365
+ * names them separately on purpose, so the shape is a discriminated result
366
+ * rather than a boolean.
367
+ */
368
+ export const UNREACHABLE = 'unreachable';
369
+ export const REJECTED = 'rejected';
370
+ export const CONFIGURED = 'configured';
371
+ /**
372
+ * The THIRD failure (ENGINES#LIPSYNC): the answers may be perfect and every
373
+ * service reachable, and the engine still cannot run because something is not
374
+ * on this machine. TTS made two states look like enough — "could not reach
375
+ * it" and "that key was refused" — because a key is the only thing a TTS
376
+ * provider ever needs. Lipsync has a binary, a python checkout and model
377
+ * weights, and telling someone their rhubarb-shaped problem is a credential
378
+ * problem sends them to fix the one thing that was already right.
379
+ */
380
+ export const PREREQUISITE = 'prerequisite';
381
+
382
+ /**
383
+ * Install-and-configure as one flow.
384
+ *
385
+ * `fetchSchema` and `validateAnswers` are injected: this module has no business
386
+ * knowing how a catalog is read or how a provider checks a key, and the tests
387
+ * have no business needing a network or a real key to exercise the branching.
388
+ */
389
+ export async function configureEngine(engine, answers, {
390
+ home = configHome(), fetchSchema, validateAnswers, save = saveCredentials, probes,
391
+ } = {}) {
392
+ let schema;
393
+ try {
394
+ schema = validateSchema(await fetchSchema(engine));
395
+ } catch (e) {
396
+ if (e instanceof SchemaError) {
397
+ // A malformed schema is the plugin's fault, not the network's, and must
398
+ // not be reported as an outage the presenter could wait out.
399
+ return { state: REJECTED, reason: `${engine} declares a wizard core cannot render: ${e.message}` };
400
+ }
401
+ return { state: UNREACHABLE, reason: `could not reach the marketplace for "${engine}": ${e.message}` };
402
+ }
403
+
404
+ // BEFORE the answers are checked, before the network is touched and before
405
+ // anything is written: an engine that cannot run here must not have a
406
+ // credential collected for it, and must not be told its key was the problem.
407
+ const unmet = unmetRequirements(schema, probes);
408
+ if (unmet.length) {
409
+ return {
410
+ state: PREREQUISITE,
411
+ schema,
412
+ unmet,
413
+ reason: `${schema.title} needs something this machine does not have: ${unmet.map(requirementLine).join('; ')}`,
414
+ };
415
+ }
416
+
417
+ const checked = checkAnswers(schema, answers);
418
+ if (!checked.ok) return { state: REJECTED, schema, reason: checked.errors.join('; ') };
419
+
420
+ if (schema.validate && validateAnswers) {
421
+ let ok;
422
+ try {
423
+ ok = await validateAnswers(schema, answers);
424
+ } catch (e) {
425
+ return { state: UNREACHABLE, schema, reason: `could not reach ${schema.title} to check the answers: ${e.message}` };
426
+ }
427
+ if (!ok) return { state: REJECTED, schema, reason: `${schema.title} did not accept those answers` };
428
+ }
429
+
430
+ const file = save(engine, answers, home);
431
+ return { state: CONFIGURED, schema, file, stored: redactAnswers(schema, answers) };
432
+ }
package/cli/zip.mjs ADDED
@@ -0,0 +1,121 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // A minimal ZIP writer, because two small text files do not justify a
5
+ // dependency — decklight already owns an ANSI parser on the same reasoning.
6
+ // Enough of the format to produce an archive every unzip reads: local headers,
7
+ // a central directory, and the end record. No zip64, no encryption, no
8
+ // directory entries (the paths carry the folder).
9
+ //
10
+ // Timestamps are pinned to the ZIP epoch (1980-01-01) rather than "now", so
11
+ // packing the same content twice produces the same bytes. A build artifact
12
+ // that changes every time you build it is one you cannot diff or checksum.
13
+
14
+ import { deflateRawSync } from 'node:zlib';
15
+
16
+ // CRC-32 by hand: node:zlib grew a crc32 export only in 20.15, and
17
+ // package.json promises Node 20 — testing what we promise means not reaching
18
+ // for something a valid Node 20 might not have.
19
+ const TABLE = (() => {
20
+ const t = new Uint32Array(256);
21
+ for (let i = 0; i < 256; i++) {
22
+ let c = i;
23
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
24
+ t[i] = c >>> 0;
25
+ }
26
+ return t;
27
+ })();
28
+
29
+ export function crc32(buf) {
30
+ let c = 0xffffffff;
31
+ for (let i = 0; i < buf.length; i++) c = TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
32
+ return (c ^ 0xffffffff) >>> 0;
33
+ }
34
+
35
+ const DOS_DATE = 0x0021; // 1980-01-01: day 1, month 1, year 0 → (1<<5)|1
36
+ const DOS_TIME = 0;
37
+
38
+ /**
39
+ * Build a ZIP archive from `[{ name, data }]`, where data is a string or
40
+ * Buffer. Each entry is deflated only when that actually makes it smaller —
41
+ * a stored entry beats a "compressed" one that grew.
42
+ *
43
+ * `prefix` is how many bytes will sit in front of this archive in the file it
44
+ * ends up in. Every offset a ZIP records is measured from the start of the
45
+ * FILE, not the archive, so an archive appended to something else has to be
46
+ * written knowing that — which is exactly how self-extracting archives have
47
+ * always worked, and how the `.decklight` container (DECK_FILE) puts a playable
48
+ * deck in front of its own signature.
49
+ */
50
+ export function zipSync(entries, { prefix = 0, comment = '' } = {}) {
51
+ const local = [];
52
+ const central = [];
53
+ let offset = prefix;
54
+
55
+ for (const { name, data } of entries) {
56
+ const nameBuf = Buffer.from(name, 'utf8');
57
+ const raw = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8');
58
+ const deflated = deflateRawSync(raw);
59
+ const useDeflate = deflated.length < raw.length;
60
+ const body = useDeflate ? deflated : raw;
61
+ const method = useDeflate ? 8 : 0;
62
+ const crc = crc32(raw);
63
+
64
+ const lh = Buffer.alloc(30);
65
+ lh.writeUInt32LE(0x04034b50, 0); // local file header signature
66
+ lh.writeUInt16LE(20, 4); // version needed to extract (2.0)
67
+ lh.writeUInt16LE(0, 6); // general purpose flags
68
+ lh.writeUInt16LE(method, 8);
69
+ lh.writeUInt16LE(DOS_TIME, 10);
70
+ lh.writeUInt16LE(DOS_DATE, 12);
71
+ lh.writeUInt32LE(crc, 14);
72
+ lh.writeUInt32LE(body.length, 18);
73
+ lh.writeUInt32LE(raw.length, 22);
74
+ lh.writeUInt16LE(nameBuf.length, 26);
75
+ lh.writeUInt16LE(0, 28); // extra field length
76
+ local.push(lh, nameBuf, body);
77
+
78
+ const cd = Buffer.alloc(46);
79
+ cd.writeUInt32LE(0x02014b50, 0); // central directory header signature
80
+ cd.writeUInt16LE(20, 4); // version made by
81
+ cd.writeUInt16LE(20, 6); // version needed
82
+ cd.writeUInt16LE(0, 8);
83
+ cd.writeUInt16LE(method, 10);
84
+ cd.writeUInt16LE(DOS_TIME, 12);
85
+ cd.writeUInt16LE(DOS_DATE, 14);
86
+ cd.writeUInt32LE(crc, 16);
87
+ cd.writeUInt32LE(body.length, 20);
88
+ cd.writeUInt32LE(raw.length, 24);
89
+ cd.writeUInt16LE(nameBuf.length, 28);
90
+ cd.writeUInt16LE(0, 30); // extra
91
+ cd.writeUInt16LE(0, 32); // comment
92
+ cd.writeUInt16LE(0, 34); // disk number
93
+ cd.writeUInt16LE(0, 36); // internal attributes
94
+ // external attributes: regular file, 0644. The >>> 0 matters — JS `<<` is
95
+ // signed, so 0o100644 << 16 lands negative and writeUInt32LE throws.
96
+ cd.writeUInt32LE((0o100644 << 16) >>> 0, 38);
97
+ cd.writeUInt32LE(offset, 42);
98
+ central.push(cd, nameBuf);
99
+
100
+ offset += lh.length + nameBuf.length + body.length;
101
+ }
102
+
103
+ const cdBuf = Buffer.concat(central);
104
+ // The archive comment is a real, boring ZIP field — and it is the last thing
105
+ // in the file, which is what makes it the right place to close the HTML
106
+ // comment wrapping a `.decklight` container (DECK_FILE). Trailing bytes AFTER
107
+ // the end record would work for our own reader and make `unzip` complain
108
+ // about garbage; the comment field is where trailing bytes are supposed to go.
109
+ const tail = Buffer.from(comment, 'utf8');
110
+ const end = Buffer.alloc(22);
111
+ end.writeUInt32LE(0x06054b50, 0); // end of central directory
112
+ end.writeUInt16LE(0, 4);
113
+ end.writeUInt16LE(0, 6);
114
+ end.writeUInt16LE(entries.length, 8);
115
+ end.writeUInt16LE(entries.length, 10);
116
+ end.writeUInt32LE(cdBuf.length, 12);
117
+ end.writeUInt32LE(offset, 16);
118
+ end.writeUInt16LE(tail.length, 20); // archive comment length
119
+
120
+ return Buffer.concat([...local, cdBuf, end, tail]);
121
+ }