@bigmistqke/whiteboard 0.0.0-stage → 0.2.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 (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +628 -2
  3. package/bin/whiteboard.ts +488 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/whiteboard.js +542 -0
  6. package/dist/client/runtime.js +544 -0
  7. package/dist/define.js +7 -0
  8. package/dist/plugins/callout/README.md +13 -0
  9. package/dist/plugins/callout/index.js +27 -0
  10. package/dist/plugins/callout/style.css +12 -0
  11. package/dist/plugins/chat/README.md +46 -0
  12. package/dist/plugins/chat/client.js +3 -0
  13. package/dist/plugins/chat/index.js +47 -0
  14. package/dist/plugins/chat/style.css +24 -0
  15. package/dist/plugins/claude-code/index.js +120 -0
  16. package/dist/plugins/code/README.md +42 -0
  17. package/dist/plugins/code/diff.js +65 -0
  18. package/dist/plugins/code/index.js +77 -0
  19. package/dist/plugins/code/style.css +29 -0
  20. package/dist/plugins/comments/client.js +10 -0
  21. package/dist/plugins/comments/index.js +54 -0
  22. package/dist/plugins/comments/style.css +40 -0
  23. package/dist/plugins/details/README.md +17 -0
  24. package/dist/plugins/details/index.js +17 -0
  25. package/dist/plugins/details/style.css +3 -0
  26. package/dist/plugins/forge/README.md +12 -0
  27. package/dist/plugins/forge/index.js +83 -0
  28. package/dist/plugins/form/README.md +111 -0
  29. package/dist/plugins/form/index.js +102 -0
  30. package/dist/plugins/form/style.css +41 -0
  31. package/dist/plugins/gallery/README.md +30 -0
  32. package/dist/plugins/gallery/client.js +1 -0
  33. package/dist/plugins/gallery/index.js +74 -0
  34. package/dist/plugins/gallery/style.css +27 -0
  35. package/dist/plugins/grid/README.md +33 -0
  36. package/dist/plugins/grid/index.js +33 -0
  37. package/dist/plugins/grid/style.css +25 -0
  38. package/dist/plugins/iframe/README.md +18 -0
  39. package/dist/plugins/iframe/client.js +1 -0
  40. package/dist/plugins/iframe/index.js +40 -0
  41. package/dist/plugins/iframe/style.css +29 -0
  42. package/dist/plugins/index.js +30 -0
  43. package/dist/plugins/mermaid/README.md +21 -0
  44. package/dist/plugins/mermaid/index.js +35 -0
  45. package/dist/plugins/mermaid/style.css +16 -0
  46. package/dist/plugins/quiet/README.md +26 -0
  47. package/dist/plugins/quiet/index.js +17 -0
  48. package/dist/plugins/terminal/client.js +41 -0
  49. package/dist/plugins/terminal/host.js +332 -0
  50. package/dist/plugins/terminal/index.js +171 -0
  51. package/dist/plugins/terminal/modes.js +32 -0
  52. package/dist/plugins/terminal/server.js +256 -0
  53. package/dist/plugins/terminal/sizes.js +57 -0
  54. package/dist/plugins/terminal/style.css +357 -0
  55. package/dist/solid/index.js +36 -0
  56. package/dist/src/auth.js +54 -0
  57. package/dist/src/client/page/base.css +295 -0
  58. package/dist/src/client/page/main.js +1228 -0
  59. package/dist/src/config.js +76 -0
  60. package/dist/src/events.js +183 -0
  61. package/dist/src/html.js +34 -0
  62. package/dist/src/icons.js +6 -0
  63. package/dist/src/load.js +77 -0
  64. package/dist/src/loader.js +126 -0
  65. package/dist/src/package.js +33 -0
  66. package/dist/src/pages/blocks.js +50 -0
  67. package/dist/src/pages/index.js +15 -0
  68. package/dist/src/pages/markdown.js +410 -0
  69. package/dist/src/pages/render.js +311 -0
  70. package/dist/src/plugins.js +238 -0
  71. package/dist/src/running.js +24 -0
  72. package/dist/src/serve.js +71 -0
  73. package/dist/src/server.js +725 -0
  74. package/dist/src/status.js +71 -0
  75. package/package.json +131 -4
  76. package/plugins/callout/README.md +13 -0
  77. package/plugins/callout/index.ts +25 -0
  78. package/plugins/callout/style.css +12 -0
  79. package/plugins/chat/README.md +46 -0
  80. package/plugins/chat/autosize.ts +101 -0
  81. package/plugins/chat/client.tsx +93 -0
  82. package/plugins/chat/index.ts +61 -0
  83. package/plugins/chat/style.css +24 -0
  84. package/plugins/claude-code/index.ts +136 -0
  85. package/plugins/code/README.md +42 -0
  86. package/plugins/code/diff.ts +64 -0
  87. package/plugins/code/index.ts +94 -0
  88. package/plugins/code/style.css +29 -0
  89. package/plugins/comments/client.ts +492 -0
  90. package/plugins/comments/index.ts +54 -0
  91. package/plugins/comments/style.css +40 -0
  92. package/plugins/details/README.md +17 -0
  93. package/plugins/details/index.ts +21 -0
  94. package/plugins/details/style.css +3 -0
  95. package/plugins/forge/README.md +12 -0
  96. package/plugins/forge/index.ts +71 -0
  97. package/plugins/form/README.md +111 -0
  98. package/plugins/form/index.ts +104 -0
  99. package/plugins/form/style.css +41 -0
  100. package/plugins/gallery/README.md +30 -0
  101. package/plugins/gallery/client.tsx +64 -0
  102. package/plugins/gallery/index.ts +67 -0
  103. package/plugins/gallery/style.css +27 -0
  104. package/plugins/grid/README.md +33 -0
  105. package/plugins/grid/index.ts +36 -0
  106. package/plugins/grid/style.css +25 -0
  107. package/plugins/iframe/README.md +18 -0
  108. package/plugins/iframe/client.ts +46 -0
  109. package/plugins/iframe/index.ts +54 -0
  110. package/plugins/iframe/style.css +29 -0
  111. package/plugins/index.ts +21 -0
  112. package/plugins/mermaid/README.md +21 -0
  113. package/plugins/mermaid/index.ts +40 -0
  114. package/plugins/mermaid/style.css +16 -0
  115. package/plugins/quiet/README.md +26 -0
  116. package/plugins/quiet/index.ts +27 -0
  117. package/plugins/terminal/client.ts +317 -0
  118. package/plugins/terminal/host.ts +326 -0
  119. package/plugins/terminal/index.ts +138 -0
  120. package/plugins/terminal/modes.ts +30 -0
  121. package/plugins/terminal/server.ts +215 -0
  122. package/plugins/terminal/sizes.ts +60 -0
  123. package/plugins/terminal/style.css +71 -0
  124. package/skills/whiteboard/SKILL.md +302 -0
  125. package/solid/index.tsx +59 -0
  126. package/src/auth.ts +66 -0
  127. package/src/client/forms.ts +185 -0
  128. package/src/client/markdown.ts +36 -0
  129. package/src/client/page/base.css +295 -0
  130. package/src/client/page/elsewhere.ts +70 -0
  131. package/src/client/page/fresh.ts +205 -0
  132. package/src/client/page/live.ts +30 -0
  133. package/src/client/page/main.ts +272 -0
  134. package/src/client/page/orphans.ts +46 -0
  135. package/src/client/page/sort.ts +38 -0
  136. package/src/client/page/theme.ts +32 -0
  137. package/src/client/page/view.ts +9 -0
  138. package/src/client/page/waiting.ts +182 -0
  139. package/src/client/read.ts +73 -0
  140. package/src/client/runtime.ts +183 -0
  141. package/src/client/toast.ts +25 -0
  142. package/src/config.ts +96 -0
  143. package/src/define.ts +612 -0
  144. package/src/events.ts +218 -0
  145. package/src/html.ts +40 -0
  146. package/src/icons.ts +8 -0
  147. package/src/load.ts +89 -0
  148. package/src/loader.ts +112 -0
  149. package/src/package.ts +39 -0
  150. package/src/pages/blocks.ts +70 -0
  151. package/src/pages/index.ts +42 -0
  152. package/src/pages/markdown.ts +364 -0
  153. package/src/pages/render.ts +233 -0
  154. package/src/plugins.ts +197 -0
  155. package/src/running.ts +22 -0
  156. package/src/serve.ts +52 -0
  157. package/src/server.ts +667 -0
  158. package/src/status.ts +113 -0
package/src/events.ts ADDED
@@ -0,0 +1,218 @@
1
+ // The project's events, one JSON object per line, in `.whiteboard/events.ndjson`. An event has a
2
+ // `type`: a submitted form's type is the form's name; a plugin can append events of its own.
3
+ //
4
+ // Two layers. The primitives work on the log and nothing else: read it, follow it, append to it,
5
+ // record that an event was picked up. Handing out (`handOut`) is built from them alone: it gives
6
+ // each answer to an agent once, also one given before it started, and never the agent's own. The
7
+ // command line offers both (`events`, `events --follow`, `append`, `pick`; `wait`, `watch`), and a
8
+ // script can import them (`@bigmistqke/whiteboard/log`) to use the log in ways of its own.
9
+ import fs from 'node:fs'
10
+ import crypto from 'node:crypto'
11
+ import type { WbEvent } from './define.ts'
12
+ import { fromReader } from './status.ts'
13
+
14
+ export { fromReader }
15
+
16
+ /** What is appended: the id and time are added. */
17
+ export interface EventInput {
18
+ page?: unknown
19
+ type?: unknown
20
+ action?: string | null
21
+ data?: Record<string, unknown>
22
+ }
23
+
24
+ /** Which events: `page` (and the pages below it) and `type`, as `whiteboard wait` takes them. */
25
+ export interface EventFilter {
26
+ page?: string | null
27
+ type?: string | null
28
+ /** `page` alone, not the pages below it */
29
+ exact?: boolean
30
+ }
31
+
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
+ // ---- primitives ----------------------------------------------------------------------------------
39
+
40
+ /**
41
+ * Append one event; `action` is the button that submitted a form, null for anything else. `from`
42
+ * is set only for events the command line writes ('cli'), so that waits skip them and pages can
43
+ * tell them apart; what the browser appends has none.
44
+ */
45
+ export function appendEvent(file: string, input: EventInput, from: 'cli' | null = null): WbEvent {
46
+ const event: WbEvent = {
47
+ id: `${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`,
48
+ ts: new Date().toISOString(),
49
+ page: String(input.page ?? ''),
50
+ type: String(input.type ?? ''),
51
+ action: input.action ?? null,
52
+ data: input.data ?? {},
53
+ ...(from ? { from } : {}),
54
+ }
55
+ fs.appendFileSync(file, JSON.stringify(event) + '\n')
56
+ return event
57
+ }
58
+
59
+ export function parseLines(text: string): WbEvent[] {
60
+ const out: WbEvent[] = []
61
+ for (const line of text.split('\n')) {
62
+ if (!line.trim()) continue
63
+ let event
64
+ try { event = JSON.parse(line) } catch { continue /* a corrupt line */ }
65
+ out.push(event)
66
+ }
67
+ return out
68
+ }
69
+
70
+ export function readEvents(file: string): WbEvent[] {
71
+ return read(file).events
72
+ }
73
+
74
+ /**
75
+ * The events in the log, and the byte offset they end at: after its last whole line. A line still
76
+ * being written is left out, and following from `end` gets it whole, so reading and then following
77
+ * from `end` never loses or splits an event.
78
+ */
79
+ export function read(file: string): { events: WbEvent[]; end: number } {
80
+ let buf: Buffer
81
+ try { buf = fs.readFileSync(file) } catch { return { events: [], end: 0 } }
82
+ const end = buf.lastIndexOf(0x0a) + 1
83
+ return { events: parseLines(buf.subarray(0, end).toString('utf8')), end }
84
+ }
85
+
86
+ /**
87
+ * Call `onEvent` for each event appended to the log from byte `from` on (a line boundary, such as
88
+ * `read`'s `end`), in order, as whole lines arrive. Checks every `interval` ms (default 200).
89
+ * Returns a function that stops it.
90
+ */
91
+ export function follow(file: string, from: number, onEvent: (event: WbEvent) => void, { interval = 200 } = {}): () => void {
92
+ let offset = from
93
+ let partial = ''
94
+ const poll = () => {
95
+ let size: number
96
+ try { size = fs.statSync(file).size } catch { return }
97
+ if (size < offset) { offset = 0; partial = '' } // truncated
98
+ if (size === offset) return
99
+ const fd = fs.openSync(file, 'r')
100
+ const buf = Buffer.alloc(size - offset)
101
+ fs.readSync(fd, buf, 0, buf.length, offset)
102
+ fs.closeSync(fd)
103
+ offset = size
104
+ const text = partial + buf.toString('utf8')
105
+ const cut = text.lastIndexOf('\n')
106
+ partial = text.slice(cut + 1)
107
+ for (const e of parseLines(text.slice(0, cut + 1))) onEvent(e)
108
+ }
109
+ const timer = setInterval(poll, interval)
110
+ return () => clearInterval(timer)
111
+ }
112
+
113
+ /** `page` matches the page itself and every page below it, unless `exact`. */
114
+ export function matches(event: WbEvent, { page, type, exact }: EventFilter = {}): boolean {
115
+ if (page && event.page !== page && (exact || !event.page.startsWith(page + '/'))) return false
116
+ if (type && event.type !== type) return false
117
+ return true
118
+ }
119
+
120
+ // When an event is handed to an agent, a `whiteboard:picked` event naming it is appended. The log
121
+ // is the only record: a wait that starts hands out the matching events nobody picked up yet,
122
+ // whatever its filter, and pages show the same events as picked up.
123
+
124
+ /** The type of the event that says another event was handed to an agent: `{ event: <its id> }`. */
125
+ export const PICKED = 'whiteboard:picked'
126
+
127
+ /** The ids of the events that were picked up. Only the command line's picks count. */
128
+ export function pickedUp(events: WbEvent[]): Set<string> {
129
+ return new Set(events.filter(e => e.type === PICKED && !fromReader(e)).map(e => String(e.data?.event)))
130
+ }
131
+
132
+ /** Record that `event` was handed to an agent: from then on it counts as picked up. */
133
+ export function pick(file: string, event: WbEvent): WbEvent {
134
+ return appendEvent(file, { page: event.page, type: PICKED, data: { event: event.id } }, 'cli')
135
+ }
136
+
137
+ // ---- handing out ---------------------------------------------------------------------------------
138
+
139
+ /**
140
+ * Which event types reach an agent unasked: a form's answers (types without a colon) always, and of
141
+ * the plugins' events (`<plugin>:<what>`) those declared `handOut: true`, given in `handedOut`.
142
+ */
143
+ export const forAgent = (handedOut: ReadonlySet<string> = new Set()) => (type: string): boolean =>
144
+ !type.includes(':') || handedOut.has(type)
145
+
146
+ export interface HandOutOptions {
147
+ /** which event types it hands out unasked (see forAgent); a filter's `type` is handed out always */
148
+ forAgent?: (type: string) => boolean
149
+ /** stop after this many (default: no limit) */
150
+ count?: number
151
+ /** after the backlog, follow the log for new events (default true) */
152
+ follow?: boolean
153
+ /** how often to look for new events, in ms (default 200) */
154
+ interval?: number
155
+ /** stops following */
156
+ signal?: AbortSignal
157
+ /**
158
+ * Leave an event for now (the fallback: another listener would take it). A left event is looked
159
+ * at again each time `recheck` calls back, and handed out then if nobody picked it up meanwhile
160
+ * and it is no longer left.
161
+ */
162
+ skip?: (event: WbEvent) => boolean
163
+ recheck?: (again: () => void) => void
164
+ }
165
+
166
+ /**
167
+ * Hand the reader's events that match `filter` to `onEvent`, each marked as picked up once it is
168
+ * handed out. First the backlog: those nobody picked up yet, also from before this started,
169
+ * whatever filter picked up the others. Then, with `follow`, every new one as it comes, also when
170
+ * another running hand-out gets it too. The backlog and the following split the log at one line
171
+ * boundary, so no event falls between them. Events an agent wrote are never handed out, and of the
172
+ * plugins' events only those for an agent (`forAgent`), unless the filter asks for a type by name.
173
+ *
174
+ * Resolves with how many were handed out: once `count` is reached, after the backlog without
175
+ * `follow`, or when `signal` aborts.
176
+ */
177
+ export function handOut(file: string, filter: EventFilter, onEvent: (event: WbEvent) => void, options: HandOutOptions = {}): Promise<number> {
178
+ const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent(), skip, recheck } = options
179
+ return new Promise(resolve => {
180
+ let got = 0
181
+ let stop = () => {}
182
+ const finish = () => { stop(); signal?.removeEventListener('abort', finish); resolve(got) }
183
+ // the reader's events, and of those, the ones for an agent, unless the filter names a type
184
+ const wanted = (e: WbEvent) => fromReader(e) && matches(e, filter) && (!!filter.type || isForAgent(e.type))
185
+ // false once enough were handed out
186
+ const hand = (e: WbEvent) => {
187
+ onEvent(e)
188
+ pick(file, e)
189
+ return ++got < count
190
+ }
191
+ // the events left for now (skip), by id
192
+ const left = new Map<string, WbEvent>()
193
+ // false once enough were handed out; a left event is kept to look at again
194
+ const offer = (e: WbEvent) => {
195
+ if (skip?.(e)) { left.set(e.id, e); return true }
196
+ return hand(e)
197
+ }
198
+ if (count <= 0 || signal?.aborted) return finish()
199
+ const { events, end } = read(file)
200
+ const picked = pickedUp(events)
201
+ for (const e of events) {
202
+ if (wanted(e) && !picked.has(e.id) && !offer(e)) return finish()
203
+ }
204
+ if (!following) return finish()
205
+ signal?.addEventListener('abort', finish)
206
+ recheck?.(() => {
207
+ if (!left.size || got >= count) return
208
+ const picked = pickedUp(read(file).events)
209
+ for (const [id, e] of left) {
210
+ if (picked.has(id)) { left.delete(id); continue }
211
+ if (skip?.(e)) continue
212
+ left.delete(id)
213
+ if (!hand(e)) return finish()
214
+ }
215
+ })
216
+ stop = follow(file, end, e => { if (got < count && wanted(e) && !offer(e)) finish() }, { interval })
217
+ })
218
+ }
package/src/html.ts ADDED
@@ -0,0 +1,40 @@
1
+ // HTML from a template literal, escaped by default:
2
+ //
3
+ // html`<li><a href="/${id}">${title}</a></li>`
4
+ //
5
+ // Every interpolated value is escaped, in text and in attributes alike, unless it is HTML already:
6
+ // what `html` itself returns, or a string passed through `raw()` on purpose (markdown's output, say).
7
+ // An array is joined, so `${items.map(i => html`<li>${i}</li>`)}` needs no `.join('')`; null,
8
+ // undefined and false render as nothing, so `${cond && html`…`}` works when `cond` is a boolean (a
9
+ // count of 0 would render as 0: write `count > 0 && …`).
10
+ //
11
+ // Everything that builds HTML uses it: the core's page shell, the page on the server and in the
12
+ // browser, and plugins (`import { html, raw } from '@bigmistqke/whiteboard'`).
13
+
14
+ /** A piece of HTML that is not escaped again. `String(piece)` is its markup. */
15
+ export class Html {
16
+ value: string
17
+ constructor(value: string) { this.value = value }
18
+ toString() { return this.value }
19
+ }
20
+
21
+ const ESCAPE: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }
22
+
23
+ /** Text → HTML that shows it as text. */
24
+ export const escape = (value: unknown): string => String(value).replace(/[&<>"']/g, c => ESCAPE[c]!)
25
+
26
+ /** Markup to use as it is: only for HTML that is safe already, never for text from outside. */
27
+ export const raw = (value: unknown): Html => new Html(String(value ?? ''))
28
+
29
+ function part(value: unknown): string {
30
+ if (value == null || value === false) return ''
31
+ if (value instanceof Html) return value.value
32
+ if (Array.isArray(value)) return value.map(part).join('')
33
+ return escape(value)
34
+ }
35
+
36
+ export function html(strings: TemplateStringsArray, ...values: unknown[]): Html {
37
+ let out = strings[0]!
38
+ for (let i = 0; i < values.length; i++) out += part(values[i]) + strings[i + 1]
39
+ return new Html(out)
40
+ }
package/src/icons.ts ADDED
@@ -0,0 +1,8 @@
1
+ // Icons the page and the server both draw, as SVG markup. No Node in it: the browser runtime
2
+ // imports it too.
3
+
4
+ /** An inbox: what awaits the reader (the header's menu, the overview). */
5
+ export const INBOX_ICON = '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path d="M2 9.5 3.8 3.2A1 1 0 0 1 4.8 2.5h6.4a1 1 0 0 1 1 .7L14 9.5V13a.5.5 0 0 1-.5.5h-11A.5.5 0 0 1 2 13Zm0 0h3.5l1 1.5h3l1-1.5H14" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/></svg>'
6
+
7
+ /** "Awaiting you: 2 things", and where: what the inbox says to a reader who hovers it. */
8
+ export const awaitingLabel = (n: number, where = '') => `Awaiting you: ${n === 1 ? '1 question or message' : `${n} questions and messages`}${where}`
package/src/load.ts ADDED
@@ -0,0 +1,89 @@
1
+ // Loading a project's config with Node itself: Node runs the TypeScript of `config.ts`, and these
2
+ // hooks do the two things it cannot do alone.
3
+ //
4
+ // - `@bigmistqke/whiteboard` and its parts always mean this engine's own files, so a config works in a
5
+ // project without node_modules (a Rust repository, a home folder), and it always matches the
6
+ // server that runs it. Which file a subpath is comes from the package's `exports`, read afresh
7
+ // on every resolve, so a part added to the package works without restarting the server: its
8
+ // `source` (the TypeScript) when the engine runs from source, else its build.
9
+ // - Reloading. Node evaluates a module once per URL; the config and every local module it imports
10
+ // get a version in their URL, and a new version imports them again. Modules in node_modules are
11
+ // left alone: they don't change while the server runs.
12
+ import fs from 'node:fs'
13
+ import { registerHooks, type ModuleFormat } from 'node:module'
14
+ import path from 'node:path'
15
+ import { pathToFileURL } from 'node:url'
16
+ import { FROM_SOURCE, PACKAGE_DIR } from './package.ts'
17
+
18
+ const ENGINE_DIR = PACKAGE_DIR
19
+ const PACKAGE = '@bigmistqke/whiteboard'
20
+
21
+ /** The file `@bigmistqke/whiteboard` or one of its parts is, by the package's `exports`; null for none. */
22
+ function ownFile(specifier: string): string | null {
23
+ if (specifier !== PACKAGE && !specifier.startsWith(PACKAGE + '/')) return null
24
+ let exports: Record<string, string | { source?: string; default?: string }> | undefined
25
+ try { exports = JSON.parse(fs.readFileSync(path.join(ENGINE_DIR, 'package.json'), 'utf8')).exports } catch { return null }
26
+ const target = exports?.[specifier === PACKAGE ? '.' : `./${specifier.slice(PACKAGE.length + 1)}`]
27
+ const file = typeof target === 'string' ? target : (FROM_SOURCE && target?.source) || target?.default
28
+ return file ? path.join(ENGINE_DIR, file) : null
29
+ }
30
+
31
+ const versionOf = (url: string) => new URL(url).searchParams.get('wb-v')
32
+
33
+ /**
34
+ * Install the hooks, once: the first time something loads a config or the package's own parts, not
35
+ * on import, so a command that loads nothing leaves the process's module loading alone.
36
+ */
37
+ let installed = false
38
+ export function installHooks() {
39
+ if (installed) return
40
+ installed = true
41
+ registerHooks({
42
+ resolve(specifier, context, next) {
43
+ const own = ownFile(specifier)
44
+ if (own) {
45
+ const url = pathToFileURL(own).href
46
+ const v = context.parentURL && versionOf(context.parentURL)
47
+ return { url: v ? `${url}?wb-v=${v}` : url, shortCircuit: true, format: moduleFormat(own) ?? 'module' }
48
+ }
49
+ const resolved = next(specifier, context)
50
+ if (!resolved.url.startsWith('file:') || resolved.url.includes('/node_modules/')) return resolved
51
+ const v = versionOf(resolved.url) ?? (context.parentURL?.startsWith('file:') && versionOf(context.parentURL))
52
+ if (!v) return resolved
53
+ const url = new URL(resolved.url)
54
+ url.searchParams.set('wb-v', v)
55
+ // A .whiteboard folder has no package.json of its own to say these are ES modules, so Node goes
56
+ // by the nearest one above it: in a repository whose package.json is CommonJS (no "type"), it
57
+ // would load the config as CommonJS and fail on its imports. What is in .whiteboard/ is always
58
+ // a module, by its extension; other local files keep the format their package gives them.
59
+ const inProject = url.pathname.split('/').includes('.whiteboard')
60
+ return { ...resolved, url: url.href, format: inProject ? moduleFormat(url.pathname) : resolved.format ?? moduleFormat(url.pathname) }
61
+ },
62
+ })
63
+ }
64
+
65
+ function moduleFormat(file: string): ModuleFormat | undefined {
66
+ if (/\.[mc]?ts$/.test(file)) return file.endsWith('.cts') ? 'commonjs-typescript' : 'module-typescript'
67
+ if (/\.c?js$/.test(file)) return file.endsWith('.cjs') ? 'commonjs' : 'module'
68
+ return undefined
69
+ }
70
+
71
+ let version = 0
72
+
73
+ /**
74
+ * Import one of the package's own parts (`plugins`) afresh, with everything it imports, the way
75
+ * `importFresh` does a config: for what the core loads itself on a config's behalf, such as the
76
+ * built-in plugins, which must reload along with the config.
77
+ */
78
+ export function importOwn(part: string): Promise<any> {
79
+ installHooks()
80
+ const file = ownFile(`${PACKAGE}/${part}`)
81
+ if (!file) throw new Error(`the package has no part "${part}"`)
82
+ return import(`${pathToFileURL(file).href}?wb-v=${++version}`)
83
+ }
84
+
85
+ /** Import `file` and everything local it imports afresh. */
86
+ export function importFresh(file: string): Promise<any> {
87
+ installHooks()
88
+ return import(`${pathToFileURL(file).href}?wb-v=${++version}`)
89
+ }
package/src/loader.ts ADDED
@@ -0,0 +1,112 @@
1
+ // The project's config: its plugins, its stylesheet and whether it serves the repository's files.
2
+ // Node loads it (see load.ts), so it can be TypeScript and import plugins from the project's own
3
+ // node_modules. What the loader makes of it: the plugins (the built-in ones, then the config's), and
4
+ // the pages (how markdown is rendered with their blocks).
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { importFresh, importOwn } from './load.ts'
9
+ import { createPages, type Pages } from './pages/index.ts'
10
+ import { pluginCommands } from './plugins.ts'
11
+ import type { Config, Plugin } from './define.ts'
12
+ import type { Project } from './config.ts'
13
+
14
+ /** A config as loaded: what went wrong is in `errors`. */
15
+ export interface LoadedConfig {
16
+ /** how pages render, with the plugins' blocks; null when the config failed to load, or for the command line */
17
+ pages: Pages | null
18
+ plugins: Plugin[]
19
+ /** the plugins' event types declared `handOut: true`: those that reach an agent unasked */
20
+ handedOut: Set<string>
21
+ /** the plugins' event types declared `forReader: true`: from the agent, a message for the reader */
22
+ forReader: Set<string>
23
+ files: boolean
24
+ errors: unknown[]
25
+ }
26
+
27
+ const NAME = /^[\w-]+$/
28
+ /** The command line's own commands: a plugin can't be named like one, since its commands are `whiteboard <name>`. */
29
+ export const BUILTIN_COMMANDS = new Set(['serve', 'init', 'root', 'new', 'show', 'url', 'docs', 'events', 'wait', 'watch', 'append', 'pick', 'status', 'skill', 'help'])
30
+ // folders in .whiteboard/ that are the core's or meant for the project's own plugins (a plugin's own
31
+ // folder holds its data, ignored by git), and the built-in commands
32
+ const RESERVED = new Set(['pages', 'plugins', ...BUILTIN_COMMANDS])
33
+
34
+ /** A plugin's own folder, `.whiteboard/<name>/`, made with a .gitignore that ignores all of it. */
35
+ export function pluginDir(wb: string, name: string): string {
36
+ const dir = path.join(wb, name)
37
+ fs.mkdirSync(dir, { recursive: true })
38
+ const ignore = path.join(dir, '.gitignore')
39
+ if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, `# what the ${name} plugin keeps; not for git\n*\n`)
40
+ return dir
41
+ }
42
+
43
+ /** A file reference (URL, file: URL string, or absolute path) → absolute path. */
44
+ export function toPath(ref: unknown): string {
45
+ if (ref instanceof URL || (typeof ref === 'string' && ref.startsWith('file:'))) return fileURLToPath(ref)
46
+ return String(ref)
47
+ }
48
+
49
+ /** The built-in plugins, afresh with every load of the config, like what a config imports itself. */
50
+ async function builtinPlugins(): Promise<Plugin[]> {
51
+ const { builtins } = await importOwn('plugins')
52
+ return builtins()
53
+ }
54
+
55
+ /** Check a plugin, as the config gives it. */
56
+ function checkPlugin(e: Plugin, where: string | null) {
57
+ if (typeof e !== 'object' || !NAME.test(e?.name ?? '')) throw new Error(`a plugin in ${where} needs a name: letters, digits, - and _`)
58
+ if (RESERVED.has(e.name)) throw new Error(`plugin name "${e.name}" in ${where} is taken by the core (a folder in .whiteboard/ or a command)`)
59
+ pluginCommands(e) // checks them
60
+ for (const type of Object.keys(e.events ?? {}))
61
+ if (!type.startsWith(`${e.name}:`) || type.length <= e.name.length + 1) throw new Error(`plugin ${e.name}: event type "${type}" must be named after it: ${e.name}:<what>`)
62
+ }
63
+
64
+ /**
65
+ * The config, cached until invalidate() (which loads it afresh). Errors are returned, not thrown:
66
+ * a config that fails to load leaves the project without its plugins, so pages show as raw text,
67
+ * and serves no repository files.
68
+ *
69
+ * The project's plugins are the built-in ones, then the config's: one with a built-in's name
70
+ * replaces it. Their blocks make the pages. `pages: false` leaves the pages out, for the command
71
+ * line, which only needs the plugins (their commands, the session, their events).
72
+ */
73
+ export function createConfigLoader(proj: Project, { pages: withPages = true } = {}) {
74
+ let cached: Promise<LoadedConfig> | null = null
75
+
76
+ async function load(): Promise<Omit<LoadedConfig, 'errors'>> {
77
+ // no config file: the defaults, the same as an empty config
78
+ const configFile = proj.configFile
79
+ const mod = configFile ? await importFresh(configFile) : { default: {} }
80
+ // a config can also be a function that returns one
81
+ const exported: Config | (() => Config | Promise<Config>) = mod.default
82
+ const config: Config = typeof exported === 'function' ? await exported() : exported
83
+ const plugins: Plugin[] = await builtinPlugins()
84
+ const builtin = new Set(plugins.map(p => p.name))
85
+ const added = new Set<string>()
86
+ for (const e of [config?.plugins ?? []].flat(Infinity) as Plugin[]) {
87
+ if (!e) continue
88
+ checkPlugin(e, configFile)
89
+ if (added.has(e.name)) throw new Error(`two plugins are named "${e.name}" in ${configFile}`)
90
+ added.add(e.name)
91
+ // one with a built-in's name replaces it, in its place
92
+ if (builtin.has(e.name)) plugins[plugins.findIndex(p => p.name === e.name)] = e
93
+ else plugins.push(e)
94
+ }
95
+ const blocks = plugins.flatMap(p => Object.entries(p.blocks ?? {}).map(([name, block]) => ({ name, block, plugin: p.name })))
96
+ const styles = plugins.map(p => p.style).filter((s): s is URL | string => !!s)
97
+ const links = plugins.flatMap(p => p.links ? [p.links.bind(p)] : [])
98
+ const pages = withPages ? createPages({ blocks, style: config?.style, styles, links }) : null
99
+ const declared = (flag: 'handOut' | 'forReader') => new Set(plugins.flatMap(p => Object.entries(p.events ?? {}).filter(([, spec]) => spec?.[flag]).map(([type]) => type)))
100
+ return { pages, plugins, handedOut: declared('handOut'), forReader: declared('forReader'), files: config?.files !== false }
101
+ }
102
+
103
+ function config(): Promise<LoadedConfig> {
104
+ cached ??= load().then(
105
+ value => ({ ...value, errors: [] }),
106
+ error => ({ pages: null, plugins: [], handedOut: new Set<string>(), forReader: new Set<string>(), files: false, errors: [error] }),
107
+ )
108
+ return cached
109
+ }
110
+
111
+ return { config, invalidate: () => { cached = null } }
112
+ }
package/src/package.ts ADDED
@@ -0,0 +1,39 @@
1
+ // Where this package is on disk. Its modules run from source in the repository and from dist/ once
2
+ // built, at different depths, so a path into the package is found from its root, never by counting
3
+ // folders up from a module.
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+
8
+ function findRoot(from: string): string {
9
+ for (let dir = from; ; dir = path.dirname(dir)) {
10
+ try {
11
+ if (JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).name === '@bigmistqke/whiteboard') return dir
12
+ } catch { /* no package.json here, or not ours */ }
13
+ if (path.dirname(dir) === dir) throw new Error(`whiteboard: no package.json of @bigmistqke/whiteboard above ${from}`)
14
+ }
15
+ }
16
+
17
+ /** The package's folder: where its package.json is. */
18
+ export const PACKAGE_DIR = findRoot(path.dirname(fileURLToPath(import.meta.url)))
19
+
20
+ /** A path inside the package. */
21
+ export const packagePath = (...parts: string[]) => path.join(PACKAGE_DIR, ...parts)
22
+
23
+ /**
24
+ * Is the engine running from its TypeScript source (`bin/whiteboard.ts`), rather than from its build
25
+ * (`dist/bin/whiteboard.js`, what an installed package runs)? Then what a config imports from the
26
+ * package comes from source too (the `source` export conditions), so the two never mix.
27
+ */
28
+ export const FROM_SOURCE = fileURLToPath(import.meta.url).endsWith('.ts')
29
+
30
+ /**
31
+ * A browser file built from the module at `moduleUrl`'s folder: `name` in that folder's place in
32
+ * dist/. The same whether the module runs from source (plugins/form/index.ts gives
33
+ * dist/plugins/form/client.js) or from dist/ itself.
34
+ */
35
+ export function builtFile(moduleUrl: string, name: string): string {
36
+ const rel = path.relative(PACKAGE_DIR, path.dirname(fileURLToPath(moduleUrl)))
37
+ const inDist = rel === 'dist' || rel.startsWith('dist' + path.sep)
38
+ return path.join(PACKAGE_DIR, inDist ? '' : 'dist', rel, name)
39
+ }
@@ -0,0 +1,70 @@
1
+ // The blocks of a project's plugins, checked and resolved into what the markdown engine uses.
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import type { Html } from '../html.ts'
6
+ import type { Block } from '../define.ts'
7
+
8
+ /** A block as the plugins bring it: its name, and the plugin it comes from. */
9
+ export interface BlockEntry { name: string; block: Block<any>; plugin: string }
10
+
11
+ const NAME = /^[\w-]+$/
12
+
13
+ /** A block as the engine uses it: checked, with its files as absolute paths. */
14
+ export interface ResolvedBlock {
15
+ name: string
16
+ /** the block for code in general (`fence: 'any'`) */
17
+ code: boolean
18
+ /** it renders the code fences of its name (`fence: true` or `'any'`) */
19
+ fences: boolean
20
+ props: ((ctx: any) => unknown) | null
21
+ html: ((ctx: any) => string | Html | null | Promise<string | Html | null>) | null
22
+ client: string | null
23
+ style: string | null
24
+ /** the plugin it comes from */
25
+ source: string
26
+ }
27
+
28
+ export interface ResolvedBlocks { blocks: Map<string, ResolvedBlock>; code: ResolvedBlock | null }
29
+
30
+ /** A block's file reference (URL, file: URL string, or absolute path) → absolute path. */
31
+ function toPath(ref: unknown, field: string, block: string): string | null {
32
+ if (ref == null) return null
33
+ if (ref instanceof URL || (typeof ref === 'string' && ref.startsWith('file:'))) return fileURLToPath(ref)
34
+ if (typeof ref === 'string' && path.isAbsolute(ref)) return ref
35
+ throw new Error(`block "${block}": ${field} must be a URL, e.g. new URL('./${field}.js', import.meta.url)`)
36
+ }
37
+
38
+ /** Check and resolve one block into what the engine uses. */
39
+ function normalize({ name, block: b, plugin }: BlockEntry): ResolvedBlock {
40
+ if (typeof b !== 'object' || !b) throw new Error(`plugin ${plugin}: block "${name}" is not an object`)
41
+ if (!NAME.test(name)) throw new Error(`plugin ${plugin}: block name ${JSON.stringify(name)}: use letters, digits, - and _`)
42
+ const files = { client: toPath(b.client, 'client', name), style: toPath(b.style, 'style', name) }
43
+ for (const [field, file] of Object.entries(files))
44
+ if (file && !fs.existsSync(file)) throw new Error(`plugin ${plugin}, block "${name}": ${field} file not found: ${file}`)
45
+ return {
46
+ name,
47
+ code: b.fence === 'any',
48
+ fences: b.fence === true || b.fence === 'any',
49
+ props: typeof b.props === 'function' ? b.props.bind(b) : null,
50
+ html: typeof b.html === 'function' ? b.html.bind(b) : null,
51
+ ...files,
52
+ source: plugin,
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Resolve the plugins' blocks. A block name is one plugin's: two plugins bringing the same block is
58
+ * an error. `code` is the block for code fences no block claims by name: the last one with
59
+ * `fence: 'any'`.
60
+ */
61
+ export function resolveBlocks(entries: BlockEntry[]): ResolvedBlocks {
62
+ const blocks = new Map<string, ResolvedBlock>()
63
+ for (const entry of entries) {
64
+ const n = normalize(entry)
65
+ const other = blocks.get(n.name)
66
+ if (other) throw new Error(`block "${n.name}" comes from two plugins: ${other.source} and ${n.source}`)
67
+ blocks.set(n.name, n)
68
+ }
69
+ return { blocks, code: [...blocks.values()].findLast(t => t.code) ?? null }
70
+ }
@@ -0,0 +1,42 @@
1
+ // Markdown pages: how the core turns a stored page into what the reader sees, with the blocks the
2
+ // project's plugins bring (`:::name`, `::name`, `:name`, ```` ```name ````). The loader makes one per
3
+ // loaded config (see loader.ts); the server renders with it.
4
+ import { resolveBlocks, type BlockEntry } from './blocks.ts'
5
+ import { createDocs, createMessageRender, createRender } from './render.ts'
6
+ import { formNames } from './markdown.ts'
7
+ import type { PageSource, RenderContext, Rendered, StoredPage } from '../define.ts'
8
+ import type { TextLink } from '../define.ts'
9
+
10
+ export interface PagesOptions {
11
+ /** the blocks of the project's plugins, in plugin order */
12
+ blocks: BlockEntry[]
13
+ /** the project's stylesheet, linked on every page after the others */
14
+ style?: URL | string
15
+ /** the plugins' stylesheets, linked on every page */
16
+ styles?: (URL | string)[]
17
+ /** the plugins' text links (Plugin.links), each asked once per project folder */
18
+ links?: ((ctx: { dir: string }) => TextLink[])[]
19
+ }
20
+
21
+ /** How the core renders pages for one loaded config. */
22
+ export interface Pages {
23
+ /** a stored page as HTML, with its title, head additions and the data its browser part needs */
24
+ render(page: StoredPage, ctx: RenderContext): Promise<Rendered>
25
+ /** how pages are written, and which blocks the plugins bring: what `whiteboard docs` prints first */
26
+ docs(ctx: RenderContext): string
27
+ /** the questions a page asks: its named forms, whose answers are events of their name */
28
+ questions(page: PageSource): string[]
29
+ /** a message's markdown (a comment, a chat message) as HTML, and the stylesheets it needs */
30
+ message(text: string, ctx: RenderContext): Promise<{ html: string; styles: string[] }>
31
+ }
32
+
33
+ export function createPages(options: PagesOptions): Pages {
34
+ const resolved = resolveBlocks(options.blocks)
35
+ const blocks = () => resolved
36
+ return {
37
+ render: createRender(blocks, options.style, options.styles ?? [], options.links ?? []),
38
+ message: createMessageRender(blocks, options.links ?? []),
39
+ docs: createDocs(blocks),
40
+ questions: page => formNames(page.source),
41
+ }
42
+ }