@popcorn245/cornfield 0.20.0 → 0.22.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.
@@ -58,9 +58,10 @@
58
58
  * (refused as a duplicate). A fence without an id gets one from cornfield, the same on every look (`handRunId`), confirmed by a reply block in the
59
59
  * thread that the poll's signed-in maintainer posts (the block's `requestedBy` is the author; the audit row names who posted it). A reply the forge
60
60
  * refuses is posted on a later look; the run is kept meanwhile (on pull it may be claimed at once)
61
+ * - a `retryOf` is checked as an API request's is (`retryProblem`: a run of this repo that failed or was stopped), before the cap
61
62
  * - the cap and the one-run-per-subject rule are `reserve`'s, in the same transaction as the insert, so a hand-written request counts toward later
62
63
  * cap checks and is refused when they say so; the rate limit guards people at the dashboard and does not apply
63
- * - what started nothing (not a maintainer, edited, malformed with the contract's reason, duplicate, old, cap, subject) is kept in `actions` and shown by `list` as `handWritten.refused`
64
+ * - what started nothing (not a maintainer, edited, malformed with the contract's reason, duplicate, old, retryOf, cap, subject) is kept in `actions` and shown by `list` as `handWritten.refused`
64
65
  *
65
66
  * ## Waiting, and the answer (issue #101)
66
67
  *
@@ -179,7 +180,7 @@ export const NUDGE_FRESH_MS = 10 * 60_000;
179
180
  export const MAX_HAND_JUDGED = 50;
180
181
  /** The runs that are over once the runner has said so */
181
182
  /** The keys of a request as the API and the button send it: the contract's fields, less what cornfield writes, plus `force` */
182
- export const REQUEST_BODY_KEYS = Object.freeze(['kind', 'profile', 'refs', 'branch', 'brief', 'limits', 'nodes', 'requestedBy', 'force']);
183
+ export const REQUEST_BODY_KEYS = Object.freeze(['kind', 'profile', 'refs', 'branch', 'brief', 'limits', 'nodes', 'requestedBy', 'retryOf', 'force']);
183
184
 
184
185
  /** The states in which a run is over for good unless the runner says more */
185
186
  export const FINISHED = Object.freeze(['done', 'failed', 'stopped', 'merged', 'closed']);
@@ -260,14 +261,15 @@ function answerOf(row) {
260
261
  export function publicRun(row, nowMs, quietMs, extra = {}) {
261
262
  const { status, open } = statusOf(row, nowMs, quietMs);
262
263
  let limits = null;
263
- try { limits = JSON.parse(row.request).limits ?? null; } catch { limits = null; }
264
+ let retryOf = null;
265
+ try { const asked = JSON.parse(row.request); limits = asked.limits ?? null; retryOf = typeof asked.retryOf === 'string' ? asked.retryOf : null; } catch { limits = null; }
264
266
  return {
265
267
  runId: row.run_id, kind: row.kind, profile: row.profile,
266
268
  refs: { ...(row.issue != null ? { issue: row.issue } : {}), ...(row.proposal != null ? { proposal: row.proposal } : {}), ...(row.thread != null ? { thread: row.thread } : {}) },
267
269
  status, open, requestedBy: row.requested_by, requestedAt: row.requested_at, via: row.via, byHand: row.via === 'hand', transport: row.transport, target: row.target,
268
270
  claimedAt: row.claimed_at,
269
271
  comment: row.comment_id ? { id: row.comment_id, url: row.comment_url } : null,
270
- limits,
272
+ limits, retryOf,
271
273
  report: row.reported_at ? { state: row.state, at: row.reported_at, by: byFromText(row.reported_by), note: row.note, url: row.url, tokens: row.tokens, cost: row.cost } : null,
272
274
  stopRequested: row.stop_requested_at ? { at: row.stop_requested_at, by: row.stop_requested_by } : null,
273
275
  answer: answerOf(row),
@@ -283,10 +285,13 @@ export function publicRun(row, nowMs, quietMs, extra = {}) {
283
285
  * @param {{ at: string, kind: string, actor: string | null, ref: string | null, note: string | null, url: string | null }[]} events
284
286
  * @param {{ status: string }} now `statusOf`'s answer
285
287
  * @param {number} quietMs
288
+ * @param {{ retryOf?: string | null, retriedBy?: { runId: string, at: string }[] }} [links] the run this one starts again, and the runs that start it again
286
289
  */
287
- export function timelineOf(row, events, now, quietMs) {
290
+ export function timelineOf(row, events, now, quietMs, links = {}) {
288
291
  const out = [{ at: row.requested_at, kind: 'requested', actor: row.requested_by, ref: row.profile, note: null, url: row.comment_url }];
289
- out.push(...events.map((e) => ({ ...e, actor: byFromText(e.actor) })));
292
+ if (links.retryOf) out.push({ at: row.requested_at, kind: 'retry-of', actor: null, ref: links.retryOf, note: null, url: null });
293
+ const later = (links.retriedBy ?? []).map((r) => ({ at: r.at, kind: 'retried-by', actor: null, ref: r.runId, note: null, url: null }));
294
+ out.push(...[...events.map((e) => ({ ...e, actor: byFromText(e.actor) })), ...later].sort((a, b) => Date.parse(a.at) - Date.parse(b.at)));
290
295
  if (now.status === 'quiet') out.push({ at: iso(Date.parse(row.last_activity) + quietMs), kind: 'quiet', actor: null, ref: null, note: null, url: null });
291
296
  return out;
292
297
  }
@@ -427,6 +432,12 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
427
432
  const ask = db.prepare('SELECT at, kind, actor, ref, note, url FROM run_events WHERE run_id = ? ORDER BY at, rowid LIMIT ?');
428
433
  for (const r of rows) events.set(r.run_id, ask.all(r.run_id, TIMELINE_LIMIT));
429
434
  }
435
+ // The runs that start these again: found by the id their request names
436
+ const retried = new Map();
437
+ if (rows.length) {
438
+ const again = /** @type {{ run_id: string, requested_at: string, again: string }[]} */ (db.prepare(`SELECT run_id, requested_at, json_extract(request, '$.retryOf') AS again FROM runs WHERE repo = ? AND ${POSTED} AND json_extract(request, '$.retryOf') IN (${rows.map(() => '?').join(',')}) ORDER BY requested_at, run_id`).all(repo, ...rows.map((r) => r.run_id)));
439
+ for (const a of again) retried.set(a.again, [...(retried.get(a.again) ?? []), { runId: a.run_id, at: a.requested_at }]);
440
+ }
430
441
  const mirrors = new Map(rows.length ? /** @type {{ run_id: string, comment_url: string | null, gone: number }[]} */ (db.prepare(`SELECT run_id, comment_url, gone FROM run_mirrors WHERE run_id IN (${rows.map(() => '?').join(',')})`).all(...rows.map((r) => r.run_id))).map((m) => [m.run_id, m]) : []);
431
442
  return new Map(rows.map((r) => {
432
443
  const mine = nodesOf.get(r.run_id);
@@ -435,8 +446,11 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
435
446
  ? open.filter((o) => o.run_id !== r.run_id && nodesOf.get(o.run_id).nodes.some((id) => mine.nodes.includes(id))).map((o) => o.run_id)
436
447
  : [];
437
448
  let brief = '';
438
- try { brief = String(JSON.parse(r.request).brief ?? '').slice(0, BRIEF_SHOWN); } catch { brief = ''; }
439
- return [r.run_id, { brief, nodes: mine.nodes, nodesFrom: mine.from, collidesWith, timeline: timelineOf(r, events.get(r.run_id) ?? [], statusOf(r, at, quietMs), quietMs),
449
+ let briefCut = false;
450
+ let retryOf = null;
451
+ try { const asked = JSON.parse(r.request); const whole = String(asked.brief ?? ''); brief = whole.slice(0, BRIEF_SHOWN); briefCut = whole.length > BRIEF_SHOWN; retryOf = typeof asked.retryOf === 'string' ? asked.retryOf : null; } catch { brief = ''; }
452
+ const retriedBy = retried.get(r.run_id) ?? [];
453
+ return [r.run_id, { brief, briefCut, retriedBy: retriedBy.map((x) => x.runId), nodes: mine.nodes, nodesFrom: mine.from, collidesWith, timeline: timelineOf(r, events.get(r.run_id) ?? [], statusOf(r, at, quietMs), quietMs, { retryOf, retriedBy }),
440
454
  thread: { number: r.target, mirror: kept && kept.comment_url && kept.gone === 0 ? { url: kept.comment_url } : null } }];
441
455
  }));
442
456
  }
@@ -562,6 +576,16 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
562
576
  }
563
577
  }
564
578
 
579
+ /** A request that starts again names a run of this repo that is over without having done its work: `failed` or `stopped`. Throws a `Refused` otherwise */
580
+ function retryProblem(db, runId) {
581
+ const row = /** @type {RunRow | undefined} */ (db.prepare(`SELECT * FROM runs WHERE run_id = ? AND repo = ? AND ${POSTED}`).get(runId, repo));
582
+ if (!row) throw new Refused(404, `"retryOf" names ${runId}, which is not a run of ${repo}.`, 'not-found');
583
+ const { status, open } = statusOf(row, now(), quietMs);
584
+ if (open) throw new Refused(409, `"retryOf" names ${runId}, which is still open (${status}). Only a run that failed or was stopped is started again; stop it first, or wait.`, 'retry-open');
585
+ if (status !== 'failed' && status !== 'stopped') throw new Refused(409, `"retryOf" names ${runId}, which ${status === 'quiet' ? 'went quiet' : `ended as ${status}`}. Only a run that failed or was stopped is started again.`, 'retry-not-over');
586
+ return row;
587
+ }
588
+
565
589
  /** What a request's audit row says: the shape of what was asked and never its words (a brief may be long, and may be anything) */
566
590
  function askedOf(body, via) {
567
591
  const out = /** @type {Record<string, unknown>} */ ({});
@@ -579,6 +603,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
579
603
  out.refs = refs;
580
604
  }
581
605
  if (typeof body.brief === 'string') out.briefChars = body.brief.length;
606
+ if (typeof body.retryOf === 'string' && isRunId(body.retryOf)) out.retryOf = body.retryOf;
582
607
  if (body.force === true) out.force = true;
583
608
  if (transport !== 'forge') out.transport = transport;
584
609
  if (via) Object.assign(out, { via: 'api', token: via.token });
@@ -604,7 +629,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
604
629
  let runId = null;
605
630
  try {
606
631
  if (problem) throw new Refused(problem.status, problem.message, 'invalid');
607
- if (!isObject(body)) throw new Refused(400, `A request is a JSON object: { kind, refs, profile?, brief?, branch?, limits?, nodes?, force? }.`, 'invalid');
632
+ if (!isObject(body)) throw new Refused(400, `A request is a JSON object: { kind, refs, profile?, brief?, branch?, limits?, nodes?, retryOf?, force? }.`, 'invalid');
608
633
  const { force, requestedBy, trigger: forged, ...fields } = body;
609
634
  // What caused a request is cornfield's to write, from a trigger's own call; a caller cannot say it was a trigger
610
635
  if (forged !== undefined) throw new Refused(400, '"trigger" is written by cornfield for an automatic request; leave it out.', 'invalid');
@@ -691,6 +716,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
691
716
  }
692
717
  }
693
718
  const db = await auth.store();
719
+ if (made.retryOf !== undefined) retryProblem(db, made.retryOf);
694
720
  reserve(db, made, { target: number, who, via, force: force === true, trigger: Boolean(made.trigger), derived });
695
721
  // What was read is what the map marks for this run until it pushes: kept, so the overlay has it now and the poll need not read it again
696
722
  if (derived) db.prepare('INSERT OR REPLACE INTO run_reads (run_id, source, sha, data, at) VALUES (?, ?, ?, ?, ?)').run(made.runId, 'mentions', '', JSON.stringify(derived), iso(now()));
@@ -985,6 +1011,18 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
985
1011
  return row ? publicRun(row, now(), quietMs, extrasFor(db, [row], now()).get(row.run_id)) : null;
986
1012
  }
987
1013
 
1014
+ /**
1015
+ * The whole brief of one run of this repo, for **Start again** (the list and `get` show the first `BRIEF_SHOWN` characters): '' for a request
1016
+ * without one, null when this repo has no such run. The route that answers it is the signed-in maintainer's only (server/agent-api.js)
1017
+ */
1018
+ async function briefOf(runId) {
1019
+ if (!isRunId(runId)) return null;
1020
+ const db = await auth.store();
1021
+ const row = /** @type {{ request: string } | undefined} */ (db.prepare(`SELECT request FROM runs WHERE run_id = ? AND repo = ? AND ${POSTED}`).get(runId, repo));
1022
+ if (!row) return null;
1023
+ try { return String(JSON.parse(row.request).brief ?? ''); } catch { return ''; }
1024
+ }
1025
+
988
1026
  /** The runs a follow looks at: posted, not over for good (a trusted pull request merged or closed), and active within the follow window or waiting on a maintainer */
989
1027
  function followable(db, at) {
990
1028
  const window = Math.max(2 * quietMs, FOLLOW_FLOOR_MS);
@@ -1199,6 +1237,8 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1199
1237
  }
1200
1238
  if (at - Date.parse(request.requestedAt) >= quietMs) return { accepted: false, why: 'old', reason: 'posted more than agents.quietAfter ago, so the run would be quiet at once and count for nothing; write it again to ask now' };
1201
1239
  try {
1240
+ // `retryOf` is checked as it is for a request from the API: first, then the cap and the one-run-per-subject rule
1241
+ if (request.retryOf !== undefined) retryProblem(db, request.retryOf);
1202
1242
  reserve(db, request, { target: t.number, who: { userId: '' }, via: null, force: false, hand: { comment } });
1203
1243
  } catch (err) {
1204
1244
  if (err instanceof Refused) return { accepted: false, why: err.code ?? 'refused', reason: err.message };
@@ -1875,7 +1915,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1875
1915
  return hit ? hit.run_id : null;
1876
1916
  }
1877
1917
 
1878
- return { request, stop, answer, list, get, follow, discover, discovers, hasWork, resume, queued, claim, runnerGet, report, openOn, maxOpen: cap, profiles, transport };
1918
+ return { request, stop, answer, list, get, brief: briefOf, follow, discover, discovers, hasWork, resume, queued, claim, runnerGet, report, openOn, maxOpen: cap, profiles, transport };
1879
1919
  }
1880
1920
 
1881
1921
  /** @typedef {ReturnType<typeof createRuns>} Runs */
package/server/server.js CHANGED
@@ -16,6 +16,9 @@
16
16
  * GET /cornfield/house.json the repo's house file, when `sources.house` is the built-in house source;
17
17
  * Home Assistant's floors, areas and devices, when it is `home-assistant`
18
18
  * GET /repo/<path>.js a browser module the config names (and the files in its folder)
19
+ * GET /cornfield/theme.css, /cornfield/theme/<name>.css
20
+ * the stylesheets the config's `theme` names (css, names): those files only, as text/css
21
+ * GET /cornfield/theme/assets/<path> an image or font beside the theme files (png, svg, webp, gif, avif, woff2, woff; 1 MB each)
19
22
  * GET /api/forge/… issues, pull requests, their files and checks, release notes: read from the forge (server/forge-routes.js)
20
23
  * POST /api/forge/pulls/<n>/merge|rerun land a green pull request, re-run a failed check (server/forge-actions.js)
21
24
  * POST /api/forge/issues/<n>/spec, /pulls/<n>/build the pipeline's steps (server/pipeline.js, server/forge-actions.js)
@@ -50,6 +53,7 @@ import { createHash, randomBytes } from 'node:crypto';
50
53
  import { fileURLToPath } from 'node:url';
51
54
  import { browserSources, BUILTIN_SOURCES, parseDuration, specPollMs, triggersOf, DEFAULTS, hookWants, ideaLabel, runnerQuietAfterMs } from '../core/config.js';
52
55
  import { CLOUD_FILE } from '../core/cloud.js';
56
+ import { MAX_THEME_ASSET_BYTES, MAX_THEME_BYTES, THEME_ASSET_PREFIX, THEME_NAME, THEME_SVG_CSP, clientTheme, cssProblems, fontOrigins, fontUrl, themeAssetFile, themeAssetPath } from '../core/theme.js';
53
57
  import { decodePath, inside, notFound, sendFile } from './files.js';
54
58
  import { serveProposals } from './proposals.js';
55
59
  import { serveForge } from './forge-routes.js';
@@ -90,14 +94,96 @@ function importMapOf(config) {
90
94
  * The Content-Security-Policy of every page: everything from this origin, nothing from anywhere else
91
95
  * (the explorer runs offline from any CDN). An import map is inline, so it is allowed by its hash.
92
96
  */
93
- function cspOf(importMap) {
97
+ function cspOf(importMap, theme) {
98
+ const { style, font } = fontOrigins(theme);
94
99
  const hash = importMap ? ` 'sha256-${createHash('sha256').update(importMap).digest('base64')}'` : '';
95
100
  return [
96
- "default-src 'self'", `script-src 'self'${hash}`, "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob:",
97
- "connect-src 'self'", "font-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'", "form-action 'self'",
101
+ "default-src 'self'", `script-src 'self'${hash}`, `style-src 'self' 'unsafe-inline'${style.map((o) => ` ${o}`).join('')}`, "img-src 'self' data: blob:",
102
+ "connect-src 'self'", `font-src 'self'${font.map((o) => ` ${o}`).join('')}`, "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'", "form-action 'self'",
98
103
  ].join('; ');
99
104
  }
100
105
 
106
+ /** The config's theme names that may reach the page: plain ones only (core/theme.js THEME_NAME), and the default when it is one of them */
107
+ function themeNamesOf(theme) {
108
+ const names = Object.keys(theme.names || {}).filter((n) => THEME_NAME.test(n));
109
+ return { names, fallback: theme.default && names.includes(theme.default) ? theme.default : null };
110
+ }
111
+
112
+ /** `<html>` with the named themes on it, for theme-boot.js to read before the first paint */
113
+ function themeHtmlTag(theme) {
114
+ const { names, fallback } = themeNamesOf(theme);
115
+ return names.length ? `<html lang="en" data-theme-names="${names.join(' ')}"${fallback ? ` data-theme-default="${fallback}"` : ''}>` : '<html lang="en">';
116
+ }
117
+
118
+ /**
119
+ * The links that go after cornfield's own stylesheets, in this order: the allow-listed font stylesheets, the repo's theme.css, and the
120
+ * default named theme. explorer/index.html includes theme-boot.js once, after these, so it points that link at the viewer's choice
121
+ * before the first paint. Always links, never inlined CSS.
122
+ */
123
+ function themeHead(theme) {
124
+ const out = [];
125
+ for (const f of theme.fonts || []) {
126
+ const u = fontUrl(f);
127
+ if (u) out.push(`<link rel="stylesheet" href="${escapeHtml(u.href)}" referrerpolicy="no-referrer" />`);
128
+ }
129
+ if (theme.css) out.push('<link rel="stylesheet" href="/cornfield/theme.css" data-cf-theme="css" />');
130
+ const { names, fallback } = themeNamesOf(theme);
131
+ if (names.length) out.push(`<link rel="stylesheet" id="cf-theme-name-css"${fallback ? ` href="/cornfield/theme/${fallback}.css"` : ''} data-cf-theme="name" />`);
132
+ return out.join('\n ');
133
+ }
134
+
135
+ /** The theme files the config names, by the path they are served at: `Map<'/cornfield/theme.css' | '/cornfield/theme/<name>.css', rel>` */
136
+ function themeFilesOf(config) {
137
+ const t = config.theme || {};
138
+ const out = new Map();
139
+ if (t.css) out.set('/cornfield/theme.css', t.css);
140
+ for (const [n, rel] of Object.entries(t.names || {})) if (THEME_NAME.test(n)) out.set(`/cornfield/theme/${n}.css`, rel);
141
+ return out;
142
+ }
143
+
144
+ /**
145
+ * Serves one theme file: text/css and nosniff, only a file the config names, only a plain file whose real path is still inside the repo
146
+ * (a link out is refused), only up to MAX_THEME_BYTES, and only if it passes the same CSS checks as `cornfield validate`.
147
+ */
148
+ function sendTheme(req, res, config, rel, reqPath) {
149
+ try {
150
+ const file = inside(config.root, rel);
151
+ const real = file && fs.realpathSync(file);
152
+ const base = fs.realpathSync(config.root);
153
+ if (!real || !real.startsWith(base + path.sep)) return notFound(res, reqPath);
154
+ const stats = fs.statSync(real);
155
+ if (!stats.isFile() || stats.size > MAX_THEME_BYTES) return notFound(res, reqPath);
156
+ const text = fs.readFileSync(real, 'utf8');
157
+ if (cssProblems(text, { fonts: config.theme.fonts }).length) return notFound(res, reqPath);
158
+ res.writeHead(200, { 'Content-Type': 'text/css; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' });
159
+ return res.end(req.method === 'HEAD' ? undefined : text);
160
+ } catch {
161
+ return notFound(res, reqPath);
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Serves one image or font from beside the theme (docs/config.md#theme): only a THEME_ASSET_TYPES file under the theme folder
167
+ * (core/theme.js `themeAssetPath`, `themeAssetFile`: plain names, no dot segments, no link out, at most 1 MB), never a listing,
168
+ * with nosniff; an SVG gets a policy of its own, so opened by itself it runs and loads nothing.
169
+ */
170
+ function sendThemeAsset(req, res, config, reqPath) {
171
+ try {
172
+ const rel = themeAssetPath(reqPath.slice(THEME_ASSET_PREFIX.length));
173
+ const found = rel && themeAssetFile(config.root, config.theme || {}, rel);
174
+ if (!found || 'problem' in found) return notFound(res, reqPath);
175
+ const body = fs.readFileSync(found.file);
176
+ if (body.length > MAX_THEME_ASSET_BYTES) return notFound(res, reqPath); // it grew since it was looked at
177
+ res.writeHead(200, {
178
+ 'Content-Type': found.type, 'Content-Length': body.length, 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff',
179
+ ...(found.type === 'image/svg+xml' ? { 'Content-Security-Policy': THEME_SVG_CSP } : {}),
180
+ });
181
+ return res.end(req.method === 'HEAD' ? undefined : body);
182
+ } catch {
183
+ return notFound(res, reqPath);
184
+ }
185
+ }
186
+
101
187
  /** The browser modules the config names from the repo: each one's folder may be served (its .js files only) */
102
188
  function repoModuleDirs(config) {
103
189
  const dirs = [];
@@ -120,6 +206,8 @@ export function clientConfig(config, signIn = false) {
120
206
  version: PKG.version,
121
207
  title: config.title,
122
208
  links: config.links || [],
209
+ // The theme's names and default, never a file's path (docs/config.md#theme)
210
+ theme: clientTheme(config.theme),
123
211
  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.approveLands ? { approveLands: true } : {}) } : null,
124
212
  // Threads (docs/threads.md): the idea label, or false when `threads: false` turns the Threads tab off
125
213
  threads: config.threads === false ? false : { label: ideaLabel(config) },
@@ -167,7 +255,9 @@ export function createCornfieldServer(config, opts = {}) {
167
255
  if (config.approveLands && !auth.enabled) throw new Error('The config says proposals.approveLands, but sign-in is not set up. An approval is a signed-in maintainer\'s, and it lands as them, so without sign-in nothing would ever land: set up sign-in (docs/sign-in.md), or remove approveLands.');
168
256
  const root = config.root;
169
257
  const importMap = importMapOf(config);
170
- const csp = cspOf(importMap);
258
+ const theme = config.theme || {};
259
+ const csp = cspOf(importMap, theme);
260
+ const themeFile = themeFilesOf(config);
171
261
  const repoModules = repoModuleDirs(config);
172
262
  const publicHost = config.publicUrl ? new URL(config.publicUrl).hostname : null;
173
263
  const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost };
@@ -220,6 +310,8 @@ export function createCornfieldServer(config, opts = {}) {
220
310
  const page = () => {
221
311
  const html = fs.readFileSync(path.join(EXPLORER_DIR, 'index.html'), 'utf8')
222
312
  .replace('<!--@importmap-->', importMap ? `<script type="importmap">${importMap}</script>` : '')
313
+ .replace('<html lang="en">', () => themeHtmlTag(theme))
314
+ .replace('<!--@theme-->', () => themeHead(theme)) // a function, so a `$` in a font URL is not a replacement pattern
223
315
  .replace(/<title>[^<]*<\/title>/, `<title>${escapeHtml(config.title)} · cornfield</title>`);
224
316
  return html;
225
317
  };
@@ -313,6 +405,8 @@ export function createCornfieldServer(config, opts = {}) {
313
405
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' });
314
406
  return res.end(req.method === 'HEAD' ? undefined : page());
315
407
  }
408
+ if (themeFile.has(reqPath)) return sendTheme(req, res, config, themeFile.get(reqPath), reqPath);
409
+ if (reqPath.startsWith(THEME_ASSET_PREFIX)) return sendThemeAsset(req, res, config, reqPath);
316
410
  if (reqPath === '/cornfield/config.json') return sendJson(res, 200, clientConfig(config, signedIn));
317
411
  if (reqPath === '/topology.json') {
318
412
  const file = inside(root, config.topology);