@bigmistqke/whiteboard 0.7.0 → 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 (66) hide show
  1. package/README.md +10 -209
  2. package/bin/whiteboard.ts +82 -239
  3. package/dist/bin/whiteboard.js +70 -200
  4. package/dist/client/runtime.js +66 -7
  5. package/dist/plugins/chat/public/style.css +10 -6
  6. package/dist/plugins/code/README.md +10 -0
  7. package/dist/plugins/code/index.js +31 -22
  8. package/dist/plugins/code/public/client.js +1 -0
  9. package/dist/plugins/code/public/style.css +33 -2
  10. package/dist/plugins/comments/public/client.js +1 -1
  11. package/dist/plugins/form/public/style.css +2 -0
  12. package/dist/plugins/iframe/index.js +2 -2
  13. package/dist/plugins/lightbox/public/client.js +1 -1
  14. package/dist/plugins/terminal/index.js +7 -9
  15. package/dist/plugins/terminal/public/client.js +1 -1
  16. package/dist/plugins/terminal/public/style.css +3 -3
  17. package/dist/plugins/toc/index.js +1 -1
  18. package/dist/plugins/toc/public/client.js +1 -1
  19. package/dist/plugins/window/index.js +4 -4
  20. package/dist/src/build.js +159 -0
  21. package/dist/src/client/page/main.js +1 -1
  22. package/dist/src/document.js +93 -0
  23. package/dist/src/events.js +3 -13
  24. package/dist/src/hub.js +47 -35
  25. package/dist/src/listen.js +100 -0
  26. package/dist/src/listeners.js +67 -0
  27. package/dist/src/pages/index.js +1 -1
  28. package/dist/src/pages/markdown.js +23 -11
  29. package/dist/src/pages/render.js +13 -8
  30. package/dist/src/server.js +166 -514
  31. package/dist/src/site.js +173 -0
  32. package/dist/src/status.js +63 -1
  33. package/package.json +1 -1
  34. package/plugins/README.md +258 -0
  35. package/plugins/chat/public/style.css +10 -6
  36. package/plugins/code/README.md +10 -0
  37. package/plugins/code/client.ts +73 -0
  38. package/plugins/code/index.ts +38 -26
  39. package/plugins/code/public/style.css +33 -2
  40. package/plugins/comments/client.ts +8 -1
  41. package/plugins/form/public/style.css +2 -0
  42. package/plugins/iframe/index.ts +2 -2
  43. package/plugins/lightbox/client.ts +13 -3
  44. package/plugins/terminal/client.ts +10 -2
  45. package/plugins/terminal/index.ts +8 -6
  46. package/plugins/terminal/public/style.css +3 -3
  47. package/plugins/toc/client.ts +9 -2
  48. package/plugins/toc/index.ts +1 -1
  49. package/plugins/window/index.ts +4 -4
  50. package/skills/whiteboard/SKILL.md +3 -1
  51. package/src/build.ts +213 -0
  52. package/src/client/page/elsewhere.ts +2 -1
  53. package/src/client/runtime.ts +88 -10
  54. package/src/client/toast.ts +1 -1
  55. package/src/define.ts +34 -18
  56. package/src/document.ts +191 -0
  57. package/src/events.ts +11 -16
  58. package/src/hub.ts +48 -34
  59. package/src/listen.ts +125 -0
  60. package/src/listeners.ts +95 -0
  61. package/src/pages/index.ts +1 -1
  62. package/src/pages/markdown.ts +29 -18
  63. package/src/pages/render.ts +13 -8
  64. package/src/server.ts +165 -609
  65. package/src/site.ts +165 -0
  66. package/src/status.ts +100 -0
package/README.md CHANGED
@@ -472,9 +472,10 @@ whiteboard build 'docs/guide/*.md' --out preview # or what is given, over the
472
472
  (so no answers, chats or comments), new-content marks and toasts, and the
473
473
  plugins and blocks in `skip`: their blocks render as nothing, their
474
474
  stylesheets, browser modules and what they add to the page aren't included.
