@bigmistqke/whiteboard 0.5.0 → 0.6.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.
Files changed (106) hide show
  1. package/README.md +125 -25
  2. package/bin/whiteboard.ts +299 -16
  3. package/dist/bin/whiteboard.js +247 -17
  4. package/dist/client/runtime.js +22 -10
  5. package/dist/plugins/ansi/README.md +36 -0
  6. package/dist/plugins/ansi/index.js +64 -0
  7. package/dist/plugins/ansi/public/style.css +28 -0
  8. package/dist/plugins/badge/README.md +28 -0
  9. package/dist/plugins/badge/index.js +24 -0
  10. package/dist/plugins/badge/public/style.css +30 -0
  11. package/dist/plugins/chat/public/style.css +7 -2
  12. package/dist/plugins/code/README.md +4 -2
  13. package/dist/plugins/code/diff.js +12 -2
  14. package/dist/plugins/grid/README.md +12 -12
  15. package/dist/plugins/grid/index.js +7 -19
  16. package/dist/plugins/grid/public/style.css +4 -33
  17. package/dist/plugins/iframe/README.md +7 -7
  18. package/dist/plugins/iframe/index.js +11 -11
  19. package/dist/plugins/iframe/public/style.css +15 -0
  20. package/dist/plugins/index.js +7 -3
  21. package/dist/plugins/lightbox/README.md +22 -0
  22. package/dist/plugins/lightbox/index.js +20 -0
  23. package/dist/plugins/lightbox/public/client.js +4 -0
  24. package/dist/plugins/lightbox/public/style.css +66 -0
  25. package/dist/plugins/steps/README.md +3 -3
  26. package/dist/plugins/steps/index.js +3 -42
  27. package/dist/plugins/steps/public/client.js +1 -1
  28. package/dist/plugins/terminal/host.js +1 -1
  29. package/dist/plugins/terminal/public/client.js +1 -1
  30. package/dist/plugins/window/README.md +34 -14
  31. package/dist/plugins/window/index.js +21 -13
  32. package/dist/src/auth.js +4 -3
  33. package/dist/src/client/page/base.css +61 -1
  34. package/dist/src/client/page/main.js +60 -14
  35. package/dist/src/entries.js +217 -0
  36. package/dist/src/events.js +1 -1
  37. package/dist/src/hub.js +272 -0
  38. package/dist/src/loader.js +4 -1
  39. package/dist/src/package.js +23 -1
  40. package/dist/src/pages/blocks.js +1 -0
  41. package/dist/src/pages/index.js +1 -1
  42. package/dist/src/pages/markdown.js +87 -33
  43. package/dist/src/pages/render.js +116 -14
  44. package/dist/src/pages/window.js +16 -18
  45. package/dist/src/running.js +37 -2
  46. package/dist/src/serve.js +111 -2
  47. package/dist/src/server.js +49 -14
  48. package/package.json +1 -1
  49. package/plugins/ansi/README.md +36 -0
  50. package/plugins/ansi/index.ts +95 -0
  51. package/plugins/ansi/public/style.css +28 -0
  52. package/plugins/badge/README.md +28 -0
  53. package/plugins/badge/index.ts +35 -0
  54. package/plugins/badge/public/style.css +30 -0
  55. package/plugins/chat/public/style.css +7 -2
  56. package/plugins/code/README.md +4 -2
  57. package/plugins/code/diff.ts +14 -2
  58. package/plugins/grid/README.md +12 -12
  59. package/plugins/grid/index.ts +11 -26
  60. package/plugins/grid/public/style.css +4 -33
  61. package/plugins/iframe/README.md +7 -7
  62. package/plugins/iframe/index.ts +15 -15
  63. package/plugins/iframe/public/style.css +15 -0
  64. package/plugins/index.ts +6 -2
  65. package/plugins/lightbox/README.md +22 -0
  66. package/plugins/lightbox/client.ts +99 -0
  67. package/plugins/lightbox/index.ts +25 -0
  68. package/plugins/lightbox/public/style.css +66 -0
  69. package/plugins/steps/README.md +3 -3
  70. package/plugins/steps/client.ts +15 -6
  71. package/plugins/steps/index.ts +3 -46
  72. package/plugins/terminal/client.ts +16 -7
  73. package/plugins/window/README.md +34 -14
  74. package/plugins/window/index.ts +20 -13
  75. package/skills/whiteboard/SKILL.md +17 -10
  76. package/src/auth.ts +5 -3
  77. package/src/client/base.ts +19 -0
  78. package/src/client/forms.ts +2 -1
  79. package/src/client/markdown.ts +2 -1
  80. package/src/client/page/base.css +61 -1
  81. package/src/client/page/elsewhere.ts +72 -16
  82. package/src/client/page/fresh.ts +2 -1
  83. package/src/client/page/sort.ts +2 -1
  84. package/src/client/runtime.ts +11 -9
  85. package/src/define.ts +66 -7
  86. package/src/entries.ts +269 -0
  87. package/src/events.ts +2 -1
  88. package/src/hub.ts +355 -0
  89. package/src/loader.ts +7 -1
  90. package/src/package.ts +22 -0
  91. package/src/pages/blocks.ts +3 -0
  92. package/src/pages/index.ts +4 -2
  93. package/src/pages/markdown.ts +89 -32
  94. package/src/pages/render.ts +134 -13
  95. package/src/pages/window.ts +16 -25
  96. package/src/running.ts +47 -1
  97. package/src/serve.ts +114 -1
  98. package/src/server.ts +80 -14
  99. package/dist/plugins/gallery/README.md +0 -30
  100. package/dist/plugins/gallery/index.js +0 -75
  101. package/dist/plugins/gallery/public/client.js +0 -1
  102. package/dist/plugins/gallery/public/style.css +0 -90
  103. package/plugins/gallery/README.md +0 -30
  104. package/plugins/gallery/client.tsx +0 -70
  105. package/plugins/gallery/index.ts +0 -89
  106. package/plugins/gallery/public/style.css +0 -90
