cornfield 0.51.5 → 0.51.6

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.
@@ -77,7 +77,8 @@ export { DERIVER_CONTRACT, deriverProblems };
77
77
  * @property {(rel: string) => boolean} exists
78
78
  * @property {(rel: string) => boolean} isDir
79
79
  * @property {(rel: string) => string[]} list a folder's entries, sorted
80
- * @property {(rel: string, test?: (file: string) => boolean) => string[]} walk every file under a folder that `test` accepts, skipping node_modules, .git and the like
80
+ * @property {(rel: string, test?: (file: string) => boolean, onSkip?: (rel: string, reason: 'outside' | 'walked' | 'missing') => void, seen?: Set<string>) => string[]} walk every file under a folder that `test` accepts, skipping node_modules, .git and the like; a symlink is followed only while it stays in the repo, and a real folder is walked once (`onSkip` hears of each link left out; walks that share `seen` read a folder once between them)
81
+ * @property {(rel: string) => boolean} inside whether a path is in the repo once its symlinks are followed
81
82
  */
82
83
 
83
84
  /**
package/core/repo.js CHANGED
@@ -24,13 +24,70 @@ export function repoReader(root) {
24
24
  try { return fs.statSync(abs(rel)).isDirectory(); } catch { return false; }
25
25
  };
26
26
  const list = (rel) => (isDir(rel) ? fs.readdirSync(abs(rel)).sort() : []);
27
- /** Every file under `rel` that `test` accepts, skipping SKIP_DIRS */
28
- const walk = (rel, test = () => true) => list(rel).flatMap((name) => {
29
- if (SKIP_DIRS.has(name)) return [];
30
- const child = rel && rel !== '.' ? `${rel}/${name}` : name;
31
- return isDir(child) ? walk(child, test) : test(child) ? [child] : [];
32
- });
33
- return { root, read, exists, isDir, list, walk };
27
+ const realRoot = (() => { try { return fs.realpathSync(root); } catch { return path.resolve(root); } })();
28
+ /** Whether real path `real` is `dir` or under it (by whole segments: `/x/repo-other` is not under `/x/repo`) */
29
+ const under = (dir, real) => { const r = path.relative(dir, real); return r === '' || (r !== '..' && !r.startsWith(`..${path.sep}`) && !path.isAbsolute(r)); };
30
+ const within = (real) => under(realRoot, real);
31
+ /**
32
+ * Whether `rel` lies in the repo once every symlink on its way is followed. A path that is not there is judged by
33
+ * the nearest folder on its way that is, with the rest as written (a `..` included): nothing can be read from it.
34
+ */
35
+ const inside = (rel) => {
36
+ if (String(rel).includes('\0')) return false;
37
+ let at = abs(rel);
38
+ let rest = '';
39
+ for (;;) {
40
+ try { return within(path.resolve(fs.realpathSync(at), rest)); } catch { /* not there, or a link loop: try its folder */ }
41
+ const up = path.dirname(at);
42
+ if (up === at) return false;
43
+ rest = path.join(path.basename(at), rest);
44
+ at = up;
45
+ }
46
+ };
47
+ /**
48
+ * Every file under `rel` that `test` accepts, sorted by folder, skipping SKIP_DIRS. A symlink is followed only while
49
+ * it stays in the repo, and a real folder is walked once: a link to a folder under `rel` is left to the real folder,
50
+ * and of two links to one other folder the first wins. `onSkip(path, reason)` hears of each link left out: 'outside'
51
+ * (out of the repo, to a folder or to a file `test` accepts), 'walked' (to a folder already walked) or 'missing' (to
52
+ * nothing, or a loop of links, named like a file `test` accepts). Walks that share `seen` (a set of real folders) read
53
+ * each folder once between them, a folder two of them name in the repo's own words in silence. Only links pay a
54
+ * `realpath`.
55
+ */
56
+ const walk = (rel, test = () => true, onSkip = () => {}, seen = new Set()) => {
57
+ const start = rel && rel !== '.' ? rel : '';
58
+ let startReal;
59
+ try { startReal = fs.realpathSync(abs(start)); } catch { return []; }
60
+ if (!within(startReal)) { onSkip(start, 'outside'); return []; }
61
+ const linked = startReal !== path.join(realRoot, start);
62
+ if (seen.has(startReal)) { if (linked) onSkip(start, 'walked'); return []; }
63
+ // `viaLink`: `dir` is reached through a link, so a real folder in it may be one walked by its own name
64
+ const go = (dir, real, viaLink) => {
65
+ seen.add(real);
66
+ let entries;
67
+ try { entries = fs.readdirSync(abs(dir), { withFileTypes: true }); } catch { return []; }
68
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
69
+ return entries.flatMap((e) => {
70
+ if (SKIP_DIRS.has(e.name)) return [];
71
+ const child = dir ? `${dir}/${e.name}` : e.name;
72
+ if (!e.isSymbolicLink()) {
73
+ if (!e.isDirectory()) return test(child) ? [child] : [];
74
+ const childReal = path.join(real, e.name);
75
+ if (seen.has(childReal)) { if (viaLink) onSkip(child, 'walked'); return []; }
76
+ return go(child, childReal, viaLink);
77
+ }
78
+ let target;
79
+ try { target = fs.realpathSync(abs(child)); } catch { if (test(child)) onSkip(child, 'missing'); return []; }
80
+ const folder = isDir(child);
81
+ if (!within(target)) { if (folder || test(child)) onSkip(child, 'outside'); return []; }
82
+ if (!folder) return test(child) ? [child] : [];
83
+ const ownRoute = under(startReal, target) && !path.relative(startReal, target).split(path.sep).some((s) => SKIP_DIRS.has(s));
84
+ if (ownRoute || seen.has(target)) { onSkip(child, 'walked'); return []; }
85
+ return go(child, target, true);
86
+ });
87
+ };
88
+ return go(start, startReal, linked);
89
+ };
90
+ return { root, read, exists, isDir, list, walk, inside };
34
91
  }
