@bigmistqke/whiteboard 0.4.0 → 0.6.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 (128) hide show
  1. package/README.md +177 -26
  2. package/bin/whiteboard.ts +331 -16
  3. package/dist/bin/whiteboard.js +268 -17
  4. package/dist/client/runtime.js +66 -23
  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/draft/README.md +14 -0
  15. package/dist/plugins/draft/index.js +21 -0
  16. package/dist/plugins/draft/public/style.css +21 -0
  17. package/dist/plugins/grid/README.md +12 -12
  18. package/dist/plugins/grid/index.js +7 -19
  19. package/dist/plugins/grid/public/style.css +4 -33
  20. package/dist/plugins/iframe/README.md +7 -7
  21. package/dist/plugins/iframe/index.js +11 -11
  22. package/dist/plugins/iframe/public/style.css +15 -0
  23. package/dist/plugins/index.js +11 -3
  24. package/dist/plugins/lightbox/README.md +22 -0
  25. package/dist/plugins/lightbox/index.js +20 -0
  26. package/dist/plugins/lightbox/public/client.js +4 -0
  27. package/dist/plugins/lightbox/public/style.css +66 -0
  28. package/dist/plugins/steps/README.md +42 -0
  29. package/dist/plugins/steps/index.js +60 -0
  30. package/dist/plugins/steps/public/client.js +1 -0
  31. package/dist/plugins/steps/public/style.css +77 -0
  32. package/dist/plugins/terminal/host.js +9 -3
  33. package/dist/plugins/terminal/public/client.js +1 -1
  34. package/dist/plugins/terminal/sizes.js +2 -1
  35. package/dist/plugins/toc/README.md +21 -3
  36. package/dist/plugins/toc/index.js +8 -2
  37. package/dist/plugins/toc/public/client.js +1 -1
  38. package/dist/plugins/toc/public/style.css +10 -4
  39. package/dist/plugins/window/README.md +34 -14
  40. package/dist/plugins/window/index.js +21 -13
  41. package/dist/src/auth.js +6 -4
  42. package/dist/src/client/page/base.css +61 -1
  43. package/dist/src/client/page/main.js +74 -20
  44. package/dist/src/entries.js +211 -0
  45. package/dist/src/events.js +1 -1
  46. package/dist/src/hub.js +272 -0
  47. package/dist/src/loader.js +12 -3
  48. package/dist/src/package.js +23 -1
  49. package/dist/src/pages/blocks.js +1 -0
  50. package/dist/src/pages/index.js +1 -1
  51. package/dist/src/pages/markdown.js +87 -33
  52. package/dist/src/pages/render.js +157 -28
  53. package/dist/src/pages/window.js +17 -18
  54. package/dist/src/running.js +37 -2
  55. package/dist/src/serve.js +111 -2
  56. package/dist/src/server.js +264 -23
  57. package/package.json +3 -2
  58. package/plugins/ansi/README.md +36 -0
  59. package/plugins/ansi/index.ts +95 -0
  60. package/plugins/ansi/public/style.css +28 -0
  61. package/plugins/badge/README.md +28 -0
  62. package/plugins/badge/index.ts +35 -0
  63. package/plugins/badge/public/style.css +30 -0
  64. package/plugins/chat/public/style.css +7 -2
  65. package/plugins/code/README.md +4 -2
  66. package/plugins/code/diff.ts +14 -2
  67. package/plugins/code/index.ts +3 -1
  68. package/plugins/draft/README.md +14 -0
  69. package/plugins/draft/index.ts +23 -0
  70. package/plugins/draft/public/style.css +21 -0
  71. package/plugins/grid/README.md +12 -12
  72. package/plugins/grid/index.ts +11 -26
  73. package/plugins/grid/public/style.css +4 -33
  74. package/plugins/iframe/README.md +7 -7
  75. package/plugins/iframe/index.ts +15 -15
  76. package/plugins/iframe/public/style.css +15 -0
  77. package/plugins/index.ts +10 -2
  78. package/plugins/lightbox/README.md +22 -0
  79. package/plugins/lightbox/client.ts +99 -0
  80. package/plugins/lightbox/index.ts +25 -0
  81. package/plugins/lightbox/public/style.css +66 -0
  82. package/plugins/mermaid/index.ts +4 -2
  83. package/plugins/steps/README.md +42 -0
  84. package/plugins/steps/client.ts +75 -0
  85. package/plugins/steps/index.ts +84 -0
  86. package/plugins/steps/public/style.css +77 -0
  87. package/plugins/terminal/client.ts +16 -7
  88. package/plugins/terminal/host.ts +12 -6
  89. package/plugins/terminal/sizes.ts +3 -1
  90. package/plugins/toc/README.md +21 -3
  91. package/plugins/toc/client.ts +47 -6
  92. package/plugins/toc/index.ts +19 -6
  93. package/plugins/toc/public/style.css +10 -4
  94. package/plugins/window/README.md +34 -14
  95. package/plugins/window/index.ts +20 -13
  96. package/skills/whiteboard/SKILL.md +18 -10
  97. package/src/auth.ts +8 -5
  98. package/src/client/base.ts +19 -0
  99. package/src/client/forms.ts +2 -1
  100. package/src/client/markdown.ts +2 -1
  101. package/src/client/page/base.css +61 -1
  102. package/src/client/page/elsewhere.ts +72 -16
  103. package/src/client/page/fresh.ts +2 -1
  104. package/src/client/page/main.ts +18 -6
  105. package/src/client/page/sort.ts +2 -1
  106. package/src/client/runtime.ts +62 -25
  107. package/src/define.ts +126 -19
  108. package/src/entries.ts +258 -0
  109. package/src/events.ts +2 -1
  110. package/src/hub.ts +355 -0
  111. package/src/loader.ts +14 -3
  112. package/src/package.ts +22 -0
  113. package/src/pages/blocks.ts +3 -0
  114. package/src/pages/index.ts +6 -4
  115. package/src/pages/markdown.ts +89 -32
  116. package/src/pages/render.ts +181 -28
  117. package/src/pages/window.ts +23 -25
  118. package/src/running.ts +47 -1
  119. package/src/serve.ts +114 -1
  120. package/src/server.ts +332 -26
  121. package/dist/plugins/gallery/README.md +0 -30
  122. package/dist/plugins/gallery/index.js +0 -75
  123. package/dist/plugins/gallery/public/client.js +0 -1
  124. package/dist/plugins/gallery/public/style.css +0 -90
  125. package/plugins/gallery/README.md +0 -30
  126. package/plugins/gallery/client.tsx +0 -70
  127. package/plugins/gallery/index.ts +0 -89
  128. package/plugins/gallery/public/style.css +0 -90
