@wastech-mdlint/viewer 0.0.0-stage → 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 (189) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +86 -2
  3. package/assets/favicon.ico +0 -0
  4. package/assets/viewer.css +4184 -0
  5. package/dist/asset-routes.d.ts +4 -0
  6. package/dist/asset-routes.js +107 -0
  7. package/dist/blame.d.ts +8 -0
  8. package/dist/blame.js +54 -0
  9. package/dist/branch-changes.d.ts +8 -0
  10. package/dist/branch-changes.js +49 -0
  11. package/dist/candidate-lint-worker.d.ts +1 -0
  12. package/dist/candidate-lint-worker.js +67 -0
  13. package/dist/candidate-lint.d.ts +39 -0
  14. package/dist/candidate-lint.js +115 -0
  15. package/dist/change-banner.d.ts +38 -0
  16. package/dist/change-banner.js +108 -0
  17. package/dist/change-diff.d.ts +23 -0
  18. package/dist/change-diff.js +140 -0
  19. package/dist/change-marks.d.ts +32 -0
  20. package/dist/change-marks.js +363 -0
  21. package/dist/changes-article.d.ts +15 -0
  22. package/dist/changes-article.js +244 -0
  23. package/dist/changes-routes.d.ts +12 -0
  24. package/dist/changes-routes.js +271 -0
  25. package/dist/changes.d.ts +113 -0
  26. package/dist/changes.js +324 -0
  27. package/dist/cli-args.d.ts +21 -0
  28. package/dist/cli-args.js +93 -0
  29. package/dist/client/banner-height.d.ts +1 -0
  30. package/dist/client/banner-height.js +33 -0
  31. package/dist/client/change-marks.d.ts +1 -0
  32. package/dist/client/change-marks.js +56 -0
  33. package/dist/client/changes.d.ts +1 -0
  34. package/dist/client/changes.js +183 -0
  35. package/dist/client/chart-option.d.ts +3 -0
  36. package/dist/client/chart-option.js +76 -0
  37. package/dist/client/charts.d.ts +1 -0
  38. package/dist/client/charts.js +54 -0
  39. package/dist/client/clipboard.d.ts +1 -0
  40. package/dist/client/clipboard.js +43 -0
  41. package/dist/client/code-copy.d.ts +1 -0
  42. package/dist/client/code-copy.js +29 -0
  43. package/dist/client/column-resize.d.ts +1 -0
  44. package/dist/client/column-resize.js +120 -0
  45. package/dist/client/config-dom.d.ts +13 -0
  46. package/dist/client/config-dom.js +47 -0
  47. package/dist/client/config-draft.d.ts +73 -0
  48. package/dist/client/config-draft.js +218 -0
  49. package/dist/client/config-editor.d.ts +3 -0
  50. package/dist/client/config-editor.js +677 -0
  51. package/dist/client/config-fields.d.ts +35 -0
  52. package/dist/client/config-fields.js +339 -0
  53. package/dist/client/config-json.d.ts +18 -0
  54. package/dist/client/config-json.js +96 -0
  55. package/dist/client/config-preview.d.ts +9 -0
  56. package/dist/client/config-preview.js +91 -0
  57. package/dist/client/config-rules.d.ts +14 -0
  58. package/dist/client/config-rules.js +202 -0
  59. package/dist/client/config-types.d.ts +91 -0
  60. package/dist/client/config-types.js +4 -0
  61. package/dist/client/copy-path.d.ts +1 -0
  62. package/dist/client/copy-path.js +32 -0
  63. package/dist/client/dashboard-requests.d.ts +11 -0
  64. package/dist/client/dashboard-requests.js +28 -0
  65. package/dist/client/dashboard.d.ts +1 -0
  66. package/dist/client/dashboard.js +119 -0
  67. package/dist/client/diagnostics.d.ts +1 -0
  68. package/dist/client/diagnostics.js +164 -0
  69. package/dist/client/diagrams.d.ts +1 -0
  70. package/dist/client/diagrams.js +81 -0
  71. package/dist/client/diff-expand.d.ts +1 -0
  72. package/dist/client/diff-expand.js +42 -0
  73. package/dist/client/display-settings-model.d.ts +74 -0
  74. package/dist/client/display-settings-model.js +229 -0
  75. package/dist/client/display-settings.d.ts +1 -0
  76. package/dist/client/display-settings.js +411 -0
  77. package/dist/client/echarts.d.ts +30 -0
  78. package/dist/client/echarts.js +14 -0
  79. package/dist/client/graph-layout.d.ts +88 -0
  80. package/dist/client/graph-layout.js +198 -0
  81. package/dist/client/graph.d.ts +2 -0
  82. package/dist/client/graph.js +566 -0
  83. package/dist/client/history.d.ts +21 -0
  84. package/dist/client/history.js +86 -0
  85. package/dist/client/live-reload-model.d.ts +28 -0
  86. package/dist/client/live-reload-model.js +52 -0
  87. package/dist/client/live-reload.d.ts +9 -0
  88. package/dist/client/live-reload.js +138 -0
  89. package/dist/client/menu.d.ts +14 -0
  90. package/dist/client/menu.js +176 -0
  91. package/dist/client/navigation-feedback.d.ts +1 -0
  92. package/dist/client/navigation-feedback.js +141 -0
  93. package/dist/client/open-config.d.ts +1 -0
  94. package/dist/client/open-config.js +48 -0
  95. package/dist/client/outline-spy.d.ts +1 -0
  96. package/dist/client/outline-spy.js +60 -0
  97. package/dist/client/prompts.d.ts +7 -0
  98. package/dist/client/prompts.js +65 -0
  99. package/dist/client/review.d.ts +1 -0
  100. package/dist/client/review.js +379 -0
  101. package/dist/client/search.d.ts +1 -0
  102. package/dist/client/search.js +199 -0
  103. package/dist/client/segmented.d.ts +13 -0
  104. package/dist/client/segmented.js +70 -0
  105. package/dist/client/source-lines.d.ts +16 -0
  106. package/dist/client/source-lines.js +47 -0
  107. package/dist/client/theme-toggle.d.ts +10 -0
  108. package/dist/client/theme-toggle.js +100 -0
  109. package/dist/client/theme.d.ts +0 -0
  110. package/dist/client/theme.js +50 -0
  111. package/dist/client/tree-marks.d.ts +31 -0
  112. package/dist/client/tree-marks.js +102 -0
  113. package/dist/client/tree-state.d.ts +0 -0
  114. package/dist/client/tree-state.js +179 -0
  115. package/dist/client/viewer.d.ts +1 -0
  116. package/dist/client/viewer.js +53 -0
  117. package/dist/config-editor.d.ts +166 -0
  118. package/dist/config-editor.js +378 -0
  119. package/dist/config-routes.d.ts +18 -0
  120. package/dist/config-routes.js +213 -0
  121. package/dist/context-view.d.ts +41 -0
  122. package/dist/context-view.js +295 -0
  123. package/dist/corpus-routes.d.ts +31 -0
  124. package/dist/corpus-routes.js +258 -0
  125. package/dist/corpus.d.ts +134 -0
  126. package/dist/corpus.js +653 -0
  127. package/dist/dashboard-article.d.ts +14 -0
  128. package/dist/dashboard-article.js +290 -0
  129. package/dist/dashboard.d.ts +94 -0
  130. package/dist/dashboard.js +468 -0
  131. package/dist/diagnostics.d.ts +23 -0
  132. package/dist/diagnostics.js +44 -0
  133. package/dist/document-routes.d.ts +39 -0
  134. package/dist/document-routes.js +396 -0
  135. package/dist/event-hub.d.ts +39 -0
  136. package/dist/event-hub.js +120 -0
  137. package/dist/findings-panel.d.ts +4 -0
  138. package/dist/findings-panel.js +74 -0
  139. package/dist/folder-page.d.ts +8 -0
  140. package/dist/folder-page.js +74 -0
  141. package/dist/graph-view.d.ts +66 -0
  142. package/dist/graph-view.js +236 -0
  143. package/dist/highlight.d.ts +24 -0
  144. package/dist/highlight.js +100 -0
  145. package/dist/http-send.d.ts +9 -0
  146. package/dist/http-send.js +53 -0
  147. package/dist/index.d.ts +2 -0
  148. package/dist/index.js +72 -0
  149. package/dist/open-file.d.ts +36 -0
  150. package/dist/open-file.js +87 -0
  151. package/dist/page-tree.d.ts +3 -0
  152. package/dist/page-tree.js +105 -0
  153. package/dist/page.d.ts +73 -0
  154. package/dist/page.js +478 -0
  155. package/dist/prompts.d.ts +25 -0
  156. package/dist/prompts.js +82 -0
  157. package/dist/render-cache.d.ts +23 -0
  158. package/dist/render-cache.js +38 -0
  159. package/dist/render-document.d.ts +60 -0
  160. package/dist/render-document.js +440 -0
  161. package/dist/request-path.d.ts +17 -0
  162. package/dist/request-path.js +51 -0
  163. package/dist/review-context.d.ts +24 -0
  164. package/dist/review-context.js +109 -0
  165. package/dist/review-queries.d.ts +26 -0
  166. package/dist/review-queries.js +69 -0
  167. package/dist/review-state.d.ts +106 -0
  168. package/dist/review-state.js +251 -0
  169. package/dist/review-store.d.ts +145 -0
  170. package/dist/review-store.js +530 -0
  171. package/dist/router.d.ts +28 -0
  172. package/dist/router.js +294 -0
  173. package/dist/search.d.ts +22 -0
  174. package/dist/search.js +164 -0
  175. package/dist/security.d.ts +95 -0
  176. package/dist/security.js +196 -0
  177. package/dist/server.d.ts +21 -0
  178. package/dist/server.js +224 -0
  179. package/dist/speculation-rules.d.ts +4 -0
  180. package/dist/speculation-rules.js +49 -0
  181. package/dist/state-dir.d.ts +6 -0
  182. package/dist/state-dir.js +31 -0
  183. package/dist/tree-marks.d.ts +49 -0
  184. package/dist/tree-marks.js +108 -0
  185. package/dist/viewer-context.d.ts +37 -0
  186. package/dist/viewer-context.js +74 -0
  187. package/dist/watch.d.ts +41 -0
  188. package/dist/watch.js +135 -0
  189. package/package.json +57 -4