35
92
 
36
93
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.51.5",
3
+ "version": "0.51.6",
4
4
  "description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
5
5
  "license": "MIT",
6
6
  "author": "popcorn245 (https://github.com/popcorn245)",
@@ -24,17 +24,30 @@ export const DEFAULT_PATHS = ['README.md', 'docs'];
24
24
  const isMarkdown = (f) => /\.md$/i.test(f);
25
25
  const isReadme = (f) => /^readme\.md$/i.test(path.posix.basename(f));
26
26
 
27
+ /** What a docs warning says of a link the walk leaves out (core/repo.js `walk`) */
28
+ const SKIPPED = { outside: 'is a link to somewhere outside the repo; it is not followed', walked: 'leads to a folder already read; it is not read again', missing: 'is a link to nothing; it is not read' };
29
+
30
+ /** The files the site writes itself: a doc's page may not land on one (see `docOutputs`) */
31
+ export const SITE_OUTPUTS = ['map.html', 'site.css', '.cornfield-site'];
32
+
27
33
  /**
28
- * The Markdown files the paths name, sorted, each once.
29
- * @param {{ exists: Function, isDir: Function, walk: Function }} io
34
+ * The Markdown files the paths name, sorted, each once. A path that leaves the repo (`..`, an absolute path, a
35
+ * symlink to somewhere else), and a file or folder under one that does, is left out and said by `refuse`.
36
+ * @param {{ exists: Function, isDir: Function, walk: Function, inside?: Function }} io
30
37
  * @param {string[]} paths
38
+ * @param {(message: string, severity: 'problem' | 'warning') => void} [refuse]
31
39
  */