@@ -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";
@@ -11,6 +11,7 @@ import _taggedTemplateLiteral from "../_virtual/_@oxc-project_runtime@0.156.0/he
11
11
  import { stripTypeScriptTypes } from "node:module";
12
12
  import fs from "node:fs";
13
13
  import path from "node:path";
14
+ import { parse } from "yaml";
14
15
  // src/server.ts
15
16
  var _templateObject;
16
17
  const ENGINE_DIR = PACKAGE_DIR;
@@ -47,9 +48,10 @@ const OWN_FILES = /* @__PURE__ */ new Set([
47
48
  ]);
48
49
  const SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
49
50
  const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/;
50
- function createServer(project) {
51
+ function createServer(project, { base = "", entry, label, name, files: filesOption, overview, onChange } = {}) {
52
+ const projectName = () => name ?? project.name;
51
53
  const loader = createConfigLoader(project);
52
- const auth = createAuth(project.wb);
54
+ const auth = createAuth(project.wb, base);
53
55
  const watchers = /* @__PURE__ */ new Set();
54
56
  const streams = /* @__PURE__ */ new Set();
55
57
  const watch = (dir, options, fn) => {
@@ -136,7 +138,7 @@ function createServer(project) {
136
138
  /** The loaded config. Also applies its `files` setting to what is served and watched. */
137
139
  async function config() {
138
140
  const c = await loader.config();
139
- setFiles(c.files);
141
+ setFiles(filesOption ?? c.files);
140
142
  publicDirs = [...c.publicDirs.values()];
141
143
  return c;
142
144
  }
@@ -156,7 +158,7 @@ function createServer(project) {
156
158
  if (!within(dir, project.wb) && !ENGINE_WATCHED.some((d) => within(dir, d))) watch(dir, {}, (name) => onSourceChange(path.join(dir, name)));
157
159
  }
158
160
  }
159
- return `/_/file${file.split(path.sep).map(encodeURIComponent).join("/")}`;
161
+ return `${base}/_/file${file.split(path.sep).map(encodeURIComponent).join("/")}`;
160
162
  }
161
163
  const within = (file, dir) => file === dir || file.startsWith(dir + path.sep);
162
164
  /** Resolve a path inside a base folder, refusing anything that escapes it. */
@@ -165,14 +167,34 @@ function createServer(project) {
165
167
  return within(p, base) ? p : null;
166
168
  }
167
169
  const isRepoId = (id) => id === "-" || id.startsWith("-/");
170
+ /** A page's frontmatter, parsed as YAML; empty, with the reason, when it isn't fields. */
168
171
  function frontmatter(source) {
169
172
  const m = FRONTMATTER.exec(source);
170
- const out = {};
171
- if (m) for (const line of m[1].split(/\r?\n/)) {
172
- const kv = /^([\w-]+)\s*:\s*(.*)$/.exec(line);
173
- if (kv) out[kv[1]] = kv[2].trim().replace(/^["']|["']$/g, "");
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
+ };
174
185
  }
175
- return out;
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
+ };
176
198
  }
177
199
  function pageSource(id, file) {
178
200
  const source = fs.readFileSync(file, "utf8");
@@ -183,7 +205,10 @@ function createServer(project) {
183
205
  mtime: fs.statSync(file).mtimeMs,
184
206
  source,
185
207
  body: source.replace(FRONTMATTER, ""),
186
- frontmatter: frontmatter(source)
208
+ ...(({ data, error }) => ({
209
+ frontmatter: data,
210
+ frontmatterError: error
211
+ }))(frontmatter(source))
187
212
  };
188
213
  }
189
214
  /** The pages in a folder of the pages folder, newest first, with when each was last answered. */
@@ -280,10 +305,10 @@ function createServer(project) {
280
305
  /** The URL that serves a file or folder on disk, or null when nothing here serves it. */
281
306
  function urlOf(abs) {
282
307
  const rel = (dir) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join("/");
283
- if (within(abs, project.pagesDir)) return `/${rel(project.pagesDir).replace(/\.md$/, "")}`;
308
+ if (within(abs, project.pagesDir)) return `${base}/${rel(project.pagesDir).replace(/\.md$/, "")}`;
284
309
  if (FILES && within(abs, project.dir)) {
285
310
  if (rel(project.dir).split("/").some((part) => SKIP_DIRS.has(part))) return null;
286
- return `/-/${rel(project.dir)}`;
311
+ return `${base}/-/${rel(project.dir)}`;
287
312
  }
288
313
  return null;
289
314
  }
@@ -300,18 +325,23 @@ function createServer(project) {
300
325
  const list = (items) => html`<ul>
301
326
  ${items.map(([href, text]) => html`<li><a href="${href}">${text}</a></li>`)}
302
327
  </ul>`;
303
- 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])) };
304
329
  if (page.kind === "folder") return { html: list(page.entries.map((e) => [encodeURIComponent(e.name) + (e.dir ? "/" : ""), e.name + (e.dir ? "/" : "")])) };
