@bigmistqke/whiteboard 0.0.0-stage → 0.1.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 (138) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +609 -2
  3. package/bin/whiteboard.ts +431 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/whiteboard.js +471 -0
  6. package/dist/client/runtime.js +391 -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 +45 -0
  12. package/dist/plugins/chat/client.js +3 -0
  13. package/dist/plugins/chat/index.js +46 -0
  14. package/dist/plugins/chat/style.css +17 -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 +64 -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 +51 -0
  22. package/dist/plugins/comments/style.css +32 -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/form/README.md +111 -0
  27. package/dist/plugins/form/index.js +102 -0
  28. package/dist/plugins/form/style.css +41 -0
  29. package/dist/plugins/gallery/README.md +30 -0
  30. package/dist/plugins/gallery/client.js +1 -0
  31. package/dist/plugins/gallery/index.js +74 -0
  32. package/dist/plugins/gallery/style.css +27 -0
  33. package/dist/plugins/grid/README.md +33 -0
  34. package/dist/plugins/grid/index.js +33 -0
  35. package/dist/plugins/grid/style.css +25 -0
  36. package/dist/plugins/index.js +26 -0
  37. package/dist/plugins/mermaid/README.md +21 -0
  38. package/dist/plugins/mermaid/index.js +34 -0
  39. package/dist/plugins/mermaid/style.css +16 -0
  40. package/dist/plugins/quiet/README.md +26 -0
  41. package/dist/plugins/quiet/index.js +17 -0
  42. package/dist/plugins/terminal/client.js +41 -0
  43. package/dist/plugins/terminal/host.js +332 -0
  44. package/dist/plugins/terminal/index.js +171 -0
  45. package/dist/plugins/terminal/modes.js +32 -0
  46. package/dist/plugins/terminal/server.js +256 -0
  47. package/dist/plugins/terminal/sizes.js +57 -0
  48. package/dist/plugins/terminal/style.css +357 -0
  49. package/dist/solid/index.js +35 -0
  50. package/dist/src/auth.js +54 -0
  51. package/dist/src/client/page/base.css +274 -0
  52. package/dist/src/client/page/main.js +1004 -0
  53. package/dist/src/config.js +76 -0
  54. package/dist/src/events.js +162 -0
  55. package/dist/src/html.js +34 -0
  56. package/dist/src/load.js +77 -0
  57. package/dist/src/loader.js +120 -0
  58. package/dist/src/package.js +33 -0
  59. package/dist/src/pages/blocks.js +49 -0
  60. package/dist/src/pages/index.js +14 -0
  61. package/dist/src/pages/markdown.js +307 -0
  62. package/dist/src/pages/render.js +257 -0
  63. package/dist/src/plugins.js +238 -0
  64. package/dist/src/running.js +24 -0
  65. package/dist/src/serve.js +71 -0
  66. package/dist/src/server.js +700 -0
  67. package/dist/src/status.js +43 -0
  68. package/package.json +131 -4
  69. package/plugins/callout/README.md +13 -0
  70. package/plugins/callout/index.ts +25 -0
  71. package/plugins/callout/style.css +12 -0
  72. package/plugins/chat/README.md +45 -0
  73. package/plugins/chat/autosize.ts +101 -0
  74. package/plugins/chat/client.tsx +81 -0
  75. package/plugins/chat/index.ts +61 -0
  76. package/plugins/chat/style.css +17 -0
  77. package/plugins/claude-code/index.ts +136 -0
  78. package/plugins/code/README.md +42 -0
  79. package/plugins/code/diff.ts +58 -0
  80. package/plugins/code/index.ts +94 -0
  81. package/plugins/code/style.css +29 -0
  82. package/plugins/comments/client.ts +448 -0
  83. package/plugins/comments/index.ts +52 -0
  84. package/plugins/comments/style.css +32 -0
  85. package/plugins/details/README.md +17 -0
  86. package/plugins/details/index.ts +21 -0
  87. package/plugins/details/style.css +3 -0
  88. package/plugins/form/README.md +111 -0
  89. package/plugins/form/index.ts +104 -0
  90. package/plugins/form/style.css +41 -0
  91. package/plugins/gallery/README.md +30 -0
  92. package/plugins/gallery/client.tsx +64 -0
  93. package/plugins/gallery/index.ts +67 -0
  94. package/plugins/gallery/style.css +27 -0
  95. package/plugins/grid/README.md +33 -0
  96. package/plugins/grid/index.ts +36 -0
  97. package/plugins/grid/style.css +25 -0
  98. package/plugins/index.ts +19 -0
  99. package/plugins/mermaid/README.md +21 -0
  100. package/plugins/mermaid/index.ts +39 -0
  101. package/plugins/mermaid/style.css +16 -0
  102. package/plugins/quiet/README.md +26 -0
  103. package/plugins/quiet/index.ts +27 -0
  104. package/plugins/terminal/client.ts +317 -0
  105. package/plugins/terminal/host.ts +326 -0
  106. package/plugins/terminal/index.ts +138 -0
  107. package/plugins/terminal/modes.ts +30 -0
  108. package/plugins/terminal/server.ts +215 -0
  109. package/plugins/terminal/sizes.ts +60 -0
  110. package/plugins/terminal/style.css +71 -0
  111. package/skills/whiteboard/SKILL.md +292 -0
  112. package/solid/index.tsx +56 -0
  113. package/src/auth.ts +66 -0
  114. package/src/client/forms.ts +186 -0
  115. package/src/client/page/base.css +274 -0
  116. package/src/client/page/fresh.ts +205 -0
  117. package/src/client/page/main.ts +249 -0
  118. package/src/client/page/orphans.ts +46 -0
  119. package/src/client/page/theme.ts +32 -0
  120. package/src/client/page/view.ts +9 -0
  121. package/src/client/page/waiting.ts +109 -0
  122. package/src/client/runtime.ts +170 -0
  123. package/src/config.ts +96 -0
  124. package/src/define.ts +546 -0
  125. package/src/events.ts +194 -0
  126. package/src/html.ts +40 -0
  127. package/src/load.ts +89 -0
  128. package/src/loader.ts +109 -0
  129. package/src/package.ts +39 -0
  130. package/src/pages/blocks.ts +67 -0
  131. package/src/pages/index.ts +36 -0
  132. package/src/pages/markdown.ts +276 -0
  133. package/src/pages/render.ts +196 -0
  134. package/src/plugins.ts +197 -0
  135. package/src/running.ts +22 -0
  136. package/src/serve.ts +52 -0
  137. package/src/server.ts +644 -0
  138. package/src/status.ts +69 -0