32
- export function docFiles(io, paths) {
40
+ export function docFiles(io, paths, refuse = () => {}) {
33
41
  const out = new Set();
42
+ const inside = io.inside || (() => true);
43
+ const seen = new Set(); // the real folders read so far: two paths that reach one folder read it once
44
+ const told = new Set();
34
45
  for (const p of paths) {
35
- const rel = p.replace(/^\.\/+/, '').replace(/\/+$/, '');
36
- if (io.isDir(rel)) io.walk(rel, isMarkdown).forEach((f) => out.add(f));
37
- else if (isMarkdown(rel) && io.exists(rel)) out.add(rel);
46
+ const rel = path.posix.normalize(p.replace(/^\.\/+/, '').replace(/\/+$/, '') || '.');
47
+ if (path.isAbsolute(p) || path.win32.isAbsolute(p) || rel === '..' || rel.startsWith('../') || !inside(rel)) { refuse(`docs: ${JSON.stringify(p)} is outside the repo; only files and folders of the repo are read.`, 'problem'); continue; }
48
+ if (io.isDir(rel)) {
49
+ io.walk(rel, isMarkdown, (f, why) => { const m = `docs: ${f || '.'} ${SKIPPED[why]}.`; if (!told.has(m)) { told.add(m); refuse(m, 'warning'); } }, seen).forEach((f) => out.add(f));
50
+ } else if (isMarkdown(rel) && io.exists(rel)) out.add(rel);
38
51
  }
39
52
  return [...out].sort();
40
53
  }
@@ -54,6 +67,31 @@ export function docOutput(file) {
54
67
  return route.endsWith('/') ? `${route.slice(1)}index.html` : `${route.slice(1)}.html`;
55
68
  }
56
69
 
70
+ /**
71
+ * Where each doc lands, by file. A doc whose page would land on a file the site writes itself (`map.md` → `map.html`),
72
+ * or on another doc's page (`index.md` beside a README), goes to the next free `-doc` name (`map-doc.html`), so no
73
+ * page is written over; `renamed` lists `[file, output, other]` for each. A README keeps the folder's `index.html`,
74
+ * and the first of two docs keeps its name. A doc with no clash keeps `docOutput(file)`.
75
+ * @param {string[]} files
76
+ */
77
+ export function docOutputs(files) {
78
+ const taken = new Map(SITE_OUTPUTS.map((o) => [o, null]));
79
+ const outputs = new Map();
80
+ const renamed = [];
81
+ for (const file of [...files].sort((a, b) => Number(isReadme(b)) - Number(isReadme(a)))) {
82
+ let out = docOutput(file);
83
+ if (taken.has(out)) {
84
+ const other = taken.get(out);
85
+ const stem = out.replace(/\.html$/, '');
86
+ for (let n = 1; taken.has(out); n++) out = `${stem}-doc${n > 1 ? `-${n}` : ''}.html`;
87
+ renamed.push([file, out, other]);
88
+ }
89
+ taken.set(out, file);
90
+ outputs.set(file, out);
91
+ }
92
+ return { outputs, renamed };
93
+ }
94
+
57
95
  /** The page node id of a doc: `page-doc-` and its path, in kebab case */
58
96
  export const docPageId = (file) => `page-doc-${file.replace(/\.md$/i, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`;
59
97
 
@@ -84,13 +122,18 @@ export default {
84
122
  derive(ctx) {
85
123
  const { paths = DEFAULT_PATHS, app: appId = 'app-docs', label = 'docs', parent = 'root' } = ctx.options || {};
86
124
  if (!Array.isArray(paths) || !paths.every((p) => typeof p === 'string' && p)) throw new Error('options.paths is a list of files and folders, like ["README.md", "docs"].');
87
- const files = docFiles(ctx, paths);
88
- const empty = { nodes: [], edges: [], info: { pages: [] } };
89
- if (!files.length) return { ...empty, warnings: ctx.options?.paths ? [`docs: no Markdown in ${paths.join(', ')}.`] : [] };
90
-
91
125
  const warnings = [];
92
126
  const problems = [];
93
- const nodes = [{ id: appId, type: 'app', label, file: paths.map((p) => p.replace(/^\.\/+/, '').replace(/\/+$/, '')).find((p) => ctx.exists(p)) }];
127
+ const refuse = (message, severity) => (severity === 'problem' ? problems : warnings).push(message);
128
+ const files = docFiles(ctx, paths, refuse);
129
+ const empty = { nodes: [], edges: [], info: { pages: [] } };
130
+ if (!files.length) return { ...empty, warnings: [...warnings, ...(ctx.options?.paths ? [`docs: no Markdown in ${paths.join(', ')}.`] : [])], problems };
131
+
132
+ // Two docs that would be one page id are a problem (below); only the first is placed, and only its name can clash
133
+ const ids = new Set();
134
+ const { outputs, renamed } = docOutputs(files.filter((f) => !ids.has(docPageId(f)) && ids.add(docPageId(f))));
135
+ for (const [file, output, other] of renamed) warnings.push(`docs: ${file} would be page ${docOutput(file)}, ${other ? `which ${other} has` : 'which the site writes itself'}; it is written to ${output}.`);
136
+ const nodes = [{ id: appId, type: 'app', label, file: paths.map((p) => p.replace(/^\.\/+/, '').replace(/\/+$/, '')).find((p) => ctx.exists(p) && ctx.inside(p)) }];
94
137
  const edges = [];
95
138
  if (ctx.nodes.some((n) => n.id === parent)) edges.push({ from: parent, to: appId });
96
139
 
@@ -102,7 +145,7 @@ export default {
102
145
  if (clash) { problems.push(`docs: ${file} and ${clash.file} would both be page "${id}"; rename one.`); continue; }
103
146
  const text = ctx.read(file);
104
147
  const { title, headings } = renderMarkdown(text);
105
- const page = { id, file, route: docRoute(file), output: docOutput(file), title: title || path.posix.basename(file, '.md'), anchors: headings.map((h) => h.id), text };
148
+ const page = { id, file, route: docRoute(file), output: outputs.get(file), title: title || path.posix.basename(file, '.md'), anchors: headings.map((h) => h.id), text };
106
149
  pages.push(page);
107
150
  byFile.set(file, page);
108
151
  nodes.push({ id, type: 'page', label: page.route, file, summary: page.title });
@@ -126,6 +169,7 @@ export default {
126
169
  if (t.external) continue;
127
170
  if (t.outside) { warnings.push(`docs: ${page.file} links to "${href}", outside the repo.`); continue; }
128
171
  const target = t.path === '' ? page.file : t.path;
172
+ if (!ctx.inside(target)) { warnings.push(`docs: ${page.file} links to "${href}", which leads outside the repo.`); continue; }
129
173
  if (!ctx.exists(target)) { problems.push(`docs: ${page.file} links to "${href}", but ${target} is not in the repo.`); continue; }
130
174
  const readme = ctx.isDir(target) ? files.find((f) => path.posix.dirname(f) === target && isReadme(f)) : null;
131
175
  const doc = byFile.get(readme || target);
@@ -18,10 +18,11 @@ import { escapeHtml as esc } from '../../core/text.js';
18
18
  import { deriveTopology } from '../../core/derive.js';
19
19
  import { readTopology } from '../../core/validate.js';
20
20
  import { renderMarkdown, safeUrl } from './markdown.js';
21
- import docsDeriver, { resolveLink } from './index.js';
21
+ import docsDeriver, { resolveLink, SITE_OUTPUTS } from './index.js';
22
+ import { repoReader } from '../../core/repo.js';
22
23
 
23
24
  /** The file a built site holds, so a rebuild knows the folder is its own */
24
- export const SITE_MARKER = '.cornfield-site';
25
+ export const SITE_MARKER = SITE_OUTPUTS[2];
25
26
  const IMAGE = /\.(png|jpe?g|gif|svg|webp|avif)$/i;
26
27
 
27
28
  /** The forge URL a repo file is shown at, from the config's forge, or null */
@@ -102,6 +103,7 @@ ${body}
102
103
  `;
103
104
 
104
105
  for (const page of pages) {
106
+ if (SITE_OUTPUTS.includes(page.output) || pages.some((q) => q !== page && q.output === page.output)) throw new Error(`${page.file} would be written to ${page.output}, which another page or the site itself writes.`);
105
107
  const { html } = renderMarkdown(read(page.file), {
106
108
  link: (href, { image }) => {
107
109
  const t = resolveLink(page.file, href);
@@ -218,21 +220,32 @@ export async function buildSite({ config, derivers, out, sourceUrl = sourceUrlOf
218
220
  const derived = await deriveTopology({ root, config, derivers: list, map: readTopology(config) });
219
221
  const pages = derived.info.docs?.pages || [];
220
222
  if (!pages.length) throw new Error('There are no docs to build: the docs deriver found no Markdown (see its "paths" option).');
221
- const read = (rel) => fs.readFileSync(path.join(root, rel), 'utf8');
222
- const exists = (rel) => fs.existsSync(path.join(root, rel));
223
- const isDir = (rel) => { try { return fs.statSync(path.join(root, rel)).isDirectory(); } catch { return false; } };
223
+ // What the site reads is the repo's: a path that leads out of it, by `..` or a symlink, is as if it were not there
224
+ const io = repoReader(root);
225
+ const read = (rel) => {
226
+ if (!io.inside(rel)) throw new Error(`${rel} is outside the repo.`);
227
+ return fs.readFileSync(path.join(root, rel), 'utf8');
228
+ };
229
+ const exists = (rel) => io.inside(rel) && io.exists(rel);
230
+ const isDir = (rel) => io.inside(rel) && io.isDir(rel);
224
231
  const files = siteFiles({ title: config.title || 'Docs', pages, nodes: derived.nodes, edges: derived.edges, read, exists, isDir, sourceUrl });
225
232
  // Only a folder this builds (it leaves a marker) or an empty one is emptied: never a folder of the repo's own files
226
233
  if (fs.existsSync(out) && fs.readdirSync(out).length && !fs.existsSync(path.join(out, SITE_MARKER))) throw new Error(`${out} is not empty and is not a site cornfield built: pick another folder, or empty it first.`);
227
234
  fs.rmSync(out, { recursive: true, force: true });
228
235
  files[SITE_MARKER] = 'Built by cornfield docs. This folder is emptied on every build.\n';
236
+ const problems = [...derived.problems];
237
+ const written = [];
229
238
  for (const [rel, content] of Object.entries(files)) {
230
239
  const dest = path.join(out, rel);
240
+ // What is written lies in `out`, whatever a doc is called
241
+ if (path.relative(out, dest).split(path.sep)[0] === '..' || path.isAbsolute(path.relative(out, dest))) { problems.push(`docs: ${rel} would be written outside ${path.basename(out)}; it is not.`); continue; }
242
+ if (typeof content !== 'string' && !io.inside(content.copy)) { problems.push(`docs: ${content.copy} leads outside the repo; it is not copied.`); continue; }
231
243
  fs.mkdirSync(path.dirname(dest), { recursive: true });
232
244
  if (typeof content === 'string') fs.writeFileSync(dest, content, 'utf8');
233
245
  else fs.copyFileSync(path.join(root, content.copy), dest);
246
+ written.push(rel);
234
247
  }
235
- return { pages: pages.length, files: Object.keys(files).sort(), warnings: derived.warnings, problems: derived.problems };
248
+ return { pages: pages.length, files: written.sort(), warnings: derived.warnings, problems };
236
249
  }
237
250
 
238
251
  const SITE_CSS = `:root {