@bigmistqke/whiteboard 0.6.1 → 0.8.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.
Files changed (101) hide show
  1. package/README.md +23 -216
  2. package/bin/whiteboard.ts +82 -239
  3. package/dist/bin/whiteboard.js +70 -200
  4. package/dist/client/runtime.js +297 -61
  5. package/dist/plugins/badge/README.md +3 -1
  6. package/dist/plugins/badge/public/style.css +17 -0
  7. package/dist/plugins/chat/public/client.js +2 -2
  8. package/dist/plugins/chat/public/style.css +19 -6
  9. package/dist/plugins/code/README.md +10 -0
  10. package/dist/plugins/code/index.js +31 -22
  11. package/dist/plugins/code/public/client.js +1 -0
  12. package/dist/plugins/code/public/style.css +33 -2
  13. package/dist/plugins/comments/public/client.js +7 -2
  14. package/dist/plugins/comments/public/style.css +4 -0
  15. package/dist/plugins/form/public/style.css +2 -0
  16. package/dist/plugins/grid/public/style.css +0 -5
  17. package/dist/plugins/iframe/index.js +2 -2
  18. package/dist/plugins/index.js +5 -1
  19. package/dist/plugins/lightbox/public/client.js +1 -1
  20. package/dist/plugins/terminal/index.js +7 -9
  21. package/dist/plugins/terminal/public/client.js +1 -1
  22. package/dist/plugins/terminal/public/style.css +3 -3
  23. package/dist/plugins/timeline/README.md +40 -0
  24. package/dist/plugins/timeline/index.js +82 -0
  25. package/dist/plugins/timeline/public/style.css +118 -0
  26. package/dist/plugins/toc/README.md +13 -13
  27. package/dist/plugins/toc/index.js +6 -4
  28. package/dist/plugins/toc/public/client.js +1 -1
  29. package/dist/plugins/toc/public/style.css +19 -2
  30. package/dist/plugins/window/index.js +4 -4
  31. package/dist/solid/index.js +2 -1
  32. package/dist/src/auth.js +7 -3
  33. package/dist/src/build.js +159 -0
  34. package/dist/src/client/page/base.css +74 -35
  35. package/dist/src/client/page/main.js +16 -5
  36. package/dist/src/document.js +93 -0
  37. package/dist/src/events.js +7 -15
  38. package/dist/src/hub.js +90 -53
  39. package/dist/src/listen.js +100 -0
  40. package/dist/src/listeners.js +67 -0
  41. package/dist/src/pages/index.js +1 -1
  42. package/dist/src/pages/markdown.js +23 -11
  43. package/dist/src/pages/render.js +13 -8
  44. package/dist/src/serve.js +2 -0
  45. package/dist/src/server.js +204 -514
  46. package/dist/src/site.js +173 -0
  47. package/dist/src/status.js +63 -1
  48. package/dist/src/ws.js +128 -0
  49. package/package.json +1 -1
  50. package/plugins/README.md +258 -0
  51. package/plugins/badge/README.md +3 -1
  52. package/plugins/badge/public/style.css +17 -0
  53. package/plugins/chat/client.tsx +34 -6
  54. package/plugins/chat/public/style.css +19 -6
  55. package/plugins/code/README.md +10 -0
  56. package/plugins/code/client.ts +73 -0
  57. package/plugins/code/index.ts +38 -26
  58. package/plugins/code/public/style.css +33 -2
  59. package/plugins/comments/client.ts +56 -6
  60. package/plugins/comments/public/style.css +4 -0
  61. package/plugins/form/public/style.css +2 -0
  62. package/plugins/grid/public/style.css +0 -5
  63. package/plugins/iframe/index.ts +2 -2
  64. package/plugins/index.ts +6 -1
  65. package/plugins/lightbox/client.ts +13 -3
  66. package/plugins/terminal/client.ts +10 -2
  67. package/plugins/terminal/index.ts +8 -6
  68. package/plugins/terminal/public/style.css +3 -3
  69. package/plugins/timeline/README.md +40 -0
  70. package/plugins/timeline/index.ts +92 -0
  71. package/plugins/timeline/public/style.css +118 -0
  72. package/plugins/toc/README.md +13 -13
  73. package/plugins/toc/client.ts +58 -32
  74. package/plugins/toc/index.ts +13 -13
  75. package/plugins/toc/public/style.css +19 -2
  76. package/plugins/window/index.ts +4 -4
  77. package/skills/whiteboard/SKILL.md +3 -1
  78. package/solid/index.tsx +3 -0
  79. package/src/auth.ts +7 -2
  80. package/src/build.ts +213 -0
  81. package/src/client/forms.ts +102 -5
  82. package/src/client/page/base.css +74 -35
  83. package/src/client/page/elsewhere.ts +14 -4
  84. package/src/client/page/waiting.ts +10 -5
  85. package/src/client/read.ts +16 -3
  86. package/src/client/runtime.ts +219 -52
  87. package/src/client/toast.ts +36 -6
  88. package/src/define.ts +44 -18
  89. package/src/document.ts +191 -0
  90. package/src/events.ts +18 -17
  91. package/src/hub.ts +102 -56
  92. package/src/listen.ts +125 -0
  93. package/src/listeners.ts +95 -0
  94. package/src/pages/index.ts +1 -1
  95. package/src/pages/markdown.ts +29 -18
  96. package/src/pages/render.ts +13 -8
  97. package/src/serve.ts +2 -0
  98. package/src/server.ts +223 -611
  99. package/src/site.ts +165 -0
  100. package/src/status.ts +100 -0
  101. package/src/ws.ts +155 -0
@@ -1,22 +1,23 @@
1
- import { appendEvent, forAgent, matches, pickedUp, readEvents } from "./events.js";
2
- import { html, raw } from "./html.js";
1
+ import { appendEvent, forAgent, isEventId, matches, readEvents } from "./events.js";
2
+ import { html } from "./html.js";
3
3
  import { createConfigLoader, pluginDir, toPath } from "./loader.js";
