@bigmistqke/whiteboard 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +125 -25
  2. package/bin/whiteboard.ts +299 -16
  3. package/dist/bin/whiteboard.js +247 -17
  4. package/dist/client/runtime.js +22 -10
  5. package/dist/plugins/ansi/README.md +36 -0
  6. package/dist/plugins/ansi/index.js +64 -0
  7. package/dist/plugins/ansi/public/style.css +28 -0
  8. package/dist/plugins/badge/README.md +28 -0
  9. package/dist/plugins/badge/index.js +24 -0
  10. package/dist/plugins/badge/public/style.css +30 -0
  11. package/dist/plugins/chat/public/style.css +7 -2
  12. package/dist/plugins/code/README.md +4 -2
  13. package/dist/plugins/code/diff.js +12 -2
  14. package/dist/plugins/grid/README.md +12 -12
  15. package/dist/plugins/grid/index.js +7 -19
  16. package/dist/plugins/grid/public/style.css +4 -33
  17. package/dist/plugins/iframe/README.md +7 -7
  18. package/dist/plugins/iframe/index.js +11 -11
  19. package/dist/plugins/iframe/public/style.css +15 -0
  20. package/dist/plugins/index.js +7 -3
  21. package/dist/plugins/lightbox/README.md +22 -0
  22. package/dist/plugins/lightbox/index.js +20 -0
  23. package/dist/plugins/lightbox/public/client.js +4 -0
  24. package/dist/plugins/lightbox/public/style.css +66 -0
  25. package/dist/plugins/steps/README.md +3 -3
  26. package/dist/plugins/steps/index.js +3 -42
  27. package/dist/plugins/steps/public/client.js +1 -1
  28. package/dist/plugins/terminal/host.js +1 -1
  29. package/dist/plugins/terminal/public/client.js +1 -1
  30. package/dist/plugins/window/README.md +34 -14
  31. package/dist/plugins/window/index.js +21 -13
  32. package/dist/src/auth.js +4 -3
  33. package/dist/src/client/page/base.css +61 -1
  34. package/dist/src/client/page/main.js +60 -14
  35. package/dist/src/entries.js +217 -0
  36. package/dist/src/events.js +1 -1
  37. package/dist/src/hub.js +272 -0
  38. package/dist/src/loader.js +4 -1
  39. package/dist/src/package.js +23 -1
  40. package/dist/src/pages/blocks.js +1 -0
  41. package/dist/src/pages/index.js +1 -1
  42. package/dist/src/pages/markdown.js +87 -33
  43. package/dist/src/pages/render.js +116 -14
  44. package/dist/src/pages/window.js +16 -18
  45. package/dist/src/running.js +37 -2
  46. package/dist/src/serve.js +111 -2
  47. package/dist/src/server.js +49 -14
  48. package/package.json +1 -1
  49. package/plugins/ansi/README.md +36 -0
  50. package/plugins/ansi/index.ts +95 -0
  51. package/plugins/ansi/public/style.css +28 -0
  52. package/plugins/badge/README.md +28 -0
  53. package/plugins/badge/index.ts +35 -0
  54. package/plugins/badge/public/style.css +30 -0
  55. package/plugins/chat/public/style.css +7 -2
  56. package/plugins/code/README.md +4 -2
  57. package/plugins/code/diff.ts +14 -2
  58. package/plugins/grid/README.md +12 -12
  59. package/plugins/grid/index.ts +11 -26
  60. package/plugins/grid/public/style.css +4 -33
  61. package/plugins/iframe/README.md +7 -7
  62. package/plugins/iframe/index.ts +15 -15
  63. package/plugins/iframe/public/style.css +15 -0
  64. package/plugins/index.ts +6 -2
  65. package/plugins/lightbox/README.md +22 -0
  66. package/plugins/lightbox/client.ts +99 -0
  67. package/plugins/lightbox/index.ts +25 -0
  68. package/plugins/lightbox/public/style.css +66 -0
  69. package/plugins/steps/README.md +3 -3
  70. package/plugins/steps/client.ts +15 -6
  71. package/plugins/steps/index.ts +3 -46
  72. package/plugins/terminal/client.ts +16 -7
  73. package/plugins/window/README.md +34 -14
  74. package/plugins/window/index.ts +20 -13
  75. package/skills/whiteboard/SKILL.md +17 -10
  76. package/src/auth.ts +5 -3
  77. package/src/client/base.ts +19 -0
  78. package/src/client/forms.ts +2 -1
  79. package/src/client/markdown.ts +2 -1
  80. package/src/client/page/base.css +61 -1
  81. package/src/client/page/elsewhere.ts +72 -16
  82. package/src/client/page/fresh.ts +2 -1
  83. package/src/client/page/sort.ts +2 -1
  84. package/src/client/runtime.ts +11 -9
  85. package/src/define.ts +66 -7
  86. package/src/entries.ts +269 -0
  87. package/src/events.ts +2 -1
  88. package/src/hub.ts +355 -0
  89. package/src/loader.ts +7 -1
  90. package/src/package.ts +22 -0
  91. package/src/pages/blocks.ts +3 -0
  92. package/src/pages/index.ts +4 -2
  93. package/src/pages/markdown.ts +89 -32
  94. package/src/pages/render.ts +134 -13
  95. package/src/pages/window.ts +16 -25
  96. package/src/running.ts +47 -1
  97. package/src/serve.ts +114 -1
  98. package/src/server.ts +80 -14
  99. package/dist/plugins/gallery/README.md +0 -30
  100. package/dist/plugins/gallery/index.js +0 -75
  101. package/dist/plugins/gallery/public/client.js +0 -1
  102. package/dist/plugins/gallery/public/style.css +0 -90
  103. package/plugins/gallery/README.md +0 -30
  104. package/plugins/gallery/client.tsx +0 -70
  105. package/plugins/gallery/index.ts +0 -89
  106. package/plugins/gallery/public/style.css +0 -90
