decklight 0.5.0 → 0.7.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 (53) hide show
  1. package/README.md +20 -9
  2. package/SPEC.md +239 -17
  3. package/cli/agents.mjs +97 -2
  4. package/cli/banner.mjs +125 -0
  5. package/cli/bundle.mjs +14 -4
  6. package/cli/{rec.mjs → cast.mjs} +25 -8
  7. package/cli/comments.mjs +389 -0
  8. package/cli/commit-flow.mjs +157 -0
  9. package/cli/commit-message.mjs +475 -0
  10. package/cli/decklight.mjs +95 -25
  11. package/cli/dev.mjs +193 -25
  12. package/cli/edit.mjs +1055 -39
  13. package/cli/git-tree.mjs +87 -0
  14. package/cli/git.mjs +370 -0
  15. package/cli/history.mjs +145 -0
  16. package/cli/init.mjs +199 -7
  17. package/cli/marketplace.mjs +123 -17
  18. package/cli/port-conflict.mjs +228 -22
  19. package/cli/present.mjs +297 -12
  20. package/cli/publish.mjs +15 -40
  21. package/cli/record.mjs +154 -0
  22. package/cli/restore.mjs +120 -4
  23. package/cli/review-remote.mjs +330 -0
  24. package/cli/review-store.mjs +107 -0
  25. package/cli/review-submit.mjs +292 -0
  26. package/cli/review.mjs +361 -0
  27. package/cli/serve.mjs +60 -1
  28. package/cli/skill-content.mjs +12 -1
  29. package/cli/theme.mjs +78 -11
  30. package/cli/units.mjs +2 -2
  31. package/cli/upstream.mjs +256 -0
  32. package/cli/util.mjs +59 -0
  33. package/dist/build-info.json +1 -0
  34. package/dist/decklight.css +534 -3
  35. package/dist/decklight.js +102 -76
  36. package/dist/decklight.js.map +4 -4
  37. package/docs/architecture.svg +7 -0
  38. package/package.json +2 -1
  39. package/tools/args.mjs +20 -0
  40. package/tools/deck-html.mjs +84 -0
  41. package/tools/elevenlabs-tts.mjs +1 -1
  42. package/tools/lipsync-server.mjs +64 -2
  43. package/tools/lipsync.mjs +40 -24
  44. package/tools/local-voice.mjs +170 -16
  45. package/tools/publish-voices.mjs +78 -18
  46. package/tools/recording-impact.mjs +110 -0
  47. package/tools/review-anchor.mjs +180 -0
  48. package/tools/test-impact.mjs +259 -0
  49. package/tools/tts-engines.mjs +211 -12
  50. package/tools/tts-setup.mjs +2 -9
  51. package/tools/video.mjs +56 -12
  52. package/tools/voiceover-server.mjs +262 -11
  53. package/tools/voiceover.mjs +32 -13
package/cli/serve.mjs CHANGED
@@ -80,6 +80,30 @@ export function allowEditRequest(req) {
80
80
  return isLoopbackOrigin(origin);
81
81
  }
82
82
 