4
4
  import { describeRoutes, dispatch, mountRoutes, pluginCommands, usage } from "./plugins.js";
5
- import { createAuth } from "./auth.js";
5
+ import { createAuth, sameSite } from "./auth.js";
6
+ import { accept, refuse } from "./ws.js";
6
7
  import { FROM_SOURCE, PACKAGE_DIR, VERSION } from "./package.js";
7
- import { awaiting, covers, fromReader, heard, questionState, unreadMessages } from "./status.js";
8
+ import { SCROLL, awaiting, pickedUp, projectStatus } from "./status.js";
8
9
  import { titleOf } from "./pages/render.js";
10
+ import { createRegistry, holdStream, listenerOf } from "./listeners.js";
9
11
  import { inPublic } from "./public.js";
10
- import _taggedTemplateLiteral from "../_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js";
12
+ import { build } from "./build.js";
13
+ import { PAGE_CLIENT, RUNTIME, frontmatterOf, pageDocument, pluginParts } from "./document.js";
14
+ import { SKIP_DIRS, isRepoId, pageSource, servedSite, within } from "./site.js";
11
15
  import { stripTypeScriptTypes } from "node:module";
12
16
  import fs from "node:fs";
13
17
  import path from "node:path";
14
- import { parse } from "yaml";
18
+ import crypto from "node:crypto";
15
19
  // src/server.ts
16
- var _templateObject;
17
20
  const ENGINE_DIR = PACKAGE_DIR;
18
- const RUNTIME = path.join(ENGINE_DIR, "dist", "client", "runtime.js");
19
- const PAGE_CLIENT = path.join(ENGINE_DIR, "dist", "src", "client", "page", "main.js");
20
21
  const MIME = {
21
22
  ".css": "text/css",
22
23
  ".js": "text/javascript",
@@ -46,8 +47,6 @@ const OWN_FILES = /* @__PURE__ */ new Set([
46
47
  "server.lock",
47
48
  "token"
48
49
  ]);
49
- const SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
50
- const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/;
51
50
  function createServer(project, { base = "", entry, label, name, files: filesOption, overview, onChange } = {}) {
52
51
  const projectName = () => name ?? project.name;
53
52
  const loader = createConfigLoader(project);
@@ -71,7 +70,6 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
71
70
  pluginDirs.add(e.name);
72
71
  const dataDir = pluginDir(project.wb, e.name);
73
72
  const dir = c.publicDirs.get(e.name);
74
- const own = (ref) => asset(inPublic(dir, ref, `plugin ${e.name}`));
75
73
  const hooks = await e.setup?.({
76
74
  project: {
77
75
  name: project.name,
@@ -79,8 +77,7 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
79
77
  wb: project.wb
80
78
  },
81
79
  dataDir,
82
- authorized: auth.authorized,
83
- asset: own
80
+ authorized: auth.authorized
84
81
  }) ?? {};
85
82
  const client = hooks.client != null ? inPublic(dir, hooks.client, `plugin ${e.name}: client`) : void 0;
86
83
  return {
@@ -102,38 +99,28 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
102
99
  })));
103
100
  return setups.get(c);
104
101
  }
105
- async function shellExtras(req) {
106
- const hooks = await pluginHooks();
107
- const notices = hooks.filter((h) => h.error).map((h) => `plugin "${h.name}" failed to start: ${h.error.message}`);
108
- const parts = await Promise.all(hooks.map(async (h) => {
109
- try {
110
- return await h.shell?.(req) ?? null;
111
- } catch (err) {
112
- console.error(`plugin ${h.name}:`, err);
113
- notices.push(`plugin "${h.name}" failed on this page: ${err.message}`);
114
- return null;
115
- }
116
- }));
117
- const clients = hooks.filter((h) => h.client && !h.error).map((h) => ({
118
- name: h.name,
119
- client: asset(h.client)
120
- }));
121
- const messages = [...(await config()).forReader];
122
- return {
123
- head: parts.map((x) => raw(String(x?.head ?? ""))),
124
- body: parts.map((x) => raw(String(x?.body ?? ""))),
125
- clients,
126
- messages,
127
- notices
128
- };
129
- }
130
- /** A page with what the plugins add, their notices among the page's. */
102
+ /** A page as the server serves it: the render with what the plugins add, their failures among its notices. */
131
103
  async function page(req, stored, rendered) {
132
- const extras = await shellExtras(req);
133
- return shell(stored, {
104
+ const notices = [...rendered.notices];
105
+ const parts = await pluginParts(await pluginHooks(), req, {
106
+ asset,
107
+ messages: [...(await config()).forReader],
108
+ failed: (message) => {
109
+ console.error(message);
110
+ notices.push(message);
111
+ }
112
+ });
113
+ return pageDocument(stored, {
134
114
  ...rendered,
135
- notices: [...rendered.notices, ...extras.notices]
136
- }, extras);
115
+ notices
116
+ }, parts, {
117
+ live: true,
118
+ base,
119
+ asset,
120
+ runtime: `${base}/_/runtime.js`,
121
+ title: projectName(),
122
+ stamps: stamps()
123
+ });
137
124
  }
138
125
  /** The loaded config. Also applies its `files` setting to what is served and watched. */
139
126
  async function config() {
@@ -160,166 +147,13 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
160
147
  }
161
148
  return `${base}/_/file${file.split(path.sep).map(encodeURIComponent).join("/")}`;
162
149
  }