@@ -2,6 +2,7 @@ import { renderMarkdown } from "./markdown.js";
2
2
  import { html, raw } from "../html.js";
3
3
  import { awaitingLabel } from "../icons.js";
4
4
  import fs from "node:fs";
5
+ import os from "node:os";
5
6
  import path from "node:path";
6
7
  import { execFileSync } from "node:child_process";
7
8
  import { fileURLToPath } from "node:url";
@@ -38,18 +39,19 @@ function titleOf(file, fallback) {
38
39
  return fallback;
39
40
  }
40
41
  }
41
- function crumbs(id, name) {
42
+ function crumbs(id, name, base, entry) {
42
43
  const parts = id ? id.split("/") : [];
43
- return html`<a href="/">${name}</a
44
- >${parts.map((p, i) => html` / <a href="/${parts.slice(0, i + 1).join("/")}">${p}</a>`)}`;
44
+ const above = entry ? html`<a href="/">whiteboard</a> / ` : "";
45
+ return html`${above}<a href="${base}/">${name}</a
46
+ >${parts.map((p, i) => html` / <a href="${base}/${parts.slice(0, i + 1).join("/")}">${p}</a>`)}`;
45
47
  }
46
48
  const time = (ts) => html`<time data-ts="${ts}"></time>`;
47
- function pageList(pages) {
49
+ function pageList(pages, base) {
48
50
  return html`<ul class="wb-index">
49
51
  ${pages.map((p) => html`<li>
50
- <a href="/${p.id}">${titleOf(p.file, path.basename(p.id))}</a>${p.awaiting > 0 && html` <a
52
+ <a href="${base}/${p.id}">${titleOf(p.file, path.basename(p.id))}</a>${p.awaiting > 0 && html` <a
51
53
  class="wb-awaiting"
52
- href="/${p.id}#wb-waiting"
54
+ href="${base}/${p.id}#wb-waiting"
53
55
  title="${awaitingLabel(p.awaiting)}"
54
56
  aria-label="${awaitingLabel(p.awaiting)}"
55
57
  >${raw("<svg viewBox=\"0 0 16 16\" width=\"13\" height=\"13\" aria-hidden=\"true\"><path d=\"M2 9.5 3.8 3.2A1 1 0 0 1 4.8 2.5h6.4a1 1 0 0 1 1 .7L14 9.5V13a.5.5 0 0 1-.5.5h-11A.5.5 0 0 1 2 13Zm0 0h3.5l1 1.5h3l1-1.5H14\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linejoin=\"round\"/></svg>")}${p.awaiting}</a
@@ -141,8 +143,79 @@ function documentsIn(dir) {
141
143
  * written here), by when last updated, or by title; each row carries what it is sorted by.
142
144
  */
143
145
  function documentList(ctx) {
144
- const files = documentsIn(ctx.project.dir);
146
+ return documentsOf(ctx.project.dir, ctx.base ?? "", ctx.urlFor);
147
+ }
148
+ /**
149
+ * A project's documents by the folder they are in, each folder a fold with how many it holds, the
150
+ * top folder's own documents first: the shared server's overview, where a repository's many
151
+ * documents would otherwise be one long list. A folder holding only one folder is shown as one
152
+ * (`docs/adr/`), so the tree is no deeper than what tells folders apart.
153
+ */
154
+ function documentTree(files, dir, base, urlFor) {
155
+ const root = {
156
+ files: [],
157
+ folders: /* @__PURE__ */ new Map(),
158
+ count: 0
159
+ };
160
+ for (const f of files) {
161
+ let at = root;
162
+ at.count++;
163
+ const parts = f.split("/");
164
+ for (const part of parts.slice(0, -1)) {
165
+ if (!at.folders.has(part)) at.folders.set(part, {
166
+ files: [],
167
+ folders: /* @__PURE__ */ new Map(),
168
+ count: 0
169
+ });
170
+ at = at.folders.get(part);
171
+ at.count++;
172
+ }
173
+ at.files.push(f);
174
+ }
175
+ const row = (f) => {
176
+ const abs = path.join(dir, f);
177
+ const name = path.posix.basename(f);
178
+ const title = titleOf(abs, name);
179
+ let mtime = 0;
180
+ try {
181
+ mtime = fs.statSync(abs).mtimeMs;
182
+ } catch {}
183
+ return html`<li>
184
+ <a href="${urlFor(abs) ?? `${base}/-/${f}`}">${title}</a>
185
+ <span class="wb-meta">${title !== name && html`<code>${name}</code> · `}edited ${time(mtime)}</span>
186
+ </li>`;
187
+ };
188
+ const folder = (name, f) => {
189
+ while (!f.files.length && f.folders.size === 1) {
190
+ const [inner, next] = [...f.folders][0];
191
+ name = `${name}/${inner}`;
192
+ f = next;
193
+ }
194
+ return html`<details class="wb-folder">
195
+ <summary>${name}/ <span class="wb-meta">${f.count}</span></summary>
196
+ ${contents(f)}
197
+ </details>`;
198
+ };
199
+ const contents = (f) => html`${f.files.length > 0 && html`<ul class="wb-index">
200
+ ${f.files.map(row)}
201
+ </ul>`}${[...f.folders].toSorted(([a], [b]) => a.localeCompare(b)).map(([name, sub]) => folder(name, sub))}`;
202
+ return html`<details class="wb-documents wb-folded-documents">
203
+ <summary>Files <span class="wb-meta">${files.length}</span></summary>
204
+ ${contents(root)}
205
+ </details>`;
206
+ }
207
+ /**
208
+ * A project's documents, as its overview lists them: from its folder, linked where it serves them.
209
+ * `folded`: in a fold that says how many (the shared server's overview, where each project has them).
210
+ */
211
+ function documentsOf(dir, base, urlFor, folded = false) {
212
+ const files = documentsIn(dir);
145
213
  if (!files.length) return "";
214
+ const ctx = {
215
+ project: { dir },
216
+ base,
217
+ urlFor
218
+ };
146
219
  const rows = files.map((f, i) => {
147
220
  const abs = path.join(ctx.project.dir, f);
148
221
  const name = path.posix.basename(f);
@@ -153,12 +226,13 @@ function documentList(ctx) {
153
226
  mtime = fs.statSync(abs).mtimeMs;
154
227
  } catch {}
155
228
  return html`<li data-order="${i}" data-updated="${mtime}" data-title="${title.toLowerCase()}">
156
- <a href="${ctx.urlFor(abs) ?? `/-/${f}`}">${title}</a>
229
+ <a href="${ctx.urlFor(abs) ?? `${ctx.base ?? ""}/-/${f}`}">${title}</a>
157
230
  <span class="wb-meta"
158
231
  >${where !== "." && html`<code>${where === f ? f : `${where}/`}</code> · `}edited ${time(mtime)}</span
159
232
  >
160
233
  </li>`;
161
234
  });
235
+ if (folded) return documentTree(files, dir, base, urlFor);
162
236
  return html`<section class="wb-documents">
163
237
  <div class="wb-list-head">
164
238
  <h2>Documents</h2>
@@ -223,11 +297,12 @@ const skipped = (name) => ({
223
297
  fences: true,
224
298
  props: null,
225
299
  html: () => "",
300
+ open: null,
226
301
  client: null,
227
302
  style: null,
228
303
  source: "build"
229
304
  });
230
- function createRender(blocks, style, pluginStyles = [], links = []) {
305
+ function createRender(blocks, style, pluginStyles = [], links = [], composers = /* @__PURE__ */ new Map()) {
231
306
  const textLinks = textLinksOf(links);
232
307
  const STYLE = stylePath(style);
233
308
  const PLUGIN_STYLES = pluginStyles.map((s) => ({
@@ -247,7 +322,8 @@ function createRender(blocks, style, pluginStyles = [], links = []) {
247
322
  },
248
323
  code,
249
324
  linkFor: ctx.urlFor,
250
- textLinks: textLinks(ctx.project.dir)
325
+ textLinks: textLinks(ctx.project.dir),
326
+ composers: skip ? new Map([...composers].map(([name, compose]) => skip.has(name) ? [name, ({ children }) => String(children)] : [name, compose])) : composers
251
327
  });
252
328
  }
253
329
  async function content(page, ctx) {
@@ -255,15 +331,41 @@ function createRender(blocks, style, pluginStyles = [], links = []) {
255
331
  switch (page.kind) {
256
332
  case "page": return markdown(page.source, page.id, page.file, ctx);
257
333
  case "pages": {
258
- const list = page.pages.length ? pageList(page.pages) : html`<p class="wb-meta">No pages yet.</p>`;
334
+ if (page.groups) {
335
+ const waiting = (ps) => ps.reduce((n, p) => n + p.awaiting, 0);
336
+ const first = (ps) => ps.toSorted((a, b) => Number(b.awaiting > 0) - Number(a.awaiting > 0));
337
+ const groups = page.groups.toSorted((a, b) => Number(waiting(b.pages) > 0) - Number(waiting(a.pages) > 0));
338
+ return {
339
+ html: html`<h1>${project.name}</h1>
340
+ ${groups.map((g) => html`<section class="wb-project">
341
+ <h2>${g.title}</h2>
342
+ <p class="wb-meta">
343
+ <code>${g.dir.replace(os.homedir(), "~")}</code>
344
+ </p>
345
+ ${pageList(first(g.pages), g.base)} ${g.files && documentsOf(g.dir, g.base, () => null, true)}
346
+ </section>`)}
347
+ ${!groups.length && html`<p class="wb-meta">No pages yet.</p>`}
348
+ ${page.empty?.length ? html`<details class="wb-empty-projects">
349
+ <summary>${page.empty.length} without pages</summary>
350
+ <ul>
351
+ ${page.empty.map((e) => html`<li><a href="${e.base}/">${e.title}</a></li>`)}
352
+ </ul>
353
+ </details>` : ""}
354
+ ${page.note && html`<p class="wb-meta">${page.note}</p>`}`,
355
+ title: project.name,
356
+ islands: {},
357
+ styles: []
358
+ };
359
+ }
360
+ const list = page.pages.length ? pageList(page.pages, ctx.base ?? "") : html`<p class="wb-meta">No pages yet.</p>`;
259
361
  return {
260
362
  html: page.id ? html`<h1>${page.id}</h1>
261
363
  ${list}
262
364
  <p class="wb-meta">${page.file}</p>` : html`<h1>${project.name}</h1>
263
365
  ${list}${project.files && documentList(ctx)}
264
366
  <p class="wb-meta">
265
- <code>${project.dir}</code>${project.files && html` · <a href="/-/">files</a>`} ·
266
- <a href="/_/docs">how to write pages</a>
367
+ <code>${project.dir}</code>${project.files && html` · <a href="${ctx.base ?? ""}/-/">files</a>`} ·
368
+ <a href="${ctx.base ?? ""}/_/docs">how to write pages</a>
267
369
  </p>`,
268
370
  title: page.id || project.name,
269
371
  islands: {},
@@ -349,7 +451,7 @@ function createRender(blocks, style, pluginStyles = [], links = []) {
349
451
  aria-label="Theme"
350
452
  ></button>
351
453
  </nav>` : html`<nav class="wb-nav">
352
- <span>${crumbs(page.id, ctx.project.name)}</span
454
+ <span>${crumbs(page.id, ctx.entry?.label || ctx.project.name, ctx.base ?? "", ctx.entry)}</span
353
455
  >${page.mtime != null && html`<span class="wb-meta">updated <time id="wb-updated" data-ts="${page.mtime}"></time></span>`}<button
354
456
  type="button"
355
457
  class="wb-theme"
@@ -5,27 +5,25 @@ const OPEN = svg("<path d=\"M9 2.5h4.5V7M13.5 2.5 7.5 8.5M11.5 9.5v3a1 1 0 0 1-1
5
5
  const MAXIMIZE = svg("<path d=\"M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10\"/>");
6
6
  const RESTORE = svg("<path d=\"M6 2.5V6H2.5M13.5 6H10V2.5M10 13.5V10h3.5M2.5 10H6v3.5\"/>");
7
7
  /** A window around a block's HTML: see the top of this file. */
8
- function windowFrame({ body, label = null, open = null, wide = false, bare = false, bodyClass = "", height, className = "", controls = "" }) {
8
+ function windowFrame({ body, label = null, open = null, wide = false, height, className = "", controls = "" }) {
9
9
  const name = label != null && String(label) !== "" ? html`<span class="wb-window-title">${raw(String(label))}</span>` : open ? html`<span class="wb-window-address">${open}</span>` : html``;
10
- const header = !bare && html`<div class="wb-window-bar">
11
- <span class="wb-window-name" ${open ? html` title="${open}"` : ""}>${name}</span>
12
- ${raw(String(controls))}
13
- ${open && html`<a class="wb-window-button" href="${open}" target="_blank" rel="noopener" title="Open on its own" aria-label="Open on its own">${OPEN}</a>`}
14
- <button
15
- type="button"
16
- class="wb-window-button"
17
- data-wb-maximize
18
- title="Fill the window"
19
- aria-label="Fill the window"
20
- >
21
- <span class="wb-window-max">${MAXIMIZE}</span><span class="wb-window-restore">${RESTORE}</span>
22
- </button>
23
- </div>`;
10
+ const header = html`<div class="wb-window-bar">
11
+ <span class="wb-window-name" ${open ? html` title="${open}"` : ""}>${name}</span>
12
+ ${raw(String(controls))}
13
+ ${open && html`<a class="wb-window-button" href="${open}" target="_blank" rel="noopener" title="Open on its own" aria-label="Open on its own">${OPEN}</a>`}
14
+ <button
15
+ type="button"
16
+ class="wb-window-button"
17
+ data-wb-maximize
18
+ title="Fill the window"
19
+ aria-label="Fill the window"
20
+ >
21
+ <span class="wb-window-max">${MAXIMIZE}</span><span class="wb-window-restore">${RESTORE}</span>
22
+ </button>
23
+ </div>`;
24
24
  return html`<div class="wb-window${wide && raw(" wb-wide")}${className && raw(" " + className)}">
25
25
  ${header}
26
- <div class="wb-window-body${bodyClass && raw(" " + bodyClass)}" ${height ? html` style="height: ${height}"` : ""}>
27
- ${raw(String(body))}
28
- </div>
26
+ <div class="wb-window-body" ${height ? html` style="height: ${height}"` : ""}>${raw(String(body))}</div>
29
27
  </div>`;
30
28
  }
31
29
  export { windowFrame };
@@ -1,5 +1,10 @@
1
1
  import fs from "node:fs";
2
2
  // src/running.ts
3
+ /**
4
+ * How long a server may take to say it is there: a loaded machine (many agents, builds) can take
5
+ * seconds, and a server taken for gone is one a command starts again or does without.
6
+ */
7
+ const HEALTH_TIMEOUT = 5e3;
3
8
  /** The port the last server of this project recorded, or null. */
4
9
  function recordedPort(project) {
5
10
  try {
@@ -14,11 +19,41 @@ async function runningServer(project, { except } = {}) {
14
19
  if (!port) return null;
15
20
  const base = `http://localhost:${port}`;
16
21
  try {
17
- const res = await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(800) });
22
+ const res = await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT) });
18
23
  const health = res.ok ? await res.json() : null;
19
24
  return health?.dir === project.dir && health.pid !== except ? base : null;
20
25
  } catch {
21
26
  return null;
22
27
  }
