decklight 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/PLATFORM.md +666 -0
  2. package/README.md +224 -150
  3. package/SPEC.md +732 -886
  4. package/cli/agent-review.mjs +245 -0
  5. package/cli/agents.mjs +25 -5
  6. package/cli/associate.mjs +12 -12
  7. package/cli/audit.mjs +42 -10
  8. package/cli/banner.mjs +41 -17
  9. package/cli/bundle-audio.mjs +183 -0
  10. package/cli/bundle.mjs +383 -31
  11. package/cli/cast.mjs +7 -7
  12. package/cli/check.mjs +961 -0
  13. package/cli/clone-deck.mjs +179 -0
  14. package/cli/commands.mjs +345 -0
  15. package/cli/comments.mjs +64 -18
  16. package/cli/commit-flow.mjs +44 -19
  17. package/cli/commit-message.mjs +51 -74
  18. package/cli/commit-split.mjs +601 -0
  19. package/cli/deck-refs.mjs +59 -0
  20. package/cli/deck-routes.mjs +67 -0
  21. package/cli/deckfile.mjs +3 -5
  22. package/cli/decklight.mjs +68 -289
  23. package/cli/design-system-deps.mjs +209 -0
  24. package/cli/design-system-edit.mjs +194 -0
  25. package/cli/design-system-refs.mjs +409 -0
  26. package/cli/design-system.mjs +429 -0
  27. package/cli/doctor.mjs +115 -0
  28. package/cli/edit-git.mjs +353 -0
  29. package/cli/edit-handover.mjs +445 -0
  30. package/cli/edit-look.mjs +388 -0
  31. package/cli/edit-slides.mjs +683 -0
  32. package/cli/edit.mjs +2126 -842
  33. package/cli/enhance.mjs +483 -0
  34. package/cli/extension.mjs +10 -10
  35. package/cli/font-refs.mjs +273 -0
  36. package/cli/font.mjs +246 -0
  37. package/cli/git-tree.mjs +1 -1
  38. package/cli/git.mjs +65 -11
  39. package/cli/import.mjs +56 -10
  40. package/cli/init.mjs +400 -234
  41. package/cli/library.mjs +127 -0
  42. package/cli/loader.mjs +3 -1
  43. package/cli/marketplace.mjs +215 -21
  44. package/cli/narrate.mjs +176 -0
  45. package/cli/open-browser.mjs +63 -0
  46. package/cli/open.mjs +943 -0
  47. package/cli/pdf.mjs +41 -13
  48. package/cli/pkg.mjs +44 -2
  49. package/cli/plugin.mjs +43 -41
  50. package/cli/port-conflict.mjs +53 -23
  51. package/cli/pptx-export.mjs +57 -24
  52. package/cli/publish.mjs +8 -4
  53. package/cli/qr.mjs +1 -1
  54. package/cli/record.mjs +14 -12
  55. package/cli/remote.mjs +11 -11
  56. package/cli/restore.mjs +11 -4
  57. package/cli/review-ref.mjs +125 -0
  58. package/cli/review-remote.mjs +92 -48
  59. package/cli/review-routes.mjs +254 -0
  60. package/cli/review-store.mjs +47 -7
  61. package/cli/review-submit.mjs +47 -57
  62. package/cli/runtime-link.mjs +560 -0
  63. package/cli/serve.mjs +235 -44
  64. package/cli/setup.mjs +112 -0
  65. package/cli/sign.mjs +1 -1
  66. package/cli/skill-content.mjs +190 -33
  67. package/cli/skills.mjs +107 -24
  68. package/cli/start.mjs +110 -0
  69. package/cli/supervise.mjs +6 -6
  70. package/cli/theme-refs.mjs +515 -0
  71. package/cli/theme.mjs +181 -137
  72. package/cli/trust.mjs +83 -0
  73. package/cli/units.mjs +39 -42
  74. package/cli/update-check.mjs +1 -5
  75. package/cli/upgrade.mjs +194 -28
  76. package/cli/upstream.mjs +4 -3
  77. package/cli/util.mjs +4 -4
  78. package/cli/wizard.mjs +6 -6
  79. package/dist/build-info.json +1 -1
  80. package/dist/decklight.css +1126 -49
  81. package/dist/decklight.js +212 -115
  82. package/dist/decklight.js.map +4 -4
  83. package/docs/GLOSSARY.md +141 -0
  84. package/docs/architecture.svg +17 -17
  85. package/package.json +4 -2
  86. package/themes/README.md +9 -8
  87. package/themes/reveal-solarized.css +10 -0
  88. package/tools/args.mjs +20 -0
  89. package/tools/atomic-write.mjs +48 -0
  90. package/tools/brand-palette.mjs +717 -0
  91. package/tools/bridge.mjs +1 -1
  92. package/tools/build-groups.mjs +42 -0
  93. package/tools/color.mjs +48 -0
  94. package/tools/deck-html.mjs +396 -11
  95. package/tools/design-system-format.mjs +753 -0
  96. package/tools/elevenlabs-tts.mjs +110 -17
  97. package/tools/exec.mjs +1 -1
  98. package/tools/extension-check.mjs +31 -7
  99. package/tools/font-format.mjs +190 -0
  100. package/tools/font-stacks.mjs +24 -0
  101. package/tools/gemini-tts.mjs +3 -0
  102. package/tools/lipsync-config.mjs +103 -0
  103. package/tools/lipsync-engines.mjs +205 -2
  104. package/tools/lipsync-server.mjs +264 -41
  105. package/tools/lipsync.mjs +37 -18
  106. package/tools/local-voice.mjs +32 -42
  107. package/tools/narration-manifest.mjs +196 -0
  108. package/tools/narration-synth.mjs +416 -0
  109. package/tools/pptx.mjs +776 -19
  110. package/tools/publish-targets.mjs +1 -1
  111. package/tools/publish-voices.mjs +3 -3
  112. package/tools/recording-impact.mjs +7 -3
  113. package/tools/render-theme.mjs +33 -0
  114. package/tools/review-anchor.mjs +28 -12
  115. package/tools/semver.mjs +40 -0
  116. package/tools/sentences.mjs +180 -0
  117. package/tools/shot.mjs +14 -7
  118. package/tools/site-voices.mjs +232 -0
  119. package/tools/template-theme.mjs +1 -1
  120. package/tools/test-impact.mjs +17 -10
  121. package/tools/theme-check.mjs +30 -3
  122. package/tools/tts-cache.mjs +4 -3
  123. package/tools/tts-engines.mjs +38 -20
  124. package/tools/tts-setup.mjs +7 -7
  125. package/tools/video-options.mjs +34 -0
  126. package/tools/video.mjs +461 -48
  127. package/tools/voiceover-server.mjs +185 -104
  128. package/tools/voiceover.mjs +119 -261
  129. package/tools/zip.mjs +1 -1
  130. package/cli/dev.mjs +0 -623
  131. package/cli/present.mjs +0 -853
  132. package/cli/review.mjs +0 -361
  133. package/tools/publish-site-voices.mjs +0 -75
