@popcorn245/cornfield 0.33.1 → 0.34.1

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.
@@ -535,6 +535,7 @@ function mountDrawerBox() {
535
535
  drawerBox.id = 'whatif-drawer';
536
536
  drawerBox.className = 'hx-block hx-whatif-drawer';
537
537
  drawerBox.hidden = true;
538
+ drawerBox.tabIndex = -1; // holds the focus while it is painted again (paintDrawer)
538
539
  block.after(drawerBox); // under the facts, the mockups and the threads: the node comes first, the tools to edit it after
539
540
  drawerBox.addEventListener('click', onClick);
540
541
  return drawerBox;
@@ -560,30 +561,43 @@ function edgeToHtml(n) {
560
561
  .sort((a, b) => String(a.label).localeCompare(String(b.label)))
561
562
  .slice(0, EDGE_TO_MAX);
562
563
  if (!others.length) return '';
563
- return `<div class="hx-whatif-addstep hx-whatif-edgeto">
564
+ return `<div class="hx-whatif-edgeto">
564
565
  <label class="hx-whatif-field" data-corn="field">Edge to <select data-edge-to>${others.map((o) => `<option value="${escHtml(o.id)}">${escHtml(o.label)} (${escHtml(o.type)})</option>`).join('')}</select></label>
565
- <button type="button" class="hx-btn" data-whatif="edge-to" data-from="${escHtml(n.id)}" title="Draw an edge from this node to the one picked, without dragging">Draw an edge</button>
566
+ <button type="button" class="hx-btn hx-btn--quiet" data-whatif="edge-to" data-from="${escHtml(n.id)}" title="Draw an edge from this node to the one picked, without dragging">Draw an edge</button>
566
567
  </div>`;
567
568
  }
568
569
 
570
+ /** Paints the box; when the keyboard was in it (a Remove, a Bring back), the focus stays in it rather than falling to the page */
569
571
  function paintDrawer() {
570
572
  const box = mountDrawerBox();
571
573
  if (!box) return;
572
- const open = !!state.proposal && (!!state.selectedNode || !!state.selectedEdge);
574
+ const was = box.contains(document.activeElement) ? document.activeElement : null;
575
+ const same = (el) => el.tagName === was.tagName && ['whatif', 'id', 'from', 'to', 'kind', 'flow', 'edgeTo'].every((k) => el.dataset[k] === was.dataset[k]);
576
+ fillDrawer(box);
577
+ if (!was || box.hidden) return;
578
+ const next = [...box.querySelectorAll('button:not([disabled]), select, summary')].find(same)
579
+ // the button pressed is gone: Remove became Bring it back (or back again), or an edge left the list
580
+ || ((was.tagName === 'BUTTON' || was === box) && (box.querySelector('[data-whatif="bring-back"]:not([disabled])') || (was.closest('details') && box.querySelector('summary')) || box.querySelector('button:not([disabled])')))
581
+ || box; // nothing to hold it yet (the map is mid-rebuild): the box keeps it for the next paint
582
+ next.focus({ preventScroll: true });
583
+ }
584
+
585
+ function fillDrawer(box) {
586
+ const open = !!state.proposal && ui.editing && (!!state.selectedNode || !!state.selectedEdge); // behind the toolbar's Edit, like the rest of the what-if tools
573
587
  box.hidden = !open;
574
588
  if (!open) { box.innerHTML = ''; return; }
575
589
 
576
590
  const message = '<p class="hx-whatif-msg" data-msg="drawer" role="alert" hidden data-corn="message"></p>';
577
- const title = '<h3 class="hx-block-title">Try a change</h3>';
591
+ const title = '<h3 class="hx-sec-title">Try a change</h3>';
578
592
  if (state.selectedEdge) {
579
593
  const e = state.selectedEdge;
580
594
  const key = edgeKey(e);
581
595
  if (kindOfMark(e) === 'removed' && e.mark !== 'edit') { box.hidden = true; return; } // the proposal's own removal: not for an edit to undo
582
596
  if (e.mark === 'edit' && e.editOp === 'removed') {
583
597
  const i = removalIndex('remove-edge', (x) => edgeKey(x) === key);
584
- box.innerHTML = `${title}<p class="hx-faint">You removed this edge.</p><button type="button" class="hx-btn" data-whatif="bring-back" data-index="${i}"${i < 0 ? ' disabled' : ''}>Bring it back</button>${message}`;
598
+ box.innerHTML = `${title}<p class="hx-faint">You removed this edge.</p><button type="button" class="hx-btn hx-btn--quiet" data-whatif="bring-back" data-index="${i}"${i < 0 ? ' disabled' : ''}>Bring it back</button>${message}`;
585
599
  } else {
586
- box.innerHTML = `${title}<button type="button" class="hx-btn" data-whatif="remove-edge" data-from="${escHtml(e.from)}" data-to="${escHtml(e.to)}" data-kind="${escHtml(e.kind || '')}" data-flow="${escHtml(e.flow || '')}" title="Take this edge out of the proposal's map">Remove in this proposal</button>${message}`;
600
+ box.innerHTML = `${title}<button type="button" class="hx-btn hx-btn--quiet" data-whatif="remove-edge" data-from="${escHtml(e.from)}" data-to="${escHtml(e.to)}" data-kind="${escHtml(e.kind || '')}" data-flow="${escHtml(e.flow || '')}" title="Take this edge out of the proposal's map">Remove in this proposal</button>${message}`;
587
601
  }
588
602
  paintMessages();
589
603
  return;
@@ -593,7 +607,7 @@ function paintDrawer() {
593
607
  if (n.mark === 'removed') { box.hidden = true; return; } // the proposal's own removal
594
608
  if (n.mark === 'edit' && n.editOp === 'removed') {
595
609
  const i = removalIndex('remove-node', (x) => x.id === n.id);
596
- box.innerHTML = `${title}<p class="hx-faint">You removed this node.</p><button type="button" class="hx-btn" data-whatif="bring-back" data-index="${i}"${i < 0 ? ' disabled' : ''}>Bring it back</button>${message}`;
610
+ box.innerHTML = `${title}<p class="hx-faint">You removed this node.</p><button type="button" class="hx-btn hx-btn--quiet" data-whatif="bring-back" data-index="${i}"${i < 0 ? ' disabled' : ''}>Bring it back</button>${message}`;
597
611
  paintMessages();
598
612
  return;
599
613
  }
@@ -602,7 +616,7 @@ function paintDrawer() {
602
616
  const rows = shown.map((e) => `<li class="hx-whatif-edit"><span class="hx-whatif-edit-text">${escHtml(edgeName(e))} <span class="hx-faint">${escHtml(e.kind === 'flow' ? `flow, ${e.flow}` : e.kind || 'ownership')}</span></span><button type="button" class="hx-textbtn" data-whatif="remove-edge" data-from="${escHtml(e.from)}" data-to="${escHtml(e.to)}" data-kind="${escHtml(e.kind || '')}" data-flow="${escHtml(e.flow || '')}" aria-label="Remove the edge ${escHtml(edgeName(e))}">Remove</button></li>`);
603
617
  const help = n.mark === 'edit' || n.mark === 'added' ? 'Takes it out of this proposal, with whatever hangs on it.' : 'Shows the map without it.';
604
618
  box.innerHTML = `${title}
605
- <button type="button" class="hx-btn" data-whatif="remove-node" data-id="${escHtml(n.id)}" title="${escHtml(help)}">Remove in this proposal</button>
619
+ <button type="button" class="hx-btn hx-btn--quiet" data-whatif="remove-node" data-id="${escHtml(n.id)}" title="${escHtml(help)}">Remove in this proposal</button>
606
620
  ${edgeToHtml(n)}
607
621
  ${edges.length ? `<details class="hx-whatif-edges"><summary>Its edges (${edges.length})</summary><ul class="hx-whatif-list">${rows.join('')}</ul>${edges.length > shown.length ? `<p class="hx-faint">and ${edges.length - shown.length} more</p>` : ''}</details>` : ''}
608
622
  ${message}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popcorn245/cornfield",
3
- "version": "0.33.1",
3
+ "version": "0.34.1",
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)",
@@ -0,0 +1,135 @@
1
+ /**
2
+ * @module server/compress
3
+ *
4
+ * Compresses the text the server sends (the page, JS, CSS, JSON, SVG) with Node's own zlib: brotli when the browser
5
+ * accepts it, gzip otherwise, never for what is already compressed (images, fonts) or streamed (event streams), and never
6
+ * on top of an answer that already carries a `Content-Encoding`, never a proxied upstream's answer or a range, and never
7
+ * an answer marked `Cache-Control: no-store` (what may hold a secret: sign-in, tokens, the agent and runner APIs; BREACH).
8
+ * Every compressible answer says `Vary: Accept-Encoding`, so a cache keeps the two apart. ETags are weak (files.js) and
9
+ * the same for every encoding, so a conditional request still gets its 304.
10
+ *
11
+ * Used by wrapping the response once, at the top of the request: `compressResponse(req, res)`.
12
+ */
13
+
14
+ import zlib from 'node:zlib';
15
+
16
+ /** Content types worth compressing: text, JSON (and `+json`), JavaScript, XML, SVG */
17
+ const COMPRESSIBLE = /^(?:text\/(?!event-stream)|application\/(?:json|javascript|ecmascript|xml|manifest\+json|[\w.+-]+\+(?:json|xml))|image\/svg\+xml)/i;
18
+ /** Below this many bytes (when the length is known) compressing costs more than it saves */
19
+ const MIN_BYTES = 512;
20
+
21
+ /**
22
+ * The encoding to answer with, from an `Accept-Encoding` header: `br`, `gzip`, or null. A `q=0` refuses one.
23
+ * @param {string|undefined} header
24
+ * @returns {'br'|'gzip'|null}
25
+ */
26
+ export function pickEncoding(header) {
27
+ if (!header) return null;
28
+ const q = new Map();
29
+ for (const part of String(header).split(',')) {
30
+ const [name, ...params] = part.trim().toLowerCase().split(';');
31
+ if (!name) continue;
32
+ const m = params.map((p) => p.trim()).find((p) => p.startsWith('q='));
33
+ q.set(name.trim(), m ? Number(m.slice(2)) : 1);
34
+ }
35
+ const weight = (e) => { const v = q.has(e) ? q.get(e) : q.has('*') ? q.get('*') : 0; return Number.isFinite(v) && v > 0 ? v : 0; };
36
+ const br = weight('br');
37
+ const gzip = Math.max(weight('gzip'), weight('x-gzip'));
38
+ if (!br && !gzip) return null;
39
+ return br >= gzip ? 'br' : 'gzip'; // the one the browser prefers; brotli on a tie
40
+ }
41
+
42
+ /** Whether a `Content-Type` is one of the compressible kinds */
43
+ export const isCompressible = (type) => typeof type === 'string' && COMPRESSIBLE.test(type.trim());
44
+
45
+ const SKIP = Symbol('cornfield.noCompress');
46
+
47
+ /**
48
+ * Leaves this answer as it is: a proxied upstream's answer (it may be a stream, or a range, and the upstream saw the
49
+ * request's Accept-Encoding itself).
50
+ * @param {import('node:http').ServerResponse} res
51
+ */
52
+ export function skipCompression(res) { /** @type {any} */ (res)[SKIP] = true; }
53
+
54
+ const hasVary = (v, name) => String(v || '').split(',').some((t) => t.trim().toLowerCase() === name.toLowerCase() || t.trim() === '*');
55
+
56
+ /**
57
+ * Wraps `res` so a compressible answer goes out compressed when the request allows it. Safe to call on every request:
58
+ * it changes nothing until `writeHead` (or the first write) shows a compressible body.
59
+ * @param {import('node:http').IncomingMessage} req
60
+ * @param {import('node:http').ServerResponse} res
61
+ */
62
+ export function compressResponse(req, res) {
63
+ const encoding = pickEncoding(req.headers['accept-encoding']);
64
+ const origWriteHead = res.writeHead.bind(res);
65
+ const origWrite = res.write.bind(res);
66
+ const origEnd = res.end.bind(res);
67
+ let decided = false;
68
+ let writeImpl = origWrite;
69
+ let endImpl = origEnd;
70
+ // Sending a body without `writeHead` first (Node adds the head itself): decide before it goes
71
+ res.write = (...a) => { if (!decided) res.writeHead(res.statusCode); return writeImpl(...a); };
72
+ res.end = (...a) => { if (!decided) res.writeHead(res.statusCode); return endImpl(...a); };
73
+
74
+ const header = (extra, name) => {
75
+ if (extra && !Array.isArray(extra)) {
76
+ const key = Object.keys(extra).find((k) => k.toLowerCase() === name.toLowerCase());
77
+ if (key !== undefined) return extra[key];
78
+ }
79
+ return res.getHeader(name);
80
+ };
81
+
82
+ res.writeHead = (status, ...rest) => {
83
+ // The caller's headers may be a constant it sends again (server.js JSON_HEADERS): change a copy, never that
84
+ const at = rest.findIndex((x) => x && typeof x === 'object');
85
+ if (at >= 0 && !Array.isArray(rest[at])) rest[at] = { ...rest[at] };
86
+ const extra = at >= 0 ? rest[at] : undefined;
87
+ if (!decided) {
88
+ decided = true;
89
+ const type = header(extra, 'content-type');
90
+ const bodyless = status < 200 || status === 204 || (status === 304 && !isCompressible(type));
91
+ if (!bodyless && isCompressible(type)) {
92
+ // The answer varies by the request's Accept-Encoding whether or not this one is compressed (a 304 too)
93
+ const vary = header(extra, 'vary');
94
+ if (!hasVary(vary, 'accept-encoding')) {
95
+ if (extra && !Array.isArray(extra)) extra.Vary = vary ? `${vary}, Accept-Encoding` : 'Accept-Encoding';
96
+ else res.setHeader('Vary', vary ? `${vary}, Accept-Encoding` : 'Accept-Encoding');
97
+ }
98
+ const length = Number(header(extra, 'content-length'));
99
+ const done = header(extra, 'content-encoding');
100
+ // `no-store` marks what the server treats as secret (sign-in pages, tokens, the agent and runner APIs): a body
101
+ // that may hold a secret beside what the request sent is never compressed (the BREACH class of attack)
102
+ const cache = String(header(extra, 'cache-control') || '');
103
+ const keep = /no-transform|no-store/i.test(cache) || /** @type {any} */ (res)[SKIP]
104
+ || status === 206 || header(extra, 'content-range') !== undefined;
105
+ if (encoding && status !== 304 && !done && !keep && !(Number.isFinite(length) && length > 0 && length < MIN_BYTES)) {
106
+ if (extra && !Array.isArray(extra)) {
107
+ Object.keys(extra).filter((k) => k.toLowerCase() === 'content-length').forEach((k) => { delete extra[k]; });
108
+ extra['Content-Encoding'] = encoding;
109
+ } else res.setHeader('Content-Encoding', encoding);
110
+ res.removeHeader('Content-Length');
111
+ if (req.method !== 'HEAD') startStream();
112
+ }
113
+ }
114
+ }
115
+ return origWriteHead(status, ...rest);
116
+ };
117
+
118
+ function startStream() {
119
+ const stream = encoding === 'br'
120
+ // Quality 4 is the cheap end: about as fast as gzip, and smaller
121
+ ? zlib.createBrotliCompress({ params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4, [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT } })
122
+ : zlib.createGzip({ level: 6 });
123
+ stream.on('data', (chunk) => origWrite(chunk));
124
+ stream.on('end', () => origEnd());
125
+ stream.on('error', () => res.destroy());
126
+ stream.on('drain', () => res.emit('drain'));
127
+ writeImpl = (chunk, enc, cb) => stream.write(chunk, enc, cb);
128
+ endImpl = (chunk, enc, cb) => {
129
+ if (typeof chunk === 'function') { cb = chunk; chunk = undefined; }
130
+ if (chunk !== undefined && chunk !== null) stream.end(chunk, typeof enc === 'string' ? enc : undefined, cb);
131
+ else stream.end(cb);
132
+ return res;
133
+ };
134
+ }
135
+ }
package/server/proxy.js CHANGED
@@ -11,6 +11,7 @@
11
11
  * The session is a bearer credential for the whole dashboard, and the upstream is someone else's server.
12
12
  */
13
13
 
14
+ import { skipCompression } from './compress.js';
14
15
  import http from 'node:http';
15
16
  import https from 'node:https';
16
17
 
@@ -40,6 +41,7 @@ export function withoutOwnSetCookies(values) {
40
41
  * @param {string} target like `http://127.0.0.1:3245`
41
42
  */
42
43
  export function proxyTo(req, res, target) {
44
+ skipCompression(res); // the upstream saw Accept-Encoding and answers as it likes: a stream or a range stays as it is
43
45
  const url = new URL(target);
44
46
  const client = url.protocol === 'https:' ? https : http;
45
47
  const port = url.port || (url.protocol === 'https:' ? '443' : '80');
package/server/server.js CHANGED
@@ -75,6 +75,7 @@ import { createLander } from './lander.js';
75
75
  import { createSpecPoll } from './spec-poll.js';
76
76
  import { createRunnerWatch } from './runner-presence.js';
77
77
  import { createTriggers } from './triggers.js';
78
+ import { compressResponse } from './compress.js';
78
79
 
79
80
  export const CORNFIELD_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
80
81
  const EXPLORER_DIR = path.join(CORNFIELD_DIR, 'explorer');
@@ -403,6 +404,7 @@ export function createCornfieldServer(config, opts = {}) {
403
404
  return server;
404
405
 
405
406
  async function answer(req, res) {
407
+ compressResponse(req, res); // text, JSON, JS, CSS and SVG go out gzipped or brotli'd when the browser accepts it
406
408
  res.setHeader('Content-Security-Policy', csp);
407
409
  res.setHeader('Referrer-Policy', 'no-referrer');
408
410
  res.setHeader('X-Frame-Options', 'DENY');