package/bin/whiteboard.ts CHANGED
@@ -25,8 +25,17 @@ import {
25
25
  import { BUILTIN_COMMANDS, createConfigLoader, pluginDir } from '../src/loader.ts'
26
26
  import { pluginCommands, parseCommandArgs, usage } from '../src/plugins.ts'
27
27
  import { projectToken } from '../src/auth.ts'
28
- import { packagePath } from '../src/package.ts'
29
- import { runningServer } from '../src/running.ts'
28
+ import { PACKAGE_DIR, packagePath } from '../src/package.ts'
29
+ import { recordedSharedPort, runningServer, sharedServer } from '../src/running.ts'
30
+ import {
31
+ machineDir,
32
+ machineServerFile,
33
+ matchesEntries,
34
+ readMachineConfig,
35
+ serverPaths,
36
+ stateDir,
37
+ } from '../src/entries.ts'
38
+ import { compareVersions, VERSION } from '../src/package.ts'
30
39
  import { statusLines, takenByOther, whose } from '../src/status.ts'
31
40
  import type { Listener, PageStatus, WbEvent } from '../src/define.ts'
32
41
 
@@ -60,18 +69,27 @@ const HELP = `whiteboard — markdown pages in the browser, what the reader does
60
69
  whiteboard append --page <p> --type <t> [--data <json>] add an event to a page's log (e.g. a reply)
61
70
  whiteboard pick <event id> record an event as picked up, as wait does when it hands one out
62
71
  whiteboard status [--page <p>] per page: questions without an answer, answers no agent picked up, who listens
63
- whiteboard serve run this project's server in the foreground
72
+ whiteboard serve run this project's server in the foreground; for a project of the
73
+ machine's entries, or outside any project, the shared server
64
74
  whiteboard skill [dir] print where the agent skill is, or link it into a skills folder
75
+ whiteboard paths [--write|--read] the folders the shared server needs, ':' between them, for a sandbox
76
+ wrapper to grant: --write the entries' folders and its state, --read
77
+ the machine config and whiteboard itself
65
78
 
66
79
  filters: --page <page|file> (includes pages below it) --type <type>
67
80
  wait: --timeout <seconds> (exit 2 on timeout) --count <n> (default 1)
68
81
  wait, watch without --page: the fallback, taking only what no other wait or watch would, on any
69
- page, also once they stop; one per project (a second exits 1)
82
+ page, also once they stop; one per project (a second exits 1), or, in a project of the
83
+ machine's entries, one for the whole entry, each event with its project and url
70
84
  events: --since <iso time or event id> --last <n>
71
85
 
72
86
  Every command works on the project of the current folder: the nearest folder upward with a
73
87
  .whiteboard/ folder. A project needs no config: .whiteboard/config.ts only says what differs from
74
88
  the defaults (markdown with the built-in plugins). Each project runs its own server; its port is in .whiteboard/server.json.
89
+ A project the machine config's entries include (${machineDir()}/config.json) is served by the one shared
90
+ server instead, under its path (/<entry>/<folder>), with an index of every entry at /. It is started
91
+ outside the agents' sandboxes (\`whiteboard serve\` outside any project, or a login service), and
92
+ \`serve\` takes an older one over; commands never start it. A wait without a server waits for one.
75
93
  A page appends events {id, ts, page, type, action, data} to .whiteboard/events.ndjson;
76
94
  which types it sends is up to its plugins (\`whiteboard docs\` says). The project's plugins
77
95
  can add commands of their own; \`whiteboard help\` in a project lists them.`
@@ -99,6 +117,8 @@ const { values: opts, positionals } =
99
117
  out: { type: 'string' },
100
118
  skip: { type: 'string' },
101
119
  help: { type: 'boolean', short: 'h' },
120
+ write: { type: 'boolean' },
121
+ read: { type: 'boolean' },
102
122
  },