305
330
  return { html: html`<pre>${page.source}</pre>` };
306
331
  }
307
332
  const context = () => ({
308
333
  project: {
309
- name: project.name,
334
+ name: projectName(),
310
335
  dir: project.dir,
311
336
  files: !!FILES
312
337
  },
313
338
  asset,
314
- urlFor
339
+ urlFor,
340
+ base,
341
+ ...entry && { entry: {
342
+ name: entry,
343
+ label
344
+ } }
315
345
  });
316
346
  /** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
317
347
  const frontmatterOf = (page) => page.kind === "page" ? page.frontmatter : {};
@@ -319,6 +349,7 @@ function createServer(project) {
319
349
  async function render(page) {
320
350
  const { pages, errors } = await config();
321
351
  const notices = errors.map((e) => `config: ${e.message}`);
352
+ if (page.kind === "page" && page.frontmatterError) notices.push(`frontmatter: ${page.frontmatterError}`);
322
353
  let out;
323
354
  let rendered = !!pages;
324
355
  try {
@@ -417,11 +448,13 @@ function createServer(project) {
417
448
  head: [],
418
449
  body: [],
419
450
  clients: []
420
- }) {
451
+ }, built) {
421
452
  const handoff = {
422
453
  id: page.id,
423
454
  kind: page.kind,
424
- client: rendered ? asset(PAGE_CLIENT) : null,
455
+ live: !built,
456
+ base: built ? "" : base,
457
+ client: rendered ? (built ?? { asset }).asset(PAGE_CLIENT) : null,
425
458
  data: out.data ?? null,
426
459
  frontmatter: frontmatterOf(page),
427
460
  plugins: extras.clients,
@@ -437,9 +470,10 @@ function createServer(project) {
437
470
  "\">\n ",
438
471
  "\n <div id=\"wb-root\">",
439
472
  "</div>\n <div id=\"wb-dock\"></div>\n <script type=\"application/json\" id=\"wb-page\">\n ",
440
- "\n <\/script>\n <script type=\"module\" src=\"/_/runtime.js\"><\/script>\n ",
473
+ "\n <\/script>\n <script type=\"module\" src=\"",
474
+ "\"><\/script>\n ",
441
475
  "\n </body>\n </html>"
442
- ])), 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)), 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));
443
477
  }
444
478
  /** A listener as the server holds it. */