package/src/events.ts ADDED
@@ -0,0 +1,194 @@
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
+
159
+ /**
160
+ * Hand the reader's events that match `filter` to `onEvent`, each marked as picked up once it is
161
+ * handed out. First the backlog: those nobody picked up yet, also from before this started,
162
+ * whatever filter picked up the others. Then, with `follow`, every new one as it comes, also when
163
+ * another running hand-out gets it too. The backlog and the following split the log at one line
164
+ * boundary, so no event falls between them. Events an agent wrote are never handed out, and of the
165
+ * plugins' events only those for an agent (`forAgent`), unless the filter asks for a type by name.
166
+ *
167
+ * Resolves with how many were handed out: once `count` is reached, after the backlog without
168
+ * `follow`, or when `signal` aborts.
169
+ */
170
+ export function handOut(file: string, filter: EventFilter, onEvent: (event: WbEvent) => void, options: HandOutOptions = {}): Promise<number> {
171
+ const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent() } = options
172
+ return new Promise(resolve => {
173
+ let got = 0
174
+ let stop = () => {}
175
+ const finish = () => { stop(); signal?.removeEventListener('abort', finish); resolve(got) }
176
+ // the reader's events, and of those, the ones for an agent, unless the filter names a type
177
+ const wanted = (e: WbEvent) => fromReader(e) && matches(e, filter) && (!!filter.type || isForAgent(e.type))
178
+ // false once enough were handed out
179
+ const hand = (e: WbEvent) => {
180
+ onEvent(e)
181
+ pick(file, e)
182
+ return ++got < count
183
+ }
184
+ if (count <= 0 || signal?.aborted) return finish()
185
+ const { events, end } = read(file)
186
+ const picked = pickedUp(events)
187
+ for (const e of events) {
188
+ if (wanted(e) && !picked.has(e.id) && !hand(e)) return finish()
189
+ }
190
+ if (!following) return finish()
191
+ signal?.addEventListener('abort', finish)
192
+ stop = follow(file, end, e => { if (got < count && wanted(e) && !hand(e)) finish() }, { interval })
193
+ })
194
+ }
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/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,109 @@
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
+ files: boolean
22
+ errors: unknown[]
23
+ }
24
+
25
+ const NAME = /^[\w-]+$/
26
+ /** The command line's own commands: a plugin can't be named like one, since its commands are `whiteboard <name>`. */
27
+ export const BUILTIN_COMMANDS = new Set(['serve', 'init', 'root', 'new', 'show', 'url', 'docs', 'events', 'wait', 'watch', 'append', 'pick', 'status', 'skill', 'help'])
28
+ // folders in .whiteboard/ that are the core's or meant for the project's own plugins (a plugin's own
29
+ // folder holds its data, ignored by git), and the built-in commands
30
+ const RESERVED = new Set(['pages', 'plugins', ...BUILTIN_COMMANDS])
31
+
32
+ /** A plugin's own folder, `.whiteboard/<name>/`, made with a .gitignore that ignores all of it. */
33
+ export function pluginDir(wb: string, name: string): string {
34
+ const dir = path.join(wb, name)
35
+ fs.mkdirSync(dir, { recursive: true })
36
+ const ignore = path.join(dir, '.gitignore')
37
+ if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, `# what the ${name} plugin keeps; not for git\n*\n`)
38
+ return dir
39
+ }
40
+
41
+ /** A file reference (URL, file: URL string, or absolute path) → absolute path. */
42
+ export function toPath(ref: unknown): string {
43
+ if (ref instanceof URL || (typeof ref === 'string' && ref.startsWith('file:'))) return fileURLToPath(ref)
44
+ return String(ref)
45
+ }
46
+
47
+ /** The built-in plugins, afresh with every load of the config, like what a config imports itself. */
48
+ async function builtinPlugins(): Promise<Plugin[]> {
49
+ const { builtins } = await importOwn('plugins')
50
+ return builtins()
51
+ }
52
+
53
+ /** Check a plugin, as the config gives it. */
54
+ function checkPlugin(e: Plugin, where: string | null) {
55
+ if (typeof e !== 'object' || !NAME.test(e?.name ?? '')) throw new Error(`a plugin in ${where} needs a name: letters, digits, - and _`)
56
+ 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)`)
57
+ pluginCommands(e) // checks them
58
+ for (const type of Object.keys(e.events ?? {}))
59
+ 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>`)
60
+ }
61
+
62
+ /**
63
+ * The config, cached until invalidate() (which loads it afresh). Errors are returned, not thrown:
64
+ * a config that fails to load leaves the project without its plugins, so pages show as raw text,
65
+ * and serves no repository files.
66
+ *
67
+ * The project's plugins are the built-in ones, then the config's: one with a built-in's name
68
+ * replaces it. Their blocks make the pages. `pages: false` leaves the pages out, for the command
69
+ * line, which only needs the plugins (their commands, the session, their events).
70
+ */
71
+ export function createConfigLoader(proj: Project, { pages: withPages = true } = {}) {
72
+ let cached: Promise<LoadedConfig> | null = null
73
+
74
+ async function load(): Promise<Omit<LoadedConfig, 'errors'>> {
75
+ // no config file: the defaults, the same as an empty config
76
+ const configFile = proj.configFile
77
+ const mod = configFile ? await importFresh(configFile) : { default: {} }
78
+ // a config can also be a function that returns one
79
+ const exported: Config | (() => Config | Promise<Config>) = mod.default
80
+ const config: Config = typeof exported === 'function' ? await exported() : exported
81
+ const plugins: Plugin[] = await builtinPlugins()
82
+ const builtin = new Set(plugins.map(p => p.name))
83
+ const added = new Set<string>()
84
+ for (const e of [config?.plugins ?? []].flat(Infinity) as Plugin[]) {
85
+ if (!e) continue
86
+ checkPlugin(e, configFile)
87
+ if (added.has(e.name)) throw new Error(`two plugins are named "${e.name}" in ${configFile}`)
88
+ added.add(e.name)
89
+ // one with a built-in's name replaces it, in its place
90
+ if (builtin.has(e.name)) plugins[plugins.findIndex(p => p.name === e.name)] = e
91
+ else plugins.push(e)
92
+ }
93
+ const blocks = plugins.flatMap(p => Object.entries(p.blocks ?? {}).map(([name, block]) => ({ name, block, plugin: p.name })))
94
+ const styles = plugins.map(p => p.style).filter((s): s is URL | string => !!s)
95
+ const pages = withPages ? createPages({ blocks, style: config?.style, styles }) : null
96
+ const handedOut = new Set(plugins.flatMap(p => Object.entries(p.events ?? {}).filter(([, spec]) => spec?.handOut).map(([type]) => type)))
97
+ return { pages, plugins, handedOut, files: config?.files !== false }
98
+ }
99
+
100
+ function config(): Promise<LoadedConfig> {
101
+ cached ??= load().then(
102
+ value => ({ ...value, errors: [] }),
103
+ error => ({ pages: null, plugins: [], handedOut: new Set<string>(), files: false, errors: [error] }),
104
+ )
105
+ return cached
106
+ }
107
+
108
+ return { config, invalidate: () => { cached = null } }
109
+ }
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,67 @@
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
+ props: ((ctx: any) => unknown) | null
19
+ html: ((ctx: any) => string | Html | null | Promise<string | Html | null>) | null
20
+ client: string | null
21
+ style: string | null
22
+ /** the plugin it comes from */
23
+ source: string
24
+ }
25
+
26
+ export interface ResolvedBlocks { blocks: Map<string, ResolvedBlock>; code: ResolvedBlock | null }
27
+
28
+ /** A block's file reference (URL, file: URL string, or absolute path) → absolute path. */
29
+ function toPath(ref: unknown, field: string, block: string): string | null {
30
+ if (ref == null) return null
31
+ if (ref instanceof URL || (typeof ref === 'string' && ref.startsWith('file:'))) return fileURLToPath(ref)
32
+ if (typeof ref === 'string' && path.isAbsolute(ref)) return ref
33
+ throw new Error(`block "${block}": ${field} must be a URL, e.g. new URL('./${field}.js', import.meta.url)`)
34
+ }
35
+
36
+ /** Check and resolve one block into what the engine uses. */
37
+ function normalize({ name, block: b, plugin }: BlockEntry): ResolvedBlock {
38
+ if (typeof b !== 'object' || !b) throw new Error(`plugin ${plugin}: block "${name}" is not an object`)
39
+ if (!NAME.test(name)) throw new Error(`plugin ${plugin}: block name ${JSON.stringify(name)}: use letters, digits, - and _`)
40
+ const files = { client: toPath(b.client, 'client', name), style: toPath(b.style, 'style', name) }
41
+ for (const [field, file] of Object.entries(files))
42
+ if (file && !fs.existsSync(file)) throw new Error(`plugin ${plugin}, block "${name}": ${field} file not found: ${file}`)
43
+ return {
44
+ name,
45
+ code: b.fence === 'any',
46
+ props: typeof b.props === 'function' ? b.props.bind(b) : null,
47
+ html: typeof b.html === 'function' ? b.html.bind(b) : null,
48
+ ...files,
49
+ source: plugin,
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Resolve the plugins' blocks. A block name is one plugin's: two plugins bringing the same block is
55
+ * an error. `code` is the block for code fences no block claims by name: the last one with
56
+ * `fence: 'any'`.
57
+ */
58
+ export function resolveBlocks(entries: BlockEntry[]): ResolvedBlocks {
59
+ const blocks = new Map<string, ResolvedBlock>()
60
+ for (const entry of entries) {
61
+ const n = normalize(entry)
62
+ const other = blocks.get(n.name)
63
+ if (other) throw new Error(`block "${n.name}" comes from two plugins: ${other.source} and ${n.source}`)
64
+ blocks.set(n.name, n)
65
+ }
66
+ return { blocks, code: [...blocks.values()].findLast(t => t.code) ?? null }
67
+ }
@@ -0,0 +1,36 @@
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, createRender } from './render.ts'
6
+ import { formNames } from './markdown.ts'
7
+ import type { PageSource, RenderContext, Rendered, StoredPage } from '../define.ts'
8
+
9
+ export interface PagesOptions {
10
+ /** the blocks of the project's plugins, in plugin order */
11
+ blocks: BlockEntry[]
12
+ /** the project's stylesheet, linked on every page after the others */
13
+ style?: URL | string
14
+ /** the plugins' stylesheets, linked on every page */
15
+ styles?: (URL | string)[]
16
+ }
17
+
18
+ /** How the core renders pages for one loaded config. */
19
+ export interface Pages {
20
+ /** a stored page as HTML, with its title, head additions and the data its browser part needs */
21
+ render(page: StoredPage, ctx: RenderContext): Promise<Rendered>
22
+ /** how pages are written, and which blocks the plugins bring: what `whiteboard docs` prints first */
23
+ docs(ctx: RenderContext): string
24
+ /** the questions a page asks: its named forms, whose answers are events of their name */
25
+ questions(page: PageSource): string[]
26
+ }
27
+
28
+ export function createPages(options: PagesOptions): Pages {
29
+ const resolved = resolveBlocks(options.blocks)
30
+ const blocks = () => resolved
31
+ return {
32
+ render: createRender(blocks, options.style, options.styles ?? []),
33
+ docs: createDocs(blocks),
34
+ questions: page => formNames(page.source),
35
+ }
36
+ }