@@ -3,9 +3,9 @@
3
3
 
4
4
  // What reviews are waiting — SPEC REVIEW.
5
5
  //
6
- // `review submit` pushes a reviewer's comments to `review/<who>-<date>`. This is
6
+ // `comments submit` pushes a reviewer's comments to `review/<who>-<date>`. This is
7
7
  // the other end: the one reader that finds those branches and says how many
8
- // comments are on each. Three surfaces share it — `decklight author` at startup,
8
+ // comments are on each. Three surfaces share it — `decklight <deck>` at startup,
9
9
  // `M` in the deck, and `decklight comments --incoming` — and they share it so
10
10
  // that none of them can drift into a different answer.
11
11
  //
@@ -45,7 +45,7 @@ import { foldReview } from '../tools/review-anchor.mjs';
45
45
  /** Every review branch a remote has. A literal, not built from anything. */
46
46
  const REVIEW_GLOB = 'refs/heads/review/*';
47
47
  /** …and where they land locally: exactly where a plain `git fetch <remote>` would put them. */
48
- const refspecFor = (remote) => `+refs/heads/review/*:refs/remotes/${remote}/review/*`;
48
+ const refspecFor = (remote) => `+refs/heads/review/*:refs/remotes/${remote}/deck/review/*`;
49
49
 
50
50
  /** Refuse a remote name git could misread, rather than repairing it. */
