cornfield 0.57.2 → 0.59.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.
package/core/config.js CHANGED
@@ -33,6 +33,7 @@
33
33
  * embed: { origins: [] }, // exact origins of sibling apps that may read, and decide a review, as the signed-in maintainer (docs/embedding.md)
34
34
  * proxy: {}, // { '/api/': 'http://127.0.0.1:3245' }: same-origin paths for a live source
35
35
  * importMap: {}, // bare imports a repo-local browser module needs: { name: '/repo/path.js' }
36
+ * history: false, // true: read the repo's git history for the History layer, a node's commits and Replay (docs/config.md#history; spec 0014)
36
37
  * dataDir: null, // where cornfield keeps its own state (reviews; the SQLite file in v1)
37
38
  * }
38
39
  *
@@ -46,6 +47,7 @@ import os from 'node:os';
46
47
  import path from 'node:path';
47
48
  import { pathToFileURL, fileURLToPath } from 'node:url';
48
49
  import { repoReader } from './repo.js';
50
+ import { linkProblems } from './schema.js';
49
51
  import { themeProblems } from './theme.js';
50
52
  import { brandProblems } from './brand.js';
51
53
  import { stringsProblems } from './strings.js';
@@ -181,6 +183,7 @@ export const DEFAULTS = Object.freeze({
181
183
  embed: { origins: [] },
182
184
  proxy: {},
183
185
  importMap: {},
186
+ history: false,
184
187
  dataDir: null,
185
188
  });
186
189
 
@@ -392,6 +395,7 @@ export function configProblems(c) {
392
395
  if (l !== undefined && (!isText(l) || l.includes(',') || l.trim() !== l || l.length > MAX_LABEL)) out.push(`threads.label is the name of the label that makes an issue an idea, like "idea": text of at most ${MAX_LABEL} characters, no comma, no space at either end.`);
393
396
  }
394
397
  }
398
+ if (c.history !== undefined && typeof c.history !== 'boolean') out.push('"history" is true or false: true reads the repo\'s git history (docs/config.md#history).');
395
399
  if (c.releaseNotes !== undefined) {
396
400
  if (!isObject(c.releaseNotes)) out.push('"releaseNotes" is { breakingLabel }.');
397
401
  else if (c.releaseNotes.breakingLabel !== undefined && (!isText(c.releaseNotes.breakingLabel) || c.releaseNotes.breakingLabel.includes(','))) out.push('releaseNotes.breakingLabel is a label\'s name, like "breaking".');
@@ -415,10 +419,7 @@ export function configProblems(c) {
415
419
  } else if (!inRepo(c.proposals)) out.push('"proposals" is the proposals folder inside the repo, written relative to it (or { dir, approveLands }).');
416
420
  }
417
421
  if (c.links !== undefined) {
418
- if (!Array.isArray(c.links)) out.push('"links" is a list of { label, href }.');
419
- else c.links.forEach((l, i) => {
420
- if (!isObject(l) || !isText(l.label) || !/^(https?:\/\/|\/)/.test(String(l.href || ''))) out.push(`links[${i}] is { label, href } with an http(s) or same-origin href.`);
421
- });
422
+ for (const p of linkProblems(c.links)) out.push(p.message);
422
423
  }
423
424
  out.push(...themeProblems(c.theme));
424
425
  out.push(...brandProblems(c.brand));