83
+ /**
84
+ * A STRICTER gate: this exact origin, and nothing else.
85
+ *
86
+ * `allowEditRequest` above admits an absent Origin (curl, a probe) and the
87
+ * literal `null` — and `null` is what a SANDBOXED IFRAME sends. That is exactly
88
+ * what presenter chrome runs in (`injectChrome` mounts every plugin in one), so
89
+ * a gate that admits it would let a plugin reach an action the presenter never
90
+ * asked for. Pinning the port refuses another loopback dev server's page too,
91
+ * which the edit gate admits by design.
92
+ *
93
+ * Used by the one route in `present` that ACTS. The looser gate is right for
94
+ * `/edit/*`, where the server exists to be written to and a curl from the
95
+ * author's own machine is a feature; it is wrong here.
96
+ */
97
+ export function isOwnOrigin(req, port) {
98
+ const origin = req.headers?.origin;
99
+ if (typeof origin !== 'string' || !origin) return false;
100
+ return [
101
+ `http://127.0.0.1:${port}`,
102
+ `http://localhost:${port}`,
103
+ `http://[::1]:${port}`,
104
+ ].includes(origin);
105
+ }
106
+
83
107
  /**
84
108
  * Pure request classifier: may this request be answered at all?
85
109
  * Loopback: always. Off-loopback: only /remote/* paths carrying the per-run
@@ -183,7 +207,42 @@ export function staticFiles(root, { index = '/index.html', html: rewriteHtml = n
183
207
  }
184
208
  let body = readFileSync(file);
185
209
  if (rewriteHtml && type === MIME['.html']) body = Buffer.from(rewriteHtml(body.toString('utf8'), file), 'utf8');
186
- res.writeHead(200, { 'content-type': type ?? 'application/octet-stream', 'cache-control': 'no-cache' });
210
+ const headers = {
211
+ 'content-type': type ?? 'application/octet-stream',
212
+ 'cache-control': 'no-cache',
213
+ // Media elements are the reason both of these exist. A browser asks for
214
+ // audio and video with `Range: bytes=…`, and a server that answers 200,
215
+ // chunked, with no Content-Length gives the media stack a stream of
216
+ // unknown size: duration reads Infinity, seeking is impossible, and
217
+ // real Chrome — stricter than a bare fetch — can refuse the source
218
+ // outright, which surfaced as "no narration for slide 1" pointing at a
219
+ // file that was sitting right there.
220
+ 'accept-ranges': 'bytes',
221
+ 'content-length': body.length,
222
+ };
223
+ const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range ?? '');
224
+ if (range && (range[1] || range[2])) {
225
+ // One range, which is all a media element ever sends. Malformed or
226
+ // multipart ranges fall through to the plain 200 — RFC 7233 allows
227
+ // ignoring Range entirely, so partial support must never invent a 416
228
+ // for a request a full response satisfies.
229
+ const start = range[1] ? Number(range[1]) : Math.max(0, body.length - Number(range[2]));
230
+ const end = range[1] && range[2] ? Math.min(Number(range[2]), body.length - 1) : body.length - 1;
231
+ if (start <= end && start < body.length) {
232
+ const slice = body.subarray(start, end + 1);
233
+ res.writeHead(206, {
234
+ ...headers,
235
+ 'content-length': slice.length,
236
+ 'content-range': `bytes ${start}-${end}/${body.length}`,
237
+ });
238
+ res.end(slice);
239
+ return true;
240
+ }
241
+ res.writeHead(416, { 'content-range': `bytes */${body.length}` });
242
+ res.end();
243
+ return true;
244
+ }
245
+ res.writeHead(200, headers);
187
246
  res.end(body);
188
247
  return true;
189
248
  };
@@ -72,10 +72,12 @@ with a build and notes already wired):
72
72
 
73
73
  **CLI** (\`npx decklight@latest <command>\`, no install needed):
74
74
  - \`decklight author deck.html\` — the whole authoring loop: serve with live reload; **E** in the browser edits speaker notes back into the file
75
- - \`decklight rec script.term.yaml\` — record a truthful terminal cast in a real PTY, for \`<div class="terminal">\`
75
+ - \`decklight cast script.term.yaml\` — record a truthful terminal cast in a real PTY, for \`<div class="terminal">\` (this records a TERMINAL; \`decklight record\` records the author's voice)
76
76
  - \`decklight bundle deck.html --themes all\` — flatten into one self-contained file to hand off or publish
77
77
  - \`decklight pdf deck.html\` — render every slide to a PDF, and report the ones that overflow
78
78
  - \`decklight tts\` — live voice bridge so the deck can narrate itself on the fly
79
+ - \`decklight record deck.html\` — record the narration in the author's OWN voice: the deck shows one \`⟨CLICK⟩\` beat at a time and \`→\` ends it, writing \`slide-NN-KK.wav\` per beat so the recording paces the builds (play it back with \`narration: { files: 'voiceover', ext: 'wav', segments: true }\`)
80
+ - \`decklight review deck.html\` / \`decklight comments deck.html\` — reviewer comments on slides, stored append-only in \`<deck>.review.jsonl\` and carried by git; a comment records the slide's title and a fingerprint of its text, so it finds its slide again after the deck moves and says so when the slide changed or is gone; \`decklight review submit deck.html\` pushes the review to a \`review/<you>-<date>\` branch (one file, never the reviewer's own commits; \`--pr\` opens the pull request), and the author hears about waiting reviews at \`decklight author\` startup, in the M overlay, and via \`decklight comments deck.html --incoming\`
79
81
  - \`decklight skills\` — regenerate this skill after upgrading Decklight
80
82
 
81
83
  **Render the deck before you call a slide done.** Content that exceeds a slide
@@ -126,6 +128,15 @@ nothing changed, so an extra call is harmless. If the port is not listening
126
128
  there is no authoring server: skip it silently and carry on, never start one
127
129
  yourself. This is what makes a history someone can read afterwards, instead
128
130
  of a wall of identical timer commits.
131
+
132
+ **That history is readable, and it is how a bad edit is undone.** \`decklight
133
+ history deck.html\` lists every commit that touched the deck and marks the ones
134
+ that exist only on this machine; \`decklight restore deck.html <hash>\` puts the
135
+ deck back — written as a NEW commit, never a rewrite, so restoring is always
136
+ safe to try. In the deck itself the same history is \`H\` (a live preview of
137
+ every version; \`⏎\` restores after asking). Prefer restore over hand-reverting
138
+ your own edits: it is exact, and it keeps the record honest about what
139
+ happened.
129
140
  `;