51
51
  export function remoteNameProblem(remote) {
@@ -84,26 +84,14 @@ export function describeBranch(branch) {
84
84
  }
85
85
 
86
86
  /**
87
- * The reviews waiting on `remote` for this deck.
88
- *
89
- * Two network calls no matter how many reviews there are — one `ls-remote` to
90
- * see whether any exist at all, one `fetch` to bring them in — and then every
91
- * count is a local read. A per-branch fetch would be the obvious shape and
92
- * would put a talk's worth of round trips behind an editor's startup.
93
- *
94
- * Returns `{ state, reviews, reason }`. `state` is one of:
95
- * `ok` — the list is authoritative, and may be empty
96
- * `none` — the remote has no review branches
97
- * `no-repo` / `untracked` / `no-remote` — the feature does not apply here
98
- * `offline` / `no-credential` / `timeout` / `error` — COULD NOT ASK
99
- *
100
- * The last group is the reason this returns a state rather than an array: a
101
- * failed check must never render as "no reviews waiting".
87
+ * The review branches the remote holds, fetched, and the path the deck's
88
+ * sidecar has inside the repository — the prelude `reviewsWaiting` (the
89
+ * author's inbox) and `myReviews` (a reviewer's own, listed back to her)
90
+ * share. `state` is 'ok' with `branches` to read, 'none' when the remote
91
+ * has no review branch, or one of reviewsWaiting's reasons it could not ask.
102
92
  */
103
- export async function reviewsWaiting(deckPath, { remote = 'origin', run = runGit } = {}) {
104
- const full = resolve(deckPath);
105
- const cwd = dirname(full);
106
- const no = (state, reason = null) => ({ state, reviews: [], reason });
93
+ async function remoteReviewBranches(full, cwd, { remote, run }) {
94
+ const no = (state, reason = null) => ({ state, reason, branches: [], inRepo: null });
107
95
  const badRemote = remoteNameProblem(remote);
108
96
  if (badRemote) return no('error', `the remote name ${JSON.stringify(remote)} ${badRemote}`);
109
97
 
@@ -125,7 +113,7 @@ export async function reviewsWaiting(deckPath, { remote = 'origin', run = runGit
125
113
  .map((l) => l.split('\t')[1])
126
114
  .filter((r) => typeof r === 'string' && r.startsWith('refs/heads/review/'))
127
115
  .map((r) => r.slice('refs/heads/'.length));
128
- if (!branches.length) return { state: 'none', reviews: [], reason: null };
116
+ if (!branches.length) return { state: 'none', reason: null, branches: [], inRepo: null };
129
117
 
130
118
  const fetched = await run(['fetch', '--quiet', remote, refspecFor(remote)], { cwd });
131
119
  if (!fetched.ok) return no(classifyFailure(fetched), fetched.stderr || null);
@@ -137,6 +125,33 @@ export async function reviewsWaiting(deckPath, { remote = 'origin', run = runGit
137
125
  const prefix = await run(['rev-parse', '--show-prefix'], { cwd });
138
126
  const storeName = basename(full).replace(/\.html?$/i, '') + '.review.jsonl';
139
127
  const inRepo = `${prefix.ok ? prefix.stdout : ''}${storeName}`;
128
+ return { state: 'ok', reason: null, branches, inRepo };
129
+ }
130
+
131
+ /**
132
+ * The reviews waiting on `remote` for this deck.
133
+ *
134
+ * Two network calls no matter how many reviews there are — one `ls-remote` to
135
+ * see whether any exist at all, one `fetch` to bring them in — and then every
136
+ * count is a local read. A per-branch fetch would be the obvious shape and
137
+ * would put a talk's worth of round trips behind an editor's startup.
138
+ *
139
+ * Returns `{ state, reviews, reason }`. `state` is one of:
140
+ * `ok` — the list is authoritative, and may be empty
141
+ * `none` — the remote has no review branches
142
+ * `no-repo` / `untracked` / `no-remote` — the feature does not apply here
143
+ * `offline` / `no-credential` / `timeout` / `error` — COULD NOT ASK
144
+ *
145
+ * The last group is the reason this returns a state rather than an array: a
146
+ * failed check must never render as "no reviews waiting".
147
+ */
148
+ export async function reviewsWaiting(deckPath, { remote = 'origin', run = runGit } = {}) {
149
+ const full = resolve(deckPath);
150
+ const cwd = dirname(full);
151
+ const no = (state, reason = null) => ({ state, reviews: [], reason });
152
+ const rb = await remoteReviewBranches(full, cwd, { remote, run });
153
+ if (rb.state !== 'ok') return { state: rb.state, reviews: [], reason: rb.reason };
154
+ const { branches, inRepo } = rb;
140
155
 
141
156
  // "Waiting" used to mean "holds records your sidecar does not", because the
142
157
  // overlay MERGED a review into that sidecar and the by-id merge was the
@@ -172,10 +187,21 @@ export async function reviewsWaiting(deckPath, { remote = 'origin', run = runGit
172
187
  // …nor does a review whose every record the local sidecar already holds:
173
188
  // that is `--import`, or a real merge, and it has plainly been dealt with.
174
189
  if (!mergeById(mine, records).added) continue;
175
- // Which of ITS comments this clone has marked done. Carried per comment
176
- // rather than per branch: finishing half a long review has to leave the
177
- // other half on screen, which a single branch-level flag cannot express.
178
- const doneIds = doneComments(cwd, branch, { records });
190
+ // Which of ITS comments the author has resolved: a `{op:"resolve", re}`
191
+ // in the author's OWN sidecar naming the reviewer's id, so the mark
192
+ // travels with the deck and the reviewer sees it after a pull. Folded
193
+ // TOGETHER — their comments, our ops — because an op alone points at
194
+ // nothing. Carried per comment rather than per branch: finishing half a
195
+ // long review has to leave the other half on screen. Marks an earlier
196
+ // version kept in git config are still honoured, read and never written —
197
+ // until the sidecar speaks about that comment: once a resolve or a reopen
198
+ // names it, the record is the truth, or a legacy mark would pin a comment
199
+ // done that R had just reopened, and R could never write the resolve
200
+ // that travels.
201
+ const together = new Map(foldReview([...records, ...mine]).map((c) => [c.id, c]));
202
+ const spoken = new Set(mine.filter((r) => (r.op === 'resolve' || r.op === 'reopen') && r.re).map((r) => r.re));
203
+ const doneIds = new Set([...doneComments(cwd, branch, { records })].filter((id) => !spoken.has(id)));
204
+ for (const c of open) if (together.get(c.id)?.resolved) doneIds.add(c.id);
179
205
  const stamp = await run(['log', '-1', '--format=%aI', ref], { cwd });
180
206
  reviews.push({
181
207
  branch,
@@ -184,10 +210,6 @@ export async function reviewsWaiting(deckPath, { remote = 'origin', run = runGit
184
210
  // records ARE the review, and a count was only ever a placeholder.
185
211
  records,
186
212
  comments: open.length,
187
- // Raw, unlike `comments`: a reply here may answer a comment living in
188
- // ANOTHER branch (each reviewer clones from main), and the fold — scoped
189
- // to this one sidecar — would drop it as parentless.
190
- replies: records.filter((r) => r.re && !r.op).length,
191
213
  unreadable: skipped,
192
214
  at: stamp.ok ? stamp.stdout : null,
193
215
  // The ids the overlay strikes through, and the count that decides whether
@@ -217,6 +239,35 @@ export async function reviewsWaiting(deckPath, { remote = 'origin', run = runGit
217
239
  return { state: reviews.some((r) => !r.done) ? 'ok' : 'none', reviews, reason: null };
218
240
  }
219
241
 
242
+ /**
243
+ * What THIS reviewer submitted, read back from the remote: the records on
244
+ * every `review/<me>-*` branch of this deck, merged by id. `M` lists them
245
+ * beside the sidecar in no-trust mode (REVIEW), so what she sent stays in
246
+ * front of her whatever her local branch holds — a `git reset --hard
247
+ * origin/main` after a diverged pull, which git itself suggests, would
248
+ * otherwise hide her own comments from the overlay while they sit safe on
249
+ * the remote. `who` is the slug the branch name carries (review-submit's
250
+ * `slugUser`). Never fatal: a remote that cannot be asked is a `state`, and
251
+ * the sidecar alone is still listed.
252
+ */
253
+ export async function myReviews(deckPath, who, { remote = 'origin', run = runGit } = {}) {
254
+ const full = resolve(deckPath);
255
+ const cwd = dirname(full);
256
+ if (!who) return { state: 'none', records: [], branches: [], reason: null };
257
+ const rb = await remoteReviewBranches(full, cwd, { remote, run });
258
+ if (rb.state !== 'ok') return { state: rb.state, records: [], branches: [], reason: rb.reason };
259
+ let records = [];
260
+ const branches = [];
261
+ for (const branch of rb.branches) {
262
+ if (describeBranch(branch).who !== who) continue;
263
+ const blob = await run(['show', `refs/remotes/${remote}/${branch}:${rb.inRepo}`], { cwd });
264
+ if (!blob.ok) continue; // a review of another deck in the same repository
265
+ branches.push(branch);
266
+ records = mergeById(records, parseReview(blob.stdout).records).records;
267
+ }
268
+ return { state: branches.length ? 'ok' : 'none', records, branches, reason: null };
269
+ }
270
+
220
271
  /**
221
272
  * One line for a terminal, or `null` when there is nothing worth saying.
222
273
  *
@@ -261,8 +312,11 @@ export function reviewLine(result, { deck = '' } = {}) {
261
312
  // point. "Done" is not a second state beside it; it IS that record.
262
313
  //
263
314
  // a reviewer's comments live on their branch, which is not yours to write.
264
- // So the mark is kept HERE, in this clone's git config: private, never
265
- // pushed, and reversible with `git config --unset`.
315
+ // So the SAME record, in your own sidecar, naming their id: it is folded
316
+ // together with their branch (above), travels with the deck, and the
317
+ // reviewer sees the tick after a pull. An earlier version kept this mark
318
+ // in this clone's git config, private; those marks are still read here
319
+ // and never written again.
266
320
  //
267
321
  // A review branch stops waiting when every one of its open comments is marked,
268
322
  // which is the same sentence as before — it is just counted a comment at a time
@@ -282,16 +336,17 @@ export const doneKey = (branch, id) => `decklight-review.${branch}.done-${id}`;
282
336
  export const usableId = (id) => typeof id === 'string' && /^[a-z0-9]{1,12}$/.test(id);
283
337
 
284
338
  /**
285
- * Which comments of this review are marked done in THIS clone.
339
+ * Which comments of this review an EARLIER version marked done in this clone's
340
+ * git config. Read, never written: the mark is a resolve record in the sidecar
341
+ * now (see above), and these are honoured so nobody's work is silently
342
+ * un-marked by an upgrade.
286
343
  *
287
344
  * One `--get-regexp` rather than a lookup per comment: a review can carry
288
345
  * dozens, and forty git invocations to draw one overlay is the kind of cost
289
346
  * that only shows up on somebody else's machine.
290
347
  *
291
348
  * A legacy WHOLE-REVIEW mark (`[decklight-review "<branch>"] done`, which is
292
- * what the first version of this wrote) is honoured as "all of them": the
293
- * feature shipped, somebody may have marked a review with it, and silently
294
- * un-marking their work to simplify this function would be a poor trade.
349
+ * what the first version of this wrote) is honoured as "all of them".
295
350
  */
296
351
  export function doneComments(cwd, branch, { run = null, exec = execFileSync, records = [] } = {}) {
297
352
  const g = run ?? ((args) => exec('git', args, { cwd, encoding: 'utf8' }).trim());
@@ -315,16 +370,5 @@ export function doneComments(cwd, branch, { run = null, exec = execFileSync, rec
315
370
  return ids;
316
371
  }
317
372
 
318
- /** Mark one comment done, or take the mark off. Never fatal: a mark is a convenience. */
319
- export function setCommentDone(cwd, branch, id, done, { run = null, exec = execFileSync } = {}) {
320
- if (!usableId(id)) return false;
321
- const g = run ?? ((args) => exec('git', args, { cwd, encoding: 'utf8' }).trim());
322
- try {
323
- if (done) g(['config', doneKey(branch, id), 'true']);
324
- else g(['config', '--unset', doneKey(branch, id)]);
325
- return true;
326
- } catch { return false; }
327
- }
328
-
329
373
  /** git config takes a REGEX, and a branch name is full of characters one means. */
330
374
  function escapeRe(s) { return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
@@ -0,0 +1,254 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The review routes — SPEC REVIEW — as one thing every server that opens a
5
+ // deck registers, whichever way it was opened:
6
+ //
7
+ // GET /deck/review/comments what has been said
8
+ // POST /deck/review/comments append one record: a comment, a resolve, a
9
+ // reopen, a delete or a re-anchor (`op`, naming the
10
+ // comment by `re`)
11
+ // POST /deck/review/submit push what was said to a branch of its own
12
+ //
13
+ // What a page needs to know before it comments (`review` on /deck/ping: the
14
+ // mode, whether comments commit, who is writing, the store) comes from
15
+ // `ping()` here too. The edit server adds the owner's routes beside these
16
+ // (/deck/review/incoming, /deck/review/at: a fetch, a look into git history),
17
+ // registered by it alone, the way the no-trust mode alone registers
18
+ // /deck/upstream. A reviewer's comment is resolved through THIS route, by an
19
+ // op in the author's own sidecar naming the reviewer's id.
20
+ //
21
+ // A review is
22
+ // something you can do in either mode of the one server: without trust, where the
23
+ // sidecar is the only file the process will ever write, and write mode, where
24
+ // it is one file among the deck's own. What is written is the same either way:
25
+ // an append to `<deck>.review.jsonl`, never a rewrite, which is what lets two
26
+ // reviewers' files merge and keeps the deck byte for byte as it was.
27
+
28
+ import { appendFileSync } from 'node:fs';
29
+ import { basename, dirname } from 'node:path';
30
+ import { execFileSync } from 'node:child_process';
31
+ import { commitSubject, oneline, ensureReviewAttribute } from './git.mjs';
32
+ import { reviewPathFor, parseReview, serializeRecord, newId, mergeById, slugUser } from './review-store.mjs';
33
+ import { appendToReviewRef, reviewState, reviewRef } from './review-ref.mjs';
34
+
35
+ /** The reviewer, as git knows them: "Name <email>", either half, or ''. */
36
+ export function reviewerIdentity(cwd, exec = execFileSync) {
37
+ const cfg = (key) => {
38
+ try { return exec('git', ['config', key], { cwd, encoding: 'utf8' }).trim(); } catch { return ''; }
39
+ };
40
+ const name = cfg('user.name');
41
+ const email = cfg('user.email');
42
+ if (name && email) return `${name} <${email}>`;
43
+ return name || email || '';
44
+ }
45
+
46
+ /**
47
+ * The record a posted comment becomes.
48
+ *
49
+ * Pure, so the shape is testable without a server: the browser sends what it
50
+ * knows about the slide (its number, title and fingerprint) and the server adds
51
+ * what only it knows (who, when, and which commit of the deck was on screen).
52
+ *
53
+ * `body` is the reviewer's own prose and is stored verbatim — it is data here,
54
+ * never an argument to anything. The one place it could reach a command line is
55
+ * a commit subject, and that goes through `commitSubject`.
56
+ */
57
+ export function reviewRecord(input, { by, at, deck, id }) {
58
+ const rec = { id, at, ...(by ? { by } : {}), ...(deck ? { deck } : {}) };
59
+ rec.slide = Number(input.slide);
60
+ if (input.title) rec.title = String(input.title).slice(0, 200);
61
+ if (input.fp) rec.fp = String(input.fp).slice(0, 32);
62
+ rec.body = String(input.body);
63
+ return rec;
64
+ }
65
+
66
+ /** What a posted comment must carry to be worth storing, or the reason it is not. */
67
+ export function commentProblem(input) {
68
+ if (!input || typeof input !== 'object') return 'not a comment';
69
+ const body = typeof input.body === 'string' ? input.body.trim() : '';
70
+ if (!body) return 'a comment needs something in it';
71
+ if (body.length > 4000) return 'that comment is longer than 4000 characters';
72
+ const n = Number(input.slide);
73
+ if (!Number.isInteger(n) || n < 1 || n > 9999) return 'a comment belongs to a slide';
74
+ return null;
75
+ }
76
+
77
+ /** The most a comment's request body may be: prose, not an upload. */
78
+ export const REVIEW_BODY_MAX = 1e5;
79
+
80
+ /**
81
+ * The routes for one deck.
82
+ *
83
+ * `inRepo` says whether the deck sits in a git repository (which commit of it
84
+ * a comment is about is recorded only then); `gitOn` whether each comment is
85
+ * committed by itself as it lands (no-trust mode does, write mode leaves the
86
+ * sidecar to the deck's own commits); `mode` is what the ping says the server
87
+ * is ('no-trust' | 'write'); `out` is the terminal; `onSubmitted` is told
88
+ * when a submit went through, for the exit line.
89
+ */
90
+ export function createReviewRoutes(deckPath, { inRepo = false, gitOn = false, mode = 'no-trust', out = process.stdout, onSubmitted = () => {}, onRecord = () => {}, mine = null } = {}) {
91
+ // Both may be functions: the one server changes mode mid-session, and what
92
+ // the ping says and whether a comment commits follow the mode of the moment.
93
+ const modeOf = typeof mode === 'function' ? mode : () => mode;
94
+ const commits = typeof gitOn === 'function' ? gitOn : () => gitOn;
95
+ const deckDir = dirname(deckPath);
96
+ const name = basename(deckPath);
97
+ const storePath = reviewPathFor(deckPath);
98
+ const storeName = basename(storePath);
99
+ const by = inRepo ? reviewerIdentity(deckDir) : '';
100
+ // The slug the review branches carry (REVIEW: a review is a branch). Every
101
+ // reader here folds the sidecar with the branches this slug names.
102
+ const who = inRepo ? slugUser(by) : '';
103
+ // WHICH VERSION OF THE DECK a comment is about: provenance, not bookkeeping,
104
+ // so it is gated on being in a repository and not on committing.
105
+ const deckHead = () => {
106
+ if (!inRepo) return null;
107
+ try { return execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: deckDir, encoding: 'utf8' }).trim(); }
108
+ catch { return null; }
109
+ };
110
+ const json = (res, code, body) => {
111
+ res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store' });
112
+ res.end(JSON.stringify(body));
113
+ };
114
+
115
+ /** The `review` block of /deck/ping: what a page needs to know before it comments. */
116
+ const ping = () => ({ mode: modeOf(), git: commits(), by: by || null, store: storeName,
117
+ ...(commits() ? { branch: reviewRef(who).slice('refs/heads/'.length) } : {}) });
118
+ const list = async () => {
119
+ // ONE reader (review-ref.mjs `reviewState`): the sidecar beside the deck
120
+ // and this reviewer's local review branches, merged by id. `skipped`
121
+ // travels rather than being swallowed: a reader showing fewer comments
122
+ // than the file holds should be able to say so.
123
+ const { records, skipped } = reviewState(deckPath, commits() ? who : '');
124
+ if (!mine) return { ok: true, records, skipped };
125
+ // …and what this reviewer already submitted, as the remote holds it
126
+ // (REVIEW): merged by id behind the sidecar, so a comment that is in
127
+ // both is one, and one her local branch lost is still hers to see.
128
+ let remote = { state: 'none', records: [], branches: [] };
129
+ try { remote = await mine(); } catch { /* the sidecar alone, then */ }
130
+ return { ok: true, records: mergeById(records, remote.records).records, skipped,
131
+ mine: { state: remote.state, branches: remote.branches } };
132
+ };
133
+ /**
134
+ * Store one record. Where it goes is the mode's (REVIEW):
135
+ *
136
+ * no-trust, in a repository, git not off — a commit of its own on this
137
+ * reviewer's LOCAL review branch (`review/<me>-<date>`), never the
138
+ * sidecar in the work tree and never the checked-out branch, so her
139
+ * pull never diverges and a reset never loses a comment. `committed`
140
+ * says so and `branch` names it.
141
+ *
142
+ * otherwise — appended to the sidecar beside the deck: write mode (the
143
+ * author's own file, which K commits with the deck), no repository (the
144
+ * file IS the deliverable, for --import), or --no-git (asked for).
145
+ *
146
+ * `{ ok, id?, committed, branch? }` or `{ ok: false, error, code }`.
147
+ */
148
+ const append = (rec, subject) => {
149
+ const line = `${serializeRecord(rec)}\n`;
150
+ // The reviewer's own prose reaching a command line, so it goes through
151
+ // the sanitizer every other untrusted subject does: one line, capped,
152
+ // never leading `-`.
153
+ if (commits()) {
154
+ try {
155
+ const r = appendToReviewRef(deckPath, line, subject, { who });
156
+ onRecord(rec, {});
157
+ return { ok: true, ...(rec.id ? { id: rec.id } : {}), committed: true, branch: r.branch };
158
+ } catch (e) { return { ok: false, code: 500, error: oneline(e) }; }
159
+ }
160
+ try {
161
+ // Append, never rewrite — that is what makes `merge=union` work and a
162
+ // second reviewer harmless.
163
+ appendFileSync(storePath, line);
164
+ } catch (e) { return { ok: false, code: 500, error: oneline(e) }; }
165
+ // …and `merge=union` works only when the repository says so: the first
166
+ // record in a repository writes the attribute, carried by the deck's
167
+ // next commit (write mode, onRecord).
168
+ const attr = inRepo ? ensureReviewAttribute(deckDir) : null;
169
+ onRecord(rec, { wrote: attr });
170
+ return { ok: true, ...(rec.id ? { id: rec.id } : {}), committed: false };
171
+ };
172
+ /**
173
+ * Store one record: a NEW comment (no `op`), a resolve (`op: 'resolve', re`),
174
+ * a reopen (`op: 'reopen', re`: the resolve taken back, as a line of its own
175
+ * so the file stays a log), a delete (`op: 'delete', re`: the comment
176
+ * withdrawn by whoever wrote it, folded out of every view, its line kept)
177
+ * or a re-anchor (`op: 'anchor', re, slide`: a comment moved to the slide
178
+ * somebody is looking at, the reconciliation for a slide deleted or
179
+ * rewritten past what fingerprint and title can find).
180
+ * All five are appends: this file is never rewritten. There is no reply
181
+ * (REVIEW): a comment is one-way, and a record that names another with no
182
+ * `op` is refused rather than stored as one.
183
+ */
184
+ const post = (body) => {
185
+ let input;
186
+ try { input = JSON.parse(body || '{}'); } catch { return { ok: false, code: 400, error: 'bad payload' }; }
187
+ const { op, re, slide, title, fp } = input;
188
+ if (op === undefined) {
189
+ const bad = commentProblem(input);
190
+ if (bad) return { ok: false, code: 400, error: bad };
191
+ const rec = reviewRecord(input, { by, at: new Date().toISOString(), deck: deckHead(), id: newId() });
192
+ const r = append(rec, commitSubject(`review: ${rec.body}`, `review: a comment on ${name}`));
193
+ if (r.ok) out.write(` comment on slide ${rec.slide} → ${r.committed ? `${r.branch} (a commit on your review branch)` : storeName}\n`);
194
+ return r;
195
+ }
196
+ if (!['anchor', 'resolve', 'reopen', 'delete'].includes(op)) return { ok: false, code: 400, error: 'a record is a comment, a resolve, a reopen, a delete or a move' };
197
+ if (typeof re !== 'string' || !/^[a-z0-9]{1,12}$/.test(re)) return { ok: false, code: 400, error: 'bad comment id' };
198
+ if (op === 'anchor') {
199
+ const n = Number(slide);
200
+ if (!Number.isInteger(n) || n < 1 || n > 9999) return { ok: false, code: 400, error: 'an anchor needs a slide' };
201
+ if (title !== undefined && (typeof title !== 'string' || title.length > 500)) return { ok: false, code: 400, error: 'bad title' };
202
+ if (fp !== undefined && (typeof fp !== 'string' || !/^[0-9a-f]{1,16}$/.test(fp))) return { ok: false, code: 400, error: 'bad fingerprint' };
203
+ }
204
+ const at = new Date().toISOString();
205
+ // An op records no deck version: it is about the comment, not about the
206
+ // slide.
207
+ const rec = op === 'anchor'
208
+ ? { op: 'anchor', re, slide: Number(slide), ...(title !== undefined ? { title } : {}), ...(fp !== undefined ? { fp } : {}), at, ...(by ? { by } : {}) }
209
+ : { op, re, at, ...(by ? { by } : {}) };
210
+ const r = append(rec, op === 'anchor'
211
+ ? commitSubject(`review: move ${re} to slide ${rec.slide}`, 'review: re-anchor a comment')
212
+ : commitSubject(`review: ${op} ${re}`, `review: ${op} a comment`));
213
+ if (r.ok) out.write(` review: ${op === 'anchor' ? `moved ${re} to slide ${rec.slide}` : op === 'resolve' ? `resolved ${re}` : op === 'reopen' ? `reopened ${re}` : `deleted ${re}`}${r.committed ? ` → ${r.branch}` : ''}\n`);
214
+ return r;
215
+ };
216
+ const submit = async () => {
217
+ // The browser NEVER runs git: it asks, and this server — the only thing
218
+ // in the room holding a capability — does the pushing, with the same
219
+ // code the typed `comments submit` runs.
220
+ try {
221
+ const { submitReview } = await import('./review-submit.mjs');
222
+ const lines = [];
223
+ const r = submitReview(deckPath, { out: { write: (t) => lines.push(t) } });
224
+ out.write(lines.join('')); // the terminal is a log of what happened
225
+ onSubmitted();
226
+ return { ok: true, branch: r.branch, comments: r.comments, resubmit: r.resubmit };
227
+ } catch (e) {
228
+ // A refusal (no remote, nothing to send) arrives with its way forward
229
+ // in the message — the browser toasts it verbatim.
230
+ return { ok: false, code: 500, error: String(e?.message ?? e) };
231
+ }
232
+ };
233
+
234
+ /** Is `url` one of these routes? The caller reads the body (REVIEW_BODY_MAX) before `handle`. */
235
+ const matches = (req, url) => url.pathname === '/deck/review/comments' || url.pathname === '/deck/review/submit';
236
+ /** Answer the request; true when it was one of these routes. `body` is the POST text. */
237
+ async function handle(req, res, url, body = '') {
238
+ if (!matches(req, url)) return false;
239
+ if (req.method === 'GET' && url.pathname === '/deck/review/comments') { json(res, 200, await list()); return true; }
240
+ if (req.method === 'POST' && url.pathname === '/deck/review/comments') {
241
+ const r = post(body);
242
+ json(res, r.ok ? 200 : r.code, r.ok ? r : { ok: false, error: r.error });
243
+ return true;
244
+ }
245
+ if (req.method === 'POST' && url.pathname === '/deck/review/submit') {
246
+ const r = await submit();
247
+ json(res, r.ok ? 200 : r.code, r.ok ? r : { ok: false, error: r.error });
248
+ return true;
249
+ }
250
+ return false;
251
+ }
252
+
253
+ return { handle, matches, ping, list, post, submit, storePath, storeName, by, name };
254
+ }
@@ -21,12 +21,12 @@
21
21
  // prose, not the bookkeeping.
22
22
  //
23
23
  // Nothing here touches git or the filesystem. The store is the shape; who reads
24
- // and writes it is cli/review.mjs (the reviewer) and cli/comments.mjs (the
24
+ // and writes it is cli/review-routes.mjs (the reviewer) and cli/comments.mjs (the
25
25
  // author).
26
26
  //
27
- // `foldReview` — turning the log into comments-with-replies — lives in
28
- // src/core/review.js instead, because the BROWSER needs it too and the runtime
29
- // may never import from cli/. The dependency only ever points one way.
27
+ // `foldReview` — turning the log into comments, resolved or not — lives in
28
+ // tools/review-anchor.mjs instead, because the BROWSER needs it too and the
29
+ // runtime may never import from cli/. The dependency only ever points one way.
30
30
 
31
31
  /** The sidecar that belongs to a deck: `talk.html` → `talk.review.jsonl`. */
32
32
  export const reviewPathFor = (deckPath) => String(deckPath).replace(/\.html?$/i, '') + '.review.jsonl';
@@ -51,8 +51,8 @@ export function parseReview(text) {
51
51
  if (!line.trim()) continue;
52
52
  let rec;
53
53
  try { rec = JSON.parse(line); } catch { skipped++; continue; }
54
- // An object with no id and no `re` is not a record of anything — it cannot
55
- // be replied to, resolved, or pointed at a slide.
54
+ // An object with no id and no `re` is not a record of anything — it is
55
+ // neither a comment nor an op on one.
56
56
  if (!rec || typeof rec !== 'object' || Array.isArray(rec) || (!rec.id && !rec.re)) { skipped++; continue; }
57
57
  records.push(rec);
58
58
  }
@@ -79,7 +79,7 @@ export function serializeRecord(rec) {
79
79
  */
80
80
  export function mergeById(existing, incoming) {
81
81
  // ops carry no id of their own — the tuple is their identity, so the same
82
- // resolve or re-anchor arriving twice (an import replayed) stays one line
82
+ // resolve, reopen, delete or re-anchor arriving twice (an import replayed) stays one line
83
83
  const key = (r) => (r.op ? `${r.op}:${r.re}:${r.at ?? ''}:${r.by ?? ''}` : r.id);
84
84
  const seen = new Set(existing.map(key));
85
85
  const added = [];
@@ -105,3 +105,43 @@ export function mergeById(existing, incoming) {
105
105
  export function newId(rand = () => Math.random()) {
106
106
  return Math.floor(rand() * 0xffffffff).toString(36).padStart(6, '0').slice(-6);
107
107
  }
108
+
109
+ /**
110
+ * A branch-safe rendering of who is speaking.
111
+ *
112
+ * The email's local part first — it is nearly always `[a-z0-9._-]` already and
113
+ * it is the half that identifies a person rather than describing them. The
114
+ * display name is the fallback and needs the most work: "Ana Ruiz" has a space,
115
+ * which git refuses in a ref.
116
+ *
117
+ * Lossy on purpose, and the loss is covered: the FULL identity rides in the
118
+ * commit's `Signed-off-by`, so the branch name never has to be the only record
119
+ * of who wrote a review.
120
+ */
121
+ export function slugUser(identity) {
122
+ const s = String(identity ?? '');
123
+ const email = /<([^>]*)>/.exec(s)?.[1] ?? (s.includes('@') ? s : '');
124
+ const from = email ? email.split('@')[0] : s;
125
+ const slug = from.toLowerCase().normalize('NFKD')
126
+ .replace(/[^a-z0-9._-]+/g, '-')
127
+ .replace(/^[-._]+|[-._]+$/g, '')
128
+ .replace(/-{2,}/g, '-')
129
+ .slice(0, 32);
130
+ // Never empty: a machine with no git identity still gets to submit, and
131
+ // "reviewer" is a true statement about whoever that is.
132
+ return slug || 'reviewer';
133
+ }
134
+
135
+ /**
136
+ * `review/<user>-<YYYY-MM-DD>`.
137
+ *
138
+ * The date is an ISO 8601 calendar date and NOT a full timestamp, because git
139
+ * refuses a `:` in a ref name and an ISO time is full of them. One branch per
140
+ * reviewer per day is also the more useful shape: a second submit the same day
141
+ * lands on the same branch, so a morning's reviewing is one branch and one pull
142
+ * request rather than one per time you pressed the button.
143
+ */
144
+ export function branchName(identity, when = new Date()) {
145
+ const day = when.toISOString().slice(0, 10);
146
+ return `review/${slugUser(identity)}-${day}`;
147
+ }