103
123
  })
104
124
 
@@ -114,13 +134,58 @@ Run \`whiteboard init\` in the folder that should become one.`)
114
134
 
115
135
  const filter = (): EventFilter => ({ page: opts.page ? pageId(needProject(), opts.page) : undefined, type: opts.type })
116
136
 
117
- /** The running server of this project: its base URL, or null. */
118
- const running = (proj: Project) => runningServer(proj)
137
+ /**
138
+ * Is this project one of the machine's entries (see src/entries.ts)? Then the shared server serves
139
+ * it, under its path, and no server of its own runs. A project outside every include runs its own.
140
+ */
141
+ function isShared(proj: Project): boolean {
142
+ const config = readMachineConfig()
143
+ return !!config && !!matchesEntries(config, proj.dir)
144
+ }
145
+
146
+ /**
147
+ * The running server of this project: the URL it is served at (`http://localhost:4777`, or
148
+ * `http://localhost:4777/rg/develop` under the shared server), or null.
149
+ */
150
+ async function running(proj: Project): Promise<string | null> {
151
+ if (!isShared(proj)) return runningServer(proj)
152
+ const file = machineServerFile()
153
+ const shared = await sharedServer(file)
154
+ if (!shared) return null
155
+ // a project made a moment ago: the server looks again
156
+ const mine =
157
+ shared.projects.find(p => p.dir === proj.dir) ??
158
+ (await sharedServer(file, { rescan: true }))?.projects.find(p => p.dir === proj.dir)
159
+ return mine ? `${shared.origin}${mine.base}` : null
160
+ }
119
161
 