@@ -0,0 +1,244 @@
1
+ import { h } from "hastscript";
2
+ import { BASELINES, changesHref, documentViewHref } from "./change-banner.js";
3
+ import { plural, renderDiff, stats, statusBadge } from "./change-diff.js";
4
+ import { changeCardId, documentContext, ordered, totalOf, } from "./changes.js";
5
+ import { findingsText, renderAffected, renderConfigOnly, renderContextSummary, renderDocumentContext, } from "./context-view.js";
6
+ import { firstScreenMarker } from "./page.js";
7
+ import { documentHref } from "./render-document.js";
8
+ import { reviewChip, reviewProblem, reviewToggle, sectionProgress, } from "./review-state.js";
9
+ // The Changes page's article: the controls, the summary of the branch, the list of changed
10
+ // documents and one card per change with its diff.
11
+ // A diff longer than this starts folded, so a branch with a few large rewrites still opens on the
12
+ // list of what changed rather than on the first rewrite.
13
+ const FOLDED_DIFF_LINES = 300;
14
+ /**
15
+ * The Changes page's article, rendered on the server so it reads the same without script. With the
16
+ * review's context, the summary also says what the change does to findings and every session's
17
+ * budget, the documents it reaches follow the list, and each card shows its document's context.
18
+ */
19
+ export function renderChangesArticle(result, worktree, context, reviewed) {
20
+ const baseline = reviewed?.baseline ?? "base";
21
+ const article = [
22
+ h("h1", "Changes"),
23
+ renderControls(worktree, baseline, reviewed),
24
+ ];
25
+ if ("available" in result) {
26
+ article.push(h("p.changes-unavailable", result.message), h("p.changes-hint", result.hint));
27
+ return article;
28
+ }
29
+ article.push(...renderSummary(result, worktree, context));
30
+ if (reviewed !== undefined && result.documents.length > 0) {
31
+ article.push(renderReviewProgress(result, reviewed.marks));
32
+ }
33
+ const documents = ordered(result, context);
34
+ const markOf = (relPath) => reviewed?.marks.ok === true
35
+ ? reviewed.marks.documents.get(relPath)
36
+ : undefined;
37
+ if (result.set.outsideCorpus.length > 0) {
38
+ article.push(renderOutsideCorpus(result.set.outsideCorpus));
39
+ }
40
+ if (result.documents.length > 0) {
41
+ article.push(renderFileList({ documents, context, markOf, reviewed }));
42
+ }
43
+ const affected = context === undefined ? undefined : renderAffected(context.delta);
44
+ if (affected !== undefined) {
45
+ article.push(affected);
46
+ }
47
+ const cards = [
48
+ ...(result.config === undefined
49
+ ? []
50
+ : [configCard(result.config, context)]),
51
+ ...documents.map((review) => documentCard(review, {
52
+ worktree,
53
+ context,
54
+ mark: markOf(review.path),
55
+ reviewed,
56
+ })),
57
+ ];
58
+ // The page is drawn once the overview and the first card are read; the diffs of the rest, most of
59
+ // the page, follow out of sight.
60
+ article.push(...cards.slice(0, 1), ...(cards.length > 1 ? [firstScreenMarker()] : []), ...cards.slice(1));
61
+ return article;
62
+ }
63
+ // What to compare: the work tree or the commits only, and — with review marks — the base branch or
64
+ // the reader's last review.
65
+ function renderControls(worktree, baseline, reviewed) {
66
+ return h("div.changes-controls", [
67
+ h("nav.changes-mode.segmented", { ariaLabel: "What to compare" }, [
68
+ h("a.segment", {
69
+ href: changesHref(true, baseline),
70
+ ariaCurrent: worktree ? "page" : undefined,
71
+ }, "Work tree"),
72
+ h("a.segment", {
73
+ href: changesHref(false, baseline),
74
+ ariaCurrent: worktree ? undefined : "page",
75
+ }, "Commits only"),
76
+ ]),
77
+ reviewed === undefined
78
+ ? undefined
79
+ : h("nav.changes-since.segmented", { ariaLabel: "Compare with" }, BASELINES.map(([value, label]) => h("a.segment", {
80
+ href: changesHref(worktree, value),
81
+ ariaCurrent: value === baseline ? "page" : undefined,
82
+ }, label))),
83
+ ]);
84
+ }
85
+ function renderSummary(result, worktree, context) {
86
+ const { set } = result;
87
+ const added = totalOf(result, "added");
88
+ const removed = totalOf(result, "removed");
89
+ return [
90
+ h("p.changes-summary", [
91
+ result.documents.length === 0
92
+ ? "No document changed"
93
+ : `${plural(result.documents.length, "document")} changed`,
94
+ result.documents.length === 0 ? "" : ` · +${added} −${removed}`,
95
+ ]),
96
+ h("p.changes-base", [
97
+ "Compared with ",
98
+ h("code", set.base.ref),
99
+ set.mergeBase === set.base.commit
100
+ ? " at its tip "
101
+ : " where this branch left it, at ",
102
+ h("code", set.mergeBase.slice(0, 7)),
103
+ worktree
104
+ ? ", including uncommitted and untracked files."
105
+ : ", up to the last commit.",
106
+ ]),
107
+ ...(context === undefined ? [] : renderContextSummary(context)),
108
+ ];
109
+ }
110
+ function renderReviewProgress(result, marks) {
111
+ if (!marks.ok) {
112
+ return reviewProblem(marks.message);
113
+ }
114
+ return h("p.changes-review", [
115
+ h("span.changes-review-count", `${String(result.documents.length - marks.left)} of ${plural(result.documents.length, "document")} reviewed`),
116
+ // Starting over needs the script that sends the request, so it is hidden until then.
117
+ h("button.review-reset", { type: "button", hidden: true }, "Reset review"),
118
+ ]);
119
+ }
120
+ function renderOutsideCorpus(outsideCorpus) {
121
+ return h("details.changes-outside", [
122
+ h("summary", `${plural(outsideCorpus.length, "Markdown file")} changed outside the corpus`),
123
+ h("p", "The config's include and exclude leave these out, so the linter and this review do not read them."),
124
+ h("ul", outsideCorpus.map((change) => h("li", [statusBadge(change.status), " ", h("code", change.path)]))),
125
+ ]);
126
+ }
127
+ function renderFileList(list) {
128
+ return h("nav.changes-files", { ariaLabel: "Changed documents" }, h("ol", list.documents.map((review) => {
129
+ const delta = documentContext(list.context, review.path);
130
+ const findings = delta === undefined ? undefined : findingsText(delta.findings);
131
+ const mark = list.markOf(review.path);
132
+ return h("li", { dataReview: mark?.status }, [
133
+ statusBadge(review.status),
134
+ " ",
135
+ h("a", { href: `#${changeCardId(review.path)}` }, review.path),
136
+ " ",
137
+ h("span.change-stats", stats(shownDiff(review, mark, list.reviewed).diff)),
138
+ reviewChip(mark),
139
+ review.eager ? eagerBadge() : undefined,
140
+ findings === undefined
141
+ ? undefined
142
+ : h("span.change-findings", { title: "Findings the change adds and removes" }, findings),
143
+ ]);
144
+ })));
145
+ }
146
+ function eagerBadge() {
147
+ return h("span.change-eager", { title: "Loaded into every agent session" }, "every session");
148
+ }
149
+ function configCard(config, context) {
150
+ return changeCard({
151
+ id: changeCardId(config.path),
152
+ status: config.status,
153
+ path: config.path,
154
+ note: "The config decides which files are documents and which rules run.",
155
+ diff: config.diff,
156
+ ...(config.headText === undefined ? {} : { headText: config.headText }),
157
+ context: context === undefined
158
+ ? undefined
159
+ : renderConfigOnly(context.delta.configOnly),
160
+ });
161
+ }
162
+ function documentCard(review, shown) {
163
+ const { mark, reviewed } = shown;
164
+ const baseline = reviewed?.baseline ?? "base";
165
+ const delta = documentContext(shown.context, review.path);
166
+ const diff = shownDiff(review, mark, reviewed);
167
+ return changeCard({
168
+ id: changeCardId(review.path),
169
+ status: review.status,
170
+ path: review.path,
171
+ href: review.status === "D"
172
+ ? undefined
173
+ : documentViewHref(documentHref(review.path), "rendered", baseline),
174
+ oldPath: review.oldPath,
175
+ eager: review.eager,
176
+ note: diff.note,
177
+ diff: diff.diff,
178
+ headText: review.headText,
179
+ context: delta === undefined ? undefined : renderDocumentContext(delta),
180
+ ...(mark === undefined
181
+ ? {}
182
+ : { mark, toggle: reviewToggle(review, mark, shown.worktree) }),
183
+ });
184
+ }
185
+ const NO_DIFF = {
186
+ hunks: [],
187
+ added: 0,
188
+ removed: 0,
189
+ newlineAtEndChanged: false,
190
+ };
191
+ /**
192
+ * The diff a card shows and what it is against. Comparing with the reader's last review, a document
193
+ * changed since then shows the diff from the version they reviewed; one they reviewed as it is has
194
+ * nothing to show; one never reviewed, or whose reviewed text is no longer kept, falls back to the
195
+ * base branch, and the card says so rather than passing one comparison off as the other.
196
+ */
197
+ function shownDiff(review, mark, reviewed) {
198
+ if (reviewed?.baseline !== "review" || mark === undefined) {
199
+ return { diff: review.diff };
200
+ }
201
+ if (mark.status === "reviewed") {
202
+ return { diff: NO_DIFF, note: "Unchanged since your review." };
203
+ }
204
+ const since = reviewed.since.get(review.path);
205
+ if (mark.status === "changed" && since !== undefined) {
206
+ return { diff: since.diff, note: "Changes since your last review." };
207
+ }
208
+ return {
209
+ diff: review.diff,
210
+ note: mark.status === "changed"
211
+ ? "The version you reviewed is no longer kept, so this compares with the base branch."
212
+ : "Not reviewed yet, so this compares with the base branch.",
213
+ };
214
+ }
215
+ function changeCard(card) {
216
+ const lineCount = card.diff.hunks.reduce((sum, hunk) => sum + hunk.lines.length, 0);
217
+ // A reviewed card folds to its header and the diff's summary line, as a viewed file does in a
218
+ // pull request, so what is left stands out; its diff opens with one click.
219
+ const folded = card.mark?.status === "reviewed" || lineCount > FOLDED_DIFF_LINES;
220
+ return h("section.change-card", { id: card.id, dataReview: card.mark?.status }, [
221
+ h("header.change-card-header", [
222
+ statusBadge(card.status),
223
+ card.href === undefined
224
+ ? h("span.change-path", card.path)
225
+ : h("a.change-path", { href: card.href }, card.path),
226
+ card.oldPath === undefined
227
+ ? undefined
228
+ : h("span.change-from", `from ${card.oldPath}`),
229
+ card.eager === true ? eagerBadge() : undefined,
230
+ reviewChip(card.mark),
231
+ sectionProgress(card.mark),
232
+ h("span.change-stats", stats(card.diff)),
233
+ card.toggle,
234
+ ]),
235
+ card.note === undefined ? undefined : h("p.change-note", card.note),
236
+ card.context,
237
+ h("details.change-diff", { open: !folded }, [
238
+ h("summary", lineCount <= FOLDED_DIFF_LINES
239
+ ? "Diff"
240
+ : `Show the diff (${plural(lineCount, "line")})`),
241
+ renderDiff(card.diff, card.headText),
242
+ ]),
243
+ ]);
244
+ }
@@ -0,0 +1,12 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { type ViewerContext } from "./viewer-context.js";
3
+ export declare class ChangesRoutes {
4
+ private readonly ctx;
5
+ constructor(ctx: ViewerContext);
6
+ sendChangesPage(request: IncomingMessage, response: ServerResponse, params: URLSearchParams): Promise<void>;
7
+ sendChangesData(response: ServerResponse, params: URLSearchParams): Promise<void>;
8
+ sendChangeDiff(response: ServerResponse, params: URLSearchParams): Promise<void>;
9
+ private sendDiffSinceReview;
10
+ changeMarks(response: ServerResponse, target: string, body: unknown): Promise<void>;
11
+ changeSectionMark(response: ServerResponse, body: unknown): Promise<void>;
12
+ }
@@ -0,0 +1,271 @@
1
+ import { renderChangesArticle } from "./changes-article.js";
2
+ import { changesPayload, diffPayload, } from "./changes.js";
3
+ import { sendHtml, sendJson } from "./http-send.js";
4
+ import { contextOf, marksOf, sinceOf, worktreeOf } from "./review-queries.js";
5
+ import { baselineOf, markOf, markReview, parseMarkRequest, parseResetRequest, parseSectionRequest, sectionHashes, sectionMarksOf, } from "./review-state.js";
6
+ import { contentHash, } from "./review-store.js";
7
+ import { NO_CHANGES } from "./viewer-context.js";
8
+ // The Changes page, its JSON, one document's diff, and the review marks the reader sets on them.
9
+ const REVIEW_OFF = "Review marks are off: they need a git work tree, and a viewer bound to a loopback address, since a mark records this user's review on this machine.";
10
+ export class ChangesRoutes {
11
+ ctx;
12
+ constructor(ctx) {
13
+ this.ctx = ctx;
14
+ }
15
+ async sendChangesPage(request, response, params) {
16
+ const { ctx } = this;
17
+ if (ctx.changes === undefined) {
18
+ await ctx.sendNotFound(request, response, NO_CHANGES);
19
+ return;
20
+ }
21
+ const worktree = worktreeOf(params);
22
+ const review = await ctx.changes.review(worktree);
23
+ const marks = await marksOf(ctx, review);
24
+ const baseline = baselineOf(params);
25
+ sendHtml(response, 200, await ctx.page({
26
+ title: "Changes",
27
+ section: "changes",
28
+ firstScreen: true,
29
+ article: renderChangesArticle(review, worktree, await contextOf(ctx, review), marks === undefined || "available" in review
30
+ ? undefined
31
+ : {
32
+ marks,
33
+ baseline,
34
+ since: baseline === "review"
35
+ ? await sinceOf(ctx, review, marks)
36
+ : new Map(),
37
+ }),
38
+ // The "Viewed" checkboxes send their mark with it.
39
+ changeToken: marks === undefined ? undefined : ctx.changeToken,
40
+ }), request.method === "HEAD");
41
+ }
42
+ async sendChangesData(response, params) {
43
+ const { ctx } = this;
44
+ if (ctx.changes === undefined) {
45
+ sendJson(response, { error: NO_CHANGES }, 404);
46
+ return;
47
+ }
48
+ const review = await ctx.changes.review(worktreeOf(params));
49
+ sendJson(response, changesPayload(review, await contextOf(ctx, review), await marksOf(ctx, review)));
50
+ }
51
+ async sendChangeDiff(response, params) {
52
+ const { changes } = this.ctx;
53
+ if (changes === undefined) {
54
+ sendJson(response, { error: NO_CHANGES }, 404);
55
+ return;
56
+ }
57
+ const review = await changes.review(worktreeOf(params));
58
+ if ("available" in review) {
59
+ sendJson(response, changesPayload(review), 409);
60
+ return;
61
+ }
62
+ // Only ever compared against the review's own paths, like the graph's parameters.
63
+ const relPath = params.get("path") ?? "";
64
+ if (baselineOf(params) === "review") {
65
+ await this.sendDiffSinceReview(response, review, relPath);
66
+ return;
67
+ }
68
+ const answer = diffPayload(review, relPath);
69
+ if (answer === undefined) {
70
+ sendJson(response, { error: "This path is not among the changed documents." }, 404);
71
+ return;
72
+ }
73
+ sendJson(response, answer);
74
+ }
75
+ // A document's diff from the version the reader last reviewed, rather than from the base branch.
76
+ async sendDiffSinceReview(response, review, relPath) {
77
+ const entry = review.documents.find((document) => document.path === relPath);
78
+ const marks = await marksOf(this.ctx, review);
79
+ const since = entry === undefined
80
+ ? undefined
81
+ : (await sinceOf(this.ctx, review, marks)).get(relPath);
82
+ if (since === undefined) {
83
+ sendJson(response, {
84
+ error: "This path has no reviewed version to compare with: it is not among the changed documents, was never reviewed, is reviewed as it is, or its reviewed text is no longer kept.",
85
+ }, 404);
86
+ return;
87
+ }
88
+ sendJson(response, diffPayload({ ...review, documents: [since] }, relPath));
89
+ }
90
+ // Records that the reader reviewed a document, or takes that back, or forgets the marks of every
91
+ // document a page listed. The text marked is always the one this server's review holds for the
92
+ // page's comparison, never one the request supplies, and only when its hash is the one the page
93
+ // showed: a reader can mark exactly the version they saw, as a config save applies only to the
94
+ // version the page edited.
95
+ async changeMarks(response, target, body) {
96
+ const { reviewStore, changes } = this.ctx;
97
+ if (reviewStore === undefined || changes === undefined) {
98
+ sendJson(response, { status: "refused", error: REVIEW_OFF }, 403);
99
+ return;
100
+ }
101
+ const parsed = target === "/api/review/mark"
102
+ ? parseMarkRequest(body)
103
+ : parseResetRequest(body);
104
+ if (!parsed.ok) {
105
+ sendJson(response, { status: "refused", error: parsed.message }, 400);
106
+ return;
107
+ }
108
+ const review = await changes.review(parsed.request.worktree);
109
+ if ("available" in review) {
110
+ sendJson(response, { status: "refused", error: review.message }, 409);
111
+ return;
112
+ }
113
+ const matched = listedEntries(review, parsed.request);
114
+ if (!matched.ok) {
115
+ sendJson(response, { status: "conflict", error: matched.message }, 409);
116
+ return;
117
+ }
118
+ const { entries } = matched;
119
+ const outcome = await reviewStore.update(markChangeOf(parsed.request, entries));
120
+ if (!outcome.ok) {
121
+ sendUpdateFailure(response, outcome);
122
+ return;
123
+ }
124
+ // Every open page counts what is left, so each is told; nothing on disk the watcher sees changed.
125
+ this.ctx.events.broadcast("review", {});
126
+ const marks = markReview(review, { ok: true, marks: outcome.marks });
127
+ sendJson(response, {
128
+ status: "saved",
129
+ documents: entries.map((entry) => {
130
+ const mark = markOf(entry, outcome.marks);
131
+ return {
132
+ path: entry.path,
133
+ review: { status: mark.status, hash: mark.hash },
134
+ // Marking a document marks its sections too, so the outline follows the answer.
135
+ sections: [...sectionMarksOf(entry, outcome.marks).values()].map((section) => ({ key: section.key, status: section.status })),
136
+ };
137
+ }),
138
+ left: marks.ok ? marks.left : review.documents.length,
139
+ total: review.documents.length,
140
+ });
141
+ }
142
+ // One section of a changed document marked reviewed or not, from its page's outline. Always the
143
+ // work tree's review, the one a document's page shows; the section's text is the review's own, and
144
+ // only the version the page showed may be marked, as for a whole document.
145
+ async changeSectionMark(response, body) {
146
+ const { reviewStore, changes } = this.ctx;
147
+ if (reviewStore === undefined || changes === undefined) {
148
+ sendJson(response, { status: "refused", error: REVIEW_OFF }, 403);
149
+ return;
150
+ }
151
+ const parsed = parseSectionRequest(body);
152
+ if (!parsed.ok) {
153
+ sendJson(response, { status: "refused", error: parsed.message }, 400);
154
+ return;
155
+ }
156
+ const review = await changes.review(true);
157
+ if ("available" in review) {
158
+ sendJson(response, { status: "refused", error: review.message }, 409);
159
+ return;
160
+ }
161
+ const { request: asked } = parsed;
162
+ // Only ever compared against the review's own paths and the document's own section keys.
163
+ const entry = review.documents.find((document) => document.path === asked.path);
164
+ const section = entry === undefined
165
+ ? undefined
166
+ : sectionHashes(entry).find((candidate) => candidate.key === asked.section);
167
+ if (entry === undefined || section?.hash !== asked.hash) {
168
+ sendJson(response, {
169
+ status: "conflict",
170
+ error: "The section changed since this page showed it, or is no longer there. Reload the page to review it as it is now.",
171
+ }, 409);
172
+ return;
173
+ }
174
+ const outcome = await reviewStore.update({
175
+ kind: "section",
176
+ path: entry.path,
177
+ ...(entry.oldPath === undefined ? {} : { oldPath: entry.oldPath }),
178
+ key: section.key,
179
+ hash: section.hash,
180
+ reviewed: asked.reviewed,
181
+ });
182
+ if (!outcome.ok) {
183
+ sendUpdateFailure(response, outcome);
184
+ return;
185
+ }
186
+ this.ctx.events.broadcast("review", {});
187
+ const marks = markReview(review, { ok: true, marks: outcome.marks });
188
+ const mark = markOf(entry, outcome.marks);
189
+ sendJson(response, {
190
+ status: "saved",
191
+ section: {
192
+ key: section.key,
193
+ status: sectionMarksOf(entry, outcome.marks).get(section.key)?.status,
194
+ },
195
+ documents: [
196
+ { path: entry.path, review: { status: mark.status, hash: mark.hash } },
197
+ ],
198
+ left: marks.ok ? marks.left : review.documents.length,
199
+ total: review.documents.length,
200
+ });
201
+ }
202
+ }
203
+ // The review's entries for the documents a mark or reset request lists, each still at the version
204
+ // the page showed. The first one that is not answers for the whole request, so nothing is marked
205
+ // from a page that no longer shows what is on disk.
206
+ function listedEntries(review, request) {
207
+ const listed = "documents" in request
208
+ ? request.documents
209
+ : [{ path: request.path, hash: request.hash }];
210
+ const entries = [];
211
+ for (const { path: relPath, hash } of listed) {
212
+ // Only ever compared against the review's own paths.
213
+ const entry = review.documents.find((document) => document.path === relPath);
214
+ if (entry === undefined) {
215
+ return {
216
+ ok: false,
217
+ message: "This document is no longer among the changes. Reload the page to see what changed now.",
218
+ };
219
+ }
220
+ if (contentHash(entry.headText) !== hash) {
221
+ return {
222
+ ok: false,
223
+ message: "The document changed since this page showed it. Reload the page to review the version there now.",
224
+ };
225
+ }
226
+ entries.push(entry);
227
+ }
228
+ return { ok: true, entries };
229
+ }
230
+ // What the store records for a request whose entries all matched: a reset forgets every listed
231
+ // document's mark, a mark or an unmark changes the one document's.
232
+ function markChangeOf(request, entries) {
233
+ if ("documents" in request) {
234
+ return {
235
+ kind: "reset",
236
+ documents: entries.map((entry) => ({
237
+ path: entry.path,
238
+ ...(entry.oldPath === undefined ? {} : { oldPath: entry.oldPath }),
239
+ hash: contentHash(entry.headText),
240
+ })),
241
+ };
242
+ }
243
+ const entry = entries[0];
244
+ if (request.reviewed) {
245
+ return {
246
+ kind: "mark",
247
+ path: entry.path,
248
+ hash: request.hash,
249
+ text: entry.headText,
250
+ sections: sectionHashes(entry),
251
+ };
252
+ }
253
+ return {
254
+ kind: "unmark",
255
+ path: entry.path,
256
+ ...(entry.oldPath === undefined ? {} : { oldPath: entry.oldPath }),
257
+ hash: request.hash,
258
+ sections: sectionHashes(entry),
259
+ };
260
+ }
261
+ const FAILURE_STATUS = {
262
+ failed: 500,
263
+ busy: 503,
264
+ refused: 409,
265
+ };
266
+ // A mark the store could not write: a write that failed, another viewer holding the lock, or marks
267
+ // it refused to change because it cannot read the ones already there — each its own status, so the
268
+ // page can say which.
269
+ function sendUpdateFailure(response, outcome) {
270
+ sendJson(response, { status: outcome.status, error: outcome.message }, FAILURE_STATUS[outcome.status]);
271
+ }
@@ -0,0 +1,113 @@
1
+ import { type BranchContext, type BranchReview, type CorpusSnapshot, type DocumentContextDelta, type GitRepository, type GitUnavailable, type ReviewedConfig, type ReviewedDocument } from "@wastech-mdlint/core";
2
+ import type { Corpus } from "./corpus.js";
3
+ import type { ReviewMarksView } from "./review-state.js";
4
+ export type DocumentReview = ReviewedDocument;
5
+ export type ConfigReview = ReviewedConfig;
6
+ /** The corpus as the review read it: one moment, whatever updates land while it is computed. */
7
+ export type ReviewSnapshot = CorpusSnapshot;
8
+ export type Review = BranchReview & {
9
+ snapshot: ReviewSnapshot;
10
+ };
11
+ /** What a review's change does to the context, as core computes it. */
12
+ export type ReviewContext = BranchContext;
13
+ export type ReviewResult = Review | GitUnavailable;
14
+ /**
15
+ * Keeps the review between requests, for as long as the viewer runs.
16
+ *
17
+ * A review is stale when the work tree changed — which the corpus watcher reports, and the server
18
+ * passes on through `invalidate` — or when `HEAD` or the base moved without the work tree changing,
19
+ * as a commit, a `reset --soft` or a fetch does. Where the repository is watched, the watcher on
20
+ * git's `HEAD` and refs reports the second too, through `gitMoved`, and a kept review is answered
21
+ * without asking git: that one short process was most of the time a document page took to answer,
22
+ * and every navigation paid it although nothing had moved. Without a watcher nothing would report
23
+ * it, so git is asked on every request instead.
24
+ *
25
+ * Requests that arrive while a review is being computed wait for that one rather than starting
26
+ * their own: after a save, the reloading document page, the open pages' scripts and every other tab
27
+ * all ask at once, and each would otherwise run the whole review again.
28
+ */
29
+ export declare class ChangeTracker {
30
+ private readonly corpus;
31
+ private readonly repository;
32
+ private readonly options;
33
+ private readonly cache;
34
+ private readonly pending;
35
+ private generation;
36
+ private readonly contexts;
37
+ private warming;
38
+ private watched;
39
+ private constructor();
40
+ /**
41
+ * A tracker for the repository holding the corpus, or `undefined` outside any git work tree or
42
+ * without git — where there is no branch to review and the viewer shows no Changes section. A
43
+ * repository git refuses to read (owned by another user, or a git too old) still gets a tracker, so
44
+ * the section can say why it is empty.
45
+ */
46
+ static open(corpus: Corpus, options: {
47
+ base?: string;
48
+ env?: NodeJS.ProcessEnv;
49
+ watched?: boolean;
50
+ }): Promise<ChangeTracker | undefined>;
51
+ /** The repository, when git can read it: where review marks are kept is decided from it. */
52
+ get git(): GitRepository | undefined;
53
+ /** The review kept for a mode, without asking git whether it is still current. */
54
+ cached(worktree: boolean): Review | undefined;
55
+ /**
56
+ * Compute the work-tree review and what it does to the context in the background, ahead of the
57
+ * first page that needs them. The context — the base linted beside the head — is what the Changes
58
+ * page, the dashboard's Branch column and a changed document's small graph wait for, a second or so
59
+ * on a corpus of six hundred documents. Every page used to ask for the changes as it opened, which
60
+ * computed it on the way; pages now draw the branch's marks from the review alone, so without this
61
+ * the first of those pages waited for all of it.
62
+ */
63
+ warm(): void;
64
+ /**
65
+ * Resolves once every warm-up started so far has finished, so the viewer can close without git
66
+ * still running in the repository: on Windows a directory a process is working in cannot be
67
+ * removed, and a test's temporary repository could not be cleaned up.
68
+ */
69
+ idle(): Promise<void>;
70
+ /**
71
+ * Called when the watcher on git's `HEAD` and refs saw something move. Each kept review is checked
72
+ * against git and dropped when it no longer matches, and the work-tree one is computed again where
73
+ * it was; true when that one is now a different review, which the open pages are then told. A ref
74
+ * of some other branch moving changes nothing they show, and answers false.
75
+ */
76
+ gitMoved(): Promise<boolean>;
77
+ /**
78
+ * A watch on git's `HEAD` or refs ended or never started, so a move there would go unreported:
79
+ * from now on a kept review is checked against git on every request again.
80
+ */
81
+ watchLost(): void;
82
+ /** Forget every review; the next request computes a fresh one. */
83
+ invalidate(): void;
84
+ review(worktree: boolean): Promise<ReviewResult>;
85
+ /**
86
+ * What `review`'s change does to the context, computed on first request and kept with the review,
87
+ * so it lasts exactly as long as the review does. Apart from the review because only the Changes
88
+ * page and its JSON need it: a document's page, which waits for the review, never waits for a lint
89
+ * of two corpora as well. `undefined` when the work-tree review it is built on cannot be made.
90
+ */
91
+ context(review: Review): Promise<ReviewContext | undefined>;
92
+ private computeContext;
93
+ private compute;
94
+ }
95
+ /**
96
+ * `/api/changes`: what the page lists, as data. Diffs are left to `/api/changes/diff`. With the
97
+ * review's context, every document carries its findings, size and links, and the list is in the
98
+ * page's order; without it — it could not be computed — those are `null`. With review marks, every
99
+ * document carries its status and the hash a mark must name, and `review` counts what is left; both
100
+ * are `null` where marks are off, and `review` says why when they could not be read. No time from the
101
+ * marks appears here, so the payload depends only on the files and the marks.
102
+ */
103
+ export declare function changesPayload(result: ReviewResult, context?: ReviewContext, marks?: ReviewMarksView): unknown;
104
+ export declare function ordered(review: Review, context?: ReviewContext): DocumentReview[];
105
+ export declare function documentContext(context: ReviewContext | undefined, relPath: string): DocumentContextDelta | undefined;
106
+ /**
107
+ * The diff of one path in the review — a document or the config — or `undefined` when the review
108
+ * holds no such path. The path is only ever compared with the review's own, never read from disk.
109
+ */
110
+ export declare function diffPayload(review: Review, relPath: string): unknown;
111
+ export declare function totalOf(review: Review, side: "added" | "removed"): number;
112
+ /** The id of a path's card on the Changes page; it holds a `.`, as every id the viewer makes does. */
113
+ export declare function changeCardId(relPath: string): string;