130
141
  }
131
142
 
package/cli/theme.mjs CHANGED
@@ -19,10 +19,11 @@
19
19
  // exactly what an older theme is missing.
20
20
 
21
21
  import { existsSync, readFileSync, writeFileSync } from 'node:fs';
22
+ import { escapeHtml } from '../tools/escape.mjs';
22
23
  import path, { resolve } from 'node:path';
23
24
  import { argReader, isMain } from '../tools/args.mjs';
24
25
  import { validateTheme, themeNameFrom, validThemeName, REQUIRED } from '../tools/theme-check.mjs';
25
- import { checkoutPath, classifySource, configHome, MarketplaceError } from './marketplace.mjs';
26
+ import { checkoutPath, classifySource, configHome, MarketplaceError, loadRegistry, loadCatalog, resolveEntry} from './marketplace.mjs';
26
27
 
27
28
  const USAGE = `usage: decklight theme <check|add> …
28
29
 
@@ -42,13 +43,37 @@ const USAGE = `usage: decklight theme <check|add> …
42
43
  a theme that does not pass is not installed — a deck cannot be made to carry
43
44
  something the shipped set would not be allowed to contain`;
44
45
 
45
- /** The <style> block an installed theme becomes, marked so the runtime groups it. */
46
- export function themeStyleBlock(name, css) {
46
+ /**
47
+ * The <style> block an installed theme becomes, marked so the runtime groups it.
48
+ *
49
+ * PROVENANCE TRAVELS WITH THE DECK, and it has to: a bundled deck opened on
50
+ * another machine has no `~/.decklight/marketplaces.json` to look a catalog up
51
+ * in, and the theme picker still has to draw a heading. So whatever the picker
52
+ * shows is written here, at install time, or it is not available at all.
53
+ *
54
+ * Two attributes, because identity and label are different things.
55
+ * `data-theme-marketplace` is the manifest's own kebab `name` — stable, and
56
+ * what a later dedup or upgrade would key on. `data-theme-source` is the
57
+ * catalog's human title, written only when it supplied one, and never derived
58
+ * from the name: stripping a prefix off `decklight-confluent` to guess
59
+ * "Confluent" breaks the moment a catalog is called `acme-themes`, and it puts
60
+ * decklight in the business of inventing names for other people's catalogs.
61
+ *
62
+ * `data-theme-added` stays on every installed block. Old decks keep working,
63
+ * and it remains what the runtime falls back to — the "never decklight's to
64
+ * begin with" distinction it was added for is untouched.
65
+ */
66
+ export function themeStyleBlock(name, css, { marketplace = null, title = null } = {}) {
47
67
  // </style> inside a theme's own comment would end the block early. Themes
48
68
  // are CSS and have no business containing one, but a downloaded file is
49
69
  // somebody else's, and "somebody else's" is exactly when to check.
50
70
  const safe = css.replace(/<\/(style)/gi, '<\\/$1');
51
- return `<style data-theme="${name}" data-theme-added media="not all">\n${safe.trim()}\n</style>`;
71
+ // Both values come out of a manifest somebody else wrote, and they land in a
72
+ // double-quoted attribute — so they are escaped, not trusted. A title of
73
+ // `"><script>` is the whole reason this is not a template hole.
74
+ const from = marketplace ? ` data-theme-marketplace="${escapeHtml(marketplace)}"` : '';
75
+ const label = title ? ` data-theme-source="${escapeHtml(title)}"` : '';
76
+ return `<style data-theme="${escapeHtml(name)}" data-theme-added${from}${label} media="not all">\n${safe.trim()}\n</style>`;
52
77
  }
53
78
 
54
79
  /** Where an existing block for this name starts and ends, or null. */
