@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,196 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { isIP } from "node:net";
3
+ // A local server that reads the repository is a target for any web page the user has open: the page
4
+ // cannot read our responses across origins, but it can make the browser send requests, and with DNS
5
+ // rebinding it can make our origin look like its own. The checks below are the standing answer to
6
+ // both, and each one is cheap enough that none is left to the others.
7
+ export const DEFAULT_HOST = "127.0.0.1";
8
+ const LOOPBACK_NAMES = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
9
+ export function isLoopbackHost(host) {
10
+ return LOOPBACK_NAMES.has(host.toLowerCase());
11
+ }
12
+ /**
13
+ * Whether pages may carry a file's absolute path, for the button that copies it.
14
+ *
15
+ * Absolute paths stay out of what the viewer shows by default: they say where the checkout lives and
16
+ * under which user account. A reader of a viewer bound to a loopback address is on this machine and
17
+ * already knows; one bound with `--host` to another address is read from other machines, which do
18
+ * not, so there the path is withheld and the copy menu says why.
19
+ */
20
+ export function exposesAbsolutePaths(host) {
21
+ return isLoopbackHost(host);
22
+ }
23
+ /**
24
+ * Whether a request's `Host` header names this server.
25
+ *
26
+ * DNS rebinding works by pointing an attacker-controlled name at 127.0.0.1 after the page has loaded,
27
+ * so the browser treats our responses as same-origin with the attacker's page. The request still
28
+ * carries the attacker's name in `Host`, which is what this rejects. IP literals are accepted for any
29
+ * address because a rebinding attack needs a *name* to re-point, and a server bound with `--host` to
30
+ * a LAN address is reached by its IP; `localhost` and the configured host are the only names.
31
+ */
32
+ export function isAllowedHostHeader(hostHeader, bound) {
33
+ if (hostHeader === undefined || hostHeader.length === 0) {
34
+ return false;
35
+ }
36
+ let parsed;
37
+ try {
38
+ parsed = new URL(`http://${hostHeader}`);
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ // `URL` drops a port equal to the scheme default, so 80 has to be compared as the empty string.
44
+ const expectedPort = bound.port === 80 ? "" : String(bound.port);
45
+ if (parsed.port !== expectedPort) {
46
+ return false;
47
+ }
48
+ const hostname = parsed.hostname.toLowerCase();
49
+ const bareHostname = hostname.replace(/^\[|\]$/g, "");
50
+ return (hostname === "localhost" ||
51
+ isIP(bareHostname) !== 0 ||
52
+ hostname === bound.host.toLowerCase());
53
+ }
54
+ /**
55
+ * Whether a request was made by another site's page rather than by navigating to us.
56
+ *
57
+ * Navigations are allowed from anywhere: following a link to a document is the point of the tool,
58
+ * and the response goes to the user, not to the linking page. Everything else from another origin —
59
+ * a `fetch`, an `EventSource`, an `<img>` or `<script>` tag — is refused. `same-site` counts as
60
+ * foreign too, because every other port on localhost is the same site, and another dev server the
61
+ * user runs is exactly the kind of page that should not reach this one.
62
+ */
63
+ export function isForeignRequest(headers) {
64
+ // An opaque origin arrives as the string "null", which never equals ours, so a sandboxed frame or
65
+ // a `file:` page is refused by the same comparison.
66
+ if (headers.origin !== undefined &&
67
+ headers.origin !== `http://${headers.host ?? ""}`) {
68
+ return true;
69
+ }
70
+ const site = headers["sec-fetch-site"];
71
+ if (site === "cross-site" || site === "same-site") {
72
+ return headers["sec-fetch-mode"] !== "navigate";
73
+ }
74
+ return false;
75
+ }
76
+ // Shared by every response. `Cross-Origin-Resource-Policy: same-origin` is what stops another page
77
+ // from embedding our scripts or images with a no-cors tag, the request shape `isForeignRequest`
78
+ // cannot see when a browser omits the fetch-metadata headers.
79
+ const COMMON_HEADERS = {
80
+ "X-Content-Type-Options": "nosniff",
81
+ "Referrer-Policy": "no-referrer",
82
+ "Cross-Origin-Resource-Policy": "same-origin",
83
+ "Cross-Origin-Opener-Policy": "same-origin",
84
+ "X-Frame-Options": "DENY",
85
+ };
86
+ /**
87
+ * Headers for a rendered page.
88
+ *
89
+ * Scripts only from this origin, never inline: the rendered Markdown is sanitized, and this is the
90
+ * second line if sanitizing ever misses something. Styles do allow `'unsafe-inline'`, because both
91
+ * Shiki (a `style` attribute per token) and Mermaid (a `<style>` inside each SVG) emit them, and the
92
+ * sanitizer already strips every `style` an author wrote. `no-store` because the page reflects the
93
+ * file on disk right now, and a cached copy after an edit is the wrong answer.
94
+ */
95
+ export function pageHeaders() {
96
+ return {
97
+ ...COMMON_HEADERS,
98
+ "Content-Security-Policy": [
99
+ "default-src 'none'",
100
+ "script-src 'self'",
101
+ "style-src 'self' 'unsafe-inline'",
102
+ "img-src 'self' data:",
103
+ "font-src 'self'",
104
+ "connect-src 'self'",
105
+ "base-uri 'none'",
106
+ // The header's search form submits to this server; nothing may post anywhere else.
107
+ "form-action 'self'",
108
+ "frame-ancestors 'none'",
109
+ ].join("; "),
110
+ "Cache-Control": "no-store",
111
+ };
112
+ }
113
+ /**
114
+ * Headers for a repository file served as-is (an image a document embeds).
115
+ *
116
+ * `sandbox` matters for SVG: opened directly, an SVG is a document that can run script in our
117
+ * origin, and an SVG in a repository is just as untrusted as the Markdown around it.
118
+ */
119
+ export function rawFileHeaders() {
120
+ return {
121
+ ...COMMON_HEADERS,
122
+ "Content-Security-Policy": "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox",
123
+ "Cache-Control": "no-store",
124
+ };
125
+ }
126
+ /** Headers for the viewer's own scripts and styles, which change only with the package. */
127
+ export function assetHeaders() {
128
+ return { ...COMMON_HEADERS, "Cache-Control": "no-cache" };
129
+ }
130
+ /**
131
+ * The per-process change token for a viewer bound to `host`, or `undefined` where the viewer takes no
132
+ * request with a body at all.
133
+ *
134
+ * Every such request makes the server act for whoever sent it: a preview lints the repository under a
135
+ * config the request supplies — a scope widened past `.gitignore`, a custom rule whose finding quotes
136
+ * the text it matched, which together read any file in the checkout — a save rewrites the config, an
137
+ * open starts a program, a mark records a review in this user's name. On a loopback binding the
138
+ * sender is on this machine. With `--host` it is anyone who reaches the port, and a token carried in a
139
+ * page every one of them can load proves nothing about who they are. So off loopback there is no
140
+ * token for a page to carry, and the router refuses those requests before reading their bodies.
141
+ */
142
+ export function changeTokenFor(host) {
143
+ return isLoopbackHost(host) ? randomBytes(32).toString("hex") : undefined;
144
+ }
145
+ /** Why a request with a body is refused on a binding other machines reach (`changeTokenFor`). */
146
+ export const CHANGES_OFF_REMOTELY = "Forbidden: the viewer is reachable from other machines (--host), so it previews, saves, opens and marks nothing. Start it on a loopback address to make changes.";
147
+ // The header the config page's script sends its per-process token in. A custom header is also what
148
+ // makes a cross-origin `fetch` carrying it a preflighted request, which this server never approves.
149
+ export const TOKEN_HEADER = "x-wastech-viewer-token";
150
+ /**
151
+ * Why a request that changes or computes from the config is refused, or `undefined` to let it in.
152
+ *
153
+ * Checked on top of the `Host` and cross-site checks every request passes, because these are the
154
+ * only requests with a body the server acts on. A browser always sends `Origin` on a POST, so a
155
+ * missing one is a request no page of ours made. Fetch metadata, when present, must say
156
+ * same-origin. The body must be declared JSON: an HTML form cannot send that type, and a page that
157
+ * sets it on a cross-origin `fetch` triggers a preflight. Last, the token: it is random per process
158
+ * and appears only in the config page, so a request that carries it was made by a page this server
159
+ * rendered.
160
+ */
161
+ export function changeRequestProblem(headers, token) {
162
+ if (headers.origin === undefined ||
163
+ headers.origin !== `http://${headers.host ?? ""}`) {
164
+ return {
165
+ status: 403,
166
+ message: "Forbidden: a change must come from the viewer's own page.",
167
+ };
168
+ }
169
+ const site = headers["sec-fetch-site"];
170
+ if (site !== undefined && site !== "same-origin") {
171
+ return {
172
+ status: 403,
173
+ message: "Forbidden: a change must come from the viewer's own page.",
174
+ };
175
+ }
176
+ const mediaType = (headers["content-type"] ?? "")
177
+ .split(";", 1)[0]
178
+ .trim()
179
+ .toLowerCase();
180
+ if (mediaType !== "application/json") {
181
+ return {
182
+ status: 415,
183
+ message: "The request body must be sent as application/json.",
184
+ };
185
+ }
186
+ const sent = Buffer.from(headers[TOKEN_HEADER] ?? "", "utf8");
187
+ const expected = Buffer.from(token, "utf8");
188
+ // Compared in constant time, so the response time says nothing about how much of a guess matched.
189
+ if (sent.length !== expected.length || !timingSafeEqual(sent, expected)) {
190
+ return {
191
+ status: 403,
192
+ message: "Forbidden: the page that sent this change is out of date. Reload it and try again.",
193
+ };
194
+ }
195
+ return undefined;
196
+ }
@@ -0,0 +1,21 @@
1
+ import { type Launcher } from "./open-file.js";
2
+ export type ViewerOptions = {
3
+ cwd: string;
4
+ configPath?: string;
5
+ host: string;
6
+ port: number;
7
+ portExplicit: boolean;
8
+ watch: boolean;
9
+ allowConfigWrites?: boolean;
10
+ launch?: Launcher;
11
+ base?: string;
12
+ gitEnv?: NodeJS.ProcessEnv;
13
+ stateDir?: string;
14
+ };
15
+ export type RunningViewer = {
16
+ url: string;
17
+ documentCount: number;
18
+ notices: string[];
19
+ close(): Promise<void>;
20
+ };
21
+ export declare function startViewer(options: ViewerOptions): Promise<RunningViewer>;
package/dist/server.js ADDED
@@ -0,0 +1,224 @@
1
+ import { createServer } from "node:http";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { ChangeTracker } from "./changes.js";
5
+ import { Corpus } from "./corpus.js";
6
+ import { Diagnostics } from "./diagnostics.js";
7
+ import { EventHub } from "./event-hub.js";
8
+ import { sendText } from "./http-send.js";
9
+ import { launchDetached, openRefusal } from "./open-file.js";
10
+ import { RenderCache } from "./render-cache.js";
11
+ import { SinceReview } from "./review-state.js";
12
+ import { ReviewStore } from "./review-store.js";
13
+ import { ViewerRouter } from "./router.js";
14
+ import { DocumentSearch } from "./search.js";
15
+ import { changeTokenFor, exposesAbsolutePaths, isLoopbackHost, } from "./security.js";
16
+ import { defaultStateDir } from "./state-dir.js";
17
+ import { viewerContext } from "./viewer-context.js";
18
+ import { watchGitRefs, watchRepository } from "./watch.js";
19
+ // How many ports above the default to try before giving up, so a second viewer started beside a
20
+ // first one simply lands next to it.
21
+ const PORT_ATTEMPTS = 20;
22
+ export async function startViewer(options) {
23
+ const corpus = await Corpus.load({
24
+ cwd: options.cwd,
25
+ configPath: options.configPath,
26
+ });
27
+ const notices = [];
28
+ const changes = await ChangeTracker.open(corpus, {
29
+ base: options.base,
30
+ env: options.gitEnv,
31
+ watched: options.watch,
32
+ });
33
+ if (changes !== undefined) {
34
+ // Computed once now: a `--base` that names nothing is reported where it was typed, and the first
35
+ // visit to the Changes section finds the review ready.
36
+ const first = await changes.review(true);
37
+ if ("available" in first) {
38
+ notices.push(`changes: ${first.message} ${first.hint}`);
39
+ }
40
+ }
41
+ const ctx = createContext(options, corpus, changes);
42
+ const bound = { host: options.host, port: options.port };
43
+ const router = new ViewerRouter(ctx, bound);
44
+ const stopWatching = options.watch ? watchCorpus(ctx) : () => { };
45
+ const stopWatchingRefs = options.watch ? watchRefs(ctx) : () => { };
46
+ const server = createServer((request, response) => {
47
+ router.handle(request, response).catch((error) => {
48
+ // Logged locally with the request path only; the response stays generic so an error message
49
+ // carrying an absolute path never reaches the page.
50
+ process.stderr.write(`wastech-mdlint-viewer: ${request.url ?? ""}: ${error.message}\n`);
51
+ if (!response.headersSent) {
52
+ sendText(response, 500, "The viewer could not build this page; see the terminal for details.");
53
+ }
54
+ else {
55
+ response.end();
56
+ }
57
+ });
58
+ });
59
+ bound.port = await listen(server, options.host, options.port, options.portExplicit);
60
+ // The first lint runs once the server is answering, so the address is printed without waiting for
61
+ // it; pages opened before it finishes show their findings when the `diagnostics` event arrives.
62
+ const initialLint = setImmediate(() => {
63
+ ctx.relint();
64
+ if (options.watch && changes !== undefined) {
65
+ changes.warm();
66
+ }
67
+ });
68
+ return {
69
+ url: `http://${displayHost(options.host)}:${bound.port}/`,
70
+ documentCount: corpus.documents.size,
71
+ notices,
72
+ async close() {
73
+ clearImmediate(initialLint);
74
+ stopWatching();
75
+ stopWatchingRefs();
76
+ ctx.events.close();
77
+ await router.close();
78
+ await changes?.idle();
79
+ await new Promise((resolve) => {
80
+ server.close(() => {
81
+ resolve();
82
+ });
83
+ server.closeAllConnections();
84
+ });
85
+ },
86
+ };
87
+ }
88
+ // The state every route shares, built once for the whole run.
89
+ function createContext(options, corpus, changes) {
90
+ const git = changes?.git;
91
+ const reviewStore = openReviewStore(options, git);
92
+ return viewerContext({
93
+ corpus,
94
+ changes,
95
+ git,
96
+ reviewStore,
97
+ sinceReviews: reviewStore === undefined ? undefined : new SinceReview(reviewStore),
98
+ search: new DocumentSearch(),
99
+ diagnostics: new Diagnostics(),
100
+ renders: new RenderCache(corpus),
101
+ events: new EventHub(),
102
+ allowConfigWrites: options.allowConfigWrites === true,
103
+ showAbsolutePaths: exposesAbsolutePaths(options.host),
104
+ watch: options.watch,
105
+ launch: options.launch ?? launchDetached,
106
+ openRefused: openRefusal(options.host),
107
+ changeToken: changeTokenFor(options.host),
108
+ });
109
+ }
110
+ // Review marks, for a reader on this machine only: from another one, anyone who reached the port
111
+ // could record a review in this user's name and read which documents they have reviewed. Nothing
112
+ // is created here; the clone's folder appears with the first mark.
113
+ function openReviewStore(options, git) {
114
+ if (git === undefined || !isLoopbackHost(options.host)) {
115
+ return undefined;
116
+ }
117
+ return new ReviewStore({
118
+ // A relative `--state-dir` is taken from where the viewer was started, as a shell user
119
+ // expects, and fixed now, so it means the same folder for as long as the viewer runs.
120
+ stateDir: options.stateDir === undefined
121
+ ? defaultStateDir(process.platform, process.env, os.homedir())
122
+ : path.resolve(options.stateDir),
123
+ commonDir: git.commonDir,
124
+ keyOf: (relPath) => git.topLevelPath(relPath),
125
+ });
126
+ }
127
+ // Watches the work tree and applies what changed to the corpus. Changes are applied one batch at a
128
+ // time, in order: two overlapping updates could otherwise finish out of order and leave the older
129
+ // corpus in place.
130
+ function watchCorpus(ctx) {
131
+ let updates = Promise.resolve();
132
+ return watchRepository(ctx.corpus.rootDir, (paths) => {
133
+ updates = updates
134
+ .then(() => applyChanges(ctx, paths))
135
+ .catch((error) => {
136
+ process.stderr.write(`wastech-mdlint-viewer: could not apply changes: ${error.message}\n`);
137
+ });
138
+ });
139
+ }
140
+ async function applyChanges(ctx, paths) {
141
+ const { corpus, changes, events } = ctx;
142
+ const change = await corpus.applyChanges(paths);
143
+ // Every reported path, even one that changed no document: a Markdown file outside the corpus, or a
144
+ // document saved back to its committed text, changes the review all the same.
145
+ changes?.invalidate();
146
+ if (change.structural) {
147
+ ctx.renders.clear();
148
+ }
149
+ for (const changedPath of change.changed) {
150
+ const document = corpus.documents.get(changedPath);
151
+ if (document !== undefined) {
152
+ ctx.renders.forget(document);
153
+ }
154
+ }
155
+ if (change.changed.length === 0 && !change.structural) {
156
+ return;
157
+ }
158
+ // Every open page answers this event — a document page by reloading and waiting for its review,
159
+ // every other page's script by asking for the changes — so the review they will all join is
160
+ // started before they ask, and its context after it.
161
+ if (changes !== undefined && events.size > 0) {
162
+ changes.warm();
163
+ }
164
+ events.broadcast("change", {
165
+ paths: change.changed,
166
+ structural: change.structural,
167
+ });
168
+ ctx.relint();
169
+ }
170
+ // A commit, a checkout, a reset or a fetch moves what the review compares without touching the work
171
+ // tree. The review is rebuilt as soon as git records the move, and open pages are told only when it
172
+ // really is a different review: a ref of some other branch moving changes nothing they show.
173
+ function watchRefs(ctx) {
174
+ const { git, changes } = ctx;
175
+ if (git === undefined || changes === undefined) {
176
+ return () => { };
177
+ }
178
+ return watchGitRefs(git, {
179
+ onMove: () => {
180
+ void refreshAfterGitMove(ctx, changes);
181
+ },
182
+ onLost: () => {
183
+ changes.watchLost();
184
+ },
185
+ });
186
+ }
187
+ async function refreshAfterGitMove(ctx, changes) {
188
+ if (await changes.gitMoved().catch(() => false)) {
189
+ ctx.events.broadcast("git", {});
190
+ changes.warm();
191
+ }
192
+ }
193
+ async function listen(server, host, port, portExplicit) {
194
+ for (let attempt = 0;; attempt += 1) {
195
+ const candidate = port === 0 ? 0 : port + attempt;
196
+ try {
197
+ await new Promise((resolve, reject) => {
198
+ server.once("error", reject);
199
+ server.listen(candidate, host, () => {
200
+ server.off("error", reject);
201
+ resolve();
202
+ });
203
+ });
204
+ return server.address().port;
205
+ }
206
+ catch (error) {
207
+ const inUse = error.code === "EADDRINUSE";
208
+ if (!inUse ||
209
+ portExplicit ||
210
+ port === 0 ||
211
+ attempt + 1 >= PORT_ATTEMPTS) {
212
+ throw error;
213
+ }
214
+ }
215
+ }
216
+ }
217
+ // The address to print. A wildcard bind is reachable at localhost too, and that is the address the
218
+ // Host check accepts by name.
219
+ function displayHost(host) {
220
+ if (host === "0.0.0.0" || host === "::") {
221
+ return "localhost";
222
+ }
223
+ return host.includes(":") ? `[${host}]` : host;
224
+ }
@@ -0,0 +1,4 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ /** Where the pages' `Speculation-Rules` header points. */
3
+ export declare const SPECULATION_RULES_PATH = "/speculation-rules.json";
4
+ export declare function sendSpeculationRules(request: IncomingMessage, response: ServerResponse): void;
@@ -0,0 +1,49 @@
1
+ import { assetHeaders } from "./security.js";
2
+ /**
3
+ * The rules by which a browser fetches a document's page ahead of the click: a link to a document
4
+ * the pointer rests on for a moment (or presses) is fetched then, and the click is answered from
5
+ * that copy, so moving between documents no longer waits for the server to render the next one.
6
+ * Served as a file the pages name in a `Speculation-Rules` header rather than inline, which the
7
+ * Content-Security-Policy, allowing scripts from this origin only, would refuse.
8
+ *
9
+ * Only fetching, never rendering ahead: a page rendered in the background would run its scripts —
10
+ * restoring the tree from a scroll position saved before the click, opening an event stream of its
11
+ * own — before the reader ever saw it. A fetched page is only text until it is opened, and when it
12
+ * is opened later than it was fetched, its event stream sends it what happened in between.
13
+ *
14
+ * Left out: links within the page (`#…`), and the header's Blame switch, which makes git blame
15
+ * every line — work for a click that may never come.
16
+ *
17
+ * The header's sections are fetched the same way: the Changes page and the dashboard are the
18
+ * longest waits in the viewer, a fifth of a second of the server's and more, and a reader rests on
19
+ * a section a moment before choosing it. Only the header's links to them, not every link to the
20
+ * dashboard: the dashboard's own column headers link to it re-sorted, and pointing across them
21
+ * would have the server build the whole table again and again for nothing.
22
+ */
23
+ const SPECULATION_RULES = JSON.stringify({
24
+ prefetch: [
25
+ {
26
+ where: {
27
+ and: [
28
+ { href_matches: "/doc/*" },
29
+ { not: { selector_matches: 'a[href^="#"]' } },
30
+ { not: { selector_matches: ".blame-toggle" } },
31
+ ],
32
+ },
33
+ eagerness: "moderate",
34
+ },
35
+ {
36
+ where: { selector_matches: ".section-nav a" },
37
+ eagerness: "moderate",
38
+ },
39
+ ],
40
+ });
41
+ /** Where the pages' `Speculation-Rules` header points. */
42
+ export const SPECULATION_RULES_PATH = "/speculation-rules.json";
43
+ export function sendSpeculationRules(request, response) {
44
+ response.writeHead(200, {
45
+ ...assetHeaders(),
46
+ "Content-Type": "application/speculationrules+json",
47
+ });
48
+ response.end(request.method === "HEAD" ? undefined : SPECULATION_RULES);
49
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The state directory when `--state-dir` does not name one. Pure, with the platform, environment
3
+ * and home directory passed in, so each platform's answer is testable on any machine; the matching
4
+ * `path` flavor is used for each, so a Windows answer is a Windows path wherever it is computed.
5
+ */
6
+ export declare function defaultStateDir(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, home: string): string;
@@ -0,0 +1,31 @@
1
+ import path from "node:path";
2
+ // Where the viewer keeps what it remembers for a user between runs — today, which documents they
3
+ // have reviewed. Never the work tree, where it would show up as an untracked file and could be
4
+ // committed, and never `.git`, which belongs to git and is shared by everyone with access to the
5
+ // clone. Each platform's own place for an application's local state: what is kept there is
6
+ // rebuilt by reviewing again, so it is state, not configuration, and it stays on this machine
7
+ // rather than roaming with a Windows profile.
8
+ /**
9
+ * The state directory when `--state-dir` does not name one. Pure, with the platform, environment
10
+ * and home directory passed in, so each platform's answer is testable on any machine; the matching
11
+ * `path` flavor is used for each, so a Windows answer is a Windows path wherever it is computed.
12
+ */
13
+ export function defaultStateDir(platform, env, home) {
14
+ if (platform === "win32") {
15
+ const local = env.LOCALAPPDATA;
16
+ const base = local !== undefined && path.win32.isAbsolute(local)
17
+ ? local
18
+ : path.win32.join(home, "AppData", "Local");
19
+ return path.win32.join(base, "wastech-mdlint", "viewer");
20
+ }
21
+ if (platform === "darwin") {
22
+ return path.posix.join(home, "Library", "Application Support", "wastech-mdlint", "viewer");
23
+ }
24
+ // The XDG base directory specification has a relative value ignored, as if it were unset: it would
25
+ // otherwise resolve against whatever directory the viewer happened to start in.
26
+ const xdg = env.XDG_STATE_HOME;
27
+ const base = xdg !== undefined && path.posix.isAbsolute(xdg)
28
+ ? xdg
29
+ : path.posix.join(home, ".local", "state");
30
+ return path.posix.join(base, "wastech-mdlint", "viewer");
31
+ }
@@ -0,0 +1,49 @@
1
+ import type { Element } from "hast";
2
+ import type { Review } from "./changes.js";
3
+ import type { Diagnostics, FileCounts } from "./diagnostics.js";
4
+ import type { ReviewStore } from "./review-store.js";
5
+ export type ReviewStatus = "unreviewed" | "reviewed" | "changed";
6
+ export type ChangeLetter = "A" | "M" | "D" | "R";
7
+ /** A document the branch changed, as the tree marks it. */
8
+ export type ChangedFile = {
9
+ status: ChangeLetter;
10
+ oldPath?: string;
11
+ review: ReviewStatus | null;
12
+ };
13
+ export type ChangeMarks = {
14
+ files: ReadonlyMap<string, ChangedFile>;
15
+ changed: number;
16
+ review: {
17
+ left: number;
18
+ total: number;
19
+ } | null;
20
+ };
21
+ export type TreeMarks = {
22
+ findings: Readonly<Record<string, FileCounts>> | undefined;
23
+ changes: ChangeMarks | undefined;
24
+ current: readonly ("findings" | "changes")[];
25
+ };
26
+ /**
27
+ * The marks as the server holds them now, without asking git: the review is the one kept from the
28
+ * last request that needed it. A document's page has waited for a current one before it gets here;
29
+ * any other page takes what is kept rather than wait for git, and when nothing is kept, its script
30
+ * asks for the changes as the page opens.
31
+ */
32
+ export declare function treeMarksOf(state: {
33
+ diagnostics: Diagnostics;
34
+ review: Review | undefined;
35
+ reviewStore: ReviewStore | undefined;
36
+ watch: boolean;
37
+ }): Promise<TreeMarks>;
38
+ /** A file's count of findings, red when any is an error. */
39
+ export declare function findingsBadge(counts: FileCounts): Element;
40
+ /** The letter of what the branch did to a file, naming where a renamed one came from. */
41
+ export declare function changeLetter(file: ChangedFile): Element;
42
+ /** The dot beside a changed file left to review: never reviewed, or changed since. */
43
+ export declare function reviewDot(status: ReviewStatus | null): Element | undefined;
44
+ /**
45
+ * The count on the header's Changes section: what is left against everything that changed, the queue
46
+ * a reviewer works down, or only how many changed where marks cannot be read. Nothing when nothing
47
+ * changed.
48
+ */
49
+ export declare function changesCount(marks: ChangeMarks): Element | undefined;