163
- const within = (file, dir) => file === dir || file.startsWith(dir + path.sep);
164
- /** Resolve a path inside a base folder, refusing anything that escapes it. */
165
- function inside(base, rel) {
166
- const p = path.resolve(base, "." + path.posix.normalize("/" + rel));
167
- return within(p, base) ? p : null;
168
- }
169
- const isRepoId = (id) => id === "-" || id.startsWith("-/");
170
- /** A page's frontmatter, parsed as YAML; empty, with the reason, when it isn't fields. */
171
- function frontmatter(source) {
172
- const m = FRONTMATTER.exec(source);
173
- if (!m) return {
174
- data: {},
175
- error: null
176
- };
177
- let data;
178
- try {
179
- data = parse(m[1]);
180
- } catch (err) {
181
- return {
182
- data: {},
183
- error: err.message
184
- };
185
- }
186
- if (data == null) return {
187
- data: {},
188
- error: null
189
- };
190
- if (typeof data !== "object" || Array.isArray(data)) return {
191
- data: {},
192
- error: "it must be fields (`key: value` lines), not a single value or a list"
193
- };
194
- return {
195
- data,
196
- error: null
197
- };
198
- }
199
- function pageSource(id, file) {
200
- const source = fs.readFileSync(file, "utf8");
201
- return {
202
- kind: "page",
203
- id,
204
- file,
205
- mtime: fs.statSync(file).mtimeMs,
206
- source,
207
- body: source.replace(FRONTMATTER, ""),
208
- ...(({ data, error }) => ({
209
- frontmatter: data,
210
- frontmatterError: error
211
- }))(frontmatter(source))
212
- };
213
- }
214
- /** The pages in a folder of the pages folder, newest first, with when each was last answered. */
215
- function pagesIn(dir) {
216
- const last = /* @__PURE__ */ new Map();
217
- for (const e of readEvents(project.eventsFile)) if (fromReader(e)) last.set(e.page, e.ts);
218
- const out = [];
219
- const walk = (d) => {
220
- if (!fs.existsSync(d)) return;
221
- for (const ent of fs.readdirSync(d, { withFileTypes: true })) {
222
- if (ent.name.startsWith(".") || ent.name === "node_modules") continue;
223
- const full = path.join(d, ent.name);
224
- if (ent.isDirectory()) walk(full);
225
- else if (ent.name.endsWith(".md")) {
226
- const id = path.relative(project.pagesDir, full).split(path.sep).join("/").replace(/\.md$/, "");
227
- out.push({
228
- id,
229
- file: full,
230
- mtime: fs.statSync(full).mtimeMs,
231
- lastEvent: last.get(id) ?? null,
232
- awaiting: 0
233
- });
234
- }
235
- }
236
- };
237
- walk(dir);
238
- return out.sort((a, b) => b.mtime - a.mtime);
239
- }
240
- /** Text files show as files; anything with a NUL byte near the start is binary. */
241
- function isText(file) {
242
- const fd = fs.openSync(file, "r");
243
- const buf = Buffer.alloc(8192);
244
- const n = fs.readSync(fd, buf, 0, buf.length, 0);
245
- fs.closeSync(fd);
246
- return !buf.subarray(0, n).includes(0);
247
- }
248
- /**
249
- * A page id → the stored page, or one of: { redirect } (a folder asked for without its slash),
250
- * { raw: file } (serve the bytes), null (nothing there).
251
- */
252
- function stored(id) {
253
- if (!id) return {
254
- kind: "pages",
255
- id: "",
256
- file: project.pagesDir,
257
- mtime: null,
258
- pages: pagesIn(project.pagesDir)
259
- };
260
- if (isRepoId(id)) {
261
- const rel = id.slice(2);
262
- const target = inside(project.dir, rel);
263
- if (!target || path.relative(project.dir, target).split(path.sep).includes(".git") || !fs.existsSync(target)) return null;
264
- const stat = fs.statSync(target);
265
- if (stat.isDirectory()) {
266
- const entries = fs.readdirSync(target, { withFileTypes: true }).filter((e) => !SKIP_DIRS.has(e.name) && e.name !== ".DS_Store").map((e) => ({
267
- name: e.name,
268
- dir: e.isDirectory()
269
- })).sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name));
270
- return {
271
- kind: "folder",
272
- id,
273
- file: target,
274
- mtime: stat.mtimeMs,
275
- entries
276
- };
277
- }
278
- if (/\.(md|markdown)$/i.test(target)) return pageSource(id, target);
279
- if (stat.size > 1e6 || !isText(target)) return { raw: target };
280
- return {
281
- kind: "file",
282
- id,
283
- file: target,
284
- mtime: stat.mtimeMs,
285
- source: fs.readFileSync(target, "utf8")
286
- };
287
- }
288
- const target = inside(project.pagesDir, id);
289
- if (!target) return null;
290
- if (path.extname(id) && fs.existsSync(target) && fs.statSync(target).isFile()) return { raw: target };
291
- if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
292
- const index = path.join(target, "index.md");
293
- if (fs.existsSync(index)) return pageSource(id, index);
294
- return {
295
- kind: "pages",
296
- id,
297
- file: target,
298
- mtime: null,
299
- pages: pagesIn(target)
300
- };
301
- }
302
- const file = target + ".md";
303
- return fs.existsSync(file) ? pageSource(id, file) : null;
304
- }
305
- /** The URL that serves a file or folder on disk, or null when nothing here serves it. */
306
- function urlOf(abs) {
307
- const rel = (dir) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join("/");
308
- if (within(abs, project.pagesDir)) return `${base}/${rel(project.pagesDir).replace(/\.md$/, "")}`;
309
- if (FILES && within(abs, project.dir)) {
310
- if (rel(project.dir).split("/").some((part) => SKIP_DIRS.has(part))) return null;
311
- return `${base}/-/${rel(project.dir)}`;
312
- }
313
- return null;
314
- }
315
- /** For links: the target if it exists (also with .md added), mapped to its URL. */
316
- function urlFor(abs) {
317
- for (const candidate of [abs, abs + ".md"]) if (fs.existsSync(candidate)) {
318
- const url = urlOf(candidate);
319
- if (url) return url + (fs.statSync(candidate).isDirectory() && !url.endsWith("/") ? "/" : "");
320
- }
321
- return null;
322
- }
150
+ const site = servedSite(project, {
151
+ base,
152
+ files: () => !!FILES
153
+ });
154
+ const stored = site.page;
155
+ const pagesIn = site.pagesIn;
156
+ const urlFor = site.urlFor;
323
157
  /** A config that failed to load: the page as stored, as text, under the error. */