445
479
  const listeners = /* @__PURE__ */ new Set();
@@ -462,6 +496,7 @@ function createServer(project) {
462
496
  for (const c of clients) notify(c, kind);
463
497
  };
464
498
  function pageChanged(id) {
499
+ onChange?.();
465
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");
466
501
  for (const c of clients) if (c.isDir && !c.page) notify(c, "change");
467
502
  }
@@ -470,7 +505,10 @@ function createServer(project) {
470
505
  if (f.split("/").some((part) => SKIP_DIRS.has(part))) return;
471
506
  if (f.startsWith(".whiteboard/")) {
472
507
  const inner = f.slice(12);
473
- if (inner === "events.ndjson") return notifyAll("events");
508
+ if (inner === "events.ndjson") {
509
+ onChange?.();
510
+ return notifyAll("events");
511
+ }
474
512
  if (inner.startsWith("pages/")) {
475
513
  if (inner.endsWith(".md")) pageChanged(inner.slice(6).replace(/\.md$/, ""));
476
514
  return;
@@ -559,10 +597,11 @@ function createServer(project) {
559
597
  const found = stored(id);
560
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"}.` };
561
599
  if ("raw" in found) return found;
562
- 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}/` };
563
601
  if (found.kind === "pages") {
564
602
  const counts = new Map((await status(found.id || null)).map((s) => [s.page, awaiting(s)]));
565
603
  for (const p of found.pages) p.awaiting = counts.get(p.id) ?? 0;
604
+ if (!found.id && overview) Object.assign(found, await overview());
566
605
  }
567
606
  return { page: found };
568
607
  }
@@ -599,7 +638,9 @@ function createServer(project) {
599
638
  if (p === "/api/health") return sendJson(res, 200, {
600
639
  ok: true,
601
640
  dir: project.dir,
602
- pid: process.pid
641
+ pid: process.pid,
642
+ version: VERSION,
643
+ base
603
644
  });
604
645
  if (p === "/api/events" && req.method === "POST") {
605
646
  const body = JSON.parse(await readBody(req));
@@ -740,10 +781,210 @@ function createServer(project) {
740
781
  send(res, 500, String(err?.stack || err), "text/plain");
741
782
  }
742
783
  }
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
856
+ };
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;
961
+ }
743
962
  return {
744
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
+ },
745
985
  status: (page = null) => status(page),
746
986
  config,
987
+ build,
747
988
  close() {
748
989
  for (const w of watchers) w.close();
749
990
  watchers.clear();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bigmistqke/whiteboard",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
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",
@@ -106,7 +106,8 @@
106
106
  "remark-parse": "^11.0.0",
107
107
  "remark-rehype": "^11.1.2",
108
108
  "shiki": "^4.6.0",
109
- "unified": "^11.0.5"
109
+ "unified": "^11.0.5",
110
+ "yaml": "^2.9.1"
110
111
  },
111
112
  "peerDependencies": {
112
113
  "@solidjs/web": "^2.0.0-rc.21",
@@ -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
+ ````
@@ -0,0 +1,95 @@
1
+ // Terminal output in a page: an `ansi` fence holds what a program printed, escape codes and all, and
2
+ // the page shows it as the terminal did. The text goes through a headless terminal (xterm's, the
3
+ // one the terminal plugin keeps its screens in), so what a terminal does with it is what shows:
4
+ // colours (16, 256 and true colour), bold, a progress line `\r` writes over, the cursor moving.
5
+ // Rendered on the server to plain HTML, so nothing runs on the page and a built site has it too.
6
+ import fs from 'node:fs'
7
+ import { definePlugin, html, raw, windowFrame, type FenceContext, type Plugin } from '@bigmistqke/whiteboard'
8
+ import xtermHeadless from '@xterm/headless'
9
+ import xtermSerialize from '@xterm/addon-serialize'
10
+ import { builtinPublic } from '../../src/package.ts'
11
+
12
+ // CommonJS packages: their exports are the default's
13
+ const { Terminal } = xtermHeadless
14
+ const { SerializeAddon } = xtermSerialize
15
+
16
+ /** The widest a line is laid out before it wraps, as a terminal would. */
17
+ const MAX_COLS = 240
18
+ const ESC = '\x1b'
19
+
20
+ /**
21
+ * Escapes written out as text count as escapes: an agent writing a page often can't put the ESC
22
+ * byte itself in a file, so `\e[31m`, `\x1b[31m`, `\033[31m`, `\u001b[31m` and `^[[31m` are one.
23
+ */
24
+ export const unescape = (text: string): string => text.replace(/\\e(?=\[)|\\x1b|\\033|\\u001b|\^\[(?=\[)/gi, ESC)
25
+
26
+ /** How wide a line shows: its characters, without its escape sequences. */
27
+ const shown = (line: string) =>
28
+ [
29
+ ...line
30
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g, '')
31
+ .split('\r')
32
+ .at(-1)!,
33
+ ].length
34
+
35
+ /**
36
+ * What the text shows in a terminal as wide as its widest line (up to MAX_COLS), as HTML rows: the
37
+ * serializer's spans, colours inline, text escaped; trailing blank space and blank rows left out.
38
+ */
39
+ export async function toHtml(text: string): Promise<string> {
40
+ const input = unescape(text).replace(/\r?\n$/, '')
41
+ const lines = input.split(/\r?\n/)
42
+ const cols = Math.min(MAX_COLS, Math.max(20, ...lines.map(shown)))
43
+ const term = new Terminal({
44
+ cols,
45
+ rows: Math.max(1, lines.length),
46
+ scrollback: 100_000,
47
+ allowProposedApi: true,
48
+ convertEol: true,
49
+ })
50
+ const serializer = new SerializeAddon()
51
+ term.loadAddon(serializer)
52
+ await new Promise<void>(resolve => term.write(input, resolve))
53
+ const out = serializer.serializeAsHTML({ includeGlobalBackground: false })
54
+ term.dispose()
55
+ // the rows, without the wrapper that sets the serializer's own colours and font
56
+ const body = /<pre><div style='[^']*'>([\s\S]*)<\/div><\/pre>/.exec(out)?.[1] ?? ''
57
+ const rows = [...body.matchAll(/<div>([\s\S]*?)<\/div>/g)].map(m =>
58
+ // a row's padding to the terminal's width is no part of the output
59
+ m[1]!
60
+ .replace(/<span><\/span>/g, '')
61
+ .replace(/<span> +<\/span>$/, '')
62
+ .replace(/(<span>[^<]*?) +(<\/span>)$/, '$1$2'),
63
+ )
64
+ while (
65
+ rows.length &&
66
+ !rows
67
+ .at(-1)!
68
+ .replace(/<[^>]+>/g, '')
69
+ .trim()
70
+ )
71
+ rows.pop()
72
+ return rows.map(r => `<span class="wb-ansi-row">${r}</span>`).join('\n')
73
+ }
74
+
75
+ export async function render(ctx: FenceContext) {
76
+ const body = html`<pre class="wb-ansi"><code>${raw(await toHtml(ctx.text))}</code></pre>`
77
+ // a title makes it a terminal window with that label, as `compose=window` would
78
+ const title = ctx.attrs.title
79
+ return title ? windowFrame({ body, label: String(html`${title}`), className: 'wb-ansi-window' }) : body
80
+ }
81
+
82
+ export default function ansi(): Plugin {
83
+ return definePlugin({
84
+ name: 'ansi',
85
+ public: builtinPublic('ansi'),
86
+ blocks: {
87
+ ansi: {
88
+ fence: true,
89
+ html: render,
90
+ style: 'style.css',
91
+ },
92
+ },
93
+ docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
94
+ })
95
+ }
@@ -0,0 +1,28 @@
1
+ /* Terminal output: dark as a terminal in either theme, since the colours in it are a terminal's
2
+ palette, written inline. Wide output scrolls sideways rather than wrapping. */
3
+ .wb-ansi {
4
+ margin: 1.6em 0;
5
+ padding: 12px 16px;
6
+ overflow-x: auto;
7
+ background: #0f1115;
8
+ color: #d7dae0;
9
+ border-radius: var(--radius, 6px);
10
+ font: 0.82rem/1.45 var(--mono, ui-monospace, SFMono-Regular, Menlo, monospace);
11
+ white-space: pre;
12
+ tab-size: 8;
13
+ }
14
+ .wb-ansi code {
15
+ font: inherit;
16
+ background: none;
17
+ padding: 0;
18
+ color: inherit;
19
+ }
20
+ /* in a window (title=, or compose=window) the terminal fills it, the frame its edge */
21
+ .wb-window-body:has(> .wb-ansi:only-child) {
22
+ padding: 0;
23
+ background: #0f1115;
24
+ }
25
+ .wb-window-body > .wb-ansi {
26
+ margin: 0;
27
+ border-radius: 0;
28
+ }
@@ -0,0 +1,28 @@
1
+ A status as a coloured dot and a word, inline wherever text goes: in a
2
+ heading, a table cell, a list item, a sentence. `done ok yes good` are
3
+ green, `active new info` blue, `open todo maybe warning` amber,
4
+ `blocked no bad error` red; any other word is grey.
5
+
6
+ ```markdown
7
+ ### Parser :badge[done]
8
+
9
+ | step | state |
10
+ | --- | --- |
11
+ | parse | :badge[done] |
12
+ | render | :badge[active] |
13
+ | docs | :badge[todo] |
14
+
15
+ The release is :badge[blocked] on review.
16
+ ```
17
+
18
+ A grid card whose heading ends in a badge shows it at the card's right edge.
19
+
20
+ ### Parser :badge[done]
21
+
22
+ | step | state |
23
+ | --- | --- |
24
+ | parse | :badge[done] |
25
+ | render | :badge[active] |
26
+ | docs | :badge[todo] |
27
+
28
+ The release is :badge[blocked] on review.
@@ -0,0 +1,35 @@
1
+ import fs from 'node:fs'
2
+ import { definePlugin, type Plugin } from '@bigmistqke/whiteboard'
3
+ // Static block: no component, so no JavaScript on the page.
4
+ import { html, raw, type DirectiveContext } from '@bigmistqke/whiteboard'
5
+ import { builtinPublic } from '../../src/package.ts'
6
+
7
+ /** The word a badge's colour is chosen by: its text, lowercased, runs of other characters a `-`. */
8
+ export const tone = (s: string) =>
9
+ s
10
+ .toLowerCase()
11
+ .trim()
12
+ .replace(/[^a-z0-9]+/g, '-')
13
+ .replace(/^-|-$/g, '')
14
+
15
+ /** `:badge[done]`: a coloured dot and a word, inline wherever text goes. */
16
+ export function render(ctx: DirectiveContext) {
17
+ const text = ctx.labelText?.trim()
18
+ if (!text) return html``
19
+ // the label is HTML already; its plain text picks the colour
20
+ return html`<span class="wb-badge" data-badge="${tone(text)}">${raw(ctx.label ?? '')}</span>`
21
+ }
22
+
23
+ export default function badge(): Plugin {
24
+ return definePlugin({
25
+ name: 'badge',
26
+ public: builtinPublic('badge'),
27
+ blocks: {
28
+ badge: {
29
+ html: render,
30
+ style: 'style.css',
31
+ },
32
+ },
33
+ docs: () => fs.readFileSync(new URL('./README.md', import.meta.url), 'utf8'),
34
+ })
35
+ }