@bigmistqke/whiteboard 0.5.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 (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 +211 -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 +18 -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 +258 -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
@@ -1,9 +1,26 @@
1
- Windows: a header with a label, a button that fills the browser window with
1
+ A window: a header with a label, a button that fills the browser window with
2
2
  what it shows (the same button, or Esc, puts it back), and one that opens it on
3
- its own. `bare` leaves the header out; `wide` makes it wider than the text
4
- column; `height` (pixels or a CSS length) fixes its height, scrolling inside.
3
+ its own.
5
4
 
6
- **One image or video**, its label the title, ↗ opening the file:
5
+ **Any block goes in one with `compose=window`**: an image, a video, another
6
+ page, a diagram, a grid. Its label is the window's title (or `title="A
7
+ title"`, for a block without a label, such as a fence), and ↗ opens what it
8
+ shows on its own, an image's file or a page's address. `wide` makes it wider
9
+ than the text column.
10
+
11
+ ````markdown
12
+ ::image[The new onboarding]{src="onboarding.png" compose=window}
13
+
14
+ ```mermaid {compose=window title="How a page is served"}
15
+ graph LR; file --> server --> browser
16
+ ```
17
+
18
+ :::grid{cols=2 compose=window title="Two options"}
19
+ …
20
+ :::
21
+ ````
22
+
23
+ **One image or video**, without it, is just itself:
7
24
 
8
25
  ```markdown
9
26
  ::image[The new onboarding]{src="onboarding.png"}
@@ -13,17 +30,20 @@ column; `height` (pixels or a CSS length) fixes its height, scrolling inside.
13
30
 
14
31
  A video has its controls; `loop`, `autoplay` (which starts it muted, as
15
32
  browsers require) and `poster` are as for a `<video>`. A plain markdown image,
16
- `![…](shot.png)`, stays an image without a window.
33
+ `![…](shot.png)`, is the same as `::image` without it.
17
34
 
18
- **Any markdown**, in `:::window`: a diagram, a table, a screenshot with words
19
- under it. When it holds one image or video, ↗ opens that file.
35
+ **Any markdown**, in `:::window`: a table, a screenshot with words under it,
36
+ what has no block of its own. When it holds one image or video, ↗ opens that
37
+ file. `height` (pixels or a CSS length) fixes its height, scrolling inside.
20
38
 
21
- ````markdown
22
- :::window[How a page is served]{wide}
23
- ```mermaid
24
- graph LR; file --> server --> browser
25
- ```
39
+ ```markdown
40
+ :::window[What each one takes]
41
+ | block | what |
42
+ | --- | --- |
43
+ | `::image` | one image |
26
44
  :::
27
- ````
45
+ ```
28
46
 
29
- An iframe (`::iframe`) is a window around another page.
47
+ `compose=window` is this plugin's `compose`: any plugin can compose itself
48
+ around blocks the same way, and a block names several in order:
49
+ `compose=lightbox,window`.
@@ -15,7 +15,7 @@ function openOf(children) {
15
15
  const height = (value) => value && /^\d+(\.\d+)?$/.test(value) ? `${value}px` : value && /^\d+(\.\d+)?(px|em|rem|vh|svh|dvh)$/.test(value) ? value : void 0;
16
16
  /** http(s), protocol-relative, or a path on this server; never `javascript:` or `data:`. */
17
17
  const safeSrc = (src) => /^(https?:)?\/\//i.test(src) || !/^[a-z][a-z0-9+.-]*:/i.test(src);
18
- /** ::image[label]{src} and ::video[label]{src loop autoplay muted poster}: one file, in a window. */
18
+ /** ::image[label]{src} and ::video[label]{src loop autoplay muted poster}: one file (in a window with `compose=window`). */
19
19
  const media = (kind) => (ctx) => {
20
20
  const src = (ctx.attrs.src ?? "").trim();
21
21
  if (!src) return html`<pre class="wb-error">
@@ -24,28 +24,24 @@ ${kind}: needs a src, like ::${kind}[a label]{src="${kind === "image" ? "shot.pn
24
24
  const alt = ctx.labelText ?? ctx.attrs.alt ?? "";
25
25
  const flag = (name) => name in ctx.attrs && raw(` ${name}`);
26
26
  const poster = ctx.attrs.poster && safeSrc(ctx.attrs.poster) ? html` poster="${ctx.attrs.poster}"` : "";
27
- const body = kind === "image" ? html`<img src="${src}" alt="${alt}" loading="lazy" />` : html`<video
27
+ return kind === "image" ? html`<img src="${src}" alt="${alt}" loading="lazy" />` : html`<video
28
28
  src="${src}"
29
29
  controls${flag("loop")}${flag("autoplay")}${"autoplay" in ctx.attrs || "muted" in ctx.attrs ? raw(" muted") : ""}
30
30
  playsinline
31
31
  preload="metadata"
32
32
  ${poster}${alt ? html` aria-label="${alt}"` : ""}
33
33
  ></video>`;
34
- return windowFrame({
35
- label: ctx.label,
36
- open: src,
37
- wide: "wide" in ctx.attrs,
38
- bare: "bare" in ctx.attrs,
39
- height: height(ctx.attrs.height),
40
- body
41
- });
34
+ };
35
+ /** What an image or video shows on its own, for the ↗ of a window around it: its file. */
36
+ const mediaOpen = (ctx) => {
37
+ const src = (ctx.attrs.src ?? "").trim();
38
+ return src && safeSrc(src) ? src : null;
42
39
  };
43
40
  async function render(ctx) {
44
41
  return windowFrame({
45
42
  label: ctx.label,
46
43
  open: openOf(ctx.children),
47
44
  wide: "wide" in ctx.attrs,
48
- bare: "bare" in ctx.attrs,
49
45
  height: height(ctx.attrs.height),
50
46
  body: await ctx.toHtml(ctx.children)
51
47
  });
@@ -53,10 +49,22 @@ async function render(ctx) {
53
49
  function windows() {
54
50
  return definePlugin({
55
51
  name: "window",
52
+ compose: ({ children, label, open, attrs }) => windowFrame({
53
+ label: attrs.title ? html`${attrs.title}` : label,
54
+ open,
55
+ wide: "wide" in attrs,
56
+ body: children
57
+ }),
56
58
  blocks: {
57
59
  window: { html: render },
58
- image: { html: media("image") },
59
- video: { html: media("video") }
60
+ image: {
61
+ html: media("image"),
62
+ open: mediaOpen
63
+ },
64
+ video: {
65
+ html: media("video"),
66
+ open: mediaOpen
67
+ }
60
68
  },
61
69
  docs: () => fs.readFileSync(new URL("./README.md", import.meta.url), "utf8")
62
70
  });
package/dist/src/auth.js CHANGED
@@ -13,7 +13,8 @@ function projectToken(wb) {
13
13
  fs.writeFileSync(file, token + "\n", { mode: 384 });
14
14
  return token;
15
15
  }
16
- function createAuth(wb) {
16
+ /** `base`: the path the project is served under (see ServerOptions), which its cookie is kept to. */
17
+ function createAuth(wb, base = "") {
17
18
  const token = projectToken(wb);
18
19
  const same = (a, b) => typeof a === "string" && a.length === b.length && crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));
19
20
  const cookies = (req) => Object.fromEntries((req.headers.cookie ?? "").split(";").map((c) => c.trim().split("=")).filter(([k]) => k));
@@ -40,8 +41,8 @@ function createAuth(wb) {
40
41
  }
41
42
  const to = typeof q.to === "string" && q.to.startsWith("/") && !q.to.startsWith("//") ? q.to : "/";
42
43
  res.writeHead(302, {
43
- "set-cookie": `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000`,
44
- location: to
44
+ "set-cookie": `${COOKIE}=${token}; Path=${base || "/"}; HttpOnly; SameSite=Lax; Max-Age=31536000`,
45
+ location: base + to
45
46
  });
46
47
  res.end();
47
48
  return true;
@@ -565,6 +565,23 @@ details[open] > :last-child {
565
565
  text-overflow: ellipsis;
566
566
  white-space: nowrap;
567
567
  }
568
+ /* under a shared server, the other projects' pages, under each project's name */
569
+ .wb-elsewhere-group {
570
+ padding: var(--space-sm) var(--space-lg) var(--space-xs);
571
+ overflow: hidden;
572
+ text-overflow: ellipsis;
573
+ white-space: nowrap;
574
+ color: var(--muted);
575
+ font: var(--weight-strong) var(--ui-small)/var(--ui-line-height) var(--sans);
576
+ }
577
+ .wb-elsewhere-group:not(:first-child) {
578
+ margin-top: var(--space-xs);
579
+ border-top: var(--hairline) solid var(--border);
580
+ }
581
+ .wb-elsewhere-list {
582
+ max-height: min(70vh, 480px);
583
+ overflow-y: auto;
584
+ }
568
585
  .wb-nav .wb-elsewhere-list a:hover,
569
586
  .wb-nav .wb-elsewhere-list a:focus-visible {
570
587
  background: color-mix(in srgb, var(--accent) var(--tint-soft), transparent);
@@ -908,6 +925,49 @@ form[data-wb-just-sent] .wb-folded-change {
908
925
  font-size: 1.1rem;
909
926
  margin: 0;
910
927
  }
928
+ /* the shared server's overview (/): each project's pages under its name, as quiet as the
929
+ documents' heading above, and the projects without pages folded at the end */
930
+ .wb-project {
931
+ margin-top: calc(var(--rhythm) * 2.5);
932
+ }
933
+ .wb-project h2 {
934
+ font-size: 1.25rem;
935
+ margin: 0;
936
+ }
937
+ .wb-project > .wb-meta {
938
+ margin: var(--space-xs) 0 0;
939
+ }
940
+ .wb-folded-documents {
941
+ margin-top: var(--rhythm);
942
+ }
943
+ .wb-folded-documents > summary {
944
+ cursor: pointer;
945
+ font: var(--weight-strong) var(--ui-small)/var(--ui-line-height) var(--sans);
946
+ color: var(--muted);
947
+ }
948
+ .wb-folded-documents .wb-folder {
949
+ margin: var(--space-xs) 0 0 var(--space-xl);
950
+ }
951
+ .wb-folded-documents .wb-folder > summary {
952
+ cursor: pointer;
953
+ font: var(--ui-small)/var(--ui-line-height) var(--mono);
954
+ color: var(--muted);
955
+ }
956
+ .wb-folded-documents .wb-index li {
957
+ padding: var(--space-md) 0;
958
+ }
959
+ .wb-empty-projects {
960
+ margin-top: calc(var(--rhythm) * 2.5);
961
+ color: var(--muted);
962
+ font: var(--ui-small)/var(--ui-line-height) var(--sans);
963
+ }
964
+ .wb-empty-projects summary {
965
+ cursor: pointer;
966
+ }
967
+ .wb-empty-projects ul {
968
+ margin: var(--space-sm) 0 0;
969
+ padding-left: var(--space-xl);
970
+ }
911
971
  /* a list's heading with its sort control at the right (sort.ts) */
912
972
  .wb-list-head {
913
973
  display: flex;
@@ -1073,7 +1133,7 @@ main:has(+ .wb-orphans:not([hidden])) {
1073
1133
  .wb-window-body > :last-child {
1074
1134
  margin-bottom: 0;
1075
1135
  }
1076
- .wb-window-body:not(.wb-iframe-frame) {
1136
+ .wb-window-body {
1077
1137
  padding: var(--space-xl) var(--space-xl);
1078
1138
  overflow: auto;
1079
1139
  }
@@ -462,6 +462,17 @@ function viewBottom() {
462
462
  const inset = parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--wb-inset-bottom")) || 0;
463
463
  return Math.max(0, innerHeight - inset);
464
464
  }
465
+ const base = (() => {
466
+ try {
467
+ return JSON.parse(document.getElementById("wb-page")?.textContent ?? "{}");
468
+ } catch {
469
+ return {};
470
+ }
471
+ })().base ?? "";
472
+ /** A path of the project's server (`/api/events`) as this page requests it. */
473
+ const url = (path) => base + path;
474
+ /** A localStorage key, kept apart from other projects' on the same origin. */
475
+ const storageKey = (key) => base ? `${base}|${key}` : key;
465
476
  // src/client/page/fresh.ts
466
477
  const DWELL_MS = 600;
467
478
  const FADE_MS = 2500;
@@ -659,7 +670,7 @@ function trackInitial(main, page, api) {
659
670
  upToast.hide();
660
671
  downToast.hide();
661
672
  mainEl = main;
662
- storeKey = `wb-seen:${page}`;
673
+ storeKey = storageKey(`wb-seen:${page}`);
663
674
  const blocks = [...main.children];
664
675
  const sigs = blocks.map(signature);
665
676
  blocks.forEach((el, i) => sigOf.set(el, sigs[i]));
@@ -779,31 +790,65 @@ function open(yes) {
779
790
  toggle.setAttribute("aria-expanded", String(yes));
780
791
  }
781
792
  let current$1 = "";
793
+ /** This project's pages with something waiting, but this one. */
794
+ async function here() {
795
+ return (await (await fetch(url("/api/status"), { cache: "no-store" })).json()).filter((p) => p.page !== current$1).map((p) => ({
796
+ href: `${base}/${p.page.split("/").map(encodeURIComponent).join("/")}${WAITING_HASH}`,
797
+ title: p.title,
798
+ n: awaiting(p)
799
+ })).filter((w) => w.n > 0);
800
+ }
801
+ /**
802
+ * Under a shared server (see Entries in DESIGN.md): the other projects of this one's entry, by
803
+ * project, as the server's index has them; empty on a server of its own, or when it can't say.
804
+ */
805
+ async function others() {
806
+ if (!base) return [];
807
+ const entry = base.split("/")[1];
808
+ try {
809
+ const res = await fetch(`/api/index?entry=${encodeURIComponent(entry ?? "")}`, { cache: "no-store" });
810
+ if (!res.ok) return [];
811
+ return (await res.json()).filter((p) => p.base !== base).map((p) => ({
812
+ label: p.label,
813
+ pages: p.pages.map((x) => ({
814
+ href: `${x.url}${WAITING_HASH}`,
815
+ title: x.title,
816
+ n: x.open.length + x.unread
817
+ })).filter((w) => w.n > 0)
818
+ })).filter((g) => g.pages.length);
819
+ } catch {
820
+ return [];
821
+ }
822
+ }
782
823
  async function load() {
783
- let pages;
824
+ let mine;
825
+ let rest;
784
826
  try {
785
- pages = await (await fetch("/api/status", { cache: "no-store" })).json();
827
+ [mine, rest] = await Promise.all([here(), others()]);
786
828
  } catch {
787
829
  return;
788
830
  }
789
- const waiting = pages.filter((p) => p.page !== current$1).map((p) => ({
790
- p,
791
- n: awaiting(p)
792
- })).filter(({ n }) => n > 0);
793
- const total = waiting.reduce((sum, { n }) => sum + n, 0);
831
+ const all = [...mine, ...rest.flatMap((g) => g.pages)];
832
+ const total = all.reduce((sum, w) => sum + w.n, 0);
794
833
  box.hidden = total === 0;
795
834
  if (!total) open(false);
796
835
  count.textContent = String(total);
797
- toggle.title = awaitingLabel(total, ` on ${waiting.length === 1 ? "another page" : `${waiting.length} other pages`}`);
836
+ toggle.title = awaitingLabel(total, ` on ${all.length === 1 ? "another page" : `${all.length} other pages`}`);
798
837
  toggle.setAttribute("aria-label", toggle.title);
799
- list.replaceChildren(...waiting.map(({ p, n }) => {
838
+ const item = (w) => {
800
839
  const li = document.createElement("li");
801
840
  const a = document.createElement("a");
802
- a.href = `/${p.page.split("/").map(encodeURIComponent).join("/")}${WAITING_HASH}`;
803
- a.textContent = `${p.title} (${n})`;
841
+ a.href = w.href;
842
+ a.textContent = `${w.title} (${w.n})`;
804
843
  li.append(a);
805
844
  return li;
806
- }));
845
+ };
846
+ const heading = (text) => Object.assign(document.createElement("li"), {
847
+ className: "wb-elsewhere-group",
848
+ textContent: text,
849
+ title: text
850
+ });
851
+ list.replaceChildren(...rest.length && mine.length ? [heading("here")] : [], ...mine.map(item), ...rest.flatMap((g) => [heading(g.label), ...g.pages.map(item)]));
807
852
  }
808
853
  let timer = 0;
809
854
  const reload = () => {
@@ -829,6 +874,7 @@ function trackElsewhere(root, handle, core) {
829
874
  core.listeners.on(reload);
830
875
  handle.onChange(reload);
831
876
  load();
877
+ if (base) setInterval(reload, 5e3);
832
878
  }
833
879
  // src/client/page/waiting.ts
834
880
  const ORDER = STATES;
@@ -1063,7 +1109,7 @@ function trackLive(root, handle, api) {
1063
1109
  show();
1064
1110
  }
1065
1111
  // src/client/page/sort.ts
1066
- const KEY = (name) => `wb-sort:${name}`;
1112
+ const KEY = (name) => storageKey(`wb-sort:${name}`);
1067
1113
  function sortList(select) {
1068
1114
  const list = select.closest("section")?.querySelector("ul");
1069
1115
  if (!list) return;
@@ -0,0 +1,211 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ // src/entries.ts
5
+ /**
6
+ * The machine folder: the machine config, `config.json`. `$WHITEBOARD_HOME`, else
7
+ * `$XDG_CONFIG_HOME/whiteboard`, else `~/.config/whiteboard`. The shared server only reads it: what
8
+ * runs in the server (any project's plugins) must not change which folders it serves, nor how it is
9
+ * started (see Entries in DESIGN.md).
10
+ */
11
+ function machineDir(env = process.env) {
12
+ if (env.WHITEBOARD_HOME) return path.resolve(env.WHITEBOARD_HOME);
13
+ const xdg = env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
14
+ return path.join(xdg, "whiteboard");
15
+ }
16
+ /**
17
+ * The shared server's own folder, which it writes: its record (`server.json`), its log, the lock of
18
+ * a start, and the overview's project. `$WHITEBOARD_STATE`, else `state/` in `$WHITEBOARD_HOME`
19
+ * when that is set (a throwaway machine, in tests), else `$XDG_STATE_HOME/whiteboard`, else
20
+ * `~/.local/state/whiteboard`.
21
+ */
22
+ function stateDir(env = process.env) {
23
+ if (env.WHITEBOARD_STATE) return path.resolve(env.WHITEBOARD_STATE);
24
+ if (env.WHITEBOARD_HOME) return path.join(path.resolve(env.WHITEBOARD_HOME), "state");
25
+ const xdg = env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state");
26
+ return path.join(xdg, "whiteboard");
27
+ }
28
+ const machineConfigFile = (dir = machineDir()) => path.join(dir, "config.json");
29
+ const machineServerFile = (dir = stateDir()) => path.join(dir, "server.json");
30
+ const NAME = /^[a-z0-9][a-z0-9._-]*$/i;
31
+ const RESERVED = /* @__PURE__ */ new Set([
32
+ "api",
33
+ "_",
34
+ "-"
35
+ ]);
36
+ /** The machine config, checked; null when there is none. Throws on one that is malformed. */
37
+ function readMachineConfig(dir = machineDir()) {
38
+ const file = machineConfigFile(dir);
39
+ let text;
40
+ try {
41
+ text = fs.readFileSync(file, "utf8");
42
+ } catch {
43
+ return null;
44
+ }
45
+ let raw;
46
+ try {
47
+ raw = JSON.parse(text);
48
+ } catch (err) {
49
+ throw new Error(`${file}: ${err.message}`);
50
+ }
51
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`${file}: must be an object`);
52
+ const entries = {};
53
+ for (const [name, e] of Object.entries(raw.entries ?? {})) {
54
+ if (!NAME.test(name) || RESERVED.has(name)) throw new Error(`${file}: entry name ${JSON.stringify(name)}: letters, digits, . _ - only, and not api, _ or -`);
55
+ const list = (v, what) => {
56
+ if (v == null) return [];
57
+ if (!Array.isArray(v) || v.some((x) => typeof x !== "string")) throw new Error(`${file}: entries.${name}.${what} must be a list of globs`);
58
+ return v;
59
+ };
60
+ entries[name] = {
61
+ include: list(e?.include, "include"),
62
+ exclude: list(e?.exclude, "exclude")
63
+ };
64
+ }
65
+ const port = raw.port == null ? void 0 : Number(raw.port);
66
+ if (port !== void 0 && !(Number.isInteger(port) && port > 0 && port < 65536)) throw new Error(`${file}: port must be a port number`);
67
+ return {
68
+ ...port !== void 0 && { port },
69
+ entries
70
+ };
71
+ }
72
+ /** `~` and `~/…` as the home folder; the rest resolved, with / separators. */
73
+ const expandHome = (p, home = os.homedir()) => path.resolve(p.replace(/^~(?=$|[\\/])/, home)).split(path.sep).join("/");
74
+ const isGlobPart = (part) => /[*?[\]{}!]/.test(part);
75
+ const hasWhiteboard = (dir) => {
76
+ try {
77
+ return fs.statSync(path.join(dir, ".whiteboard")).isDirectory();
78
+ } catch {
79
+ return false;
80
+ }
81
+ };
82
+ /**
83
+ * Where a folder an include matched goes in its entry: its group, the include's last plain folder
84
+ * before the first wildcard (`worktrees`), and its name, what the wildcards matched (`cmux`). An
85
+ * include without wildcards is a group of one, named by the folder (`develop`).
86
+ */
87
+ function placeOf(include, dir) {
88
+ const parts = include.split("/");
89
+ const wild = parts.findIndex(isGlobPart);
90
+ if (wild < 0) return {
91
+ group: path.basename(dir),
92
+ name: ""
93
+ };
94
+ const literal = parts.slice(0, wild).join("/");
95
+ return {
96
+ group: parts[wild - 1] ?? "",
97
+ name: path.relative(literal, dir).split(path.sep).join("/")
98
+ };
99
+ }
100
+ /** Is this folder one an exclude glob leaves out (the folder itself, or one it is inside)? */
101
+ const excluded = (dir, excludes) => excludes.some((g) => {
102
+ for (let d = dir;; d = path.posix.dirname(d)) {
103
+ if (path.posix.matchesGlob(d, g)) return true;
104
+ if (path.posix.dirname(d) === d) return false;
105
+ }
106
+ });
107
+ /**
108
+ * Every project of the machine config's entries, in config order: the folders an include matches,
109
+ * no exclude matches, with a `.whiteboard/` folder. A folder two includes match is one project, the
110
+ * first include's. `home`: what `~` means (for tests).
111
+ */
112
+ function discover(config, { home = os.homedir() } = {}) {
113
+ const out = [];
114
+ const seen = /* @__PURE__ */ new Set();
115
+ const taken = /* @__PURE__ */ new Set();
116
+ for (const [entry, { include, exclude = [] }] of Object.entries(config.entries)) {
117
+ const excludes = exclude.map((g) => expandHome(g, home));
118
+ for (const glob of include.map((g) => expandHome(g, home))) {
119
+ const dirs = glob.split("/").some(isGlobPart) ? fs.globSync(glob).map((d) => path.resolve(d)).toSorted() : [glob];
120
+ for (const dir of dirs) {
121
+ const posix = dir.split(path.sep).join("/");
122
+ if (seen.has(dir) || excluded(posix, excludes) || !hasWhiteboard(dir)) continue;
123
+ seen.add(dir);
124
+ const place = placeOf(glob, posix);
125
+ const wanted = `/${entry}/${[place.group, place.name].filter(Boolean).join("/")}`;
126
+ let base = wanted;
127
+ let n = 1;
128
+ while (taken.has(base)) base = `${wanted}-${++n}`;
129
+ taken.add(base);
130
+ const name = n > 1 ? place.name ? `${place.name}-${n}` : "" : place.name;
131
+ out.push({
132
+ entry,
133
+ group: n > 1 && !place.name ? `${place.group}-${n}` : place.group,
134
+ name,
135
+ dir,
136
+ base
137
+ });
138
+ }
139
+ }
140
+ }
141
+ return out;
142
+ }
143
+ /** Does any include of the machine config match this folder, no exclude leaving it out? Cheap: no globbing of the disk. */
144
+ function matchesEntries(config, dir, { home = os.homedir() } = {}) {
145
+ const posix = path.resolve(dir).split(path.sep).join("/");
146
+ for (const [entry, { include, exclude = [] }] of Object.entries(config.entries)) {
147
+ const excludes = exclude.map((g) => expandHome(g, home));
148
+ if (include.some((g) => path.posix.matchesGlob(posix, expandHome(g, home))) && !excluded(posix, excludes)) return entry;
149
+ }
150
+ return null;
151
+ }
152
+ /**
153
+ * Follow the entries' projects: `onChange` gets the projects each time the set changes. Watching
154
+ * globs over the disk in general would mean watching every folder they could match, so it looks
155
+ * again every `interval` ms (cheap: a few folder listings), and at once when told (`rescan`).
156
+ */
157
+ function followEntries(read, onChange, { interval = 1500, home } = {}) {
158
+ let last = "";
159
+ let current = [];
160
+ const rescan = () => {
161
+ let projects = [];
162
+ try {
163
+ const config = read();
164
+ projects = config ? discover(config, { home }) : [];
165
+ } catch (err) {
166
+ console.error(`whiteboard: entries: ${err.message}`);
167
+ return current;
168
+ }
169
+ const key = JSON.stringify(projects);
170
+ if (key !== last) {
171
+ last = key;
172
+ current = projects;
173
+ onChange(projects);
174
+ }
175
+ return current;
176
+ };
177
+ rescan();
178
+ const timer = setInterval(rescan, interval);
179
+ timer.unref();
180
+ return {
181
+ rescan,
182
+ projects: () => current,
183
+ stop: () => clearInterval(timer)
184
+ };
185
+ }
186
+ /**
187
+ * The folders the entries' projects can be in: each include up to its first wildcard (all of it
188
+ * when it has none), without those inside another. What the shared server must be able to write,
189
+ * whatever folders appear below them later.
190
+ */
191
+ function entryFolders(config, { home = os.homedir() } = {}) {
192
+ const roots = Object.values(config.entries).flatMap((e) => e.include.map((g) => {
193
+ const parts = expandHome(g, home).split("/");
194
+ const wild = parts.findIndex(isGlobPart);
195
+ return wild < 0 ? parts.join("/") : parts.slice(0, wild).join("/") || "/";
196
+ }));
197
+ const unique = [...new Set(roots)].toSorted();
198
+ return unique.filter((r) => !unique.some((o) => o !== r && (r.startsWith(o + "/") || o === "/")));
199
+ }
200
+ /**
201
+ * What the shared server needs of the disk, for whatever boxes it in (a sandbox wrapper, see
202
+ * `whiteboard paths`): `write`, the entries' folders and its own state folder; `read`, the machine
203
+ * config and whiteboard itself.
204
+ */
205
+ function serverPaths(config, { home, packageDir, env = process.env }) {
206
+ return {
207
+ write: [...entryFolders(config, { home }), stateDir(env)],
208
+ read: [machineDir(env), packageDir]
209
+ };
210
+ }
211
+ export { discover, entryFolders, expandHome, followEntries, machineConfigFile, machineDir, machineServerFile, matchesEntries, readMachineConfig, serverPaths, stateDir };
@@ -264,7 +264,7 @@ function handOut(file, filter, onEvent, options = {}) {
264
264
  const hand = (e) => {
265
265
  onEvent(e);
266
266
  pick(file, e);
267
- return ++got < count;
267
+ return ++got < count && !signal?.aborted;
268
268
  };
269
269
  const left = /* @__PURE__ */ new Map();
270
270
  const offer = (e) => {