@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
@@ -0,0 +1,191 @@
1
+ // A page as the browser gets it: the page's render, the plugins' parts (markup for <head> and
2
+ // <body>, their browser modules, notices of those that failed), and the handoff the browser runtime
3
+ // starts from. Put together here once, for a page the server serves and for one `whiteboard build`
4
+ // writes; what differs is told: how a file is addressed, whether the page is live, which plugins
5
+ // are left out, where a failing plugin is said.
6
+ import path from 'node:path'
7
+ import type { IncomingMessage } from 'node:http'
8
+ import { html, raw, type Html } from './html.ts'
9
+ import { PACKAGE_DIR } from './package.ts'
10
+ import type { MountedRoute } from './plugins.ts'
11
+ import type { Plugin, PluginHooks, Rendered, SlotName, StoredPage } from './define.ts'
12
+
13
+ /** The browser runtime, built by build.ts. */
14
+ export const RUNTIME = path.join(PACKAGE_DIR, 'dist', 'client', 'runtime.js')
15
+ /** The page in the browser (markdown live: morphing, blocks' islands, forms' marks), built by build.ts. */
16
+ export const PAGE_CLIENT = path.join(PACKAGE_DIR, 'dist', 'src', 'client', 'page', 'main.js')
17
+
18
+ /** A plugin once set up: what its setup returned, its mounted routes, or why it failed. */
19
+ export interface SetUp extends PluginHooks {
20
+ name: string
21
+ table: MountedRoute[]
22
+ plugin: Plugin
23
+ error?: Error
24
+ }
25
+
26
+ /** A render as the document takes it. `page`: whether the page's browser part runs (not on raw text). */
27
+ export interface Render {
28
+ page: boolean
29
+ out: Rendered
30
+ notices: string[]
31
+ }
32
+
33
+ /** The slots at the end of <body>, in the order they are there; `corner` is the page's dock. */
34
+ const BODY_SLOTS = ['aside', 'bottom', 'overlay'] as const
35
+
36
+ /** A plugin's markup in a slot. */
37
+ type Slotted = { name: string; html: Html }
38
+
39
+ /** What the plugins add to a page. */
40
+ export interface PageParts {
41
+ head: Html[]
42
+ /** each plugin's markup in each slot, in plugin order */
43
+ slots: { [K in Exclude<SlotName, 'header'>]: Slotted[] }
44
+ /** their browser modules, which the runtime imports after the page's */
45
+ clients: { name: string; client: string }[]
46
+ /** the event types that, from the agent, are messages for the reader (EventSpec.forReader) */
47
+ messages: string[]
48
+ }
49
+
50
+ /**
51
+ * What the plugins add to a page: each one's markup for the slots (`slots`, asked with the browser's request, or
52
+ * null for a page no browser asked for), and its browser module. One that failed to start or fails
53
+ * here is left out and told to `failed`; so are those in `leaveOut` (a build's skip), silently.
54
+ */
55
+ export async function pluginParts(
56
+ hooks: SetUp[],
57
+ req: IncomingMessage | null,
58
+ {
59
+ asset,
60
+ messages,
61
+ leaveOut = new Set(),
62
+ failed,
63
+ }: {
64
+ asset(ref: string | URL): string
65
+ messages: string[]
66
+ leaveOut?: ReadonlySet<string>
67
+ failed(message: string): void
68
+ },
69
+ ): Promise<PageParts> {
70
+ const included = hooks.filter(h => !leaveOut.has(h.name))
71
+ for (const h of included) if (h.error) failed(`plugin "${h.name}" failed to start: ${h.error.message}`)
72
+ const working = included.filter(h => !h.error)
73
+ const parts = await Promise.all(
74
+ working.map(async h => {
75
+ try {
76
+ return (await h.slots?.(req)) ?? null
77
+ } catch (err) {
78
+ failed(`plugin "${h.name}" failed on this page: ${(err as Error).message}`)
79
+ return null
80
+ }
81
+ }),
82
+ )
83
+ const slotted = (slot: Exclude<SlotName, 'header'>): Slotted[] =>
84
+ working.flatMap((h, i) => {
85
+ const markup = parts[i]?.[slot]
86
+ return markup == null ? [] : [{ name: h.name, html: raw(String(markup)) }]
87
+ })
88
+ return {
89
+ head: parts.map(x => raw(String(x?.head ?? ''))),
90
+ slots: {
91
+ aside: slotted('aside'),
92
+ bottom: slotted('bottom'),
93
+ overlay: slotted('overlay'),
94
+ corner: slotted('corner'),
95
+ },
96
+ clients: working.filter(h => h.client).map(h => ({ name: h.name, client: asset(h.client!) })),
97
+ messages,
98
+ }
99
+ }
100
+
101
+ /** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
102
+ export const frontmatterOf = (page: StoredPage): Record<string, unknown> =>
103
+ page.kind === 'page' ? page.frontmatter : {}
104
+
105
+ /** JSON made safe inside a <script>. */
106
+ const json = (s: unknown) => JSON.stringify(s).replace(/</g, '\\u003c')
107
+
108
+ // the page's corner (the corner slot): the one thing the core puts on every page, empty, for the
109
+ // page's and the plugins' floating buttons and toasts; above what covers the bottom of the window.
110
+ // Above the page and what floats on it (comment threads: 20), under what fills the window (a
111
+ // maximized frame: 40, a lightbox or the terminal drawer: 50)
112
+ const DOCK_STYLE =
113
+ '#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:not(:has(> :not(:empty))){display:none}' +
114
+ // the slots (SlotName) and each plugin's element in one: laid out as what is in them says, as if
115
+ // that were where the slot is (a fixed drawer, a panel, a button in the header bar)
116
+ '[data-wb-slot]:not(#wb-dock),[data-wb-slot]>[data-plugin]{display:contents}' +
117
+ // toasts (api.toast): labels in the corner, in the page's theme colours where it has them
118
+ '.wb-toasts{display:flex;flex-direction:column;align-items:flex-end;gap:6px}.wb-toasts:empty{display:none}' +
119
+ '.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)}' +
120
+ '.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}' +
121
+ // where an agent scrolled the page to, lit up a moment
122
+ '@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}' +
123
+ '.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}' +
124
+ // a toast's details (ToastOptions.details): a ▸ on its line, unfolding them under it
125
+ '.wb-toast{max-width:min(24rem,calc(100vw - 32px));text-align:left}.wb-toast-more{margin:0 -4px 0 -2px;padding:0 4px;opacity:.75}.wb-toast-more:hover{opacity:1}' +
126
+ '.wb-toast[data-open]{flex-wrap:wrap;border-radius:12px}.wb-toast-details{flex-basis:100%;padding:2px 0 3px;font-weight:400;cursor:text}.wb-toast-details[hidden]{display:none}'
127
+
128
+ /** How a page is put out: by the server (live) or by a build (a file with no server behind it). */
129
+ export interface Output {
130
+ /** a page the server serves: events, listeners and updates; false for a built page */
131
+ live: boolean
132
+ /** what the page's own requests start with (ServerOptions.base); '' for a built page */
133
+ base: string
134
+ /** the address of a file the page loads */
135
+ asset(ref: string | URL): string
136
+ /** the address of the browser runtime */
137
+ runtime: string
138
+ /** the title when the render has none and the page no id: the project's name */
139
+ title: string
140
+ /** what the browser runs and how it looks, compared again when the live channel is back */
141
+ stamps?: { code: string; style: string }
142
+ }
143
+
144
+ /** Each plugin's own element in a slot, with what it rendered there. */
145
+ const slotted = (list: Slotted[]) => list.map(x => html`<div data-plugin="${x.name}">${x.html}</div>`)
146
+
147
+ /** A page as a document: the render, the plugins' parts, and the handoff for the browser runtime. */
148
+ export function pageDocument(
149
+ page: StoredPage,
150
+ { page: rendered, out, notices }: Render,
151
+ parts: PageParts,
152
+ o: Output,
153
+ ): string {
154
+ const handoff = {
155
+ id: page.id,
156
+ kind: page.kind,
157
+ live: o.live,
158
+ base: o.base,
159
+ client: rendered ? o.asset(PAGE_CLIENT) : null,
160
+ data: out.data ?? null,
161
+ frontmatter: frontmatterOf(page),
162
+ plugins: parts.clients,
163
+ messages: parts.messages,
164
+ ...(o.stamps && { stamps: o.stamps }),
165
+ }
166
+ // the page's head and html are HTML already; the handoff is JSON made safe for a script tag
167
+ return String(
168
+ html`<!doctype html>
169
+ <html lang="en">
170
+ <head>
171
+ <meta charset="utf-8" />
172
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
173
+ <title>${out.title || page.id || o.title}</title>
174
+ <style>
175
+ ${DOCK_STYLE}
176
+ </style>
177
+ ${raw(String(out.head ?? ''))}${parts.head}
178
+ </head>
179
+ <body data-page="${page.id}" data-kind="${page.kind}">
180
+ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
181
+ <div id="wb-root">${raw(String(out.html))}</div>
182
+ <div id="wb-dock" data-wb-slot="corner">${slotted(parts.slots.corner)}</div>
183
+ <script type="application/json" id="wb-page">
184
+ ${raw(json(handoff))}
185
+ </script>
186
+ <script type="module" src="${o.runtime}"></script>
187
+ ${BODY_SLOTS.map(name => html`<div data-wb-slot="${name}">${slotted(parts.slots[name])}</div>`)}
188
+ </body>
189
+ </html>`,
190
+ )
191
+ }
package/src/events.ts CHANGED
@@ -9,12 +9,14 @@
9
9
  import fs from 'node:fs'