120
- /** This project's server, started in the background when it is not running. @returns its base URL */
162
+ /**
163
+ * This project's server, started in the background when it is not running. Under the shared server
164
+ * nothing is started: it is started outside every agent's sandbox (a login service, or `whiteboard
165
+ * serve` in a terminal), since it serves every project of the entries and runs their plugins; a
166
+ * command inside one sandbox would start it boxed in there. Only `show` and a plugin's command that
167
+ * asks for the server get here. @returns the URL it serves the project at
168
+ */
121
169
  async function ensureServer(): Promise<string> {
122
170
  const proj = needProject()
171
+ const shared = isShared(proj)
123
172
  const base = await running(proj)
173
+ if (shared) {
174
+ const server = await sharedServer(machineServerFile())
175
+ if (base) {
176
+ // an older one goes on serving: it is replaced by restarting it, from outside the sandboxes
177
+ if (server && compareVersions(VERSION, server.version) > 0)
178
+ console.error(
179
+ `whiteboard: the shared server runs ${server.version}, this is ${VERSION}; restart it to upgrade (\`whiteboard serve\` takes it over)`,
180
+ )
181
+ return base
182
+ }
183
+ throw new Error(
184
+ server
185
+ ? `the shared server at ${server.origin} does not serve ${proj.dir}; is it in an include of ${machineDir()}/config.json?`
186
+ : `the shared server is not running. It is started outside the agents' sandboxes: as a login service, or with \`whiteboard serve\` in a terminal, outside any project`,
187
+ )
188
+ }
124
189
  if (base) return base
125
190
  // Several commands may get here at once (an agent starting three watches, say): the one that
126
191
  // creates the lock file starts the server, the others wait for it. A lock whose command is gone
@@ -177,13 +242,69 @@ async function ensureServer(): Promise<string> {
177
242
  throw new Error(`server did not start; see ${proj.logFile}`)
178
243
  }
179
244
 
245
+ /** This project's running server, or an error saying how to start one. */
246
+ async function needServer(): Promise<string> {
247
+ const proj = needProject()
248
+ const base = await running(proj)
249
+ if (base) return base
250
+ if (isShared(proj)) {
251
+ const port = recordedSharedPort(machineServerFile())
252
+ throw new Error(
253
+ port
254
+ ? `the shared server recorded on port ${port} did not answer, or does not serve ${proj.dir}`
255
+ : "the shared server is not running. It is started outside the agents' sandboxes: as a login service, or with `whiteboard serve` in a terminal, outside any project",
256
+ )
257
+ }
258
+ throw new Error('no server runs for this project; `whiteboard show <page>` starts it')
259
+ }
260
+
261
+ /** Is there a page (a markdown file) in this folder or below it? */
262
+ function hasPages(dir: string): boolean {
263
+ let entries: fs.Dirent[]
264
+ try {
265
+ entries = fs.readdirSync(dir, { withFileTypes: true })
266
+ } catch {
267
+ return false
268
+ }
269
+ return entries.some(e =>
270
+ e.isDirectory() ? !e.name.startsWith('.') && hasPages(path.join(dir, e.name)) : e.name.endsWith('.md'),
271
+ )
272
+ }
273
+
274
+ /**
275
+ * Ask the project's server. Without one running, a server made for this one question answers it,
276
+ * in this process, on no port: a command that only asks (status, docs, the hooks on every prompt)
277
+ * never starts one. It has no listeners, as no server runs to hold them.
278
+ */
180
279
  async function api(route: string): Promise<any> {
181
- const res = await fetch(`${await ensureServer()}${route}`)
280
+ const base = await running(needProject())
281
+ const res = base ? await fetch(`${base}${route}`) : await askInProcess(route)
182
282
  const body = await res.json()
183
283
  if (!res.ok) throw new Error(body.error ?? res.statusText)
184
284
  return body
185
285
  }
186
286
 
287
+ async function askInProcess(route: string): Promise<Response> {
288
+ // a project without pages has nothing open: no need to load its config to say so (the hooks ask
289
+ // on every prompt, in every project, most of which have no pages)
290
+ if (route.startsWith('/api/status') && !hasPages(needProject().pagesDir)) return Response.json([])
291
+ const { createServer } = await import('../src/server.ts')
292
+ const server = createServer(needProject())
293
+ const listener = http.createServer((req, res) => void server.handle(req, res))
294
+ await new Promise<void>(r => listener.listen(0, '127.0.0.1', r))
295
+ try {
296
+ const { port } = listener.address() as import('node:net').AddressInfo
297
+ const res = await fetch(`http://127.0.0.1:${port}${route}`)
298
+ // read now, while the server is there
299
+ const text = await res.text()
300
+ return new Response(text, { status: res.status, headers: res.headers })
301
+ } finally {
302
+ server.close()
303
+ listener.closeAllConnections()
304
+ listener.close()
305
+ }
306
+ }
307
+
187
308
  /**
188
309
  * Tell the project's server that an agent is waiting, for as long as this command runs: pages show
189
310
  * what is waited for. Holds one connection open, the listener; reconnects when the server restarts.
@@ -196,9 +317,11 @@ async function api(route: string): Promise<any> {
196
317
  function listen(f: EventFilter, command: 'wait' | 'watch', fallback = false): Promise<void> {
197
318
  return new Promise(registered => {
198
319
  const connect = async () => {
320
+ // a wait never starts a server: without one, it waits for one to appear (the log is read
321
+ // without it all the same)
199
322
  let base
200
323
  try {
201
- base = await ensureServer()
324
+ base = await needServer()
202
325
  } catch {
203
326
  return setTimeout(connect, 2000).unref()
204
327
  }
@@ -238,11 +361,14 @@ function listen(f: EventFilter, command: 'wait' | 'watch', fallback = false): Pr
238
361
  * Who else listens, kept current: the fallback leaves to them what they would take. Calls
239
362
  * `changed` after each change (the server's live channel says when).
240
363
  */
241
- async function otherListeners(changed: () => void): Promise<() => Listener[]> {
364
+ async function otherListeners(
365
+ changed: () => void,
366
+ server: () => Promise<string> = needServer,
367
+ ): Promise<() => Listener[]> {
242
368
  let list: Listener[] = []
243
369
  const load = async () => {
244
370
  try {
245
- list = (await (await fetch(`${await ensureServer()}/api/listeners`)).json()) as Listener[]
371
+ list = (await (await fetch(`${await server()}/api/listeners`)).json()) as Listener[]
246
372
  } catch {
247
373
  /* the server restarts */
248
374
  }
@@ -258,7 +384,7 @@ async function otherListeners(changed: () => void): Promise<() => Listener[]> {
258
384
  }
259
385
  let base
260
386
  try {
261
- base = await ensureServer()
387
+ base = await server()
262
388
  } catch {
263
389
  return retry()
264
390
  }
@@ -333,8 +459,11 @@ const relFile = (file: string) => path.relative(process.cwd(), file) || file
333
459
  * The project's config, as the command line needs it: for its plugins (their commands, the
334
460
  * session, which events reach an agent), so without the pages. Loaded once per command.
335
461
  */
336
- let loaded: ReturnType<ReturnType<typeof createConfigLoader>['config']> | null = null
337
- const projectConfig = (proj: Project) => (loaded ??= createConfigLoader(proj, { pages: false }).config())
462
+ const loaded = new Map<string, ReturnType<ReturnType<typeof createConfigLoader>['config']>>()
463
+ const projectConfig = (proj: Project) => {
464
+ if (!loaded.has(proj.dir)) loaded.set(proj.dir, createConfigLoader(proj, { pages: false }).config())
465
+ return loaded.get(proj.dir)!
466
+ }
338
467
 
339
468
  /**
340
469
  * The agent session this command runs in, as the project's plugins know it (Claude Code's
@@ -373,7 +502,19 @@ async function status() {
373
502
 
374
503
  switch (cmd) {
375
504
  case 'serve': {
505
+ // outside any project, with a machine config: the shared server (to start at login, say)
506
+ if (!project && readMachineConfig()) {
507
+ const { startShared } = await import('../src/serve.ts')
508
+ await startShared()
509
+ break
510
+ }
376
511
  const proj = needProject()
512
+ if (isShared(proj)) {
513
+ // the shared server, for every entry's projects; it takes over from an older one itself
514
+ const { startShared } = await import('../src/serve.ts')
515
+ await startShared()
516
+ break
517
+ }
377
518
  const base = await running(proj)
378
519
  if (base) {
379
520
  console.error(`whiteboard: ${proj.name} is already served at ${base}`)
@@ -455,7 +596,7 @@ switch (cmd) {
455
596
  case 'show':
456
597
  case 'url': {
457
598
  if (cmd === 'show' && !positionals[0]) throw new Error('usage: whiteboard show <page|file>')
458
- const base = await ensureServer()
599
+ const base = cmd === 'show' ? await ensureServer() : await needServer()
459
600
  console.log(`${base}/${pageId(project, positionals[0] ?? '')}`)
460
601
  break
461
602
  }
@@ -539,7 +680,7 @@ switch (cmd) {
539
680
  if (!target || !to) throw new Error('usage: whiteboard scroll <page|file> <heading, form name or text>')
540
681
  const proj = needProject()
541
682
  const id = pageId(proj, target)
542
- const base = await ensureServer()
683
+ const base = await needServer()
543
684
  // what the page shows, to say now when nothing on it matches
544
685
  const rendered = (await (
545
686
  await fetch(`${base}/api/render?page=${encodeURIComponent(id)}`)
@@ -659,6 +800,12 @@ switch (cmd) {
659
800
  // events (default 1); `watch` never does.
660
801
  const proj = needProject()
661
802
  const f = filter()
803
+ // without --page in a project of the machine's entries: the fallback of the whole entry
804
+ const entry = !f.page && isShared(proj) ? matchesEntries(readMachineConfig()!, proj.dir) : null
805
+ if (entry) {
806
+ await entryFallback(entry, f, cmd)
807
+ break
808
+ }
662
809
  const { handedOut } = await projectConfig(proj)
663
810
  // without --page, the fallback: only what no other listener would take, on any page, as it comes
664
811
  // and once they stop listening (an answer left in the log, too)
@@ -735,6 +882,26 @@ switch (cmd) {
735
882
  case 'status':
736
883
  await status()
737
884
  break
885
+ case 'paths': {
886
+ // what the shared server needs of the disk, from the machine config: for whatever boxes it in
887
+ // (a sandbox wrapper: `safehouse --add-dirs="$(whiteboard paths --write)" …`)
888
+ const config = readMachineConfig()
889
+ if (!config) throw new Error(`no machine config: ${machineDir()}/config.json`)
890
+ const paths = serverPaths(config, { packageDir: PACKAGE_DIR })
891
+ // a sandbox grants only folders that exist: the state folder is whiteboard's own, so it is made
892
+ // here; an entry's folder not there yet is left out (a restart grants it once it is)
893
+ try {
894
+ fs.mkdirSync(stateDir(), { recursive: true })
895
+ } catch {
896
+ /* made by whoever may: the wrapper runs outside the agents' sandboxes */
897
+ }
898
+ const write = paths.write.filter(d => fs.existsSync(d))
899
+ const read = paths.read.filter(d => fs.existsSync(d))
900
+ if (opts.write) console.log(write.join(':'))
901
+ else if (opts.read) console.log(read.join(':'))
902
+ else console.log(`write: ${write.join(':')}\nread: ${read.join(':')}`)
903
+ break
904
+ }
738
905
  case 'skill': {
739
906
  // the agent skill ships in this package; link it into whatever folder an agent reads skills from
740
907
  const source = packagePath('skills', 'whiteboard')
@@ -803,6 +970,122 @@ switch (cmd) {
803
970
  }
804
971
  }
805
972
 
973
+ /**
974
+ * The fallback of a whole entry: what no other wait or watch in any of its projects would take, on
975
+ * any page, also once they stop, from each project's own log, each event with the project it is
976
+ * from (`project`, its folder) and its page's `url`. One per entry: the shared server holds it, and
977
+ * refuses a second (exit 1). Without a shared server running it waits for one, as any wait does: who
978
+ * else listens is the server's to say. Projects that appear meanwhile are followed too.
979
+ */
980
+ async function entryFallback(entry: string, f: EventFilter, command: 'wait' | 'watch') {
981
+ const file = machineServerFile()
982
+ const count = command === 'wait' ? Number(opts.count ?? 1) : Infinity
983
+ const done = new AbortController()
984
+ let total = 0
985
+ // after the last event is recorded as picked up, which follows handing it out
986
+ done.signal.addEventListener('abort', () => setImmediate(() => process.exit(0)))
987
+ if (opts.timeout && command === 'wait')
988
+ setTimeout(
989
+ () => {
990
+ console.error('timeout')
991
+ process.exit(2)
992
+ },
993
+ Number(opts.timeout) * 1000,
994
+ )
995
+ // hold the entry's fallback at the shared server, for as long as this runs (again after a restart)
996
+ await new Promise<void>(registered => {
997
+ const connect = async () => {
998
+ const shared = await sharedServer(file)
999
+ if (!shared) return setTimeout(connect, 2000).unref()
1000
+ const q = new URLSearchParams({ entry, command, ...(f.type ? { type: f.type } : {}) })
1001
+ let again = false
1002
+ const retry = (ms: number) => {
1003
+ if (!again) {
1004
+ again = true
1005
+ setTimeout(connect, ms).unref()
1006
+ }
1007
+ }
1008
+ const req = http.get(`${shared.origin}/api/listen?${q}`, res => {
1009
+ if (res.statusCode === 409) {
1010
+ let body = ''
1011
+ res.on('data', d => (body += d))
1012
+ res.on('end', () => {
1013
+ console.error(
1014
+ `whiteboard: ${JSON.parse(body || '{}').error ?? 'another agent is the fallback'}. Add --page to wait on a page of your own.`,
1015
+ )
1016
+ process.exit(1)
1017
+ })
1018
+ return
1019
+ }
1020
+ res.resume()
1021
+ registered()
1022
+ res.on('close', () => retry(1000))
1023
+ })
1024
+ req.on('error', () => retry(2000))
1025
+ req.on('socket', socket => socket.unref())
1026
+ }
1027
+ connect()
1028
+ })
1029
+ // a hand-out per project of the entry, as the shared server knows them
1030
+ const following = new Map<string, AbortController>()
1031
+ async function start(p: { dir: string; base: string }, origin: string) {
1032
+ const proj = projectAt(p.dir)
1033
+ if (!proj) return
1034
+ const stop = new AbortController()
1035
+ following.set(p.dir, stop)
1036
+ const { handedOut } = await projectConfig(proj)
1037
+ let recheck = () => {}
1038
+ const at = async () => {
1039
+ const shared = await sharedServer(file)
1040
+ const now = shared?.projects.find(x => x.dir === p.dir)
1041
+ if (!shared || !now) throw new Error('not served')
1042
+ return `${shared.origin}${now.base}`
1043
+ }
1044
+ const others = await otherListeners(() => recheck(), at)
1045
+ // as for a project's fallback: hold each event a moment, for a wait that just started
1046
+ const held = new Set<string>()
1047
+ const skip = (e: WbEvent) => {
1048
+ if (!held.has(e.id)) {
1049
+ held.add(e.id)
1050
+ setTimeout(() => recheck(), 500).unref()
1051
+ return true
1052
+ }
1053
+ return takenByOther(others(), e)
1054
+ }
1055
+ const page = (id: string) => id.split('/').map(encodeURIComponent).join('/')
1056
+ await handOut(
1057
+ proj.eventsFile,
1058
+ { type: f.type },
1059
+ e => {
1060
+ console.log(JSON.stringify({ ...e, project: p.dir, url: `${origin}${p.base}/${page(e.page)}` }))
1061
+ if (++total >= count) done.abort()
1062
+ },
1063
+ {
1064
+ forAgent: forAgent(handedOut),
1065
+ signal: AbortSignal.any([stop.signal, done.signal]),
1066
+ skip,
1067
+ recheck: again => {
1068
+ recheck = again
1069
+ },
1070
+ },
1071
+ )
1072
+ }
1073
+ const sync = async () => {
1074
+ const shared = await sharedServer(file)
1075
+ if (!shared) return
1076
+ const mine = shared.projects.filter(p => p.entry === entry)
1077
+ for (const p of mine) if (!following.has(p.dir)) void start(p, shared.origin)
1078
+ for (const [dir, stop] of following)
1079
+ if (!mine.some(p => p.dir === dir)) {
1080
+ stop.abort()
1081
+ following.delete(dir)
1082
+ }
1083
+ }
1084
+ await sync()
1085
+ // keeps the command running, and follows projects coming and going
1086
+ setInterval(sync, 2000)
1087
+ }
1088
+
806
1089
  /** The commands the project's plugins add: `whiteboard <plugin> [sub]`. */
807
1090
  async function projectCommands(proj: Project) {
808
1091
  const { plugins, errors } = await projectConfig(proj)