@@ -0,0 +1,222 @@
1
+ /**
2
+ * @module core/history
3
+ *
4
+ * The map's own history (spec 0014 D4): which commits changed each node, when each node was born, and, for each commit,
5
+ * the trail it names from spec to issue to pull request. Read from `git log` when the config says `history: true`.
6
+ *
7
+ * Two halves:
8
+ * - pure: `parseLog` reads the fixed format `readLog` asks git for, `traceOf` reads a commit's trail from its message
9
+ * and files, and `historyOf` ties the commits to a map's nodes. No I/O; tested in Node.
10
+ * - `readLog` and `createHistory`: run git, read-only, and keep the answer per HEAD.
11
+ *
12
+ * Running git is the one program cornfield runs, so it is held tight (spec 0014, question 1):
13
+ * - a fixed list of arguments, `execFile` with no shell, the repo's path as `-C`, nothing from a request in it;
14
+ * - nothing from the repo's own config may run a program: no pager, external diff, text conversion, signature check
15
+ * or fsmonitor, and no terminal prompt;
16
+ * - a time and size ceiling, and at most MAX_COMMITS commits.
17
+ */
18
+
19
+ import { execFile } from 'node:child_process';
20
+
21
+ /** The most commits read, newest first: a long history is cut at its newest MAX_COMMITS */
22
+ export const MAX_COMMITS = 5000;
23
+ /** How long `git log` may take, and how much it may say, before it is given up on */
24
+ export const GIT_TIMEOUT_MS = 15_000;
25
+ export const GIT_MAX_BYTES = 64 * 1024 * 1024;
26
+
27
+ const RS = '\x1e';
28
+ const US = '\x1f';
29
+ /** The format each commit is written in: record separator, hash, author date (ISO), subject, body, then its files */
30
+ export const LOG_FORMAT = `${RS}%H${US}%aI${US}%s${US}%b${US}`;
31
+
32
+ /**
33
+ * The arguments `readLog` runs git with: settings that keep the repo's own config from running anything, then the log
34
+ * of the checked-out branch, first parent only (a merged branch's own commits are its pull request's), with renames.
35
+ * @param {string} root the repo's folder
36
+ */
37
+ export function gitArgs(root) {
38
+ return [
39
+ '-C', root,
40
+ '-c', 'core.pager=cat', '-c', 'core.fsmonitor=false', '-c', 'log.showSignature=false', '-c', 'diff.external=',
41
+ '--no-pager', 'log', '--first-parent', `--max-count=${MAX_COMMITS}`, `--format=${LOG_FORMAT}`,
42
+ '--name-status', '-M', '--no-ext-diff', '--no-textconv', '--no-color', 'HEAD', '--',
43
+ ];
44
+ }
45
+
46
+ /** The environment git runs in: no prompt, no system config, the user's own config kept (it is theirs, not the repo's) */
47
+ export const gitEnv = (env = process.env) => ({ ...env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1', GIT_PAGER: 'cat', GIT_EXTERNAL_DIFF: '', LC_ALL: 'C' });
48
+
49
+ /**
50
+ * @typedef {object} RawCommit
51
+ * @property {string} sha
52
+ * @property {string} date the author date, ISO 8601
53
+ * @property {string} subject
54
+ * @property {string} body
55
+ * @property {{ status: string, path: string, from?: string }[]} files A, M, D, R (with `from`), C, T
56
+ */
57
+
58
+ /**
59
+ * The commits in `readLog`'s output, oldest first. A malformed record is left out.
60
+ * @param {string} text
61
+ * @returns {RawCommit[]}
62
+ */
63
+ export function parseLog(text) {
64
+ const out = [];
65
+ for (const rec of String(text).split(RS).slice(1)) {
66
+ const parts = rec.split(US);
67
+ if (parts.length < 5) continue;
68
+ const [sha, date, subject, body] = parts;
69
+ if (!/^[0-9a-f]{40}$/.test(sha) || Number.isNaN(Date.parse(date))) continue;
70
+ const files = [];
71
+ for (const line of parts.slice(4).join(US).split('\n')) {
72
+ const cols = line.split('\t');
73
+ if (cols.length < 2 || !/^[AMDRCT]\d*$/.test(cols[0])) continue;
74
+ const status = cols[0][0];
75
+ if ((status === 'R' || status === 'C') && cols.length >= 3) files.push({ status, from: cols[1], path: cols[2] });
76
+ else files.push({ status, path: cols[1] });
77
+ }
78
+ out.push({ sha, date, subject: subject.trim(), body: body.trim(), files });
79
+ }
80
+ return out.reverse();
81
+ }
82
+
83
+ /** The words that say a commit closes an issue (GitHub's and Forgejo's) */
84
+ const CLOSES = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#(\d+)\b/gi;
85
+ const KEY = /\[([A-Z][A-Z0-9]*-\d+)\]/g;
86
+ const SPEC_WORD = /\bspecs?\s+(\d{4})\b/gi;
87
+ const SPEC_FILE = /^docs\/specs\/(\d{4})-[^/]+\.md$/;
88
+
89
+ /**
90
+ * The trail a commit names (spec 0014 D2, question 3): its pull request (the last `(#N)` in its subject, as a squash
91
+ * merge writes it), its issues (an earlier `(#N)`, a `Closes #N`), the issue keys it carries (`[CF-45]`), and its specs
92
+ * (`spec 0012` in its message, or a spec file it changed). What it does not name is not guessed.
93
+ * @param {{ subject: string, body?: string, files?: { path: string }[] }} commit
94
+ * @returns {{ pr: number | null, issues: number[], keys: string[], specs: string[] }}
95
+ */
96
+ export function traceOf({ subject, body = '', files = [] }) {
97
+ const refs = [...String(subject).matchAll(/\(#(\d+)\)/g)].map((m) => Number(m[1]));
98
+ const pr = refs.length ? refs[refs.length - 1] : null;
99
+ const issues = [];
100
+ const add = (n) => { if (n !== pr && !issues.includes(n)) issues.push(n); };
101
+ refs.slice(0, -1).forEach(add);
102
+ for (const m of `${subject}\n${body}`.matchAll(CLOSES)) add(Number(m[1]));
103
+ const keys = [...new Set([...`${subject}\n${body}`.matchAll(KEY)].map((m) => m[1]))];
104
+ const specs = [];
105
+ for (const m of `${subject}\n${body}`.matchAll(SPEC_WORD)) if (!specs.includes(m[1])) specs.push(m[1]);
106
+ for (const f of files) { const m = SPEC_FILE.exec(f.path); if (m && !specs.includes(m[1])) specs.push(m[1]); }
107
+ return { pr, issues, keys, specs };
108
+ }
109
+
110
+ /** A commit's subject without the `(#N)` its pull request left on it */
111
+ export const cleanSubject = (subject) => String(subject).replace(/\s*\(#\d+\)/g, '').trim();
112
+
113
+ /**
114
+ * @typedef {object} History
115
+ * @property {{ sha: string, date: string, subject: string, pr: number | null, issues: number[], keys: string[], specs: string[], files: number, nodes: string[] }[]} commits oldest first
116
+ * @property {Record<string, { born: number, commits: number[] }>} nodes by node id: the index of the commit it was born in, and of every commit that changed it
117
+ * @property {boolean} cut whether the history was cut at MAX_COMMITS
118
+ */
119
+
120
+ /**
121
+ * Ties commits to a map's nodes. A node owns its `file`, and everything under it when that is a folder. Renames are
122
+ * followed back (question 4): a file renamed into a node's path brings its older history with it. A node is born at the
123
+ * first commit that changed what it owns; one that nothing in the history touches is born with the first commit.
124
+ * A child is never born before its parent: its parent is born with it.
125
+ * @param {RawCommit[]} raw oldest first (parseLog)
126
+ * @param {{ nodes: { id: string, file?: string }[], edges?: { from: string, to: string, dashed?: boolean, kind?: string }[] }} topology
127
+ * @param {{ cut?: boolean }} [opts]
128
+ * @returns {History}
129
+ */
130
+ export function historyOf(raw, topology, { cut = false } = {}) {
131
+ const nodes = (topology && Array.isArray(topology.nodes) ? topology.nodes : []).filter((n) => n && typeof n.id === 'string');
132
+ // Each node's paths, newest name first; walked newest to oldest so a rename adds the older name before it is met
133
+ const owns = new Map(nodes.filter((n) => typeof n.file === 'string' && n.file.trim()).map((n) => [n.id, new Set([n.file.replace(/\/+$/, '')])]));
134
+ const covers = (p, f) => f === p || f.startsWith(`${p}/`);
135
+ const touched = raw.map(() => new Set());
136
+ for (let i = raw.length - 1; i >= 0; i--) {
137
+ for (const f of raw[i].files) {
138
+ for (const [id, paths] of owns) {
139
+ for (const p of [...paths]) {
140
+ if (!covers(p, f.path)) continue;
141
+ if (f.status !== 'D') touched[i].add(id);
142
+ // The node's own file came from another name: follow it back. A rename inside a folder node needs nothing, the folder covers both
143
+ if (f.status === 'R' && f.from && f.path === p) paths.add(f.from);
144
+ }
145
+ }
146
+ }
147
+ }
148
+ const out = {};
149
+ nodes.forEach((n) => { out[n.id] = { born: 0, commits: [] }; });
150
+ touched.forEach((ids, i) => ids.forEach((id) => out[id].commits.push(i)));
151
+ for (const n of nodes) out[n.id].born = out[n.id].commits.length ? out[n.id].commits[0] : 0;
152
+ // Parents first: ownership edges (no kind, not dashed), a parent born no later than its child
153
+ const parent = new Map();
154
+ for (const e of topology?.edges || []) if (e && !e.dashed && !e.kind && out[e.from] && out[e.to] && !parent.has(e.to) && e.from !== e.to) parent.set(e.to, e.from);
155
+ for (const n of nodes) {
156
+ const seen = new Set([n.id]);
157
+ for (let c = n.id, p = parent.get(c); p && !seen.has(p); c = p, p = parent.get(p)) {
158
+ seen.add(p);
159
+ if (out[p].born > out[c].born) out[p].born = out[c].born;
160
+ }
161
+ }
162
+ const commits = raw.map((c, i) => ({ sha: c.sha, date: c.date, subject: cleanSubject(c.subject), ...traceOf(c), files: c.files.length, nodes: [...touched[i]].sort() }));
163
+ return { commits, nodes: out, cut };
164
+ }
165
+
166
+ /**
167
+ * Runs git and reads the log of the checked-out branch. Rejects with a plain message when git is not there, the folder
168
+ * is not a repo, or git gives up.
169
+ * @param {string} root
170
+ * @param {{ env?: NodeJS.ProcessEnv, run?: typeof execFile }} [opts] `run` is the tests' fake
171
+ * @returns {Promise<{ raw: RawCommit[], cut: boolean }>}
172
+ */
173
+ export function readLog(root, { env = process.env, run = execFile } = {}) {
174
+ return new Promise((resolve, reject) => {
175
+ run('git', gitArgs(root), { env: gitEnv(env), timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BYTES, windowsHide: true, encoding: 'utf8' }, (err, stdout) => {
176
+ if (err) {
177
+ const why = err.code === 'ENOENT' ? 'git is not installed where cornfield runs' : err.killed ? `git log took longer than ${GIT_TIMEOUT_MS / 1000}s` : 'the repo has no history git can read (is it a git checkout with a commit?)';
178
+ return reject(Object.assign(new Error(`The history could not be read: ${why}.`), { code: 'ENOHISTORY' }));
179
+ }
180
+ const raw = parseLog(stdout);
181
+ resolve({ raw, cut: raw.length >= MAX_COMMITS });
182
+ });
183
+ });
184
+ }
185
+
186
+ /** The commit HEAD points at, by asking git with the same guards; null when there is none */
187
+ export function readHead(root, { env = process.env, run = execFile } = {}) {
188
+ return new Promise((resolve) => {
189
+ run('git', ['-C', root, '-c', 'core.fsmonitor=false', 'rev-parse', '--verify', '--quiet', 'HEAD'], { env: gitEnv(env), timeout: GIT_TIMEOUT_MS, windowsHide: true, encoding: 'utf8' }, (err, stdout) => {
190
+ const sha = String(stdout || '').trim();
191
+ resolve(!err && /^[0-9a-f]{40}$/.test(sha) ? sha : null);
192
+ });
193
+ });
194
+ }
195
+
196
+ /**
197
+ * The history of one repo, kept per HEAD and map: read again only when either changes. One read at a time; callers
198
+ * that ask while it runs share it.
199
+ * @param {string} root
200
+ * @param {{ env?: NodeJS.ProcessEnv, run?: typeof execFile }} [opts]
201
+ * @returns {{ get(topology: object, topologyKey: string): Promise<History & { head: string }> }}
202
+ */
203
+ export function createHistory(root, opts = {}) {
204
+ let kept = null; // { key, value }
205
+ let pending = null; // { key, promise }
206
+ return {
207
+ async get(topology, topologyKey) {
208
+ const head = await readHead(root, opts);
209
+ if (!head) throw Object.assign(new Error('The history could not be read: the repo has no commit yet, or is not a git checkout.'), { code: 'ENOHISTORY' });
210
+ const key = `${head}|${topologyKey}`;
211
+ if (kept && kept.key === key) return kept.value;
212
+ if (pending && pending.key === key) return pending.promise;
213
+ const promise = readLog(root, opts).then(({ raw, cut }) => {
214
+ const value = { head, ...historyOf(raw, topology, { cut }) };
215
+ kept = { key, value };
216
+ return value;
217
+ }).finally(() => { if (pending && pending.key === key) pending = null; });
218
+ pending = { key, promise };
219
+ return promise;
220
+ },
221
+ };
222
+ }
package/core/proposal.js CHANGED
@@ -27,6 +27,7 @@
27
27
  * change?: [{ from, to, kind?, flow?, set: { …fields }, why }],
28
28
  * remove?: [{ from, to, kind?, flow?, why }] },
29
29
  * mockups?: [{ node, path, title }],
30
+ * links?: [{ label, href }],
30
31
  * scenarios?: [{ id, title, steps: [{ node } | { edge: { from, to, kind?, flow? } }, + text, + ms?,
31
32
  * + actor?, at?, check?, expect?], stepMs?, linkNodes?, actor?, down? }] }
32
33
  *
@@ -36,6 +37,10 @@
36
37
  * backslash, no hidden segment) and ends in one of MOCKUP_EXTENSIONS. The explorer opens a mockup from its node;
37
38
  * approving the proposal covers the files (server/mockups.js). HTML and SVG are untrusted content from a branch:
38
39
  * the server and the explorer never let them run script (docs/proposals.md).
40
+ * - Links: `links` lists pages that belong to this one proposal (a walkthrough, a design doc, a preview), at most
41
+ * MAX_LINKS. Each is a `label` (text, at most MAX_LINK_LABEL characters) and an `href`: an http: or https: address,
42
+ * or a path in the site (one slash). Nothing else (`javascript:`, `data:`) and no other key. The check is the config's
43
+ * `links` check (core/schema.js); the explorer shows them beside Before / Diff / After and asks again before it draws one.
39
44
  * - An edge is identified by `from` + `to` + `kind`. No `kind` is the ownership edge (parent → child);
40
45
  * a `flow` edge also names its `flow` (one of FLOW_KINDS), and that is part of its identity.
41
46
  * - `parent` on an added node adds the ownership edge `parent → id`; `parent` is not a node field and
@@ -70,15 +75,18 @@
70
75
  * the derived map to them; a proposal is a sketch.
71
76
  */
72
77
 
73
- import { NODE_THEMES, EDGE_KINDS, FLOW_KINDS, DEVICE_KINDS, EXTERNAL_KINDS, LIVE_ID_PREFIX, parseLiveId, isLiveNode, personaNodeId, callFieldProblems } from './schema.js';
78
+ import { NODE_THEMES, linkProblems, EDGE_KINDS, FLOW_KINDS, DEVICE_KINDS, EXTERNAL_KINDS, LIVE_ID_PREFIX, parseLiveId, isLiveNode, personaNodeId, callFieldProblems } from './schema.js';
74
79
 
75
- const TOP_KEYS = ['version', 'spec', 'title', 'summary', 'nodes', 'edges', 'mockups', 'scenarios'];
80
+ const TOP_KEYS = ['version', 'spec', 'title', 'summary', 'nodes', 'edges', 'mockups', 'links', 'scenarios'];
76
81
  const MOCKUP_KEYS = ['node', 'path', 'title'];
77
82
  /** The file types a mockup may be, by lower-case extension. `.html` and `.svg` are untrusted content and are served sandboxed */
78
83
  export const MOCKUP_EXTENSIONS = ['png', 'jpg', 'jpeg', 'webp', 'svg', 'html'];
79
84
  /** Mockups in one proposal, and the characters of a path */
80
85
  export const MAX_MOCKUPS = 40;
81
86
  export const MAX_MOCKUP_PATH = 200;
87
+ /** Links in one proposal, and the characters of a link's label */
88
+ export const MAX_LINKS = 8;
89
+ export const MAX_LINK_LABEL = 60;
82
90
  const SCENARIO_KEYS = ['id', 'title', 'steps', 'stepMs', 'linkNodes', 'actor', 'down'];
83
91
  const STEP_KEYS = ['node', 'edge', 'text', 'ms', 'actor', 'at', 'check', 'expect'];
84
92
  /** What a step's `check` may ask (spec 0029 section 3): a route and a method, or a table, an op and a row shape */
@@ -502,6 +510,11 @@ export function validateProposal(topology, proposal) {
502
510
  });
503
511
  }
504
512
 
513
+ // --- links
514
+ if (proposal.links !== undefined) {
515
+ for (const p of linkProblems(proposal.links, { max: MAX_LINKS, maxLabel: MAX_LINK_LABEL, closed: true })) err(`links${p.at}`, p.message);
516
+ }
517
+
505
518
  return errors;
506
519
  }
507
520
 
package/core/schema.js CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * What a `topology.json` node and edge may be: the node types with their colour and radius, and the
5
5
  * edge kinds, the physical world's rules (spec 0029: live types and ids, which ends an edge kind
6
- * may join) and the cloud's (spec 0031: the kinds of external, a cloud node's fields, `when` and `side`). Pure data and small pure checks with no imports, so the CLI (cli/cornfield.js), the proposal checks
6
+ * may join) and the cloud's (spec 0031: the kinds of external, a cloud node's fields, `when` and `side`), and the one check of a list of links (`linkProblems`: the config's and a proposal's). Pure data and small pure checks with no imports, so the CLI (cli/cornfield.js), the proposal checks
7
7
  * (core/proposal.js) and the explorer in the browser all read the one table.