324
158
  function rawRender(page) {
325
159
  const list = (items) => html`<ul>
@@ -343,8 +177,6 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
343
177
  label
344
178
  } }
345
179
  });
346
- /** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
347
- const frontmatterOf = (page) => page.kind === "page" ? page.frontmatter : {};
348
180
  /** Render a stored page as markdown, with the plugins' blocks, and anything the reader should be told. */
349
181
  async function render(page) {
350
182
  const { pages, errors } = await config();
@@ -372,49 +204,65 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
372
204
  };
373
205
  }
374
206
  /**
375
- * Per page: the questions it asks that have no answer yet, the reader's events no wait or watch
376
- * picked up, who is listening, and the session that claimed it. What `whiteboard status` and the
377
- * hooks report. The questions are a page's named forms.
207
+ * The project's status (status.ts): the pages, below `only` when given, with their questions, the
208
+ * log read once, and who listens. What `whiteboard status`, the hooks, the page lists and the log's
209
+ * picked-up marks take.
378
210
  */
379
- async function status(only) {
380
- const { pages, handedOut, forReader } = await config();
381
- const isForAgent = forAgent(handedOut);
382
- const all = readEvents(project.eventsFile);
383
- const picked = pickedUp(all);
384
- const owner = /* @__PURE__ */ new Map();
385
- for (const e of all) if (e.type === "whiteboard:claim" && !fromReader(e)) owner.set(e.page, e.data?.session ?? null);
386
- const out = [];
387
- for (const p of pagesIn(project.pagesDir)) {
388
- if (only && p.id !== only && !p.id.startsWith(only + "/")) continue;
389
- const page = pageSource(p.id, p.file);
390
- let asks = [];
391
- try {
392
- asks = pages?.questions(page) ?? [];
393
- } catch (err) {
394
- console.error("questions:", err);
395
- }
396
- const events = all.filter((e) => e.page === p.id);
397
- const listening = listenersFor(p.id);
398
- const questions = asks.map((name) => ({
399
- name,
400
- state: questionState(name, events, listening, (id) => picked.has(id)).state
401
- }));
402
- const named = (...states) => questions.filter((q) => states.includes(q.state)).map((q) => q.name);
403
- out.push({
404
- page: p.id,
405
- title: titleOf(p.file, path.basename(p.id)),
406
- file: p.file,
407
- owner: owner.get(p.id) ?? null,
408
- asks,
409
- questions,
410
- open: named("open"),
411
- unheard: named("open").filter((name) => !heard(name, listening)),
412
- unread: unreadMessages(events, (type) => forReader.has(type)),
413
- unpicked: events.filter((e) => fromReader(e) && isForAgent(e.type) && !picked.has(e.id)),
414
- listeners: listening
415
- });
211
+ const asked = /* @__PURE__ */ new Map();
212
+ function questionsOf(renderer, id, file) {
213
+ let stat;
214
+ try {
215
+ stat = fs.statSync(file);
216
+ } catch {
217
+ return {
218
+ title: path.basename(id),
219
+ asks: []
220
+ };
416
221
  }
417
- return out;
222
+ const kept = asked.get(id);
223
+ if (kept && kept.file === file && kept.mtime === stat.mtimeMs && kept.size === stat.size && kept.renderer === renderer) return kept;
224
+ let asks = [];
225
+ try {
226
+ asks = renderer?.questions(pageSource(id, file)) ?? [];
227
+ } catch (err) {
228
+ console.error("questions:", err);
229
+ }
230
+ const now = {
231
+ file,
232
+ mtime: stat.mtimeMs,
233
+ size: stat.size,
234
+ renderer,
235
+ title: titleOf(file, path.basename(id)),
236
+ asks
237
+ };
238
+ asked.set(id, now);
239
+ return now;
240
+ }
241
+ async function snapshot(listed) {
242
+ const { pages: renderer, handedOut, forReader } = await config();
243
+ const pages = listed.map((p) => ({
244
+ id: p.id,
245
+ file: p.file,
246
+ ...questionsOf(renderer, p.id, p.file)
247
+ }));
248
+ return projectStatus({
249
+ pages,
250
+ events: readEvents(project.eventsFile),
251
+ listeners: listenersFor,
252
+ forAgent: forAgent(handedOut),
253
+ forReader: (type) => forReader.has(type)
254
+ });
255
+ }
256
+ /** Per page, below `only` when given: what `whiteboard status` and the hooks report (see snapshot). */
257
+ const status = async (only) => (await snapshot(pagesIn(project.pagesDir).filter((p) => !only || p.id === only || p.id.startsWith(only + "/")))).pages;
258
+ /** A list of pages, with when each was last answered and how much waits on it, from one status. */
259
+ async function withStatus(pages) {
260
+ const s = await snapshot(pages);
261
+ pages.forEach((p, i) => {
262
+ p.awaiting = awaiting(s.pages[i]);
263
+ p.lastEvent = s.lastAnswered(p.id);
264
+ });
265
+ return pages;
418
266
  }
419
267
  /** How to write pages here, as markdown: the pages' own docs, then each plugin's. */
420
268
  async function docs() {
@@ -441,53 +289,55 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
441
289
  plugins
442
290
  };
443
291
  }
444
- const json = (s) => JSON.stringify(s).replace(/</g, "\\u003c");
445
- const DOCK_STYLE = "#wb-dock{position:fixed;right:16px;bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:30;display:flex;flex-direction:column;align-items:flex-end;gap:6px}#wb-dock:empty{display:none}.wb-toasts{display:flex;flex-direction:column;align-items:flex-end;gap:6px}.wb-toasts:empty{display:none}.wb-toast{display:inline-flex;align-items:center;gap:8px;cursor:pointer;padding:5px 12px;border-radius:99px;font:600 .8rem/1.4 var(--sans,system-ui,sans-serif);background:var(--accent,#1d5bbf);color:var(--accent-text,#fff);border:1px solid transparent;box-shadow:0 2px 10px rgb(0 0 0/.18)}.wb-toast[hidden]{display:none}.wb-toast[data-kind=warn]{background:var(--warn,#6b4fc0)}.wb-toast[data-kind=alert]{background:var(--bad,#c4352b);color:#fff}@keyframes wb-flash{from{outline-color:var(--accent,#1d5bbf)}to{outline-color:transparent}}.wb-flash{outline:3px solid transparent;outline-offset:6px;border-radius:4px;animation:wb-flash 2s ease-out}.wb-toast-dismiss{margin-right:-4px;padding:0 4px;border-left:1px solid rgb(255 255 255/.35);opacity:.75}.wb-toast-dismiss:hover{opacity:1}";
446
- /** `extras`: what plugins add to <head> and <body> (see shellExtras). */
447
- function shell(page, { page: rendered, out, notices }, extras = {
448
- head: [],
449
- body: [],
450
- clients: []
451
- }, built) {
452
- const handoff = {
453
- id: page.id,
454
- kind: page.kind,
455
- live: !built,
456
- base: built ? "" : base,
457
- client: rendered ? (built ?? { asset }).asset(PAGE_CLIENT) : null,
458
- data: out.data ?? null,
459
- frontmatter: frontmatterOf(page),
460
- plugins: extras.clients,
461
- messages: extras.messages ?? []
292
+ /**
293
+ * What the browser runs and how it looks, as two stamps: one over its code (the runtime, the page's
294
+ * module, the plugins' scripts), one over its stylesheets (the engine's, the plugins', the
295
+ * project's in .whiteboard/). A page gets them with its HTML and asks again when its live channel
296
+ * is back: what changed while it was away (a restart, a background tab whose browser held its
297
+ * timers), it would otherwise never hear of. Made from the files themselves, not from what was
298
+ * served since the server started, so a fresh server gives the same stamps for the same files.
299
+ */
300
+ function stamps() {
301
+ const files = [RUNTIME];
302
+ const add = (dir, deep) => {
303
+ let entries;
304
+ try {
305
+ entries = fs.readdirSync(dir, { withFileTypes: true });
306
+ } catch {
307
+ return;
308
+ }
309
+ for (const e of entries) {
310
+ const full = path.join(dir, e.name);
311
+ if (e.isDirectory()) {
312
+ if (deep) add(full, deep);
313
+ } else files.push(full);
314
+ }
315
+ };
316
+ add(path.dirname(PAGE_CLIENT), false);
317
+ for (const dir of publicDirs) add(dir, true);
318
+ for (const f of fs.readdirSync(project.wb).filter((f) => f.endsWith(".css"))) files.push(path.join(project.wb, f));
319
+ const of = (list) => {
320
+ const hash = crypto.createHash("sha1");
321
+ for (const f of [...new Set(list)].toSorted()) try {
322
+ const st = fs.statSync(f);
323
+ hash.update(`${f}\0${st.mtimeMs}\0${st.size}\n`);
324
+ } catch {}
325
+ return hash.digest("hex").slice(0, 16);
326
+ };
327
+ return {
328
+ code: of(files.filter((f) => !f.endsWith(".css"))),
329
+ style: of(files.filter((f) => f.endsWith(".css")))
462
330
  };
463
- return String(html(_templateObject || (_templateObject = _taggedTemplateLiteral([
464
- "<!doctype html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n <title>",
465
- "</title>\n <style>\n ",
466
- "\n </style>\n ",
467
- "",
468
- "\n </head>\n <body data-page=\"",
469
- "\" data-kind=\"",
470
- "\">\n ",
471
- "\n <div id=\"wb-root\">",
472
- "</div>\n <div id=\"wb-dock\"></div>\n <script type=\"application/json\" id=\"wb-page\">\n ",
473
- "\n <\/script>\n <script type=\"module\" src=\"",
474
- "\"><\/script>\n ",
475
- "\n </body>\n </html>"
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));
477
331
  }
478
- /** A listener as the server holds it. */
479
- const listeners = /* @__PURE__ */ new Set();
480
- const listenersFor = (page) => [...listeners].filter((l) => page == null || covers(l, page)).map(({ page, type, command, fallback }) => ({
481
- page,
482
- type,
483
- command,
484
- ...fallback && { fallback }
485
- }));
332
+ const registry = createRegistry();
333
+ const listenersFor = (page) => registry.list(page);
486
334
  const clients = /* @__PURE__ */ new Set();
335
+ /** what the browser appended lately, by id: a send it retries is answered with what it got */
336
+ const appended = /* @__PURE__ */ new Map();
487
337
  function notify(client, kind) {
488
338
  client.pending ??= /* @__PURE__ */ new Set();
489
339
  if (client.pending.size === 0) setTimeout(() => {
490
- for (const k of client.pending) client.res.write(`event: ${k}\ndata: {}\n\n`);
340
+ for (const k of client.pending) client.send(k);
491
341
  client.pending.clear();
492
342
  }, 60);
493
343
  client.pending.add(kind);
@@ -495,6 +345,10 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
495
345
  const notifyAll = (kind) => {
496
346
  for (const c of clients) notify(c, kind);
497
347
  };
348
+ registry.onChange(() => {
349
+ notifyAll("listeners");
350
+ onChange?.();
351
+ });
498
352
  function pageChanged(id) {
499
353
  onChange?.();
500
354
  for (const c of clients) if (c.isDir ? !c.page || id.startsWith(c.page + "/") : c.page === id || c.page + "/index" === id) notify(c, "change");
@@ -599,8 +453,7 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
599
453
  if ("raw" in found) return found;
600
454
  if ((found.kind === "folder" || found.kind === "pages" && id) && !requested.endsWith("/")) return { redirect: `${base}/${id}/` };
601
455
  if (found.kind === "pages") {
602
- const counts = new Map((await status(found.id || null)).map((s) => [s.page, awaiting(s)]));
603
- for (const p of found.pages) p.awaiting = counts.get(p.id) ?? 0;
456
+ await withStatus(found.pages);
604
457
  if (!found.id && overview) Object.assign(found, await overview());
605
458
  }
606
459
  return { page: found };
@@ -645,17 +498,23 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
645
498
  if (p === "/api/events" && req.method === "POST") {
646
499
  const body = JSON.parse(await readBody(req));
647
500
  if (!body.type) return sendJson(res, 400, { error: "event type required" });
648
- return sendJson(res, 200, appendEvent(project.eventsFile, body));
501
+ const again = isEventId(body.id) ? appended.get(body.id) : void 0;
502
+ if (again) return sendJson(res, 200, again);
503
+ const event = appendEvent(project.eventsFile, body);
504
+ appended.set(event.id, event);
505
+ if (appended.size > 1e3) appended.delete(appended.keys().next().value);
506
+ return sendJson(res, 200, event);
649
507
  }
650
508
  if (p === "/api/scroll" && req.method === "POST") {
651
509
  const { page: id, to } = JSON.parse(await readBody(req));
652
510
  if (typeof id !== "string" || typeof to !== "string" || !to.trim()) return sendJson(res, 400, { error: "page and to required" });
511
+ appendEvent(project.eventsFile, {
512
+ page: id,
513
+ type: SCROLL,
514
+ data: { to }
515
+ }, "cli");
653
516
  let tabs = 0;
654
- for (const c of clients) {
655
- if (c.isDir || c.page !== id && c.page + "/index" !== id) continue;
656
- c.res.write(`event: scroll\ndata: ${JSON.stringify({ to })}\n\n`);
657
- tabs++;
658
- }
517
+ for (const c of clients) if (!c.isDir && (c.page === id || c.page + "/index" === id)) tabs++;
659
518
  return sendJson(res, 200, { tabs });
660
519
  }
661
520
  if (p === "/api/markdown" && req.method === "POST") {
@@ -682,37 +541,23 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
682
541
  if (p === "/api/docs") return sendJson(res, 200, await docs());
683
542
  if (p === "/api/status") return sendJson(res, 200, await status(q.page || null));
684
543
  if (p === "/api/listeners") return sendJson(res, 200, listenersFor(q.page ?? null));
544
+ if (p === "/api/stamps") return sendJson(res, 200, stamps());
685
545
  if (p === "/api/listen") {
686
- const fallback = "fallback" in q;
687
- if (fallback && [...listeners].some((l) => l.fallback)) return sendJson(res, 409, { error: "another agent is the fallback already" });
688
- res.writeHead(200, {
689
- "content-type": "text/event-stream",
690
- "cache-control": "no-store",
691
- connection: "keep-alive"
692
- });
693
- res.write(": listening\n\n");
694
- const l = {
695
- page: q.page || "",
696
- type: q.type || null,
697
- command: q.command === "wait" ? "wait" : "watch",
698
- ...fallback && { fallback }
699
- };
700
- listeners.add(l);
701
- notifyAll("listeners");
702
- const ping = setInterval(() => res.write(": ping\n\n"), 25e3);
703
- const end = () => {
704
- clearInterval(ping);
705
- listeners.delete(l);
706
- streams.delete(end);
707
- };
708
- streams.add(() => {
709
- end();
710
- res.end();
711
- });
712
- req.on("close", () => {
713
- end();
714
- notifyAll("listeners");
546
+ const remove = registry.add(listenerOf(url.searchParams));
547
+ if (!remove) return sendJson(res, 409, { error: "another agent is the fallback already" });
548
+ const off = "fallback" in q ? registry.onChange(() => tell()) : () => {};
549
+ const stream = holdStream(req, res, () => {
550
+ off();
551
+ remove();
552
+ streams.delete(stream.end);
715
553
  });
554
+ const tell = () => stream.send("listeners", { projects: [{
555
+ dir: project.dir,
556
+ base,
557
+ listeners: registry.list()
558
+ }] });
559
+ if ("fallback" in q) tell();
560
+ streams.add(stream.end);
716
561
  return;
717
562
  }
718
563
  if (p === "/api/page" || p === "/api/render") {
@@ -735,11 +580,12 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
735
580
  });
736
581
  res.write(": connected\n\n");
737
582
  const client = {
738
- res,
583
+ send: (event, data = {}) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),
739
584
  page: q.page || "",
740
585
  isDir: "dir" in q
741
586
  };
742
587
  clients.add(client);
588
+ client.send("reload");
743
589
  const ping = setInterval(() => res.write(": ping\n\n"), 25e3);
744
590
  const end = () => {
745
591
  clearInterval(ping);
@@ -781,210 +627,54 @@ function createServer(project, { base = "", entry, label, name, files: filesOpti
781
627
  send(res, 500, String(err?.stack || err), "text/plain");
782
628
  }
783
629
  }
784
- /** What a build leaves out unless told otherwise: what is for writing a page, not for reading it. */
785
- const BUILD_SKIP = [
786
- "form",
787
- "chat",
788
- "comments",
789
- "draft"
790
- ];
791
- /** In the folder a build writes, so that a next build knows it may replace it. */
792
- const BUILD_MARK = ".whiteboard-build";
793
- async function build(options = {}) {
794
- const cfg = await config();
795
- if (cfg.errors.length) throw new Error(`the config failed to load: ${cfg.errors[0].message}`);
796
- if (!cfg.pages) throw new Error("the config has no pages renderer");
797
- const pages = cfg.pages;
798
- const defined = (...xs) => xs.find((x) => x !== void 0);
799
- const patterns = defined(options.pages, cfg.build.pages) ?? [];
800
- const skip = new Set(defined(options.skip, cfg.build.skip) ?? BUILD_SKIP);
801
- const outDir = path.resolve(project.dir, defined(options.out, cfg.build.out) ?? "site");
802
- if (!patterns.length) throw new Error("nothing to build: name the pages, as globs from the project's folder (whiteboard build 'docs/**/*.md'), or set build.pages in the config");
803
- const warnings = [];
804
- const include = patterns.filter((p) => !p.startsWith("!"));
805
- const exclude = patterns.filter((p) => p.startsWith("!")).map((p) => p.slice(1));
806
- const files = [...new Set(include.flatMap((p) => fs.globSync(p, { cwd: project.dir }).map((f) => path.resolve(project.dir, f))))].filter((f) => /\.(md|markdown)$/i.test(f) && fs.statSync(f).isFile()).filter((f) => !exclude.some((g) => path.matchesGlob(path.relative(project.dir, f), g))).sort();
807
- if (!files.length) throw new Error(`no markdown files match ${patterns.join(" ")}`);
808
- const base = files.map(path.dirname).reduce((a, b) => {
809
- while (!within(b, a)) a = path.dirname(a);
810
- return a;
811
- });
812
- const outOf = (file) => {
813
- const rel = path.relative(base, file);
814
- return path.join(outDir, /^(readme|index)\.(md|markdown)$/i.test(path.basename(rel)) ? path.join(path.dirname(rel), "index.html") : rel.replace(/\.(md|markdown)$/i, ".html"));
815
- };
816
- const built = new Map(files.map((f) => [f, outOf(f)]));
817
- if (fs.existsSync(outDir)) {
818
- if (fs.readdirSync(outDir).length && !fs.existsSync(path.join(outDir, BUILD_MARK))) throw new Error(`${outDir} has files a build didn't write: give another folder (--out), or empty it`);
819
- fs.rmSync(outDir, { recursive: true });
820
- }
821
- fs.mkdirSync(outDir, { recursive: true });
822
- fs.writeFileSync(path.join(outDir, BUILD_MARK), "written by whiteboard build; the next build replaces this folder\n");
823
- const copied = /* @__PURE__ */ new Map();
824
- function copyAsset(file) {
825
- const known = copied.get(file);
826
- if (known) return known;
827
- const rel = within(file, ENGINE_DIR) ? path.join("_", "whiteboard", path.relative(ENGINE_DIR, file)) : within(file, project.dir) ? path.join("_", "project", path.relative(project.dir, file)) : path.join("_", "files", path.basename(path.dirname(file)), path.basename(file));
828
- const dest = path.join(outDir, TYPESCRIPT.test(rel) ? rel.replace(/\.m?ts$/i, ".js") : rel);
829
- copied.set(file, dest);
830
- fs.mkdirSync(path.dirname(dest), { recursive: true });
831
- if (TYPESCRIPT.test(file)) fs.writeFileSync(dest, typeScriptModule(file));
832
- else fs.copyFileSync(file, dest);
833
- if (/\.css$/i.test(file)) for (const m of fs.readFileSync(file, "utf8").matchAll(/url\(\s*['"]?([^'")]+)['"]?\s*\)/g)) {
834
- const ref = m[1];
835
- if (/^(data:|[a-z][a-z0-9+.-]*:|\/|#)/i.test(ref)) continue;
836
- const target = path.resolve(path.dirname(file), ref.replace(/[?#].*$/, ""));
837
- if (fs.existsSync(target) && fs.statSync(target).isFile()) copyAsset(target);
838
- }
839
- return dest;
840
- }
841
- /** a file beside the pages (an image), copied to its place below the site */
842
- function copyBeside(file) {
843
- if (!within(file, base)) return null;
844
- const dest = path.join(outDir, path.relative(base, file));
845
- if (!fs.existsSync(dest)) {
846
- fs.mkdirSync(path.dirname(dest), { recursive: true });
847
- fs.copyFileSync(file, dest);
848
- }
849
- return dest;
850
- }
851
- const hooks = await pluginHooks();
852
- const result = {
853
- out: outDir,
854
- pages: [],
855
- warnings
630
+ /** The live channel: /api/live, a WebSocket from a page of this server's (see ws.ts). */
631
+ function upgrade(req, conn, _head) {
632
+ const url = new URL((req.url ?? "/").replace(/^\/+/, "/"), "http://localhost");
633
+ if (decodeURIComponent(url.pathname) !== "/api/live") return refuse(conn, 404, "Not Found");
634
+ if (!sameSite(req)) return refuse(conn, 403, "Forbidden");
635
+ const socket = accept(req, conn);
636
+ if (!socket) return;
637
+ const client = {
638
+ send: (event, data = {}) => socket.send(JSON.stringify({
639
+ event,
640
+ data
641
+ })),
642
+ page: url.searchParams.get("page") ?? "",
643
+ isDir: url.searchParams.has("dir")
856
644
  };
857
- for (const [file, dest] of built) {
858
- const here = path.dirname(dest);
859
- const relTo = (target) => path.relative(here, target).split(path.sep).map(encodeURIComponent).join("/") || ".";
860
- const assetHere = (ref) => relTo(copyAsset(toPath(ref)));
861
- const urlFor = (abs) => {
862
- for (const candidate of [abs, abs + ".md"]) {
863
- if (!fs.existsSync(candidate)) continue;
864
- if (fs.statSync(candidate).isDirectory()) {
865
- const index = [...built.keys()].find((f) => path.dirname(f) === candidate && /^(readme|index)\.(md|markdown)$/i.test(path.basename(f)));
866
- if (index) return relTo(built.get(index));
867
- continue;
868
- }
869
- if (built.has(candidate)) return relTo(built.get(candidate));
870
- if (/\.(md|markdown)$/i.test(candidate)) {
871
- warnings.push(`${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, which is not in the build`);
872
- return null;
873
- }
874
- const copy = copyBeside(candidate);
875
- if (copy) return relTo(copy);
876
- warnings.push(`${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, outside the built pages' folder`);
877
- return null;
878
- }
879
- return null;
880
- };
881
- const id = within(file, project.pagesDir) ? path.relative(project.pagesDir, file).split(path.sep).join("/").replace(/\.(md|markdown)$/i, "") : "-/" + path.relative(project.dir, file).split(path.sep).join("/");
882
- const stored = pageSource(id, file);
883
- if (stored.frontmatterError) warnings.push(`${path.relative(project.dir, file)}: frontmatter: ${stored.frontmatterError}`);
884
- const context = {
885
- project: {
886
- name: project.name,
887
- dir: project.dir,
888
- files: !!FILES
889
- },
890
- asset: assetHere,
891
- urlFor,
892
- live: false,
893
- skip
894
- };
895
- const rendered = await pages.render(stored, context);
896
- const named = /^(readme|index)\.(md|markdown)$/i.test(path.basename(file)) ? path.basename(path.dirname(file)) : path.basename(file).replace(/\.(md|markdown)$/i, "");
897
- const title = !rendered.title || rendered.title === id ? named : rendered.title;
898
- const out = {
899
- ...rendered,
900
- title,
901
- html: String(rendered.html ?? ""),
902
- head: String(rendered.head ?? "")
903
- };
904
- const included = hooks.filter((h) => !h.error && !skip.has(h.name));
905
- const clients = included.filter((h) => h.client).map((h) => ({
906
- name: h.name,
907
- client: assetHere(h.client)
908
- }));
909
- const parts = await Promise.all(included.map(async (h) => {
910
- try {
911
- return await h.shell?.(null) ?? null;
912
- } catch (err) {
913
- warnings.push(`plugin ${h.name} failed on ${path.relative(project.dir, file)}: ${err.message}`);
914
- return null;
915
- }
916
- }));
917
- const extras = {
918
- head: parts.map((x) => raw(String(x?.head ?? ""))),
919
- body: parts.map((x) => raw(String(x?.body ?? ""))),
920
- clients
921
- };
922
- let doc = shell(stored, {
923
- page: true,
924
- out,
925
- notices: []
926
- }, extras, { asset: assetHere });
927
- doc = doc.replace(/\/_\/file(\/[^"'\s)<>]+)/g, (all, served) => {
928
- let file;
929
- try {
930
- file = path.resolve(served.split("/").map(decodeURIComponent).join(path.sep));
931
- } catch {
932
- return all;
933
- }
934
- return fs.existsSync(file) && fs.statSync(file).isFile() ? assetHere(file) : all;
935
- });
936
- doc = doc.replace(/\b(src|href|poster)="([^"#?:]+)([^"]*)"/g, (all, _attr, ref) => {
937
- if (ref.startsWith("/") || ref.startsWith("_/") || ref.startsWith("../")) return all;
938
- let decoded = ref;
939
- try {
940
- decoded = decodeURIComponent(ref);
941
- } catch {}
942
- const source = path.resolve(path.dirname(file), decoded);
943
- if (fs.existsSync(source) && fs.statSync(source).isFile() && !/\.(md|markdown)$/i.test(source)) {
944
- const target = path.resolve(here, decoded);
945
- if (within(target, outDir) && !fs.existsSync(target)) {
946
- fs.mkdirSync(path.dirname(target), { recursive: true });
947
- fs.copyFileSync(source, target);
948
- }
949
- }
950
- return all;
951
- });
952
- fs.mkdirSync(here, { recursive: true });
953
- fs.writeFileSync(dest, doc);
954
- result.pages.push({
955
- file,
956
- to: dest
957
- });
958
- }
959
- if (![...built.values()].includes(path.join(outDir, "index.html"))) warnings.push("no README.md or index.md in the top folder: the site has no index.html");
960
- return result;
645
+ clients.add(client);
646
+ const stop = () => socket.close();
647
+ streams.add(stop);
648
+ socket.onClose(() => {
649
+ clients.delete(client);
650
+ streams.delete(stop);
651
+ });
961
652
  }
962
653
  return {
963
654
  handle,
655
+ upgrade,
964
656
  listeners: () => listenersFor(null),
965
657
  async overview() {
966
658
  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
659
  return {
971
- pages,
660
+ pages: await withStatus(pagesIn(project.pagesDir)),
972
661
  files: !!FILES
973
662
  };
974
663
  },
975
664
  touch() {
976
665
  for (const c of clients) if (c.isDir && !c.page) notify(c, "change");
977
666
  },
978
- addListener(l) {
979
- listeners.add(l);
980
- notifyAll("listeners");
981
- return () => {
982
- if (listeners.delete(l)) notifyAll("listeners");
983
- };
984
- },
667
+ elsewhere: () => notifyAll("elsewhere"),
668
+ addListener: (l) => registry.add(l),
669
+ onListeners: (fn) => registry.onChange(fn),
985
670
  status: (page = null) => status(page),
986
671
  config,
987
- build,
672
+ build: (options) => build({
673
+ project,
674
+ config,
675
+ hooks: pluginHooks,
676
+ files: () => !!FILES
677
+ }, options),
988
678
  close() {
989
679
  for (const w of watchers) w.close();
990
680
  watchers.clear();