475
- A plugin's `shell` is asked with no request, since no browser asked for the
475
+ A plugin's `slots` is asked with no request, since no browser asked for the
476
476
  page: the terminal's drawer, which is only for the project's own browser,
477
- isn't there.
477
+ isn't there. Files a page names (its images, an iframe's page) are copied
478
+ beside it.
478
479
  - **What is for reading stays:** steps, the lightbox, ⤢ on
479
480
  windows, the theme toggle, the contents, details. Code and diagrams were
480
481
  rendered on the server, so the site loads no highlighter.
@@ -494,214 +495,14 @@ way, but steps, the lightbox and the theme toggle need the server.
494
495
 
495
496
  ## Writing a plugin
496
497
 
497
- Everything that extends whiteboard is a plugin: syntax for pages,
498
- behaviour on every page, commands, events. A plugin is an object with a
499
- name, and everything it adds lives under that name, so two plugins can't
500
- collide: its block `:::name`, its events `name:…`, its command
501
- `whiteboard name`, its routes `/api/name/…` and its data folder
502
- `.whiteboard/name/`. Local plugins go in `.whiteboard/plugins/`.
498
+ Everything that extends whiteboard is a plugin: syntax for pages (blocks),
499
+ behaviour on every page, commands, routes, events, and what goes in the
500
+ page's slots (its header bar, a panel beside the text, a drawer, the corner).
501
+ A plugin is an object with a name, and everything it adds lives under that
502
+ name. Local plugins go in `.whiteboard/plugins/`.
503
503
 