@@ -64,8 +89,8 @@ export function findThemeBlock(html, name) {
64
89
  * last in <head> so an active added theme wins the cascade over the deck's
65
90
  * link or inline base theme.
66
91
  */
67
- export function installTheme(html, name, css) {
68
- const block = themeStyleBlock(name, css);
92
+ export function installTheme(html, name, css, provenance = {}) {
93
+ const block = themeStyleBlock(name, css, provenance);
69
94
  const existing = findThemeBlock(html, name);
70
95
  if (existing) {
71
96
  return { html: html.slice(0, existing.start) + block + html.slice(existing.end), replaced: true };
@@ -172,17 +197,59 @@ async function addMain(args) {
172
197
  const [source, deck] = positional;
173
198
  if (!source || !deck) { console.error(`decklight theme add: needs a theme and a deck\n\n${USAGE}`); return 1; }
174
199
 
175
- const name = opt('--name') ?? themeNameFrom(source);
200
+ const deckPath = resolve(deck);
201
+ if (!existsSync(deckPath)) { console.error(`decklight theme add: no such deck: ${deck}`); return 1; }
202
+
203
+ // A marketplace ref (`confluent@decklight-confluent`, or a bare entry name)
204
+ // resolves through the registry; a file or a URL is taken as it was typed.
205
+ // Without this the CLI could not install from a catalog at all — Browse was
206
+ // the only door — and provenance would only ever reach half the decks.
207
+ let src = source;
208
+ let provenance = {};
209
+ let entryName = null;
210
+ if (!/^https?:\/\//i.test(source) && !existsSync(resolve(source))) {
211
+ const reg = loadRegistry();
212
+ const catalogs = {};
213
+ for (const mkt of Object.keys(reg.marketplaces ?? {})) {
214
+ const c = loadCatalog(mkt);
215
+ if (c?.ok) catalogs[mkt] = c.manifest;
216
+ }
217
+ let hit;
218
+ try { hit = resolveEntry(source, catalogs); }
219
+ catch (e) {
220
+ console.error(`decklight theme add: ${e.message}`);
221
+ return 1;
222
+ }
223
+ if (hit.entry.type !== 'theme') {
224
+ console.error(`decklight theme add: ${hit.qualified} is a ${hit.entry.type}, not a theme`);
225
+ return 1;
226
+ }
227
+ try {
228
+ src = resolveSource(hit.entry.source, {
229
+ name: hit.marketplace, source: reg.marketplaces[hit.marketplace]?.source,
230
+ });
231
+ } catch (e) {
232
+ console.error(`decklight theme add: ${e.message}`);
233
+ return 1;
234
+ }
235
+ // The catalog's own title, captured HERE because the deck may be opened on
236
+ // a machine where this marketplace was never registered.
237
+ provenance = { marketplace: hit.marketplace, title: catalogs[hit.marketplace]?.title?.trim() || null };
238
+ entryName = hit.entry.name;
239
+ }
240
+
241
+ // The name is settled AFTER resolution: `confluent@decklight-confluent` is a
242
+ // reference, not a filename, and deriving a theme name from it would refuse
243
+ // every marketplace install for containing an `@`.
244
+ const name = opt('--name') ?? entryName ?? themeNameFrom(source);
176
245
  if (!validThemeName(name)) {
177
246
  console.error(`decklight theme add: "${name}" is not a usable theme name`);
178
247
  console.error(' the runtime only resolves names matching [A-Za-z0-9_-]+ — pass --name to choose one');
179
248
  return 1;
180
249
  }
181
- const deckPath = resolve(deck);
182
- if (!existsSync(deckPath)) { console.error(`decklight theme add: no such deck: ${deck}`); return 1; }
183
250
 
184
251
  let css;
185
- try { css = await fetchTheme(source); } catch (e) { console.error(`decklight theme add: ${e.message}`); return 1; }
252
+ try { css = await fetchTheme(src); } catch (e) { console.error(`decklight theme add: ${e.message}`); return 1; }
186
253
 
187
254
  const result = validateTheme(css);
188
255
  for (const line of reportLines(name, result)) console.log(line);
@@ -192,7 +259,7 @@ async function addMain(args) {
192
259
  }
193
260
 
194
261
  const html = readFileSync(deckPath, 'utf8');
195
- const { html: next, replaced } = installTheme(html, name, css);
262
+ const { html: next, replaced } = installTheme(html, name, css, provenance);
196
263
  if (next === null) { console.error(`decklight theme add: ${deck} has no </head> to install into`); return 1; }
197
264
 
198
265
  if (args.includes('--dry-run')) {
package/cli/units.mjs CHANGED
@@ -111,7 +111,7 @@ export const UNIT_TYPES = {
111
111
  dir: 'engines',
112
112
  single: 'mjs',
113
113
  label: 'speech engine',
114
- use: 'decklight tts --engine <name>, then the N picker',
114
+ use: 'decklight tts --engine <name>, then the V picker',
115
115
  example: 'azure-tts',
116
116
  required: ['apiVersion', 'capability'],
117
117
  pinned: true,
@@ -144,7 +144,7 @@ export const UNIT_TYPES = {
144
144
  single: 'json',
145
145
  reference: true,
146
146
  label: 'voice',
147
- use: 'the N picker, author mode',
147
+ use: 'the V picker, author mode',
148
148
  example: 'narrator-anna',
149
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
150
  required: ['engine', 'voiceId'],
@@ -0,0 +1,256 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * `present`'s upstream check — SPEC PRESENTING (`PRESENT#UPSTREAM`).
6
+ *
7
+ * A deck cloned before a talk goes stale silently: `present` reads the file
8
+ * once and serves those bytes, so a fix the author pushed an hour ago is
9
+ * invisible. This asks the upstream, and — with `--upstream-pull` — lets the
10
+ * deck fast-forward to it.
11
+ *
12
+ * ## What makes this safe, in one place
13
+ *
14
+ * The feature is UNREACHABLE for the deck the rest of `present` is written
15
+ * against. A deck you were emailed is a single file with no repository, no
16
+ * remote and no upstream, so `resolveUpstream` returns `no-repo` and nothing —
17
+ * not the routes, not the timer — is ever registered.
18
+ *
19
+ * The gate that matters most is `untracked`, and it is not obvious: anyone
20
+ * whose $HOME is a git repository (yadm, chezmoi, a dotfiles clone) has every
21
+ * deck in ~/Downloads "inside a clone". Requiring the deck to be a file that
22
+ * repository actually VERSIONS is the honest reading of "the deck lives in a
23
+ * git clone" — without it, presenting a downloaded deck would offer to
24
+ * fast-forward somebody's home directory.
25
+ *
26
+ * ## Never a hang, never a false pass
27
+ *
28
+ * Every git call is async (`execFile`): a synchronous child would block the
29
+ * event loop of the server serving the talk, and a 15-second fetch would be a
30
+ * 15-second black slide. Every one runs with prompts disabled — the env from
31
+ * cli/git.mjs, which covers ssh as well as https — and a timeout, so an
32
+ * unreachable remote is an answer rather than a stall.
33
+ *
34
+ * And a fetch that FAILED is never reported as up to date. The comparison
35
+ * against a stale remote-tracking ref is simply not made; the state is the
36
+ * failure, `checkedAt` stays null, and "unchecked" is its own answer — the same
37
+ * rule signature verification already follows (SPEC PRESENTING: when it cannot
38
+ * be done here, that is said as its own state and never as a pass).
39
+ */
40
+
41
+ import { execFile } from 'node:child_process';
42
+ import { realpathSync } from 'node:fs';
43
+ import { homedir } from 'node:os';
44
+ import { basename, dirname, parse, resolve } from 'node:path';
45
+ import { classifyRemoteError, noPromptEnv, oneline, parseAheadBehind } from './git.mjs';
46
+
47
+ /** Every answer this can give. Frozen so a typo is a crash, not a silent miss. */
48
+ export const UPSTREAM_STATES = Object.freeze([
49
+ 'no-repo', 'untracked', 'detached', 'no-upstream',
50
+ 'up-to-date', 'behind', 'ahead', 'diverged',
51
+ 'offline', 'no-credential', 'timeout', 'error', 'disabled',
52
+ ]);
53
+
54
+ /** git, asynchronously, with prompts off and a bound. Never throws. */
55
+ export function runGit(args, { cwd, timeoutMs = 8000, exec = execFile } = {}) {
56
+ return new Promise((done) => {
57
+ exec('git', args, { cwd, encoding: 'utf8', timeout: timeoutMs, env: noPromptEnv() },
58
+ (err, stdout, stderr) => done({
59
+ ok: !err, stdout: (stdout ?? '').trim(), stderr: (stderr ?? '').trim(), err,
60
+ }));
61
+ });
62
+ }
63
+
64
+ /**
65
+ * The `-c` overrides every invocation carries.
66
+ *
67
+ * `core.hooksPath` points at a directory that does not exist and is never
68
+ * created: decklight is not the presenter typing `git pull`, and it must not
69
+ * run arbitrary local scripts in the middle of a talk. The rest keep a
70
+ * background maintenance task, a filesystem monitor or a submodule walk from
71
+ * starting behind a slide.
72
+ */
73
+ export const SAFE_CONFIG = Object.freeze([
74
+ '-c', 'gc.auto=0', '-c', 'maintenance.auto=false',
75
+ '-c', 'core.fsmonitor=false', '-c', 'submodule.recurse=false',
76
+ '-c', 'credential.interactive=false',
77
+ ]);
78
+
79
+ /** Why a git failure happened, as one of this module's states. */
80
+ export function classifyFailure({ err, stderr }) {
81
+ if (err?.killed || err?.signal) return 'timeout';
82
+ const kind = classifyRemoteError({ stderr, message: err?.message });
83
+ if (kind === 'denied') return 'no-credential';
84
+ if (kind === 'offline') return 'offline';
85
+ return 'error';
86
+ }
87
+
88
+ /**
89
+ * Is the check even a question here? Resolved once, before anything is served.
90
+ *
91
+ * Returns `{ state, repoRoot, branch, upstream }`. Anything but `ok` means the
92
+ * feature is absent — no routes, no timer, no line in the label.
93
+ */
94
+ export async function resolveUpstream(deckPath, { run = runGit, home = homedir() } = {}) {
95
+ // REALPATH FIRST. `git rev-parse --show-toplevel` answers with symlinks
96
+ // resolved, and on macOS /tmp and /var are symlinks — so comparing it against
97
+ // an unresolved deck path makes `relative()` produce a ../../.. escape, the
98
+ // tracked check fails, and the feature silently never activates for anyone
99
+ // whose deck lives under a symlinked path. It fails CLOSED, which is why it
100
+ // would have gone unnoticed rather than gone wrong.
101
+ let full;
102
+ try { full = realpathSync(resolve(deckPath)); } catch { full = resolve(deckPath); }
103
+ const cwd = dirname(full);
104
+ const no = (state) => ({ state, repoRoot: null, branch: null, upstream: null });
105
+
106
+ const top = await run(['rev-parse', '--show-toplevel'], { cwd });
107
+ if (!top.ok || !top.stdout) return no('no-repo');
108
+ // resolve() because git answers in FORWARD SLASHES on every platform,
109
+ // including Windows — so `C:/Users/x` has to become `C:\Users\x` before it
110
+ // can be compared with a path Node produced, or the tracked check below
111
+ // compares two spellings of the same directory and refuses every deck.
112
+ const repoRoot = resolve(top.stdout);
113
+
114
+ // A repository whose root is $HOME or a filesystem root is somebody's whole
115
+ // machine, not a deck's home. Belt and braces behind the tracked check below.
116
+ if (repoRoot === resolve(home) || repoRoot === parse(repoRoot).root) return no('untracked');
117
+
118
+ // THE GATE THAT MATTERS: the deck must be a file this repository versions.
119
+ // Without it, every deck in ~/Downloads is "inside a clone" for anyone whose
120
+ // home directory is one.
121
+ // Asked from the DECK'S OWN DIRECTORY, by basename — git resolves it against
122
+ // the repository itself. Computing the relative path here instead means
123
+ // comparing two absolute paths, and two absolute paths for the same file
124
+ // disagree more often than they look: git answers in forward slashes on every
125
+ // platform, macOS resolves /tmp and /var through symlinks, and a Windows temp
126
+ // directory is an 8.3 short name (RUNNER~1) that realpath may or may not
127
+ // expand. Every one of those made this refuse a deck it should have accepted.
128
+ const tracked = await run(['ls-files', '--error-unmatch', '--', basename(full)], { cwd });
129
+ if (!tracked.ok) return no('untracked');
130
+
131
+ const branch = await run(['symbolic-ref', '--quiet', '--short', 'HEAD'], { cwd: repoRoot });
132
+ if (!branch.ok || !branch.stdout) return { ...no('detached'), repoRoot };
133
+
134
+ const up = await run(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'], { cwd: repoRoot });
135
+ if (!up.ok || !up.stdout) return { ...no('no-upstream'), repoRoot, branch: branch.stdout };
136
+
137
+ return { state: 'ok', repoRoot, branch: branch.stdout, upstream: up.stdout };
138
+ }
139
+
140
+ /**
141
+ * One check cycle: fetch, then compare. Returns the status the routes serve.
142
+ *
143
+ * The fetch carries no refspec and no remote name — `git fetch` with no
144
+ * arguments fetches whatever the current branch tracks, and `@{upstream}` is a
145
+ * constant git resolves itself. NOTHING derived from anything reaches a git
146
+ * argument, which is a property worth stating because it is the one that makes
147
+ * the route safe by construction rather than by validation.
148
+ */
149
+ export async function checkUpstream(ctx, { run = runGit, now = () => Date.now() } = {}) {
150
+ const { repoRoot, branch, upstream } = ctx;
151
+ const base = { branch, upstream, behind: 0, ahead: 0, dirty: false, commits: [], checkedAt: null };
152
+
153
+ const fetched = await run([...SAFE_CONFIG, 'fetch', '--quiet', '--no-tags', '--no-recurse-submodules'],
154
+ { cwd: repoRoot, timeoutMs: 15000 });
155
+ if (!fetched.ok) {
156
+ // The comparison against a STALE ref is deliberately not made: "I could not
157
+ // ask" must never come out as "up to date".
158
+ const state = classifyFailure(fetched);
159
+ return { ...base, state, message: FAILURE_MESSAGE[state](upstream, oneline(fetched.stderr || fetched.err)) };
160
+ }
161
+
162
+ const counts = parseAheadBehind(
163
+ (await run(['rev-list', '--left-right', '--count', '@{upstream}...HEAD'], { cwd: repoRoot })).stdout,
164
+ );
165
+ if (!counts) return { ...base, state: 'error', message: 'could not count against ' + upstream };
166
+
167
+ const dirty = Boolean((await run(['status', '--porcelain', '--untracked-files=no'], { cwd: repoRoot })).stdout);
168
+ const log = await run(['log', '--format=%h\x01%s', '-n', '5', 'HEAD..@{upstream}'], { cwd: repoRoot });
169
+ const commits = log.ok && log.stdout
170
+ ? log.stdout.split('\n').map((l) => { const [hash, subject] = l.split('\x01'); return { hash, subject }; })
171
+ : [];
172
+
173
+ const state = counts.behind && counts.ahead ? 'diverged'
174
+ : counts.behind ? 'behind'
175
+ : counts.ahead ? 'ahead'
176
+ : 'up-to-date';
177
+ return { ...base, ...counts, dirty, commits, state, checkedAt: now(), message: describe(state, { ...counts, upstream, dirty }) };
178
+ }
179
+
180
+ const FAILURE_MESSAGE = {
181
+ offline: (up) => `could not reach ${up.split('/')[0]} — unchecked, NOT up to date`,
182
+ 'no-credential': (up) => `${up.split('/')[0]} refused an anonymous fetch — unchecked, NOT up to date`,
183
+ timeout: (up) => `${up.split('/')[0]} did not answer in 15s — unchecked, not up to date`,
184
+ error: (up, why) => `git said: ${why}`,
185
+ };
186
+
187
+ /** The sentence for a state that was actually determined. */
188
+ export function describe(state, { behind = 0, ahead = 0, upstream = '', dirty = false } = {}) {
189
+ const s = {
190
+ 'up-to-date': `up to date with ${upstream}`,
191
+ behind: `${behind} commit${behind === 1 ? '' : 's'} behind ${upstream}`,
192
+ ahead: `${ahead} commit${ahead === 1 ? '' : 's'} ahead of ${upstream} — nothing to pull`,
193
+ diverged: `diverged from ${upstream} (${ahead} ahead, ${behind} behind) — a fast-forward is not possible`,
194
+ }[state] ?? state;
195
+ return dirty && state === 'behind' ? `${s} · uncommitted changes here` : s;
196
+ }
197
+
198
+ /**
199
+ * May this status be pulled? Pure, and re-asked against a FRESH check
200
+ * immediately before the merge rather than trusted from the cached one.
201
+ */
202
+ export function canPull(status, { offered = false } = {}) {
203
+ if (!offered) return { ok: false, state: 'not-offered', message: 'the update control is off' };
204
+ if (!status) return { ok: false, state: 'error', message: 'nothing has been checked yet' };
205
+ if (status.state === 'up-to-date') return { ok: false, state: 'up-to-date', message: 'already up to date' };
206
+ if (status.state === 'ahead') return { ok: false, state: 'ahead', message: 'nothing to pull' };
207
+ if (status.state === 'diverged') {
208
+ return { ok: false, state: 'diverged', message: 'diverged — a fast-forward is not possible' };
209
+ }
210
+ if (status.state !== 'behind') {
211
+ return { ok: false, state: status.state, message: status.message ?? 'not in a state that can be pulled' };
212
+ }
213
+ // A checkout over uncommitted work is how somebody loses an edit they made in
214
+ // the ten minutes before a talk.
215
+ if (status.dirty) {
216
+ return { ok: false, state: 'dirty', message: 'uncommitted changes here — commit or stash them first' };
217
+ }
218
+ return { ok: true, state: 'behind' };
219
+ }
220
+
221
+ /**
222
+ * Why this run is not checking at all, as a reason string, or false.
223
+ *
224
+ * The `suppressed()` shape from cli/update-check.mjs, so a test reads like the
225
+ * rule. Deliberately NOT suppressed on a non-TTY: the answer here reaches a
226
+ * route as well as a terminal, and gating on a TTY would make the feature
227
+ * untestable and invisible to the deck.
228
+ */
229
+ export function upstreamSuppressed({ args = [], env = process.env } = {}) {
230
+ if (args.includes('--no-upstream')) return '--no-upstream';
231
+ if (args.includes('--check')) return '--check';
232
+ if (env.DECKLIGHT_NO_UPSTREAM_CHECK) return 'DECKLIGHT_NO_UPSTREAM_CHECK is set';
233
+ if (env.CI) return 'CI';
234
+ return false;
235
+ }
236
+
237
+ /**
238
+ * How often to look, or 0 for "only when asked".
239
+ *
240
+ * `0` turns off the TIMER, not the feature: the manual check and the update
241
+ * control stay, which is what somebody who does not want background network
242
+ * during a talk actually wants. `--no-upstream` is how you turn it all off, and
243
+ * the two being different is the point.
244
+ *
245
+ * A typo falls back to the default rather than disabling anything —
246
+ * resolveGitMode's rule: a mistyped flag must not silently cost you the thing
247
+ * you were configuring.
248
+ */
249
+ export function resolveInterval(args = []) {
250
+ const i = args.indexOf('--upstream-every');
251
+ if (i < 0) return 10 * 60_000;
252
+ const raw = Number(args[i + 1]);
253
+ if (raw === 0) return 0;
254
+ const minutes = Number.isFinite(raw) && raw > 0 ? raw : 10;
255
+ return Math.max(60_000, minutes * 60_000);
256
+ }
package/cli/util.mjs CHANGED
@@ -87,4 +87,63 @@ export async function runMain(cmd, fn) {
87
87
  // the first time a deck highlights language-html, which turned the old
88
88
  // escape into a lazy SyntaxError. The unicode escape is valid in strings,
89
89
  // templates, JSON, and regexes with or without the u flag.
90
+ /**
91
+ * The two recorders take inputs as different as their outputs — `cast` a YAML
92
+ * command script, `record` a deck — and the names invite the mix-up: they
93
+ * differ by two letters and both mean "record".
94
+ *
95
+ * Getting it wrong used to be silent in the direction that mattered.
96
+ * `decklight record demo.term.yaml` started a server, printed a URL and opened
97
+ * a browser on a YAML file: no error anywhere, just a page that would never be
98
+ * a deck. (The other way at least failed, if unhelpfully — `script has no
99
+ * steps`, said of a perfectly good deck.)
100
+ *
101
+ * Returns the refusal, or null when the file is the right kind or a kind
102
+ * neither command claims — an unusual extension is not evidence of a mistake,
103
+ * and refusing one would break a deck somebody named `talk.htm5`.
104
+ */
105
+ export function wrongRecorder(cmd, file) {
106
+ const name = String(file ?? '');
107
+ const isScript = /\.ya?ml$/i.test(name);
108
+ const isDeck = /\.(html?|decklight)$/i.test(name);
109
+ const wrong = (cmd === 'record' && isScript) || (cmd === 'cast' && isDeck);
110
+ if (!wrong) return null;
111
+ const what = isScript ? 'a terminal script, not a deck' : 'a deck, not a terminal script';
112
+ // Both are named, because the whole reason this is worth refusing is that
113
+ // either could have been meant — and the suggested line is the one they
114
+ // typed, repaired, so it can be copied rather than reconstructed.
115
+ return `${name} is ${what}.\n`
116
+ + ' decklight cast records a TERMINAL — a YAML command script, replayed in the deck\n'
117
+ + " decklight record records YOU — your voice narrating a deck's notes\n\n"
118
+ + ` did you mean: decklight ${isScript ? 'cast' : 'record'} ${name}`;
119
+ }
120
+
90
121
  export const scriptSafe = (s) => s.replace(/<\/script/gi, '<\\/script').replace(/<!--/g, '<\\u0021--');
122
+
123
+ /**
124
+ * The banner's version, with the build's provenance when the build recorded
125
+ * any (dist/build-info.json, written by build.mjs from `git describe`).
126
+ *
127
+ * `0.6.0+30.gd3307f4` — semver build-metadata syntax, so anything matching
128
+ * "decklight 0.6.0" still matches, and the "+30" answers the question three
129
+ * identically-named sandbox repacks in one afternoon could not: WHICH 0.6.0
130
+ * is this? A release build (zero commits past the tag, clean) shows the
131
+ * plain version — the tag is the whole truth there. A dirty tree says so,
132
+ * because a build nobody can reproduce should not look like one somebody can.
133
+ */
134
+ /**
135
+ * `git describe --tags --long --dirty=.dirty` → {tag, commits, commit, dirty},
136
+ * or null for anything that does not parse (no tags, not a repo, garbage).
137
+ * Shared by build.mjs (stamping a tarball) and the banner's live path (a
138
+ * checkout), so the two can never learn different spellings.
139
+ */
140
+ export function parseDescribe(desc) {
141
+ const m = /^v?(.+)-(\d+)-g([0-9a-f]+?)(\.dirty)?$/.exec(String(desc ?? '').trim());
142
+ return m ? { tag: m[1], commits: Number(m[2]), commit: m[3], dirty: !!m[4] } : null;
143
+ }
144
+
145
+ export function versionLine(version, info) {
146
+ if (!info || !Number.isInteger(info.commits) || !info.commit) return `decklight ${version}`;
147
+ if (info.commits === 0 && !info.dirty) return `decklight ${version}`;
148
+ return `decklight ${version}+${info.commits}.g${info.commit}${info.dirty ? '.dirty' : ''}`;
149
+ }
@@ -0,0 +1 @@
1
+ {"tag":"0.7.0","commits":0,"commit":"6575588","dirty":false}