@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
package/dist/corpus.js ADDED
@@ -0,0 +1,653 @@
1
+ import { readdir, readFile, realpath, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { buildContextGraph, candidateEscapesRoot, compareStrings, CONFIG_FILE_NAME, createScopeTester, filePart, isMarkdownFile, lintContext, loadConfiguration, loadContext, parseDocument, resolveTargetCandidates, } from "@wastech-mdlint/core";
4
+ // Names a directory link falls through to, in the order GitHub picks them for a folder view.
5
+ const DIRECTORY_INDEX_NAMES = ["README.md", "readme.md", "index.md"];
6
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/i;
7
+ /** Whether a link target leaves the repository (a URL, `mailto:`, a protocol-relative `//host`). */
8
+ export function isExternalTarget(target) {
9
+ return SCHEME.test(target) || target.startsWith("//");
10
+ }
11
+ export class Corpus {
12
+ root;
13
+ configPathOption;
14
+ state;
15
+ // The targets of each document's raw HTML (`<img src>`, `<a href>`), which core does not read:
16
+ // they are found while the page is rendered, from the tree of the same parse, and recorded here so
17
+ // `/file/` serves an embedded image the page asks for next. Keyed by the document object, which the
18
+ // corpus replaces when the file changes, so an edit drops the record with the page it came from.
19
+ embedded = new WeakMap();
20
+ // Keyed by the documents map, which the corpus replaces whenever the set of documents can change,
21
+ // so a folder gained or lost is never answered from an older listing.
22
+ folderSets = new WeakMap();
23
+ constructor(root, configPathOption,
24
+ // Replaced as a whole, never mutated, so a request rendered while an update is in flight sees
25
+ // one consistent snapshot rather than new documents against an old graph.
26
+ state) {
27
+ this.root = root;
28
+ this.configPathOption = configPathOption;
29
+ this.state = state;
30
+ }
31
+ static async load(params) {
32
+ const rootDir = path.resolve(params.cwd);
33
+ const root = { rootDir, rootRealPath: await realpath(rootDir) };
34
+ return new Corpus(root, params.configPath, await loadState(root, params.configPath));
35
+ }
36
+ get rootDir() {
37
+ return this.root.rootDir;
38
+ }
39
+ get documents() {
40
+ return this.state.documents;
41
+ }
42
+ get graph() {
43
+ return this.state.graph;
44
+ }
45
+ /**
46
+ * Every folder that holds a document, directly or further down, with `""` for the root of a
47
+ * corpus that has any. Worked out once per set of documents, as every folder link asks it.
48
+ */
49
+ get folders() {
50
+ return this.foldersOfState(this.state);
51
+ }
52
+ foldersOfState(state) {
53
+ let folders = this.folderSets.get(state.documents);
54
+ if (folders === undefined) {
55
+ folders = foldersOf(state.documents.keys());
56
+ if (state.documents.size > 0) {
57
+ folders.add("");
58
+ }
59
+ this.folderSets.set(state.documents, folders);
60
+ }
61
+ return folders;
62
+ }
63
+ /** The configuration the corpus was loaded with, replaced with it on a full reload. */
64
+ get configuration() {
65
+ return this.state.loaded;
66
+ }
67
+ /**
68
+ * The corpus as core judges a change set against it: the documents held now, the scope a deleted
69
+ * document is tested with, and the config's repository-relative path — which matches no changed
70
+ * path when the config lives outside the repository.
71
+ */
72
+ membership() {
73
+ const { documents, scope, loaded } = this.state;
74
+ return {
75
+ documents,
76
+ scope,
77
+ configPath: loaded.configPath === undefined
78
+ ? undefined
79
+ : path
80
+ .relative(this.root.rootDir, loaded.configPath)
81
+ .split(path.sep)
82
+ .join("/"),
83
+ };
84
+ }
85
+ /** Reload configuration and every document from disk. */
86
+ async reload() {
87
+ this.state = await loadState(this.root, this.configPathOption);
88
+ }
89
+ /**
90
+ * Bring the corpus up to date with a set of changed repo-relative paths.
91
+ *
92
+ * A full reload costs a walk and a parse of every document — seconds on a repository with a few
93
+ * hundred of them — while re-parsing the one file that was saved and rebuilding the graph costs
94
+ * milliseconds. So an edit to a known document is applied in place, and only what can change
95
+ * *which* files are documents pays for a full reload, because deciding membership means re-running
96
+ * core's include/exclude/gitignore discovery: the config or a `.gitignore`, a new Markdown file the
97
+ * scope takes in, a folder of documents that is gone, or a folder holding new ones. A watcher
98
+ * reports a moved or deleted folder as that one path and nothing for the files inside it, which is
99
+ * why folders are judged here at all.
100
+ *
101
+ * A path documents link to — an image that has just been saved, a file deleted — changes those
102
+ * documents' pages without changing the documents, so they are reported as changed too.
103
+ *
104
+ * `structural` reports that the set of documents may have changed, which every open page needs to
105
+ * know because each one shows the document tree.
106
+ */
107
+ async applyChanges(paths) {
108
+ const state = this.state;
109
+ const edited = paths.filter((changedPath) => state.documents.has(changedPath));
110
+ const others = paths.filter((changedPath) => !state.documents.has(changedPath));
111
+ if (await this.changesMembership(others)) {
112
+ await this.reload();
113
+ return { changed: [...paths].sort(compareStrings), structural: true };
114
+ }
115
+ const documents = new Map(state.documents);
116
+ const changed = new Set();
117
+ let structural = false;
118
+ for (const changedPath of edited) {
119
+ const previous = documents.get(changedPath);
120
+ const content = await readRepositoryFile(this.root, changedPath);
121
+ if (content === undefined) {
122
+ documents.delete(changedPath);
123
+ structural = true;
124
+ changed.add(changedPath);
125
+ }
126
+ else if (content !== previous.content) {
127
+ documents.set(changedPath, parseDocument({ path: changedPath, content }));
128
+ changed.add(changedPath);
129
+ }
130
+ }
131
+ const documentsChanged = changed.size > 0;
132
+ const relinked = await this.documentsReachingChangedFiles(others);
133
+ if (!documentsChanged && relinked.size === 0) {
134
+ return { changed: [], structural };
135
+ }
136
+ // Links resolve against the whole document set, so they are recomputed only once every changed
137
+ // document is in the map.
138
+ const links = new Map(state.links);
139
+ for (const documentPath of new Set([...changed, ...relinked])) {
140
+ const document = documents.get(documentPath);
141
+ if (document === undefined) {
142
+ links.delete(documentPath);
143
+ continue;
144
+ }
145
+ links.set(documentPath, await collectLinks(document, {
146
+ root: this.root,
147
+ documents,
148
+ siteRouter: state.loaded.settings.siteRouter,
149
+ membership: state,
150
+ }));
151
+ // Its raw HTML is resolved again when the page is next rendered.
152
+ this.embedded.delete(document);
153
+ changed.add(documentPath);
154
+ }
155
+ this.state = {
156
+ ...state,
157
+ documents,
158
+ // The graph is built from the documents alone; a file appearing beside them changes no edge,
159
+ // and keeping the same object keeps everything cached against it.
160
+ graph: documentsChanged
161
+ ? buildContextGraph(documents, {
162
+ siteRouter: state.loaded.settings.siteRouter,
163
+ idRef: state.loaded.settings.idRef,
164
+ })
165
+ : state.graph,
166
+ links,
167
+ };
168
+ return { changed: [...changed].sort(compareStrings), structural };
169
+ }
170
+ /**
171
+ * Where a local link or image target written in `fromPath` points.
172
+ *
173
+ * Candidates come from core's `resolveTargetCandidates`, the helper the context graph and the REF
174
+ * rules share, so a link the viewer can follow is a link REF-001 accepts and the reverse. Images
175
+ * resolve without the site router for the same reason core gives: a router maps URLs to Markdown
176
+ * sources, never to assets. A directory falls through to its README, which REF-001 does not do; a
177
+ * folder link that opens its README is what a reader expects from GitHub. A folder without one
178
+ * opens as a listing when it holds documents: REF-001 accepts any folder that exists, so marking
179
+ * such a link missing would contradict the linter over a link that works on GitHub.
180
+ */
181
+ resolve(fromPath, target, isImage) {
182
+ const { documents, links, loaded } = this.state;
183
+ const linked = links.get(fromPath)?.files;
184
+ for (const candidate of safeCandidates(fromPath, target, isImage, loaded.settings.siteRouter)) {
185
+ const page = documentAt(candidate, documents);
186
+ if (page !== undefined) {
187
+ return page;
188
+ }
189
+ if (linked?.has(candidate) === true) {
190
+ return { kind: "file", path: candidate };
191
+ }
192
+ const folder = folderAt(candidate, this.folders);
193
+ if (folder !== undefined) {
194
+ return folder;
195
+ }
196
+ }
197
+ return { kind: "missing" };
198
+ }
199
+ /**
200
+ * Where a target in a document's raw HTML points, by the same candidates as `resolve`, checking on
201
+ * disk whether a file there may be served. A file it finds is recorded against the document, which
202
+ * is what lets `/file/` serve it: core reads no raw HTML, so these targets are not among the links
203
+ * collected when the corpus loads.
204
+ */
205
+ async resolveEmbedded(document, target, isImage) {
206
+ const state = this.state;
207
+ let record = this.embedded.get(document);
208
+ if (record === undefined) {
209
+ record = { targets: new Set(), files: new Set() };
210
+ this.embedded.set(document, record);
211
+ }
212
+ const candidates = safeCandidates(document.path, target, isImage, state.loaded.settings.siteRouter);
213
+ for (const candidate of candidates) {
214
+ record.targets.add(candidate);
215
+ }
216
+ for (const candidate of candidates) {
217
+ const page = documentAt(candidate, state.documents);
218
+ if (page !== undefined) {
219
+ return page;
220
+ }
221
+ if (await servableFile(this.root, state, candidate)) {
222
+ record.files.add(candidate);
223
+ return { kind: "file", path: candidate };
224
+ }
225
+ const folder = folderAt(candidate, this.foldersOfState(state));
226
+ if (folder !== undefined) {
227
+ return folder;
228
+ }
229
+ }
230
+ return { kind: "missing" };
231
+ }
232
+ isLinkedFile(relPath) {
233
+ for (const links of this.state.links.values()) {
234
+ if (links.files.has(relPath)) {
235
+ return true;
236
+ }
237
+ }
238
+ for (const document of this.state.documents.values()) {
239
+ if (this.embedded.get(document)?.files.has(relPath) === true) {
240
+ return true;
241
+ }
242
+ }
243
+ return false;
244
+ }
245
+ /** Documents that link to `relPath`, each once, in stable order. */
246
+ backlinks(relPath) {
247
+ const sources = new Set();
248
+ for (const edge of this.state.graph.edges) {
249
+ if (edge.to === relPath && edge.from !== relPath) {
250
+ sources.add(edge.from);
251
+ }
252
+ }
253
+ return [...sources].sort(compareStrings);
254
+ }
255
+ /**
256
+ * The absolute path of the linked file at `relPath` if the viewer may hand it out now — judged
257
+ * again as it is served rather than trusted from when the link was collected, since a symlink can
258
+ * be pointed elsewhere in between and what it points at is what would be sent.
259
+ */
260
+ resolveFile(relPath) {
261
+ return resolveServableFile(this.root, this.state, relPath);
262
+ }
263
+ /**
264
+ * Lint the corpus as it is in memory now, with the configured rules.
265
+ *
266
+ * Through core's `lintContext`, which gives exactly what `wastech-mdlint lint` gives for the same
267
+ * tree but reuses the parsed documents and graph instead of discovering and parsing everything
268
+ * again — a fraction of a second after an edit rather than the seconds a fresh run takes.
269
+ */
270
+ lint() {
271
+ const { loaded, documents, graph } = this.state;
272
+ return lintContext({
273
+ cwd: this.root.rootDir,
274
+ context: { documents, graph },
275
+ rules: loaded.rules,
276
+ settings: loaded.settings,
277
+ });
278
+ }
279
+ /**
280
+ * Whether a candidate configuration selects the same documents as the loaded one.
281
+ *
282
+ * Parsing a document does not depend on the config, so a candidate that keeps `include`,
283
+ * `exclude` and `respectGitignore` is linted over the documents already parsed — new rules in a
284
+ * fraction of a second, new link settings after a rebuild of the graph. Only a new scope pays for
285
+ * core's discovery and a parse of the corpus it selects, because that is the one change that
286
+ * decides which files are documents.
287
+ */
288
+ sharesScope(candidate) {
289
+ return sameValues(scopeOf(this.state.loaded), scopeOf(candidate));
290
+ }
291
+ /** Whether an absolute path is, through any symlinks, inside the repository. */
292
+ async contains(absolutePath) {
293
+ const real = await realpath(absolutePath).catch(() => undefined);
294
+ if (real === undefined) {
295
+ return false;
296
+ }
297
+ const relativeToRoot = path.relative(this.root.rootRealPath, real);
298
+ return !(relativeToRoot === "" ||
299
+ relativeToRoot === ".." ||
300
+ relativeToRoot.startsWith(`..${path.sep}`) ||
301
+ path.isAbsolute(relativeToRoot));
302
+ }
303
+ /**
304
+ * Whether any of `paths`, none of them a document, can change which files are documents.
305
+ *
306
+ * Every judgment is core's scope: a Markdown path `include` takes in and nothing excludes, and a
307
+ * folder no `exclude` or `.gitignore` prunes. A folder event alone says little — some platforms
308
+ * report a folder whenever a file inside it is created — so a folder that still exists counts only
309
+ * when it holds a document the corpus lacks, and one that is gone only when documents lived in it.
310
+ */
311
+ async changesMembership(paths) {
312
+ if (paths.length === 0) {
313
+ return false;
314
+ }
315
+ const { loaded, documents, scope } = this.state;
316
+ const documentFolders = foldersOf(documents.keys());
317
+ for (const changedPath of paths) {
318
+ if (isCorpusControlFile(changedPath, loaded.configPath, this.root.rootDir)) {
319
+ return true;
320
+ }
321
+ if (documentFolders.has(changedPath)) {
322
+ if ((await this.statOf(changedPath)) === undefined) {
323
+ return true;
324
+ }
325
+ continue;
326
+ }
327
+ if (scope.includes(changedPath)) {
328
+ if (!(await scope.excludes(changedPath, false))) {
329
+ return true;
330
+ }
331
+ continue;
332
+ }
333
+ // Pruned paths are dropped before touching the disk: a build writing thousands of files into an
334
+ // excluded folder costs a pattern match each, not a `stat`.
335
+ if (await scope.excludes(changedPath, true)) {
336
+ continue;
337
+ }
338
+ if ((await this.statOf(changedPath))?.isDirectory() === true &&
339
+ (await this.holdsNewDocuments(changedPath))) {
340
+ return true;
341
+ }
342
+ }
343
+ return false;
344
+ }
345
+ // Whether a folder holds, at any depth core would walk, a Markdown file the scope takes in that is
346
+ // not a document yet. Stops at the first one, and never descends into a pruned folder.
347
+ async holdsNewDocuments(relDirectory) {
348
+ const { documents, scope } = this.state;
349
+ let entries;
350
+ try {
351
+ entries = await readdir(this.absolute(relDirectory), {
352
+ withFileTypes: true,
353
+ });
354
+ }
355
+ catch {
356
+ return false;
357
+ }
358
+ for (const entry of entries) {
359
+ const child = `${relDirectory}/${entry.name}`;
360
+ if (entry.isDirectory()) {
361
+ if (!(await scope.excludes(child, true)) &&
362
+ (await this.holdsNewDocuments(child))) {
363
+ return true;
364
+ }
365
+ }
366
+ else if (scope.includes(child) &&
367
+ !documents.has(child) &&
368
+ !(await scope.excludes(child, false))) {
369
+ return true;
370
+ }
371
+ }
372
+ return false;
373
+ }
374
+ /**
375
+ * The documents whose pages change because a file appeared or disappeared at one of `paths`, or
376
+ * under one of them when it names a folder: those with a link target there whose answer to "may
377
+ * this file be served?" is no longer the one recorded.
378
+ */
379
+ async documentsReachingChangedFiles(paths) {
380
+ const affected = new Set();
381
+ if (paths.length === 0) {
382
+ return affected;
383
+ }
384
+ const state = this.state;
385
+ // Every target under each of its folders too, so one lookup per changed path finds the targets
386
+ // at it and below it; a batch can hold thousands of paths a build wrote.
387
+ const byPath = new Map();
388
+ const index = (documentPath, record) => {
389
+ for (const target of record.targets) {
390
+ const segments = target.split("/");
391
+ for (let end = segments.length; end >= 1; end -= 1) {
392
+ const key = segments.slice(0, end).join("/");
393
+ const entries = byPath.get(key) ?? [];
394
+ entries.push({ documentPath, record, target });
395
+ byPath.set(key, entries);
396
+ }
397
+ }
398
+ };
399
+ for (const [documentPath, record] of state.links) {
400
+ index(documentPath, record);
401
+ }
402
+ for (const document of state.documents.values()) {
403
+ const record = this.embedded.get(document);
404
+ if (record !== undefined) {
405
+ index(document.path, record);
406
+ }
407
+ }
408
+ const servable = new Map();
409
+ for (const changedPath of paths) {
410
+ for (const { documentPath, record, target } of byPath.get(changedPath) ??
411
+ []) {
412
+ if (affected.has(documentPath)) {
413
+ continue;
414
+ }
415
+ let now = servable.get(target);
416
+ if (now === undefined) {
417
+ now = await servableFile(this.root, state, target);
418
+ servable.set(target, now);
419
+ }
420
+ if (now !== record.files.has(target)) {
421
+ affected.add(documentPath);
422
+ }
423
+ }
424
+ }
425
+ return affected;
426
+ }
427
+ absolute(relPath) {
428
+ return path.join(this.root.rootDir, ...relPath.split("/"));
429
+ }
430
+ statOf(relPath) {
431
+ return stat(this.absolute(relPath)).catch(() => undefined);
432
+ }
433
+ }
434
+ function scopeOf(loaded) {
435
+ const { include, exclude, respectGitignore } = loaded.config;
436
+ return [include, exclude, respectGitignore];
437
+ }
438
+ // Both sides come from the same JSON config through the same schema, so equal values serialize to
439
+ // equal text; a difference in key order only costs a discovery that was not needed.
440
+ function sameValues(left, right) {
441
+ return JSON.stringify(left) === JSON.stringify(right);
442
+ }
443
+ async function loadState(root, configPath) {
444
+ const loaded = await loadConfiguration({
445
+ cwd: root.rootDir,
446
+ explicitConfigPath: configPath,
447
+ });
448
+ const { documents, graph } = await loadContext({
449
+ cwd: root.rootDir,
450
+ config: loaded.config,
451
+ settings: loaded.settings,
452
+ });
453
+ const membership = {
454
+ scope: createScopeTester({ cwd: root.rootDir, config: loaded.config }),
455
+ servable: createScopeTester({
456
+ cwd: root.rootDir,
457
+ config: loaded.config,
458
+ respectGitignore: true,
459
+ }),
460
+ };
461
+ // Documents are checked concurrently: each check is a few filesystem round trips, and awaiting them
462
+ // one document at a time added seconds to startup on a corpus of a few hundred documents.
463
+ // `Promise.all` keeps the input order, so the map's order stays the corpus order.
464
+ const links = new Map(await Promise.all([...documents.values()].map(async (document) => [
465
+ document.path,
466
+ await collectLinks(document, {
467
+ root,
468
+ documents,
469
+ siteRouter: loaded.settings.siteRouter,
470
+ membership,
471
+ }),
472
+ ])));
473
+ return { loaded, documents, graph, links, ...membership };
474
+ }
475
+ async function collectLinks(document, scope) {
476
+ const { root, documents, siteRouter, membership } = scope;
477
+ const links = { targets: new Set(), files: new Set() };
478
+ const targets = [
479
+ ...document.links
480
+ .filter((link) => link.kind === "local-file")
481
+ .map((link) => ({ target: link.rawTarget, isImage: false })),
482
+ ...document.images.map((image) => ({
483
+ target: image.rawTarget,
484
+ isImage: true,
485
+ })),
486
+ ];
487
+ for (const { target, isImage } of targets) {
488
+ const candidates = safeCandidates(document.path, target, isImage, siteRouter);
489
+ for (const candidate of candidates) {
490
+ links.targets.add(candidate);
491
+ }
492
+ for (const candidate of candidates) {
493
+ if (documentAt(candidate, documents) !== undefined) {
494
+ break;
495
+ }
496
+ if (await servableFile(root, membership, candidate)) {
497
+ links.files.add(candidate);
498
+ break;
499
+ }
500
+ }
501
+ }
502
+ return links;
503
+ }
504
+ /** Whether the viewer may hand out the repository file at `relPath` as a linked file. */
505
+ async function servableFile(root, membership, relPath) {
506
+ return (await resolveServableFile(root, membership, relPath)) !== undefined;
507
+ }
508
+ /**
509
+ * The absolute path of the repository file at `relPath` if the viewer may hand it out as a linked
510
+ * file: it is there, and neither the path the link names nor the file it really reaches is Markdown —
511
+ * a Markdown file outside the corpus is one the config keeps out of the viewer exactly as it keeps it
512
+ * out of a lint run — or covered by an `exclude` pattern or a `.gitignore`.
513
+ *
514
+ * The patterns are tested against the real file as well as the written path because a written path
515
+ * can miss them and still reach the file. A symlink `docs/env.txt` to `../.env` passes every pattern
516
+ * under its own name and reads the ignored `.env`. And patterns compare letter case exactly while
517
+ * case-insensitive file systems — the usual Windows and macOS ones, a Windows drive mounted in WSL —
518
+ * do not, so `.GIT/config` slips past the default `.git` exclude and opens `.git/config`; a Windows 8.3
519
+ * short name (`SECRET~1.TXT`) is another spelling of the same kind.
520
+ *
521
+ * `fs.promises.realpath` follows every link and, on Windows and macOS, also returns each name as it is
522
+ * stored (the callback `fs.realpath` keeps the spelling it was given). A path that then turns out to
523
+ * differ from the real one only in letter case is refused outright, so a link means the same file —
524
+ * or none — on every operating system, as on a case-sensitive one. Linux's realpath keeps the
525
+ * spelling it was given even on a case-insensitive mount, so last, each name of the real path must be
526
+ * listed in its folder exactly as spelled: a file reached under any other spelling is refused there
527
+ * too.
528
+ */
529
+ async function resolveServableFile(root, membership, relPath) {
530
+ if (!(await mayHandOut(membership, relPath))) {
531
+ return undefined;
532
+ }
533
+ const real = await resolveRepositoryFile(root, relPath);
534
+ if (real === undefined) {
535
+ return undefined;
536
+ }
537
+ if (real.relPath !== relPath) {
538
+ // `toLowerCase` takes no locale, so it folds case the same way on every machine.
539
+ if (real.relPath.toLowerCase() === relPath.toLowerCase()) {
540
+ return undefined;
541
+ }
542
+ if (!(await mayHandOut(membership, real.relPath))) {
543
+ return undefined;
544
+ }
545
+ }
546
+ return (await listedAsSpelled(root.rootRealPath, real.relPath))
547
+ ? real.absolutePath
548
+ : undefined;
549
+ }
550
+ // Whether every name in `relPath` appears, exactly as spelled, in the listing of the folder above it.
551
+ // Last of the checks, as the only one that lists folders.
552
+ async function listedAsSpelled(rootRealPath, relPath) {
553
+ let folder = rootRealPath;
554
+ for (const name of relPath.split("/")) {
555
+ const names = await readdir(folder).catch(() => undefined);
556
+ if (names?.includes(name) !== true) {
557
+ return false;
558
+ }
559
+ folder = path.join(folder, name);
560
+ }
561
+ return true;
562
+ }
563
+ // The checks a path passes on its name alone, before anything on disk is asked about it.
564
+ async function mayHandOut(membership, relPath) {
565
+ if (isMarkdownFile(relPath) || membership.scope.includes(relPath)) {
566
+ return false;
567
+ }
568
+ return !(await membership.servable.excludes(relPath, false));
569
+ }
570
+ // Core's candidate list for a written target, minus anything that climbs out of the repository: such
571
+ // a target can never be a document and must never become a file the viewer serves.
572
+ function safeCandidates(fromPath, target, isImage, siteRouter) {
573
+ const targetFile = filePart(target);
574
+ if (targetFile.length === 0 || isExternalTarget(targetFile)) {
575
+ return [];
576
+ }
577
+ return resolveTargetCandidates(fromPath, targetFile, isImage ? undefined : siteRouter).filter((candidate) => !candidateEscapesRoot(candidate));
578
+ }
579
+ // The document a candidate names, directly or as the README of the folder it names.
580
+ function documentAt(candidate, documents) {
581
+ if (documents.has(candidate)) {
582
+ return { kind: "document", path: candidate };
583
+ }
584
+ const directory = candidate.replace(/\/+$/, "");
585
+ for (const name of DIRECTORY_INDEX_NAMES) {
586
+ const indexPath = directory === "" || directory === "." ? name : `${directory}/${name}`;
587
+ if (documents.has(indexPath)) {
588
+ return { kind: "document", path: indexPath };
589
+ }
590
+ }
591
+ return undefined;
592
+ }
593
+ // The folder a candidate names, when documents are under it. Checked after the files, so a file and
594
+ // a folder of the same name cannot both answer.
595
+ function folderAt(candidate, folders) {
596
+ const directory = candidate.replace(/\/+$/, "");
597
+ const folder = directory === "." ? "" : directory;
598
+ return folders.has(folder) ? { kind: "folder", path: folder } : undefined;
599
+ }
600
+ // Every folder that holds a document, directly or further down.
601
+ function foldersOf(paths) {
602
+ const folders = new Set();
603
+ for (const relPath of paths) {
604
+ const segments = relPath.split("/");
605
+ for (let end = 1; end < segments.length; end += 1) {
606
+ folders.add(segments.slice(0, end).join("/"));
607
+ }
608
+ }
609
+ return folders;
610
+ }
611
+ /**
612
+ * Where a repository file really is — its absolute path and its repository-relative POSIX path, both
613
+ * through every symlink and in the letter case stored on disk — or `undefined` if it is missing, not
614
+ * a regular file, or, through a symlink, outside the repository. Core's loader applies the same
615
+ * symlink rule to the documents it reads; this applies it to every file the viewer reads after
616
+ * startup.
617
+ */
618
+ async function resolveRepositoryFile(root, relPath) {
619
+ let real;
620
+ try {
621
+ real = await realpath(path.join(root.rootDir, ...relPath.split("/")));
622
+ }
623
+ catch {
624
+ return undefined;
625
+ }
626
+ const relativeToRoot = path.relative(root.rootRealPath, real);
627
+ if (relativeToRoot === "" ||
628
+ relativeToRoot === ".." ||
629
+ relativeToRoot.startsWith(`..${path.sep}`) ||
630
+ path.isAbsolute(relativeToRoot)) {
631
+ return undefined;
632
+ }
633
+ const stats = await stat(real).catch(() => undefined);
634
+ return stats?.isFile() === true
635
+ ? { absolutePath: real, relPath: relativeToRoot.split(path.sep).join("/") }
636
+ : undefined;
637
+ }
638
+ async function readRepositoryFile(root, relPath) {
639
+ const real = await resolveRepositoryFile(root, relPath);
640
+ if (real === undefined) {
641
+ return undefined;
642
+ }
643
+ return readFile(real.absolutePath, "utf8").catch(() => undefined);
644
+ }
645
+ // A change to the config or to any `.gitignore` can move files in or out of the corpus.
646
+ function isCorpusControlFile(relPath, configPath, rootDir) {
647
+ const name = relPath.split("/").pop() ?? "";
648
+ if (name === ".gitignore" || name === CONFIG_FILE_NAME) {
649
+ return true;
650
+ }
651
+ return (configPath !== undefined &&
652
+ path.relative(rootDir, configPath).split(path.sep).join("/") === relPath);
653
+ }
@@ -0,0 +1,14 @@
1
+ import type { ElementContent } from "hast";
2
+ import { type DashboardQuery, type DashboardResult, type DashboardSource } from "./dashboard.js";
3
+ export type DashboardPage = {
4
+ params: URLSearchParams;
5
+ source: DashboardSource;
6
+ } & ({
7
+ ok: true;
8
+ query: DashboardQuery;
9
+ result: DashboardResult;
10
+ } | {
11
+ ok: false;
12
+ message: string;
13
+ });
14
+ export declare function renderDashboardArticle(page: DashboardPage): ElementContent[];