504
- ### A block: a checklist the reader ticks
505
-
506
- A block is syntax: `:::name` around content, `::name` on a line, `:name`
507
- inside a line, or a code fence of that name. It renders on the server, and
508
- with a `client` it is mounted in the browser too.
509
-
510
- ```ts
511
- // .whiteboard/plugins/checklist/index.ts
512
- import { definePlugin, html, type DirectiveContext } from '@bigmistqke/whiteboard'
513
-
514
- const toText = (node: any): string => node.value ?? (node.children ?? []).map(toText).join('')
515
-
516
- export default function checklist() {
517
- return definePlugin({
518
- name: 'checklist',
519
- blocks: {
520
- checklist: {
521
- // what the browser part gets: the block's list items as text
522
- props: ctx => {
523
- const c = ctx as DirectiveContext // a block (`:::checklist`), not a code fence
524
- return {
525
- name: c.attrs.name ?? 'checklist',
526
- items: (c.children as any[]).filter(n => n.type === 'list')
527
- .flatMap(list => list.children.map((item: any) => toText(item))),
528
- }
529
- },
530
- // shown until the client mounts, then replaced
531
- html: () => html`<ul class="checklist"></ul>`,
532
- client: 'client.js', // in its public/ folder
533
- },
534
- },
535
- // its events, and whether a `wait` on the page hands them out (a tick is information: no)
536
- events: { 'checklist:tick': { description: '`{ checklist, item, checked }`' } },
537
- // for `whiteboard docs`, under a `# Plugin: checklist` heading the core adds
538
- docs: () => 'A list the reader ticks:\n\n :::checklist{name=launch}\n - Write the changelog\n :::\n',
539
- })
540
- }
541
- ```
542
-
543
- ```js
544
- // .whiteboard/plugins/checklist/public/client.js: its public/ folder is served, nothing else of it
545
- export default function mount(el, { name, items }, api) {
546
- const ticked = () => {
547
- const state = new Map()
548
- for (const e of api.events()) if (e.type === 'checklist:tick' && e.data.checklist === name) state.set(e.data.item, e.data.checked)
549
- return state
550
- }
551
- const draw = () => {
552
- const state = ticked()
553
- el.replaceChildren(...items.map(item => {
554
- const box = Object.assign(document.createElement('input'), { type: 'checkbox', checked: !!state.get(item) })
555
- box.addEventListener('change', () => api.append('checklist:tick', { checklist: name, item, checked: box.checked }))
556
- const label = document.createElement('label')
557
- label.append(box, ' ', item)
558
- return label
559
- }))
560
- }
561
- draw()
562
- // the page's events, also the ones it appends itself, come back here
563
- return api.events.on(draw)
564
- }
565
- ```
566
-
567
- ```ts
568
- // .whiteboard/config.ts
569
- import { defineConfig } from '@bigmistqke/whiteboard'
570
- import checklist from './plugins/checklist/index.ts'
571
-
572
- export default defineConfig({ plugins: [checklist()] })
573
- ```
574
-
575
- An agent can wait for a tick by asking for it: `whiteboard wait --page
576
- <file> --type checklist:tick`.
577
-
578
- ### Behaviour on every page: votes
579
-
580
- A plugin can also put something on every page, and add commands:
581
-
582
- ```ts
583
- // .whiteboard/plugins/votes/index.ts
584
- import { definePlugin } from '@bigmistqke/whiteboard'
585
- import { read } from '@bigmistqke/whiteboard/log'
586
-
587
- export default function votes() {
588
- return definePlugin({
589
- name: 'votes',
590
- events: { 'votes:up': { description: 'the reader voted the page up' } },
591
- commands: {
592
- '': {
593
- description: 'print the votes per page',
594
- run(ctx) {
595
- const counts = new Map<string, number>()
596
- for (const e of read(ctx.eventsFile).events) if (e.type === 'votes:up') counts.set(e.page, (counts.get(e.page) ?? 0) + 1)
597
- for (const [page, n] of counts) console.log(`${page}: ${n}`)
598
- },
599
- },
600
- },
601
- docs: () => 'The reader can vote a page up: a `votes:up` event. `whiteboard votes` counts them.',
602
- // from setup: what the running server adds (routes, markup, the browser module)
603
- setup: () => ({ client: 'client.js' }),
604
- })
605
- }
606
- ```
607
-
608
- ```js
609
- // .whiteboard/plugins/votes/public/client.js
610
- export default function mount(root, page, api) {
611
- const button = document.createElement('button')
612
- const draw = () => { button.textContent = `👍 ${api.events().filter(e => e.type === 'votes:up').length}` }
613
- button.addEventListener('click', () => api.append('votes:up'))
614
- api.corner().append(button) // the page's corner, for floating buttons
615
- api.events.on(draw)
616
- draw()
617
- }
618
- ```
619
-
620
- ### What a plugin can have
621
-
622
- - **`blocks`**, by name. A block has `html(ctx)` (the server's HTML; `ctx`
623
- has the block's attributes, label, content as mdast nodes, `toHtml`,
624
- `items()` and more), `props(ctx)` (JSON for its client), `client` (a
625
- browser module, mounted per block), `style` (linked on pages that use it),
626
- `fence: true` to also take the code fences of its name (```` ```mermaid ````),
627
- `fence: 'any'` for the block that takes every code fence nobody else
628
- claims, and `open(ctx)`: what it shows on its own, for a window around it.
629
- Block names are unique across a project's plugins.
630
- - **`compose(ctx)`**: itself around any block that names the plugin in its
631
- `compose` attribute, that block's HTML as `ctx.children` (see below).
632
- - **`events`**, by type (`<plugin>:<what>`): a description each, and
633
- `handOut: true` for those an agent should get unasked, like a chat
634
- message. `whiteboard docs` lists them.
635
- - **`style`**: a stylesheet on every page.
636
- - **`docs`**: markdown for agents: how to write its blocks, what its events
637
- mean, how to answer.
638
- - **`commands`**: `whiteboard <name>` and `whiteboard <name> <sub>`, with
639
- declared options that the core parses and checks. A command gets the
640
- project, its event log (`ctx.eventsFile`, for
641
- `@bigmistqke/whiteboard/log`), its token and server, what is open on each
642
- page (`ctx.status`), and handing out (`ctx.handOut`, what `wait` does).
643
- - **`session()`**: the agent session a command runs in, for a plugin that
644
- knows how its agent says so.
645
- - **`setup(ctx)`**, which runs once per loaded config on the server and
646
- returns:
647
- - `routes`, by method and path (`'POST /start'` is mounted at
648
- `/api/<name>/start`), each with what it does, whether it needs the
649
- project's token (`auth`), and the types of its body and query; the core
650
- checks all of that before the route's code runs;
651
- - `shell`, markup at the end of every page's `<head>` and `<body>`;
652
- - `client`, a module on every page, run once per page load.
653
-
654
- **A plugin can compose itself around other blocks.** With `compose`, a
655
- block whose `compose` attribute names the plugin is put in what it returns,
656
- the block's HTML as `children`, as a component gets what it wraps. The
657
- window plugin is one: `::image{src compose=window}`, ```` ```mermaid {compose=window} ````
658
- and `:::grid{compose=window}` all go in a window, and none of those blocks
659
- knows of windows. A block says what it shows on its own with `open` (an
660
- image's file), which a window's ↗ opens. Several named compose in the order
661
- written, the first innermost: `compose=lightbox,window`. A name no plugin
662
- composes is said in place.
663
-
664
- ```ts
665
- definePlugin({
666
- name: 'window',
667
- compose: ({ children, label, open }) => windowFrame({ label, open, body: children }),
668
- })
669
- ```
670
-
671
- **A plugin's browser files live in its `public/` folder**, and only that
672
- folder is served: its client modules, styles, images and fonts, never its
673
- server code or the project's files beside it. `client` and `style` (a
674
- plugin's and a block's) name files in it: `'client.js'`. `definePlugin` puts
675
- it next to the module that calls it (`plugins/checklist/public/` for
676
- `plugins/checklist/index.ts`); say another with `public: new URL('./assets/',
677
- import.meta.url)`; a plain object plugin, or one written in the config, has
678
- `.whiteboard/public/`. A file named outside it is a config error. Browser
679
- code is JavaScript or TypeScript: a `.ts` file is served with its types
680
- stripped (Node's type stripping, as for server code: types only, so no
681
- `enum` or `namespace`, and imports name their `.ts` files). JSX still needs
682
- building first. A block's `client` gets
683
- `mount(element, props, api)` and may return a cleanup, run when the block
684
- is replaced on a live update; it replaces the server's HTML when it mounts.
685
- A page module (`setup`'s `client`) gets `mount(root, page, api)`. Both get
686
- the page's `api`: its `events` and `append` (which comes back through
687
- `events.on`), the `listeners`, `forms` and `unread` messages, `onRendered`
688
- (after a live update, to put back what it adds), the page's `frontmatter`
689
- on the page handle (YAML, as parsed) and the plugin's own `settings` in it
690
- (under `plugins:` by its name: `plugins: { toc: true }` is `true` for toc), `corner()` for floating buttons, `toast()` for a label in
691
- the corner that says what is going on and goes there (one that hides after a
692
- few seconds, or one that stays with a count), `badge()` for counts in the
693
- tab title, the `theme`, and `url(path)`: the address of one of the
694
- project's server routes as this page requests it (`api.url('/api/votes/count')`).
695
- Ask for the plugin's routes through it rather than writing `/api/…`: under a
696
- shared server a project is served below a path (`/rg/develop`). Every value
697
- that changes is called for what it
698
- is now and has `.on(fn)` for each change: `api.events()`,
699
- `api.events.on(draw)`, `page.frontmatter.on(…)`. Files beside a browser module that are browser
700
- assets (scripts, styles, images, fonts) are served too.
701
-
702
- Something that covers the bottom of the window says how much in
703
- `--wb-inset-bottom`, and the page keeps clear of it. A plugin can't be
704
- named like a built-in command or a folder of the core.
504
+ How to write one, with examples, is in [plugins/README.md](plugins/README.md);
505
+ the plugins in that folder are the built-in ones.
705
506
 
706
507
  ## Pages
707
508
 
package/bin/whiteboard.ts CHANGED
@@ -36,8 +36,9 @@ import {
36
36
  stateDir,
37
37
  } from '../src/entries.ts'
38
38
  import { compareVersions, VERSION } from '../src/package.ts'
39
- import { statusLines, takenByOther, whose } from '../src/status.ts'
40
- import type { Listener, PageStatus, WbEvent } from '../src/define.ts'
39
+ import { statusLines, whose } from '../src/status.ts'
40
+ import { fallback as fallbackLoop, listen } from '../src/listen.ts'
41
+ import type { Listener, PageStatus } from '../src/define.ts'
41
42
 
42
43
  // a failing command prints its message, not a stack trace
43
44
  const fail = (err: unknown) => {
@@ -305,112 +306,6 @@ async function askInProcess(route: string): Promise<Response> {
305
306
  }
306
307
  }
307
308
 
308
- /**
309
- * Tell the project's server that an agent is waiting, for as long as this command runs: pages show
310
- * what is waited for. Holds one connection open, the listener; reconnects when the server restarts.
311
- * Reading the log does not depend on it, so answers are never missed when the server is away.
312
- */
313
- /**
314
- * Tell the server who is listening, for as long as the command runs (again after a restart). The
315
- * fallback is refused when another one runs: it exits, saying so. Resolves once the server took it.
316
- */
317
- function listen(f: EventFilter, command: 'wait' | 'watch', fallback = false): Promise<void> {
318
- return new Promise(registered => {
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)
322
- let base
323
- try {
324
- base = await needServer()
325
- } catch {
326
- return setTimeout(connect, 2000).unref()
327
- }
328
- const q = new URLSearchParams({
329
- command,
330
- ...(f.page ? { page: f.page } : {}),
331
- ...(f.type ? { type: f.type } : {}),
332
- ...(fallback ? { fallback: '' } : {}),
333
- })
334
- let again = false
335
- const retry = (ms: number) => {
336
- if (!again) {
337
- again = true
338
- setTimeout(connect, ms).unref()
339
- }
340
- }
341
- const req = http.get(`${base}/api/listen?${q}`, res => {
342
- if (res.statusCode === 409) {
343
- console.error(
344
- 'whiteboard: another agent already takes what no other listener does (a wait or watch without --page; one per project). Add --page to wait on a page of your own.',
345
- )
346
- process.exit(1)
347
- }
348
- res.resume()
349
- registered()
350
- res.on('close', () => retry(1000))
351
- })
352
- req.on('error', () => retry(2000))
353
- // the connection alone does not keep the command running
354
- req.on('socket', socket => socket.unref())
355
- }
356
- connect()
357
- })
358
- }
359
-
360
- /**
361
- * Who else listens, kept current: the fallback leaves to them what they would take. Calls
362
- * `changed` after each change (the server's live channel says when).
363
- */
364
- async function otherListeners(
365
- changed: () => void,
366
- server: () => Promise<string> = needServer,
367
- ): Promise<() => Listener[]> {
368
- let list: Listener[] = []
369
- const load = async () => {
370
- try {
371
- list = (await (await fetch(`${await server()}/api/listeners`)).json()) as Listener[]
372
- } catch {
373
- /* the server restarts */
374
- }
375
- changed()
376
- }
377
- const follow = async () => {
378
- let again = false
379
- const retry = () => {
380
- if (!again) {
381
- again = true
382
- setTimeout(follow, 1000).unref()
383
- }
384
- }
385
- let base
386
- try {
387
- base = await server()
388
- } catch {
389
- return retry()
390
- }
391
- const req = http.get(`${base}/api/watch?dir`, res => {
392
- let buf = ''
393
- res.setEncoding('utf8')
394
- res.on('data', (chunk: string) => {
395
- buf += chunk
396
- if (buf.includes('event: listeners')) {
397
- buf = ''
398
- load()
399
- }
400
- if (buf.length > 4096) buf = buf.slice(-64)
401
- })
402
- res.on('close', retry)
403
- // reconnected after a restart: who listens now
404
- load()
405
- })
406
- req.on('error', retry)
407
- req.on('socket', socket => socket.unref())
408
- }
409
- await load()
410
- follow()
411
- return () => list
412
- }
413
-
414
309
  function init(name: string | undefined) {
415
310
  const dir = process.cwd()
416
311
  const wb = path.join(dir, '.whiteboard')
@@ -708,7 +603,11 @@ switch (cmd) {
708
603
  })
709
604
  const { tabs } = (await res.json()) as { tabs: number }
710
605
  if (!tabs) {
711
- console.error(`whiteboard: no browser has ${id} open; \`whiteboard show ${target}\` prints its URL`)
606
+ // a tab may be open but not connected: a background tab connects again when it is shown, and
607
+ // then scrolls there (the scroll is in the log)
608
+ console.error(
609
+ `whiteboard: no tab of ${id} is connected now; one that is open scrolls there once it is back (a background tab connects again when it is shown). \`whiteboard show ${target}\` prints its URL`,
610
+ )
712
611
  process.exit(1)