23
28
  }
24
- export { recordedPort, runningServer };
29
+ /** The port the shared server recorded in the machine folder, or null. */
30
+ function recordedSharedPort(file) {
31
+ try {
32
+ return Number(JSON.parse(fs.readFileSync(file, "utf8")).port) || null;
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+ /**
38
+ * The machine's running shared server, or null: the port in its record, checked by asking it.
39
+ * `rescan`: have it look for projects first (one just made, say). `except`: a process not to count.
40
+ */
41
+ async function sharedServer(file, { rescan = false, except } = {}) {
42
+ const port = recordedSharedPort(file);
43
+ if (!port) return null;
44
+ const origin = `http://localhost:${port}`;
45
+ try {
46
+ const res = await fetch(`${origin}/api/health${rescan ? "?rescan" : ""}`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT) });
47
+ const health = res.ok ? await res.json() : null;
48
+ if (!health?.hub || health.pid === except) return null;
49
+ return {
50
+ origin,
51
+ pid: health.pid,
52
+ version: String(health.version ?? "0.0.0"),
53
+ projects: health.projects ?? []
54
+ };
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+ export { recordedPort, recordedSharedPort, runningServer, sharedServer };
package/dist/src/serve.js CHANGED
@@ -1,6 +1,9 @@
1
1
  import { DEFAULT_PORT } from "./config.js";
2
2
  import { createServer } from "./server.js";
3
- import { recordedPort, runningServer } from "./running.js";
3
+ import { recordedPort, recordedSharedPort, runningServer, sharedServer } from "./running.js";
4
+ import { machineConfigFile, machineDir, machineServerFile, readMachineConfig, stateDir } from "./entries.js";
5
+ import { createHub } from "./hub.js";
6
+ import { VERSION, compareVersions } from "./package.js";
4
7
  import fs from "node:fs";
5
8
  import path from "node:path";
6
9
  import http from "node:http";
@@ -68,4 +71,110 @@ async function start(project) {
68
71
  }
69
72
  throw new Error(`no free port from ${DEFAULT_PORT} to ${DEFAULT_PORT + 50}`);
70
73
  }
71
- export { start };
74
+ /** Run the shared server. Exits (0) when one as new or newer runs already. */
75
+ async function startShared(dir = machineDir(), state = stateDir()) {
76
+ const file = machineServerFile(state);
77
+ const other = await sharedServer(file, { except: process.pid });
78
+ if (other) {
79
+ if (compareVersions(VERSION, other.version) <= 0) {
80
+ console.log(`whiteboard: the shared server ${other.version} runs at ${other.origin}`);
81
+ process.exit(0);
82
+ }
83
+ await takeOver(other);
84
+ }
85
+ const config = readMachineConfig(dir);
86
+ if (!config) throw new Error(`no machine config: ${machineConfigFile(dir)}`);
87
+ fs.mkdirSync(state, { recursive: true });
88
+ const hub = createHub({
89
+ dir,
90
+ state,
91
+ onShutdown: () => process.exit(0)
92
+ });
93
+ const server = http.createServer((req, res) => {
94
+ hub.handle(req, res);
95
+ });
96
+ const first = config.port ?? DEFAULT_PORT;
97
+ const candidates = [...new Set([
98
+ other ? Number(new URL(other.origin).port) : null,
99
+ recordedSharedPort(file),
100
+ first,
101
+ ...Array.from({ length: 50 }, (_, i) => first + 1 + i)
102
+ ].filter((p) => !!p))];
103
+ for (const port of candidates) {
104
+ if (!await listenOn(server, port)) continue;
105
+ fs.writeFileSync(file, JSON.stringify({
106
+ port,
107
+ pid: process.pid,
108
+ version: VERSION
109
+ }, null, 2) + "\n");
110
+ try {
111
+ fs.unlinkSync(path.join(state, "server.lock"));
112
+ } catch {}
113
+ process.on("exit", () => {
114
+ try {
115
+ if (JSON.parse(fs.readFileSync(file, "utf8")).pid === process.pid) fs.unlinkSync(file);
116
+ } catch {}
117
+ });
118
+ const yieldToOther = async () => {
119
+ if (await sharedServer(file, { except: process.pid })) {
120
+ console.log("whiteboard: another shared server took over");
121
+ process.exit(0);
122
+ }
123
+ };
124
+ setTimeout(yieldToOther, 1500).unref();
125
+ setInterval(yieldToOther, 3e4).unref();
126
+ for (const signal of [
127
+ "SIGINT",
128
+ "SIGTERM",
129
+ "SIGHUP"
130
+ ]) process.on(signal, () => process.exit(0));
131
+ console.log(`whiteboard ${VERSION}: the shared server at http://localhost:${port}`);
132
+ for (const p of hub.projects()) console.log(` http://localhost:${port}${p.base}/ ${p.dir}`);
133
+ return port;
134
+ }
135
+ throw new Error(`no free port from ${first} to ${first + 50}`);
136
+ }
137
+ /** Ask an older shared server to make way, and wait until it has (else end its process). */
138
+ async function takeOver(other) {
139
+ console.log(`whiteboard ${VERSION}: taking over from the shared server ${other.version} at ${other.origin}`);
140
+ try {
141
+ await fetch(`${other.origin}/api/shutdown`, {
142
+ method: "POST",
143
+ headers: { "content-type": "application/json" },
144
+ body: JSON.stringify({ version: VERSION }),
145
+ signal: AbortSignal.timeout(2e3)
146
+ });
147
+ } catch {}
148
+ const gone = async () => {
149
+ try {
150
+ await fetch(`${other.origin}/api/health`, { signal: AbortSignal.timeout(300) });
151
+ return false;
152
+ } catch {
153
+ return true;
154
+ }
155
+ };
156
+ for (let i = 0; i < 25; i++) {
157
+ if (await gone()) return;
158
+ await new Promise((r) => setTimeout(r, 200));
159
+ }
160
+ try {
161
+ process.kill(other.pid, "SIGTERM");
162
+ } catch {}
163
+ for (let i = 0; i < 25 && !await gone(); i++) await new Promise((r) => setTimeout(r, 200));
164
+ }
165
+ function listenOn(server, port) {
166
+ return new Promise((resolve, reject) => {
167
+ const onError = (err) => {
168
+ server.off("listening", onListening);
169
+ err.code === "EADDRINUSE" ? resolve(false) : reject(err);
170
+ };
171
+ const onListening = () => {
172
+ server.off("error", onError);
173
+ resolve(true);
174
+ };
175
+ server.once("error", onError);
176
+ server.once("listening", onListening);
177
+ server.listen(port, "127.0.0.1");
178
+ });
179
+ }
180
+ export { start, startShared };
@@ -3,7 +3,7 @@ import { html, raw } from "./html.js";
3
3
  import { createConfigLoader, pluginDir, toPath } from "./loader.js";
4
4
  import { describeRoutes, dispatch, mountRoutes, pluginCommands, usage } from "./plugins.js";
5
5
  import { createAuth } from "./auth.js";
6
- import { FROM_SOURCE, PACKAGE_DIR } from "./package.js";
6
+ import { FROM_SOURCE, PACKAGE_DIR, VERSION } from "./package.js";
7
7
  import { awaiting, covers, fromReader, heard, questionState, unreadMessages } from "./status.js";
8
8
  import { titleOf } from "./pages/render.js";
9
9
  import { inPublic } from "./public.js";
@@ -48,9 +48,10 @@ const OWN_FILES = /* @__PURE__ */ new Set([
48
48
  ]);
49
49
  const SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
50
50
  const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/;
51
- function createServer(project) {
51
+ function createServer(project, { base = "", entry, label, name, files: filesOption, overview, onChange } = {}) {
52
+ const projectName = () => name ?? project.name;
52
53
  const loader = createConfigLoader(project);
53
- const auth = createAuth(project.wb);
54
+ const auth = createAuth(project.wb, base);
54
55
  const watchers = /* @__PURE__ */ new Set();
55
56
  const streams = /* @__PURE__ */ new Set();
56
57
  const watch = (dir, options, fn) => {
@@ -137,7 +138,7 @@ function createServer(project) {
137
138
  /** The loaded config. Also applies its `files` setting to what is served and watched. */
138
139
  async function config() {
139
140
  const c = await loader.config();
140
- setFiles(c.files);
141
+ setFiles(filesOption ?? c.files);
141
142
  publicDirs = [...c.publicDirs.values()];
142
143
  return c;
143
144
  }
@@ -157,7 +158,7 @@ function createServer(project) {
157
158
  if (!within(dir, project.wb) && !ENGINE_WATCHED.some((d) => within(dir, d))) watch(dir, {}, (name) => onSourceChange(path.join(dir, name)));
158
159
  }
159
160
  }
160
- return `/_/file${file.split(path.sep).map(encodeURIComponent).join("/")}`;
161
+ return `${base}/_/file${file.split(path.sep).map(encodeURIComponent).join("/")}`;
161
162
  }
162
163
  const within = (file, dir) => file === dir || file.startsWith(dir + path.sep);
163
164
  /** Resolve a path inside a base folder, refusing anything that escapes it. */
@@ -304,10 +305,10 @@ function createServer(project) {
304
305
  /** The URL that serves a file or folder on disk, or null when nothing here serves it. */
305
306
  function urlOf(abs) {
306
307
  const rel = (dir) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join("/");
307
- if (within(abs, project.pagesDir)) return `/${rel(project.pagesDir).replace(/\.md$/, "")}`;
308
+ if (within(abs, project.pagesDir)) return `${base}/${rel(project.pagesDir).replace(/\.md$/, "")}`;
308
309
  if (FILES && within(abs, project.dir)) {
309
310
  if (rel(project.dir).split("/").some((part) => SKIP_DIRS.has(part))) return null;
310
- return `/-/${rel(project.dir)}`;
311
+ return `${base}/-/${rel(project.dir)}`;
311
312
  }
312
313
  return null;
313
314
  }
@@ -324,18 +325,23 @@ function createServer(project) {
324
325
  const list = (items) => html`<ul>
325
326
  ${items.map(([href, text]) => html`<li><a href="${href}">${text}</a></li>`)}
326
327
  </ul>`;
327
- if (page.kind === "pages") return { html: list(page.pages.map((p) => [`/${p.id}`, p.id])) };
328
+ if (page.kind === "pages") return { html: list(page.pages.map((p) => [`${base}/${p.id}`, p.id])) };
328
329
  if (page.kind === "folder") return { html: list(page.entries.map((e) => [encodeURIComponent(e.name) + (e.dir ? "/" : ""), e.name + (e.dir ? "/" : "")])) };
329
330
  return { html: html`<pre>${page.source}</pre>` };
330
331
  }
331
332
  const context = () => ({
332
333
  project: {
333
- name: project.name,
334
+ name: projectName(),
334
335
  dir: project.dir,
335
336
  files: !!FILES
336
337
  },
337
338
  asset,
338
- urlFor
339
+ urlFor,
340
+ base,
341
+ ...entry && { entry: {
342
+ name: entry,
343
+ label
344
+ } }
339
345
  });
340
346
  /** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
341
347
  const frontmatterOf = (page) => page.kind === "page" ? page.frontmatter : {};
@@ -447,6 +453,7 @@ function createServer(project) {
447
453
  id: page.id,
448
454
  kind: page.kind,
449
455
  live: !built,
456
+ base: built ? "" : base,
450
457
  client: rendered ? (built ?? { asset }).asset(PAGE_CLIENT) : null,
451
458
  data: out.data ?? null,
452
459
  frontmatter: frontmatterOf(page),
@@ -466,7 +473,7 @@ function createServer(project) {
466
473
  "\n <\/script>\n <script type=\"module\" src=\"",
467
474
  "\"><\/script>\n ",
468
475
  "\n </body>\n </html>"
469
- ])), out.title || page.id || project.name, DOCK_STYLE, raw(out.head ?? ""), extras.head, page.id, page.kind, notices.map((n) => html`<pre class="wb-error" role="alert">${n}</pre>`), raw(String(out.html)), raw(json(handoff)), built ? built.asset(RUNTIME) : "/_/runtime.js", extras.body));
476
+ ])), out.title || page.id || projectName(), DOCK_STYLE, raw(out.head ?? ""), extras.head, page.id, page.kind, notices.map((n) => html`<pre class="wb-error" role="alert">${n}</pre>`), raw(String(out.html)), raw(json(handoff)), built ? built.asset(RUNTIME) : `${base}/_/runtime.js`, extras.body));
470
477
  }
471
478
  /** A listener as the server holds it. */
472
479
  const listeners = /* @__PURE__ */ new Set();
@@ -489,6 +496,7 @@ function createServer(project) {
489
496
  for (const c of clients) notify(c, kind);
490
497
  };
491
498
  function pageChanged(id) {
499
+ onChange?.();
492
500
  for (const c of clients) if (c.isDir ? !c.page || id.startsWith(c.page + "/") : c.page === id || c.page + "/index" === id) notify(c, "change");
493
501
  for (const c of clients) if (c.isDir && !c.page) notify(c, "change");
494
502
  }
@@ -497,7 +505,10 @@ function createServer(project) {
497
505
  if (f.split("/").some((part) => SKIP_DIRS.has(part))) return;
498
506
  if (f.startsWith(".whiteboard/")) {
499
507
  const inner = f.slice(12);
500
- if (inner === "events.ndjson") return notifyAll("events");
508
+ if (inner === "events.ndjson") {
509
+ onChange?.();
510
+ return notifyAll("events");
511
+ }
501
512
  if (inner.startsWith("pages/")) {
502
513
  if (inner.endsWith(".md")) pageChanged(inner.slice(6).replace(/\.md$/, ""));
503
514
  return;
@@ -586,10 +597,11 @@ function createServer(project) {
586
597
  const found = stored(id);
587
598
  if (!found) return { notFound: `${isRepoId(id) ? id.slice(2) : id} does not exist${isRepoId(id) ? "" : " yet. This page loads as soon as it does"}.` };
588
599
  if ("raw" in found) return found;
589
- if ((found.kind === "folder" || found.kind === "pages" && id) && !requested.endsWith("/")) return { redirect: `/${id}/` };
600
+ if ((found.kind === "folder" || found.kind === "pages" && id) && !requested.endsWith("/")) return { redirect: `${base}/${id}/` };
590
601
  if (found.kind === "pages") {
591
602
  const counts = new Map((await status(found.id || null)).map((s) => [s.page, awaiting(s)]));
592
603
  for (const p of found.pages) p.awaiting = counts.get(p.id) ?? 0;
604
+ if (!found.id && overview) Object.assign(found, await overview());
593
605
  }
594
606
  return { page: found };
595
607
  }
@@ -626,7 +638,9 @@ function createServer(project) {
626
638
  if (p === "/api/health") return sendJson(res, 200, {
627
639
  ok: true,
628
640
  dir: project.dir,
629
- pid: process.pid
641
+ pid: process.pid,
642
+ version: VERSION,
643
+ base
630
644
  });
631
645
  if (p === "/api/events" && req.method === "POST") {
632
646
  const body = JSON.parse(await readBody(req));
@@ -947,6 +961,27 @@ function createServer(project) {
947
961
  }
948
962
  return {
949
963
  handle,
964
+ listeners: () => listenersFor(null),
965
+ async overview() {
966
+ await config();
967
+ const pages = pagesIn(project.pagesDir);
968
+ const counts = new Map((await status(null)).map((s) => [s.page, awaiting(s)]));
969
+ for (const p of pages) p.awaiting = counts.get(p.id) ?? 0;
970
+ return {
971
+ pages,
972
+ files: !!FILES
973
+ };
974
+ },
975
+ touch() {
976
+ for (const c of clients) if (c.isDir && !c.page) notify(c, "change");
977
+ },
978
+ addListener(l) {
979
+ listeners.add(l);
980
+ notifyAll("listeners");
981
+ return () => {
982
+ if (listeners.delete(l)) notifyAll("listeners");
983
+ };
984
+ },
950
985
  status: (page = null) => status(page),
951
986
  config,
952
987
  build,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bigmistqke/whiteboard",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "A whiteboard for you and your agent: it writes markdown pages you read live in the browser, you answer through forms it waits on",
5
5
  "keywords": [
6
6
  "agent",
@@ -0,0 +1,36 @@
1
+ What a program printed, as its terminal showed it: an `ansi` fence holds the
2
+ output with its escape codes, and the page draws it dark, in its colours, as a
3
+ terminal does. It goes through a terminal emulator on the server, so colours
4
+ (16, 256 and true colour, foreground and background), bold, dim and underline
5
+ show, and a progress line that a carriage return writes over shows as it
6
+ ended. It is plain HTML: nothing runs on the page, and `whiteboard build` keeps
7
+ it. Wide output scrolls sideways (a line wraps at 240 columns, as a terminal
8
+ that wide would).
9
+
10
+ ````markdown
11
+ ```ansi
12
+ \e[32m✔\e[0m parses a page
13
+ \e[31m✖\e[0m renders a diff \e[2m(12ms)\e[0m
14
+ ```
15
+ ````
16
+
17
+ ```ansi
18
+ \e[32m✔\e[0m parses a page
19
+ \e[31m✖\e[0m renders a diff \e[2m(12ms)\e[0m
20
+ ```
21
+
22
+ The escape byte itself works, and so does any way of writing it out: `\e`,
23
+ `\x1b`, `\033`, `\u001b` or `^[`. A carriage return has to be the byte itself,
24
+ as a program prints it: `\r` written out stays as written, since it is as
25
+ likely a path (`C:\repo`). To capture a command's colours, have it colour
26
+ output that isn't a terminal (`--color=always`, `FORCE_COLOR=1`) and paste
27
+ what it printed.
28
+
29
+ `title` puts it in a window with that label, whose button fills the browser
30
+ window with it:
31
+
32
+ ````markdown
33
+ ```ansi {title="npm test"}
34
+ …
35
+ ```
36
+ ````