10
10
  import crypto from 'node:crypto'
11
11
  import type { WbEvent } from './define.ts'
12
- import { fromReader } from './status.ts'
12
+ import { CLAIM, PICKED, fromReader, pickedUp } from './status.ts'
13
13
 
14
- export { fromReader }
14
+ export { CLAIM, PICKED, fromReader, pickedUp }
15
15
 
16
16
  /** What is appended: the id and time are added. */
17
17
  export interface EventInput {
18
+ /** the id the browser gave it, so a send it retries is appended once (see isEventId); else a new one */
19
+ id?: unknown
18
20
  page?: unknown
19
21
  type?: unknown
20
22
  action?: string | null
@@ -29,14 +31,12 @@ export interface EventFilter {
29
31
  exact?: boolean
30
32
  }
31
33
 
32
- /**
33
- * The type of the event `whiteboard new` appends when an agent session creates a page:
34
- * `{ session }`. The colon keeps it apart from form names, which are event types too.
35
- */
36
- export const CLAIM = 'whiteboard:claim'
37
-
38
34
  // ---- primitives ----------------------------------------------------------------------------------
39
35
 
36
+ /** An event id as the log has them: the time in base 36, a dash, random hex. */
37
+ export const isEventId = (id: unknown): id is string =>
38
+ typeof id === 'string' && /^[0-9a-z]{6,12}-[0-9a-f]{6,32}$/.test(id)
39
+
40
40
  /**
41
41
  * Append one event; `action` is the button that submitted a form, null for anything else. `from`
42
42
  * is set only for events the command line writes ('cli'), so that waits skip them and pages can
@@ -44,7 +44,7 @@ export const CLAIM = 'whiteboard:claim'
44
44
  */
45
45
  export function appendEvent(file: string, input: EventInput, from: 'cli' | null = null): WbEvent {
46
46
  const event: WbEvent = {
47
- id: `${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`,
47
+ id: isEventId(input.id) ? input.id : `${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`,
48
48
  ts: new Date().toISOString(),
49
49
  page: String(input.page ?? ''),
50
50
  type: String(input.type ?? ''),
@@ -264,14 +264,6 @@ export function matches(event: WbEvent, { page, type, exact }: EventFilter = {})
264
264
  // is the only record: a wait that starts hands out the matching events nobody picked up yet,
265
265
  // whatever its filter, and pages show the same events as picked up.
266
266
 
267
- /** The type of the event that says another event was handed to an agent: `{ event: <its id> }`. */
268
- export const PICKED = 'whiteboard:picked'
269
-
270
- /** The ids of the events that were picked up. Only the command line's picks count. */
271
- export function pickedUp(events: WbEvent[]): Set<string> {
272
- return new Set(events.filter(e => e.type === PICKED && !fromReader(e)).map(e => String(e.data?.event)))
273
- }
274
-
275
267
  /** Record that `event` was handed to an agent: from then on it counts as picked up. */
276
268
  export function pick(file: string, event: WbEvent): WbEvent {
277
269
  return appendEvent(file, { page: event.page, type: PICKED, data: { event: event.id } }, 'cli')
@@ -306,6 +298,12 @@ export interface HandOutOptions {
306
298
  */
307
299
  skip?: (event: WbEvent) => boolean
308
300
  recheck?: (again: () => void) => void
301
+ /**
302
+ * Hand out only what nobody picked up by the time it is offered (the fallback: an answer another
303
+ * listener took is not its, even when it sees it only after that one stopped listening). Without
304
+ * it, a new event is handed out also when another running hand-out got it too.
305
+ */
306
+ unpicked?: boolean
309
307
  }
310
308
 
311
309
  /**
@@ -333,6 +331,7 @@ export function handOut(
333
331
  forAgent: isForAgent = forAgent(),
334
332
  skip,
335
333
  recheck,
334
+ unpicked = false,
336
335
  } = options
337
336
  return new Promise(resolve => {
338
337
  let got = 0
@@ -355,6 +354,8 @@ export function handOut(
355
354
  const left = new Map<string, WbEvent>()
356
355
  // false once enough were handed out; a left event is kept to look at again
357
356
  const offer = (e: WbEvent) => {
357
+ // the log as it is now: a pick is appended right after the event it names
358
+ if (unpicked && pickedUp(read(file).events).has(e.id)) return true
358
359
  if (skip?.(e)) {
359
360
  left.set(e.id, e)
360
361
  return true
package/src/hub.ts CHANGED
@@ -12,7 +12,8 @@
12
12
  // /api/shutdown POST { version }: a newer whiteboard takes over; an older one is refused
13
13
  // /api/listen?entry=<name>&command=wait|watch
14
14
  // the fallback of a whole entry, for as long as the connection is open: one per
15
- // entry, held on every page of its projects, also those that appear meanwhile
15
+ // entry, held on every page of its projects, also those that appear meanwhile;
16
+ // its stream is told each project with who listens there (listeners.ts)
16
17
  //
17
18
  // A project's server is made when the project is found and closed when it goes, so a project
18
19
  // appears and disappears without a restart. Each keeps its own state, config and log, as it would
@@ -20,11 +21,13 @@
20
21
  import fs from 'node:fs'
21
22
  import path from 'node:path'
22
23
  import type { IncomingMessage, ServerResponse } from 'node:http'
24
+ import type { Duplex } from 'node:stream'
23
25
  import { project as projectAt, type Project } from './config.ts'
24
26
  import { followEntries, machineDir, readMachineConfig, stateDir, type EntryProject } from './entries.ts'
25
27
  import { compareVersions, VERSION } from './package.ts'
26
28
  import { createServer, type WhiteboardServer } from './server.ts'
27
29
  import type { Listener, PageStatus } from './define.ts'
30
+ import { holdStream, listenerOf } from './listeners.ts'
28
31
 
29
32
  export interface HubOptions {
30
33
  /** the machine folder (its config.json), which the server only reads; default machineDir() */
@@ -82,6 +85,8 @@ export interface IndexProject {
82
85
 
83
86
  export interface Hub {
84
87
  handle(req: IncomingMessage, res: ServerResponse): Promise<void>
88
+ /** an upgrade request (the HTTP server's 'upgrade' event): a page's live channel */
89
+ upgrade(req: IncomingMessage, conn: Duplex, head: Buffer): void
85
90
  /** the projects it serves now */
86
91
  projects(): EntryProject[]
87
92
  /** look for projects coming and going now */
@@ -98,8 +103,20 @@ export function createHub({
98
103
  version = VERSION,
99
104
  }: HubOptions = {}): Hub {
100
105
  const served = new Map<string, Served>()
101
- // each entry's fallback, while one runs: the listener its projects hold
102
- const fallbacks = new Map<string, Listener>()
106
+ // each entry's fallback, while one runs: the listener its projects hold, and what tells its stream
107
+ const fallbacks = new Map<string, { listener: Listener; tell: () => void }>()
108
+ /** An entry's fallback held on one of its projects, followed there; false when the project refuses it. */
109
+ function hold(s: Served, fb: { listener: Listener; tell: () => void }): boolean {
110
+ const off = s.server.addListener(fb.listener)
111
+ if (!off) return false
112
+ const unfollow = s.server.onListeners(() => fb.tell())
113
+ s.fallback = () => {
114
+ unfollow()
115
+ off()
116
+ delete s.fallback
117
+ }
118
+ return true
119
+ }
103
120
 
104
121
  function sync(projects: EntryProject[]) {
105
122
  // projects come and go: the overview lists them
@@ -107,6 +124,7 @@ export function createHub({
107
124
  const wanted = new Map(projects.map(p => [`${p.base}\n${p.dir}`, p]))
108
125
  for (const [key, s] of served)
109
126
  if (!wanted.has(key)) {
127
+ s.fallback?.()
110
128
  s.server.close()
111
129
  served.delete(key)
112
130
  console.log(`whiteboard: ${s.base} is gone (${s.dir})`)
@@ -119,12 +137,16 @@ export function createHub({
119
137
  base: p.base,
120
138
  entry: p.entry,
121
139
  label: [p.group, p.name].filter(Boolean).join(' › '),
122
- onChange: () => touch(),
140
+ onChange: () => changed(p.base),
123
141
  })
124
- const fallback = fallbacks.get(p.entry)
125
- served.set(key, { ...p, project, server, ...(fallback && { fallback: server.addListener(fallback) }) })
142
+ const s: Served = { ...p, project, server }
143
+ served.set(key, s)
144
+ const fb = fallbacks.get(p.entry)
145
+ if (fb) hold(s, fb)
126
146
  console.log(`whiteboard: ${p.base} → ${p.dir}`)
127
147
  }
148
+ // an entry's fallback follows its projects coming and going
149
+ for (const fb of fallbacks.values()) fb.tell()
128
150
  }
129
151
 
130
152
  // the overview at /: a project of the shared server's own, in the machine folder, whose overview
@@ -153,9 +175,21 @@ export function createHub({
153
175
  })
154
176
  // what the overview lists changed: told a moment later, once for several changes
155
177
  let touching: ReturnType<typeof setTimeout> | undefined
178
+ // the projects that changed since: each other project's open pages are told, for their menu of
179
+ // what waits elsewhere (pushed, so no page has to ask every project now and then)
180
+ const changes = new Set<string>()
156
181
  const touch = () => {
157
182
  clearTimeout(touching)
158
- touching = setTimeout(() => root.touch(), 150)
183
+ touching = setTimeout(() => {
184
+ root.touch()
185
+ const from = [...changes]
186
+ changes.clear()
187
+ for (const s of served.values()) if (from.some(b => b !== s.base)) s.server.elsewhere()
188
+ }, 150)
189
+ }
190
+ const changed = (base: string) => {
191
+ changes.add(base)
192
+ touch()
159
193
  }
160
194
 
161
195
  const entries = followEntries(() => readMachineConfig(dir), sync, { interval, home })
@@ -258,78 +292,90 @@ export function createHub({
258
292
  res.writeHead(204)
259
293
  return void res.end()
260
294
  }
261
- let s = owner(p)
262
- let rest: string
263
- if (s) {
264
- // the project's overview is at its folder: /rg/develop/
265
- if (p === s.base) {
266
- res.writeHead(302, { location: `${s.base}/${url.search}` })
267
- return void res.end()
268
- }
269
- // the path less the project's part, encoded again for the project's server to decode
270
- rest = p.slice(s.base.length).split('/').map(encodeURIComponent).join('/') + url.search
271
- } else {
272
- // A plugin's browser module that writes `/api/<name>/…` itself, from before api.url: the page
273
- // that asked is in the Referer, and the request is that project's.
274
- const from = req.headers.referer ? new URL(req.headers.referer).pathname : null
275
- s = /^\/(api|_)\//.test(p) && from ? owner(decodeURIComponent(from)) : null
276
- // anything else outside the projects is the overview's: /, its page, its files and live channel
277
- if (!s) return root.handle(req, res)
278
- rest = (req.url ?? '/').replace(/^\/+/, '/')
295
+ // the project's overview is at its folder: /rg/develop/
296
+ const s = owner(p)
297
+ if (s && p === s.base) {
298
+ res.writeHead(302, { location: `${s.base}/${url.search}` })
299
+ return void res.end()
279
300
  }
280
- req.url = rest
281
- return s.server.handle(req, res)
301
+ return route(req, p, url).handle(req, res)
282
302
  } catch (err) {
283
303
  console.error(err)
284
304
  send(res, 500, String((err as Error)?.stack || err), 'text/plain')
285
305
  }
286
306
  }
287
307
 
308
+ /**
309
+ * Whose request this is: a project's (`req.url` made the path within it), or else the overview's.
310
+ */
311
+ function route(req: IncomingMessage, p: string, url: URL): WhiteboardServer {
312
+ let s = owner(p)
313
+ if (s) {
314
+ // the path less the project's part, encoded again for the project's server to decode
315
+ req.url = p.slice(s.base.length).split('/').map(encodeURIComponent).join('/') + url.search
316
+ return s.server
317
+ }
318
+ // A plugin's browser module that writes `/api/<name>/…` itself, from before api.url: the page
319
+ // that asked is in the Referer, and the request is that project's.
320
+ const from = req.headers.referer ? new URL(req.headers.referer).pathname : null
321
+ s = /^\/(api|_)\//.test(p) && from ? owner(decodeURIComponent(from)) : null
322
+ req.url = s ? (req.url ?? '/').replace(/^\/+/, '/') : req.url
323
+ // anything else outside the projects is the overview's: /, its page, its files and live channel
324
+ return s ? s.server : root
325
+ }
326
+
327
+ /** An upgrade (a page's live channel), routed as a request is. */
328
+ function upgrade(req: IncomingMessage, conn: Duplex, head: Buffer) {
329
+ try {
330
+ const url = new URL((req.url ?? '/').replace(/^\/+/, '/'), 'http://localhost')
331
+ route(req, decodeURIComponent(url.pathname), url).upgrade(req, conn, head)
332
+ } catch (err) {
333
+ console.error(err)
334
+ conn.destroy()
335
+ }
336
+ }
337
+
288
338
  /**
289
339
  * The fallback of a whole entry (a `wait` or `watch` without --page in one of its projects): one
290
340
  * per entry, refused (409) while another runs, or while a project of it has a fallback of its own
291
341
  * (from a whiteboard before entries). Each project holds it as a listener, so its pages say an
292
- * agent listens; the command itself reads the projects' logs.
342
+ * agent listens; its stream is told each project of the entry with who listens there, at once and
343
+ * whenever that or the projects change. The command itself reads the projects' logs.
293
344
  */
294
345
  function listenEntry(req: IncomingMessage, res: ServerResponse, q: URLSearchParams) {
295
346
  const entry = q.get('entry')!
296
- const projects = [...served.values()].filter(s => s.entry === entry)
297
347
  if (fallbacks.has(entry)) return sendJson(res, 409, { error: `another agent is the fallback of ${entry} already` })
298
- const own = projects.find(s => s.server.listeners().some(x => x.fallback))
299
- if (own)
300
- return sendJson(res, 409, {
301
- error: `${own.base} has a fallback of its own already (a wait or watch without --page)`,
302
- })
303
- const l: Listener = {
304
- page: '',
305
- type: q.get('type') || null,
306
- command: q.get('command') === 'wait' ? 'wait' : 'watch',
307
- fallback: true,
308
- }
309
- fallbacks.set(entry, l)
310
- for (const s of projects) s.fallback = s.server.addListener(l)
311
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
312
- res.write(': listening\n\n')
313
- const ping = setInterval(() => res.write(': ping\n\n'), 25000)
314
- const end = () => {
315
- clearInterval(ping)
316
- if (fallbacks.get(entry) !== l) return
317
- fallbacks.delete(entry)
318
- for (const s of served.values()) {
319
- s.fallback?.()
320
- delete s.fallback
348
+ const mine = () => [...served.values()].filter(s => s.entry === entry)
349
+ const fb = { listener: listenerOf(q, true), tell: () => {} }
350
+ const held: Served[] = []
351
+ for (const s of mine()) {
352
+ if (!hold(s, fb)) {
353
+ for (const h of held) h.fallback?.()
354
+ return sendJson(res, 409, {
355
+ error: `${s.base} has a fallback of its own already (a wait or watch without --page)`,
356
+ })
321
357
  }
358
+ held.push(s)
322
359
  }
323
- closers.add(() => {
324
- end()
325
- res.end()
360
+ fallbacks.set(entry, fb)
361
+ const stream = holdStream(req, res, () => {
362
+ closers.delete(stream.end)
363
+ if (fallbacks.get(entry) !== fb) return
364
+ fallbacks.delete(entry)
365
+ for (const s of mine()) s.fallback?.()
326
366
  })
327
- req.on('close', end)
367
+ fb.tell = () =>
368
+ stream.send('listeners', {
369
+ projects: mine().map(s => ({ dir: s.dir, base: s.base, listeners: s.server.listeners() })),
370
+ })
371
+ closers.add(stream.end)
372
+ fb.tell()
328
373
  }
329
374
  const closers = new Set<() => void>()
330
375
 
331
376
  return {
332
377
  handle,
378
+ upgrade,
333
379
  projects: list,
334
380
  rescan() {
335
381
  entries.rescan()
package/src/listen.ts ADDED
@@ -0,0 +1,125 @@
1
+ // The command's side of listening (`whiteboard wait` and `watch`): holding a listener at a server,
2
+ // and the fallback. A wait or watch on a page registers at its project's server first and only then
3
+ // reads the log, so from its first answer on the server knows it listens. A fallback (one without
4
+ // --page) registers too, and its stream is told who else listens on each project it covers
5
+ // (listeners.ts): a project's own server names that project, the shared server each project of the
6
+ // entry. The fallback hands out from each project's log what no other listener there would take.
7
+ import http from 'node:http'
8
+ import type { Listener } from './define.ts'
9
+ import type { HandOutOptions } from './events.ts'
10
+ import type { Followed, Snapshot } from './listeners.ts'
11
+ import { takenByOther } from './status.ts'
12
+
13
+ export interface ListenOptions {
14
+ /** the server's base URL; null (or a throw) while none runs, tried again */
15
+ at: () => Promise<string | null>
16
+ /** what to ask /api/listen for: page, type, command, and `fallback` or `entry` */
17
+ query: Record<string, string>
18
+ /** a fallback: who listens on each project it covers, at once and on every change */
19
+ onSnapshot?: (snapshot: Snapshot) => void
20
+ /** the server refused it (another fallback holds it): the reason it gave */
21
+ onRefused: (reason: string) => void
22
+ }
23
+
24
+ /**
25
+ * Hold a listener at a server for as long as the process runs, and again after the server restarts.
26
+ * Resolves once the server holds it; with `orNone`, also after a first try that found no server
27
+ * running (a wait reads the log all the same, and registers once one appears).
28
+ */
29
+ export function listen({ at, query, onSnapshot, onRefused }: ListenOptions, { orNone = false } = {}): Promise<void> {
30
+ return new Promise(settled => {
31
+ const connect = async () => {
32
+ let base: string | null = null
33
+ try {
34
+ base = await at()
35
+ } catch {
36
+ /* none runs */
37
+ }
38
+ if (!base) {
39
+ if (orNone) settled()
40
+ return setTimeout(connect, 2000).unref()
41
+ }
42
+ let again = false
43
+ const retry = (ms: number) => {
44
+ if (!again) {
45
+ again = true
46
+ setTimeout(connect, ms).unref()
47
+ }
48
+ }
49
+ const req = http.get(`${base}/api/listen?${new URLSearchParams(query)}`, res => {
50
+ res.setEncoding('utf8')
51
+ if (res.statusCode === 409) {
52
+ let body = ''
53
+ res.on('data', (d: string) => (body += d))
54
+ res.on('end', () => {
55
+ let reason = ''
56
+ try {
57
+ reason = JSON.parse(body).error ?? ''
58
+ } catch {}
59
+ onRefused(reason || 'another agent is the fallback already')
60
+ })
61
+ return
62
+ }
63
+ settled()
64
+ let buf = ''
65
+ res.on('data', (chunk: string) => {
66
+ buf += chunk
67
+ // an event ends at a blank line: `event: listeners` and its data
68
+ let end
69
+ while ((end = buf.indexOf('\n\n')) >= 0) {
70
+ const block = buf.slice(0, end)
71
+ buf = buf.slice(end + 2)
72
+ const event = /^event: (.*)$/m.exec(block)?.[1]
73
+ const data = /^data: (.*)$/m.exec(block)?.[1]
74
+ if (event === 'listeners' && data && onSnapshot) onSnapshot(JSON.parse(data) as Snapshot)
75
+ }
76
+ })
77
+ res.on('close', () => retry(1000))
78
+ })
79
+ req.on('error', () => retry(2000))
80
+ // the connection alone does not keep the command running
81
+ req.on('socket', socket => socket.unref())
82
+ }
83
+ void connect()
84
+ })
85
+ }
86
+
87
+ /** What the fallback hands a project's hand-out: what it leaves to others, and when to look again. */
88
+ export type FallbackHandOut = Required<Pick<HandOutOptions, 'skip' | 'recheck' | 'signal' | 'unpicked'>>
89
+
90
+ /**
91
+ * The fallback over the projects a server names: `start` is called once for each project as it
92
+ * appears, to hand out from its log what no other listener there takes (`skip`) and nobody picked
93
+ * up (`unpicked`), looked at again (`recheck`) whenever who listens there changes; a project no
94
+ * longer named is stopped (`signal`).
95
+ * @returns what takes each snapshot the server sends
96
+ */
97
+ export function fallback(start: (project: Followed, handOut: FallbackHandOut) => void): (snapshot: Snapshot) => void {
98
+ const followed = new Map<string, { listeners: Listener[]; stop: AbortController; recheck: () => void }>()
99
+ return ({ projects }) => {
100
+ for (const p of projects) {
101
+ const known = followed.get(p.dir)
102
+ if (known) {
103
+ known.listeners = p.listeners
104
+ known.recheck()
105
+ continue
106
+ }
107
+ const f = { listeners: p.listeners, stop: new AbortController(), recheck: () => {} }
108
+ followed.set(p.dir, f)
109
+ start(p, {
110
+ skip: e => takenByOther(f.listeners, e),
111
+ recheck: again => {
112
+ f.recheck = again
113
+ },
114
+ signal: f.stop.signal,
115
+ // what another listener picked up is never the fallback's, however late it sees it
116
+ unpicked: true,
117
+ })
118
+ }
119
+ for (const [dir, f] of followed)
120
+ if (!projects.some(p => p.dir === dir)) {
121
+ f.stop.abort()
122
+ followed.delete(dir)
123
+ }
124
+ }
125
+ }