8
8
  */
9
9
 
@@ -302,3 +302,50 @@ export function callFieldProblems(edge, from, to) {
302
302
  }
303
303
  return problems;
304
304
  }
305
+
306
+ /**
307
+ * Whether `href` is a place a link may lead: an `http:` or `https:` address, or a path in the site (`/docs`). Anything
308
+ * else is refused (`javascript:`, `data:`, a bare `//host`, a backslash, a space or a control character), so a link from a
309
+ * file of the repo or of a pull request can never run script or send the reader somewhere the check did not see.
310
+ * @param {unknown} href
311
+ * @returns {boolean}
312
+ */
313
+ export function isLinkHref(href) {
314
+ return typeof href === 'string' && (/^https?:\/\/[^\s\\/]/i.test(href) || /^\/(?![/\\])/.test(href)) && !/[\u0000-\u001f\u007f\s\\]/.test(href);
315
+ }
316
+
317
+ /**
318
+ * What is wrong with a list of links, `[{ label, href }]`, each with the place in the list it is at (`at`: `[1].href`) and
319
+ * a message that names it. The config's `links` and a proposal's share this one check.
320
+ * @param {unknown} list
321
+ * @param {{ max?: number, maxLabel?: number, closed?: boolean }} [limits] `max` links in the list, `maxLabel` characters in a label, `closed` refuses any key but label and href
322
+ * @returns {{ at: string, message: string }[]}
323
+ */
324
+ export function linkProblems(list, { max = Infinity, maxLabel = Infinity, closed = false } = {}) {
325
+ if (!Array.isArray(list)) return [{ at: '', message: '"links" must be a list of { label, href }.' }];
326
+ const out = [];
327
+ if (list.length > max) out.push({ at: '', message: `"links" has ${list.length} links; at most ${max}.` });
328
+ list.forEach((l, i) => {
329
+ const at = `[${i}]`;
330
+ if (l === null || typeof l !== 'object' || Array.isArray(l)) return out.push({ at, message: `links${at} must be { label, href }: an object with a label and an href.` });
331
+ if (closed) for (const key of Object.keys(l)) if (key !== 'label' && key !== 'href') out.push({ at: `${at}.${key}`, message: `Unknown key "${key}" in a link. A link has: label, href.` });
332
+ if (typeof l.label !== 'string' || l.label.trim() === '') out.push({ at: `${at}.label`, message: `links${at}.label must be the words of the link.` });
333
+ else if (l.label.length > maxLabel) out.push({ at: `${at}.label`, message: `links${at}.label is ${l.label.length} characters; at most ${maxLabel}.` });
334
+ if (!isLinkHref(l.href)) out.push({ at: `${at}.href`, message: `links${at}.href must be an http: or https: address, or a path in the site that starts with a single slash.` });
335
+ });
336
+ return out;
337
+ }
338
+
339
+ /**
340
+ * The links of a list that may be drawn, as `{ label, href }` and nothing else: what passes `linkProblems` entry by entry, at most `max`.
341
+ * A list read from a pull request is untrusted, so the page asks again here and leaves out what it would not have accepted.
342
+ * @param {unknown} list
343
+ * @param {{ max?: number, maxLabel?: number }} [limits]
344
+ * @returns {{ label: string, href: string }[]}
345
+ */
346
+ export function usableLinks(list, { max = Infinity, maxLabel = Infinity } = {}) {
347
+ if (!Array.isArray(list)) return [];
348
+ return list.slice(0, max)
349
+ .filter((l) => l && typeof l === 'object' && !Array.isArray(l) && linkProblems([l], { maxLabel }).length === 0)
350
+ .map((l) => ({ label: l.label, href: l.href }));
351
+ }
@@ -107,16 +107,24 @@ a.hx-proposal-source { min-height: 24px; } /* a link: at least the WCAG 2.5.8 ta
107
107
  a.hx-proposal-source:hover { color: var(--corn-text); text-decoration: underline; }
108
108
  a.hx-proposal-source:focus-visible { outline: var(--corn-focus-width) solid var(--corn-focus); outline-offset: var(--corn-focus-offset); }
109
109
  .hx-proposal-source[data-corn-state="draft"] { border-color: color-mix(in srgb, var(--corn-changed) 50%, transparent); }
110
+ /* The proposal's own links (its `links`): a row of text links under the head, each leaving the page in a new tab */
111
+ .hx-proposal-links { display: flex; flex-wrap: wrap; gap: var(--corn-space-1) var(--corn-space-4); margin-top: var(--corn-space-2); }
112
+ .hx-proposal-links[hidden] { display: none; }
113
+ .hx-proposal-link { display: inline-flex; align-items: center; gap: var(--corn-space-2); min-height: 24px; max-width: 100%; color: var(--corn-text-2); font-size: var(--corn-text-sm); text-decoration: underline; text-underline-offset: 3px; overflow-wrap: anywhere; }
114
+ .hx-proposal-link:hover { color: var(--corn-text); }
115
+ .hx-proposal-link:focus-visible { outline: var(--corn-focus-width) solid var(--corn-focus); outline-offset: var(--corn-focus-offset); }
116
+ .hx-proposal-link svg { flex: none; }
110
117
  .hx-proposal-ways { display: flex; flex-wrap: wrap; gap: var(--corn-space-2) var(--corn-space-3); margin-top: var(--corn-space-3); }