713
612
  }
714
613
  console.log(`scrolled ${tabs} tab${tabs > 1 ? 's' : ''} of ${id} to ${JSON.stringify(to)}`)
@@ -807,49 +706,19 @@ switch (cmd) {
807
706
  break
808
707
  }
809
708
  const { handedOut } = await projectConfig(proj)
810
- // without --page, the fallback: only what no other listener would take, on any page, as it comes
811
- // and once they stop listening (an answer left in the log, too)
812
- const fallback = !f.page
813
- let recheck = () => {}
814
- const others = fallback ? (await listen(f, cmd, true), await otherListeners(() => recheck())) : null
815
- // The fallback's copy of who else listens can lag a moment behind a wait that just started, so
816
- // it holds each event briefly before deciding: by then that wait took it, or the copy knows.
817
- const held = new Set<string>()
818
- const skip = (e: WbEvent) => {
819
- if (!held.has(e.id)) {
820
- held.add(e.id)
821
- setTimeout(() => recheck(), 500).unref()
822
- return true
823
- }
824
- return takenByOther(others!(), e)
709
+ const query = {
710
+ command: cmd,
711
+ ...(f.page ? { page: f.page } : {}),
712
+ ...(f.type ? { type: f.type } : {}),
825
713
  }
826
- handOut(proj.eventsFile, f, e => console.log(JSON.stringify(e)), {
827
- count: cmd === 'wait' ? Number(opts.count ?? 1) : Infinity,
828
- forAgent: forAgent(handedOut),
829
- ...(others && {
830
- skip,
831
- recheck: again => {
832
- recheck = again
833
- },
834
- }),
835
- }).then(async () => {
836
- // a wait on a page ends with an answer, and the agent acts on it; what is still unanswered
837
- // there needs the next wait, which is easily forgotten: say so, right with the answer
838
- if (cmd === 'wait' && !fallback) {
839
- try {
840
- const pages = (await api(`/api/status?page=${encodeURIComponent(f.page!)}`)) as PageStatus[]
841
- for (const p of pages)
842
- if (p.open.length)
843
- console.error(
844
- `whiteboard: still unanswered on ${p.page}: ${p.open.join(', ')} → run \`whiteboard wait --page ${relFile(p.file)}\` again, in the background, once you've acted on this`,
845
- )
846
- } catch {
847
- /* no status: the answer is what matters */
848
- }
849
- }
850
- process.exit(0)
851
- })
852
- if (!fallback) listen(f, cmd)
714
+ const refused = (reason: string) => {
715
+ console.error(
716
+ `whiteboard: ${reason}: another agent already takes what no other listener does (a wait or watch without --page; one per project). Add --page to wait on a page of your own.`,
717
+ )
718
+ process.exit(1)
719
+ }
720
+ const at = () => needServer().catch(() => null)
721
+ const options = { count: cmd === 'wait' ? Number(opts.count ?? 1) : Infinity, forAgent: forAgent(handedOut) }
853
722
  if (opts.timeout && cmd === 'wait')
854
723
  setTimeout(
855
724
  () => {
@@ -858,6 +727,37 @@ switch (cmd) {
858
727
  },
859
728
  Number(opts.timeout) * 1000,
860
729
  )
730
+ // without --page, the fallback: only what no other listener would take, on any page, as it comes
731
+ // and once they stop listening (an answer left in the log, too)
732
+ const fallback = !f.page
733
+ if (fallback) {
734
+ const update = fallbackLoop((_, handing) => {
735
+ void handOut(proj.eventsFile, f, e => console.log(JSON.stringify(e)), { ...options, ...handing }).then(() =>
736
+ process.exit(0),
737
+ )
738
+ })
739
+ await listen({ at, query: { ...query, fallback: '' }, onSnapshot: update, onRefused: refused })
740
+ } else {
741
+ // registered before it reads the log, so a fallback leaves its answers to it from the first one
742
+ await listen({ at, query, onRefused: refused }, { orNone: true })
743
+ void handOut(proj.eventsFile, f, e => console.log(JSON.stringify(e)), options).then(async () => {
744
+ // a wait on a page ends with an answer, and the agent acts on it; what is still unanswered
745
+ // there needs the next wait, which is easily forgotten: say so, right with the answer
746
+ if (cmd === 'wait') {
747
+ try {
748
+ const pages = (await api(`/api/status?page=${encodeURIComponent(f.page!)}`)) as PageStatus[]
749
+ for (const p of pages)
750
+ if (p.open.length)
751
+ console.error(
752
+ `whiteboard: still unanswered on ${p.page}: ${p.open.join(', ')} → run \`whiteboard wait --page ${relFile(p.file)}\` again, in the background, once you've acted on this`,
753
+ )
754
+ } catch {
755
+ /* no status: the answer is what matters */
756
+ }
757
+ }
758
+ process.exit(0)
759
+ })
760
+ }
861
761
  break
862
762
  }
863
763
  case 'append': {
@@ -992,98 +892,41 @@ async function entryFallback(entry: string, f: EventFilter, command: 'wait' | 'w
992
892
  },
993
893
  Number(opts.timeout) * 1000,
994
894
  )
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) {
895
+ let origin = ''
896
+ const page = (id: string) => id.split('/').map(encodeURIComponent).join('/')
897
+ // a hand-out per project of the entry, as the shared server names them, each event with its
898
+ // project and its page's address
899
+ const update = fallbackLoop((p, handing) => {
1032
900
  const proj = projectAt(p.dir)
1033
901
  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
902
+ void projectConfig(proj).then(({ handedOut }) =>
903
+ handOut(
904
+ proj.eventsFile,
905
+ { type: f.type },
906
+ e => {
907
+ console.log(JSON.stringify({ ...e, project: p.dir, url: `${origin}${p.base}/${page(e.page)}` }))
908
+ if (++total >= count) done.abort()
1069
909
  },
1070
- },
910
+ { forAgent: forAgent(handedOut), ...handing, signal: AbortSignal.any([handing.signal, done.signal]) },
911
+ ),
1071
912
  )
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)
913
+ })
914
+ // held at the shared server for as long as this runs (again after a restart); without one running
915
+ // it waits for one, as any wait does: who else listens is the server's to say
916
+ await listen({
917
+ at: async () => {
918
+ origin = (await sharedServer(file))?.origin ?? ''
919
+ return origin || null
920
+ },
921
+ query: { entry, command, ...(f.type ? { type: f.type } : {}) },
922
+ onSnapshot: update,
923
+ onRefused: reason => {
924
+ console.error(`whiteboard: ${reason}. Add --page to wait on a page of your own.`)
925
+ process.exit(1)
926
+ },
927
+ })
928
+ // keeps the command running: the connection does not
929
+ setInterval(() => {}, 1 << 30)
1087
930
  }
1088
931
 
1089
932
  /** The commands the project's plugins add: `whiteboard <plugin> [sub]`. */