111
118
  .hx-proposal-ways[hidden] { display: none; }
112
119
  .hx-proposal-ways .hx-btn { height: auto; min-height: 32px; padding: var(--corn-space-1) var(--corn-space-4); white-space: normal; text-align: left; }
113
120
  @container corn-box (max-width: 767px) {
114
121
  .hx-proposal-source { grid-column: 1 / -1; order: 1; justify-self: start; }
122
+ .hx-proposal-link { min-height: 44px; font-size: var(--corn-text-md); } /* targets a thumb can hit */
115
123
  .hx-proposal-ways .hx-btn, a.hx-proposal-source { min-height: 44px; } /* targets a thumb can hit */
116
124
  .hx-proposal-source { padding: 0; border: 0; border-radius: 0; background: none; } /* a line of the sheet, not a pill 44px tall */
117
125
  a.hx-proposal-source { text-decoration: underline; text-underline-offset: 3px; }
118
126
  /* The note open: the field, Cancel and the send button are all there is, so all of them stay above the keyboard */
119
- .hx-proposal-bar:has(.hx-review-form:not([hidden])) :is(.hx-proposal-name, .hx-proposal-source, .hx-proposal-counts, .hx-proposal-tools, .hx-proposal-more, .hx-review-status, .hx-review-line, .hx-rc-scroll, .hx-rc-tabs, .hx-proposal-peek) { display: none; } /* the review column's lists too: the sheet holds the note and its buttons */
127
+ .hx-proposal-bar:has(.hx-review-form:not([hidden])) :is(.hx-proposal-name, .hx-proposal-source, .hx-proposal-links, .hx-proposal-counts, .hx-proposal-tools, .hx-proposal-more, .hx-review-status, .hx-review-line, .hx-rc-scroll, .hx-rc-tabs, .hx-proposal-peek) { display: none; } /* the review column's lists too: the sheet holds the note and its buttons */
120
128
  /* Reflow: nothing is wider than the sheet, and long words and counts wrap instead of being cut */
121
129
  .hx-proposal-bar { overflow-x: hidden; overflow-wrap: anywhere; }
122
130
  .hx-proposal-head { grid-template-columns: minmax(0, 1fr) auto; }
@@ -23,7 +23,8 @@
23
23
  */
24
24
 
25
25
  import { escapeHtml as escHtml } from '../../core/text.js';
26
- import { summarize } from '../../core/proposal.js';
26
+ import { usableLinks } from '../../core/schema.js';
27
+ import { summarize, MAX_LINKS, MAX_LINK_LABEL } from '../../core/proposal.js';
27
28
  import { PROPOSAL_VIEWS, chipText, barCounts, proposalPanelHtml, yoursText, sourceChip, pullNumberOf, malformedLinkWords } from '../proposal-model.js';
28
29
  import { reviewWords } from '../review-model.js';
29
30
  import { waitingLineWords } from '../waiting-model.js';
@@ -75,6 +76,8 @@ export const markup = ({ edit = true } = {}) => ({
75
76
  + '</div>'
76
77
  + '</div>'
77
78
  + '</div>'
79
+ // The proposal's own links (`links` of the file): made in renderBar, only when it has some
80
+ + '<nav id="proposal-links" class="hx-proposal-links" aria-label="Links for this proposal" hidden></nav>'
78
81
  + '<details id="proposal-errors" class="hx-proposal-errors" data-corn="proposal-errors" hidden>'
79
82
  + '<summary data-corn="summary" id="proposal-errors-count"></summary>'
80
83
  + '<ul id="proposal-errors-list"></ul>'
@@ -95,6 +98,9 @@ export function problemsHtml(errors, max = 8) {
95
98
  return shown.join('');
96
99
  }
97
100
 
101
+ /** One link of the proposal: it opens in a new tab, and says so to a screen reader. The label is escaped; the href passed `usableLinks` and goes nowhere but its attribute */
102
+ const linkHtml = (l) => `<a class="hx-proposal-link" data-corn="link" href="${escHtml(l.href)}" target="_blank" rel="noopener noreferrer"><span>${escHtml(l.label)}</span><span class="hx-sr-only"> (opens in a new tab)</span><svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M6 3h7v7M13 3L7 9" /></svg></a>`;
103
+
98
104
  const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
99
105
  const safeHref = (u) => (typeof u === 'string' && /^https?:\/\//i.test(u) ? u : null);
100
106
 
@@ -233,6 +239,7 @@ export function mount(root, inst, options = {}) {
233
239
  if (yours) chip.insertAdjacentHTML('beforeend', `<span class="hx-proposal-sep" aria-hidden="true"> · </span><span class="hx-proposal-count hx-proposal-yours"><span class="hx-mark-dot hx-mark-dot--edit" data-corn="mark-dot" data-corn-state="edit" aria-hidden="true"></span>${escHtml(yours)}</span>`);
234
240
  addParts(chip);
235
241
  own('proposal-mode').textContent = t(inst, state.proposalView);
242
+ paintLinks(p);
236
243
 
237
244
  for (const btn of bar.querySelectorAll('[data-action="proposal-view"]')) {
238
245
  const on = btn.dataset.view === state.proposalView;
@@ -255,6 +262,15 @@ export function mount(root, inst, options = {}) {
255
262
  }
256
263
  }
257
264
 
265
+ /** The proposal's links, beside Before / Diff / After. A proposal can come from a pull request, so each is checked again here: what is not a link the file format accepts is left out */
266
+ function paintLinks(p) {
267
+ const nav = own('proposal-links');
268
+ const links = usableLinks(p && p.links, { max: MAX_LINKS, maxLabel: MAX_LINK_LABEL });
269
+ nav.hidden = links.length === 0;
270
+ nav.innerHTML = links.map(linkHtml).join('');
271
+ addParts(nav);
272
+ }
273
+
258
274
  // ---------------------------------------------------------------------------
259
275
  // The waiting line: a run waits on the open proposal (spec 0010 D2)
260
276
  // ---------------------------------------------------------------------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.57.2",
3
+ "version": "0.59.0",
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)",
package/server/server.js CHANGED
@@ -23,7 +23,8 @@
23
23
  * that says how to build them when this checkout has none (server/components.js)
24
24
  * GET /cornfield/brand/<key>.<ext> a brand image the config's `brand` names (logo, wordmark, favicon; svg or png, 512 KB each): those files only
25
25
  * GET /manifest.webmanifest the web app manifest: the repo's title, or built from `brand` when the config sets one
26
- * GET /api/forge/… issues, pull requests, their files and checks, release notes: read from the forge (server/forge-routes.js)
26
+ * GET /api/history the map's git history (core/history.js; spec 0014), when the config says `history: true`: a 404 otherwise
27
+ * GET /api/forge/… issues pull requests, their files and checks, release notes: read from the forge (server/forge-routes.js)
27
28
  * POST /api/forge/pulls/<n>/merge|rerun land a green pull request, re-run a failed check (server/forge-actions.js)
28
29
  * POST /api/forge/issues/<n>/spec, /pulls/<n>/build the pipeline's steps (server/pipeline.js, server/forge-actions.js)
29
30
  * POST /api/forge/release-drafts the release notes kept as a DRAFT release on the forge (never published, no tag made)
@@ -83,6 +84,7 @@ import { createRunnerWatch, runnerPresence } from './runner-presence.js';
83
84
  import { createTriggers } from './triggers.js';
84
85
  import { brandHead, escapeHtml, themeHead, themeHtmlTag } from './page-head.js';
85
86
  import { compressResponse } from './compress.js';
87
+ import { createHistory } from '../core/history.js';
86
88
 
87
89
  export const CORNFIELD_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
88
90
  const EXPLORER_DIR = path.join(CORNFIELD_DIR, 'explorer');
@@ -263,6 +265,8 @@ export function clientConfig(config, signIn = false) {
263
265
  forge: config.forge ? { type: config.forge.type, url: config.forge.url || (config.forge.type === 'github' ? 'https://github.com' : null), repo: config.forge.repo, mergeMethod: config.forge.mergeMethod || 'merge', ...(config.forge.baseBranch ? { baseBranch: config.forge.baseBranch } : {}), ...(config.approveLands ? { approveLands: true } : {}) } : null,
264
266
  // Threads (docs/threads.md): the idea label, or false when `threads: false` turns the Threads tab off
265
267
  threads: config.threads === false ? false : { label: ideaLabel(config) },
268
+ // The map's git history is read (spec 0014): the page then offers the History layer, a node's commits and Replay
269
+ history: config.history === true,
266
270
  sources: browserSources(config),
267
271
  // Agent runs are followed (and marked on the map) where there is a forge and a sign-in (docs/agents.md)
268
272
  ...(config.forge && signIn ? { agents: { runs: true } } : {}),
@@ -320,6 +324,8 @@ export function createCornfieldServer(config, opts = {}) {
320
324
  const components = createComponents({ dir: opts.componentsDir ?? path.join(CORNFIELD_DIR, 'components', 'dist') });
321
325
  const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost, publicOrigin, embedOrigins: embed.origins };
322
326
  const fixtureCache = new Map();
327
+ // The repo's git history, read when first asked for and kept per HEAD and map (core/history.js); only with `history: true`
328
+ const history = config.history === true ? createHistory(root) : null;
323
329
  // What the line above Approve says an approval does besides posting (spec 0007 D1, server/decision.js): landing, and the run a trigger asks for
324
330
  const approvalRun = triggersOf(config).find(([event]) => event === 'spec.approved');
325
331
  const decisionFacts = {
@@ -517,6 +523,21 @@ export function createCornfieldServer(config, opts = {}) {
517
523
  if (!file) return sendJson(res, 404, { error: `${config.topology} is not there yet: run cornfield sync` });
518
524
  return sendFile(req, res, file, reqPath);
519
525
  }
526
+ if (reqPath === '/api/history') {
527
+ if (!history) return sendJson(res, 404, { ok: false, error: 'History is off. Set history: true in cornfield.config.js to read the repo\'s git history (docs/config.md#history).' });
528
+ const file = inside(root, config.topology);
529
+ const got = file && readPlain(file);
530
+ if (!got) return sendJson(res, 404, { ok: false, error: `${config.topology} is not there yet: run cornfield sync` });
531
+ let topology;
532
+ try { topology = JSON.parse(got.body.toString('utf8')); } catch { return sendJson(res, 422, { ok: false, error: `${config.topology} is not valid JSON` }); }
533
+ try {
534
+ const data = await history.get(topology, `${got.stats.mtimeMs}|${got.stats.size}`);
535
+ return sendJson(res, 200, { ok: true, ...data });
536
+ } catch (err) {
537
+ if (err.code !== 'ENOHISTORY') throw err;
538
+ return sendJson(res, 503, { ok: false, error: err.message });
539
+ }
540
+ }
520
541
  if (reqPath === '/topology.cloud.json') {
521
542
  const file = inside(root, CLOUD_FILE);
522
543
  const got = file && readPlain(file);