@bigmistqke/whiteboard 0.3.1 → 0.5.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 (174) hide show
  1. package/README.md +119 -18
  2. package/bin/whiteboard.ts +300 -71
  3. package/dist/bin/whiteboard.js +21 -0
  4. package/dist/client/runtime.js +132 -54
  5. package/dist/define.js +21 -2
  6. package/dist/plugins/callout/index.js +3 -1
  7. package/dist/plugins/callout/public/style.css +30 -0
  8. package/dist/plugins/chat/index.js +7 -4
  9. package/dist/plugins/chat/{client.js → public/client.js} +1 -1
  10. package/dist/plugins/chat/public/style.css +98 -0
  11. package/dist/plugins/code/index.js +3 -1
  12. package/dist/plugins/code/public/style.css +68 -0
  13. package/dist/plugins/comments/index.js +4 -5
  14. package/dist/plugins/comments/public/client.js +19 -0
  15. package/dist/plugins/comments/public/style.css +185 -0
  16. package/dist/plugins/details/index.js +7 -2
  17. package/dist/plugins/details/public/style.css +7 -0
  18. package/dist/plugins/draft/README.md +14 -0
  19. package/dist/plugins/draft/index.js +21 -0
  20. package/dist/plugins/draft/public/style.css +21 -0
  21. package/dist/plugins/form/index.js +37 -8
  22. package/dist/plugins/form/public/style.css +126 -0
  23. package/dist/plugins/gallery/index.js +4 -3
  24. package/dist/plugins/gallery/public/client.js +1 -0
  25. package/dist/plugins/gallery/public/style.css +90 -0
  26. package/dist/plugins/grid/index.js +9 -3
  27. package/dist/plugins/grid/public/style.css +71 -0
  28. package/dist/plugins/iframe/index.js +13 -14
  29. package/dist/plugins/iframe/public/style.css +13 -0
  30. package/dist/plugins/index.js +7 -1
  31. package/dist/plugins/mermaid/index.js +3 -1
  32. package/dist/plugins/mermaid/{style.css → public/style.css} +7 -2
  33. package/dist/plugins/steps/README.md +42 -0
  34. package/dist/plugins/steps/index.js +99 -0
  35. package/dist/plugins/steps/public/client.js +1 -0
  36. package/dist/plugins/steps/public/style.css +77 -0
  37. package/dist/plugins/terminal/host.js +9 -3
  38. package/dist/plugins/terminal/index.js +10 -9
  39. package/dist/plugins/terminal/{style.css → public/style.css} +199 -45
  40. package/dist/plugins/terminal/sizes.js +2 -1
  41. package/dist/plugins/toc/README.md +21 -3
  42. package/dist/plugins/toc/index.js +12 -5
  43. package/dist/plugins/toc/public/client.js +1 -0
  44. package/dist/plugins/toc/public/style.css +99 -0
  45. package/dist/plugins/window/README.md +29 -0
  46. package/dist/plugins/window/index.js +64 -0
  47. package/dist/solid/index.js +14 -11
  48. package/dist/src/auth.js +2 -1
  49. package/dist/src/client/page/base.css +1078 -199
  50. package/dist/src/client/page/main.js +188 -39
  51. package/dist/src/loader.js +14 -3
  52. package/dist/src/package.js +3 -6
  53. package/dist/src/pages/blocks.js +8 -13
  54. package/dist/src/pages/markdown.js +1 -1
  55. package/dist/src/pages/render.js +106 -20
  56. package/dist/src/pages/window.js +31 -0
  57. package/dist/src/public.js +24 -0
  58. package/dist/src/server.js +251 -23
  59. package/package.json +5 -2
  60. package/plugins/callout/index.ts +3 -1
  61. package/plugins/callout/public/style.css +30 -0
  62. package/plugins/chat/autosize.ts +43 -9
  63. package/plugins/chat/client.tsx +22 -5
  64. package/plugins/chat/index.ts +22 -8
  65. package/plugins/chat/public/style.css +98 -0
  66. package/plugins/claude-code/index.ts +49 -14
  67. package/plugins/code/diff.ts +28 -8
  68. package/plugins/code/index.ts +33 -21
  69. package/plugins/code/public/style.css +68 -0
  70. package/plugins/comments/client.ts +139 -71
  71. package/plugins/comments/index.ts +9 -7
  72. package/plugins/comments/public/style.css +185 -0
  73. package/plugins/details/index.ts +7 -2
  74. package/plugins/details/public/style.css +7 -0
  75. package/plugins/draft/README.md +14 -0
  76. package/plugins/draft/index.ts +23 -0
  77. package/plugins/draft/public/style.css +21 -0
  78. package/plugins/forge/index.ts +16 -3
  79. package/plugins/form/index.ts +75 -27
  80. package/plugins/form/public/style.css +126 -0
  81. package/plugins/gallery/client.tsx +9 -3
  82. package/plugins/gallery/index.ts +31 -9
  83. package/plugins/gallery/public/style.css +90 -0
  84. package/plugins/grid/index.ts +19 -5
  85. package/plugins/grid/public/style.css +71 -0
  86. package/plugins/iframe/index.ts +20 -23
  87. package/plugins/iframe/public/style.css +13 -0
  88. package/plugins/index.ts +20 -1
  89. package/plugins/mermaid/index.ts +7 -3
  90. package/plugins/mermaid/{style.css → public/style.css} +7 -2
  91. package/plugins/steps/README.md +42 -0
  92. package/plugins/steps/client.ts +66 -0
  93. package/plugins/steps/index.ts +127 -0
  94. package/plugins/steps/public/style.css +77 -0
  95. package/plugins/terminal/client.ts +105 -48
  96. package/plugins/terminal/host.ts +143 -35
  97. package/plugins/terminal/index.ts +84 -25
  98. package/plugins/terminal/public/style.css +225 -0
  99. package/plugins/terminal/server.ts +64 -13
  100. package/plugins/terminal/sizes.ts +16 -4
  101. package/plugins/toc/README.md +21 -3
  102. package/plugins/toc/client.ts +90 -30
  103. package/plugins/toc/index.ts +26 -10
  104. package/plugins/toc/public/style.css +99 -0
  105. package/plugins/window/README.md +29 -0
  106. package/plugins/window/index.ts +85 -0
  107. package/skills/whiteboard/SKILL.md +3 -1
  108. package/solid/index.tsx +24 -9
  109. package/src/auth.ts +28 -9
  110. package/src/client/forms.ts +74 -28
  111. package/src/client/markdown.ts +15 -4
  112. package/src/client/page/base.css +1078 -199
  113. package/src/client/page/elsewhere.ts +32 -15
  114. package/src/client/page/fresh.ts +91 -23
  115. package/src/client/page/hold.ts +11 -2
  116. package/src/client/page/live.ts +10 -6
  117. package/src/client/page/main.ts +124 -42
  118. package/src/client/page/orphans.ts +25 -10
  119. package/src/client/page/sort.ts +14 -4
  120. package/src/client/page/sticky.ts +11 -3
  121. package/src/client/page/theme.ts +11 -7
  122. package/src/client/page/waiting.ts +141 -34
  123. package/src/client/page/window.ts +40 -0
  124. package/src/client/reactive.ts +19 -0
  125. package/src/client/read.ts +17 -10
  126. package/src/client/runtime.ts +170 -40
  127. package/src/client/scroll.ts +14 -4
  128. package/src/client/toast.ts +19 -5
  129. package/src/config.ts +20 -5
  130. package/src/define.ts +119 -31
  131. package/src/events.ts +111 -24
  132. package/src/html.ts +6 -2
  133. package/src/icons.ts +4 -2
  134. package/src/load.ts +10 -2
  135. package/src/loader.ts +81 -12
  136. package/src/package.ts +9 -8
  137. package/src/pages/blocks.ts +20 -14
  138. package/src/pages/index.ts +2 -2
  139. package/src/pages/markdown.ts +113 -34
  140. package/src/pages/render.ts +233 -41
  141. package/src/pages/window.ts +78 -0
  142. package/src/plugins.ts +90 -24
  143. package/src/public.ts +39 -0
  144. package/src/running.ts +8 -2
  145. package/src/serve.ts +29 -7
  146. package/src/server.ts +591 -110
  147. package/src/status.ts +15 -9
  148. package/dist/plugins/callout/style.css +0 -12
  149. package/dist/plugins/chat/style.css +0 -24
  150. package/dist/plugins/code/style.css +0 -29
  151. package/dist/plugins/comments/client.js +0 -10
  152. package/dist/plugins/comments/style.css +0 -40
  153. package/dist/plugins/details/style.css +0 -3
  154. package/dist/plugins/form/style.css +0 -44
  155. package/dist/plugins/gallery/client.js +0 -1
  156. package/dist/plugins/gallery/style.css +0 -27
  157. package/dist/plugins/grid/style.css +0 -25
  158. package/dist/plugins/iframe/client.js +0 -1
  159. package/dist/plugins/iframe/style.css +0 -29
  160. package/dist/plugins/toc/client.js +0 -1
  161. package/dist/plugins/toc/style.css +0 -19
  162. package/plugins/callout/style.css +0 -12
  163. package/plugins/chat/style.css +0 -24
  164. package/plugins/code/style.css +0 -29
  165. package/plugins/comments/style.css +0 -40
  166. package/plugins/details/style.css +0 -3
  167. package/plugins/form/style.css +0 -44
  168. package/plugins/gallery/style.css +0 -27
  169. package/plugins/grid/style.css +0 -25
  170. package/plugins/iframe/client.ts +0 -46
  171. package/plugins/iframe/style.css +0 -29
  172. package/plugins/terminal/style.css +0 -71
  173. package/plugins/toc/style.css +0 -19
  174. /package/dist/plugins/terminal/{client.js → public/client.js} +0 -0
package/src/server.ts CHANGED
@@ -17,6 +17,8 @@
17
17
  // text.
18
18
  import type { IncomingMessage, ServerResponse } from 'node:http'
19
19
  import fs from 'node:fs'
20
+ import { parse as parseYaml } from 'yaml'
21
+ import { stripTypeScriptTypes } from 'node:module'
20
22
  import path from 'node:path'
21
23
  import type { Project } from './config.ts'
22
24
  import { appendEvent, readEvents, matches, pickedUp, fromReader, forAgent, CLAIM } from './events.ts'
@@ -27,7 +29,18 @@ import { createAuth } from './auth.ts'
27
29
  import { FROM_SOURCE, PACKAGE_DIR } from './package.ts'
28
30
  import { awaiting, covers, heard, questionState, unreadMessages } from './status.ts'
29
31
  import { titleOf } from './pages/render.ts'
30
- import type { Listener, PageSource, PageStatus, Plugin, PluginHooks, Rendered, StoredPage, PagesSource } from './define.ts'
32
+ import { inPublic } from './public.ts'
33
+ import type {
34
+ Listener,
35
+ PageSource,
36
+ PageStatus,
37
+ Plugin,
38
+ PluginHooks,
39
+ Rendered,
40
+ StoredPage,
41
+ PagesSource,
42
+ BuildConfig,
43
+ } from './define.ts'
31
44
 
32
45
  const ENGINE_DIR = PACKAGE_DIR
33
46
  // the browser runtime, built by build.ts
@@ -35,19 +48,33 @@ const RUNTIME = path.join(ENGINE_DIR, 'dist', 'client', 'runtime.js')
35
48
  // the page in the browser (markdown live: morphing, blocks' islands, forms' marks), built by build.ts
36
49
  const PAGE_CLIENT = path.join(ENGINE_DIR, 'dist', 'src', 'client', 'page', 'main.js')
37
50
  const MIME: Record<string, string> = {
38
- '.css': 'text/css', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json', '.png': 'image/png',
39
- '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif',
40
- '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.mp4': 'video/mp4', '.webm': 'video/webm', '.woff': 'font/woff',
41
- '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8', '.md': 'text/markdown; charset=utf-8',
42
- '.csv': 'text/csv; charset=utf-8', '.html': 'text/html; charset=utf-8',
51
+ '.css': 'text/css',
52
+ '.js': 'text/javascript',
53
+ '.mjs': 'text/javascript',
54
+ '.json': 'application/json',
55
+ '.png': 'image/png',
56
+ '.jpg': 'image/jpeg',
57
+ '.jpeg': 'image/jpeg',
58
+ '.gif': 'image/gif',
59
+ '.webp': 'image/webp',
60
+ '.avif': 'image/avif',
61
+ '.svg': 'image/svg+xml',
62
+ '.pdf': 'application/pdf',
63
+ '.mp4': 'video/mp4',
64
+ '.webm': 'video/webm',
65
+ '.woff': 'font/woff',
66
+ '.woff2': 'font/woff2',
67
+ '.txt': 'text/plain; charset=utf-8',
68
+ '.md': 'text/markdown; charset=utf-8',
69
+ '.csv': 'text/csv; charset=utf-8',
70
+ '.html': 'text/html; charset=utf-8',
43
71
  }
44
72
  // files in .whiteboard/ that are the server's own bookkeeping, not content
45
73
  const OWN_FILES = new Set(['events.ndjson', 'server.json', 'server.log', 'server.lock', 'token'])
46
74
  const SKIP_DIRS = new Set(['node_modules', '.git'])
47
- // a page's frontmatter: `---` lines around `key: value` lines, at the very start
75
+ // a page's frontmatter: YAML between `---` lines, at the very start
48
76
  const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/
49
77
 
50
-
51
78
  /** A project's server: its request handler, and what it knows. */
52
79
  export interface WhiteboardServer {
53
80
  /** answer one request */
@@ -56,10 +83,21 @@ export interface WhiteboardServer {
56
83
  status(page?: string | null): Promise<PageStatus[]>
57
84
  /** the project's config, loaded */
58
85
  config(): Promise<LoadedConfig>
86
+ /** a static site of some pages (`whiteboard build`); options over the config's `build` */
87
+ build(options?: BuildConfig): Promise<BuildResult>
59
88
  /** stop watching and end the live connections; the server answers nothing after */
60
89
  close(): void
61
90
  }
62
91
 
92
+ export interface BuildResult {
93
+ /** the folder the site is in */
94
+ out: string
95
+ /** each page, and the file it became */
96
+ pages: { file: string; to: string }[]
97
+ /** what didn't fit: a link to a page outside the build, no index.html */
98
+ warnings: string[]
99
+ }
100
+
63
101
  export function createServer(project: Project): WhiteboardServer {
64
102
  const loader = createConfigLoader(project)
65
103
  const auth = createAuth(project.wb)
@@ -67,7 +105,15 @@ export function createServer(project: Project): WhiteboardServer {
67
105
  const watchers = new Set<fs.FSWatcher>()
68
106
  const streams = new Set<() => void>()
69
107
  const watch = (dir: string, options: fs.WatchOptions, fn: (name: string) => void) => {
70
- try { watchers.add(fs.watch(dir, options, (_evt, name) => { if (name) fn(String(name)) })) } catch { /* gone, or not built */ }
108
+ try {
109
+ watchers.add(
110
+ fs.watch(dir, options, (_evt, name) => {
111
+ if (name) fn(String(name))
112
+ }),
113
+ )
114
+ } catch {
115
+ /* gone, or not built */
116
+ }
71
117
  }
72
118
 
73
119
  // ---- plugins --------------------------------------------------------------------------------
@@ -89,17 +135,32 @@ export function createServer(project: Project): WhiteboardServer {
89
135
  async function pluginHooks(): Promise<SetUp[]> {
90
136
  const c = await config()
91
137
  if (!setups.has(c)) {
92
- setups.set(c, Promise.all(c.plugins.map(async (e): Promise<SetUp> => {
93
- try {
94
- pluginDirs.add(e.name)
95
- const dataDir = pluginDir(project.wb, e.name)
96
- const hooks = (await e.setup?.({ project: { name: project.name, dir: project.dir, wb: project.wb }, dataDir, authorized: auth.authorized, asset })) ?? {}
97
- return { name: e.name, ...hooks, table: mountRoutes(e.name, hooks.routes), plugin: e }
98
- } catch (err) {
99
- console.error(`plugin ${e.name}:`, err)
100
- return { name: e.name, table: [], plugin: e, error: err as Error }
101
- }
102
- })))
138
+ setups.set(
139
+ c,
140
+ Promise.all(
141
+ c.plugins.map(async (e): Promise<SetUp> => {
142
+ try {
143
+ pluginDirs.add(e.name)
144
+ const dataDir = pluginDir(project.wb, e.name)
145
+ // what it serves is in its public folder: its client, and what it asks ctx.asset for
146
+ const dir = c.publicDirs.get(e.name)!
147
+ const own = (ref: URL | string) => asset(inPublic(dir, ref, `plugin ${e.name}`))
148
+ const hooks =
149
+ (await e.setup?.({
150
+ project: { name: project.name, dir: project.dir, wb: project.wb },
151
+ dataDir,
152
+ authorized: auth.authorized,
153
+ asset: own,
154
+ })) ?? {}
155
+ const client = hooks.client != null ? inPublic(dir, hooks.client, `plugin ${e.name}: client`) : undefined
156
+ return { name: e.name, ...hooks, client, table: mountRoutes(e.name, hooks.routes), plugin: e }
157
+ } catch (err) {
158
+ console.error(`plugin ${e.name}:`, err)
159
+ return { name: e.name, table: [], plugin: e, error: err as Error }
160
+ }
161
+ }),
162
+ ),
163
+ )
103
164
  }
104
165
  return setups.get(c)!
105
166
  }
@@ -122,17 +183,27 @@ export function createServer(project: Project): WhiteboardServer {
122
183
  async function shellExtras(req: IncomingMessage): Promise<Extras & { notices: string[] }> {
123
184
  const hooks = await pluginHooks()
124
185
  const notices = hooks.filter(h => h.error).map(h => `plugin "${h.name}" failed to start: ${h.error!.message}`)
125
- const parts = await Promise.all(hooks.map(async h => {
126
- try { return (await h.shell?.(req)) ?? null } catch (err) {
127
- console.error(`plugin ${h.name}:`, err)
128
- notices.push(`plugin "${h.name}" failed on this page: ${(err as Error).message}`)
129
- return null
130
- }
131
- }))
186
+ const parts = await Promise.all(
187
+ hooks.map(async h => {
188
+ try {
189
+ return (await h.shell?.(req)) ?? null
190
+ } catch (err) {
191
+ console.error(`plugin ${h.name}:`, err)
192
+ notices.push(`plugin "${h.name}" failed on this page: ${(err as Error).message}`)
193
+ return null
194
+ }
195
+ }),
196
+ )
132
197
  // their browser modules, which the runtime imports after the page's
133
198
  const clients = hooks.filter(h => h.client && !h.error).map(h => ({ name: h.name, client: asset(h.client!) }))
134
199
  const messages = [...(await config()).forReader]
135
- return { head: parts.map(x => raw(String(x?.head ?? ''))), body: parts.map(x => raw(String(x?.body ?? ''))), clients, messages, notices }
200
+ return {
201
+ head: parts.map(x => raw(String(x?.head ?? ''))),
202
+ body: parts.map(x => raw(String(x?.body ?? ''))),
203
+ clients,
204
+ messages,
205
+ notices,
206
+ }
136
207
  }
137
208
 
138
209
  /** A page with what the plugins add, their notices among the page's. */
@@ -145,19 +216,25 @@ export function createServer(project: Project): WhiteboardServer {
145
216
  async function config(): Promise<LoadedConfig> {
146
217
  const c = await loader.config()
147
218
  setFiles(c.files)
219
+ publicDirs = [...c.publicDirs.values()]
148
220
  return c
149
221
  }
150
222
 
151
- // ---- assets: files a plugin asks to serve -------------------------------------------------------
152
- // Served at /_/file/<absolute path>, only once asked for. Beside a file asked for, its neighbours
153
- // too, since a client module may import them, but only browser assets (scripts, styles, images,
154
- // fonts): a plugin's module in .whiteboard/ must not open up the project's token, log or config.
155
- // Those folders are watched from then on.
223
+ // ---- assets: the browser's files ----------------------------------------------------------------
224
+ // Served at /_/file/<absolute path>, and only these: the files the core names (its page module and
225
+ // styles, the project's stylesheet), and what is inside a plugin's public folder (public.ts): its
226
+ // client modules, styles, images, fonts. Nothing else of a plugin, and nothing beside its public
227
+ // folder: not its server code, not the project's token, log or config. TypeScript there is
228
+ // served with its types stripped (Node's own type stripping, as for server code: erasable syntax
229
+ // only, positions kept). The folders of what is served are watched from then on.
156
230
 
157
231
  const assets = new Set<string>()
158
232
  const assetDirs = new Set<string>()
159
- const BROWSER_ASSET = /\.(m?js|css|map|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|wasm)$/i
160
- const servable = (file: string) => assets.has(file) || (assetDirs.has(path.dirname(file)) && BROWSER_ASSET.test(file))
233
+ const TYPESCRIPT = /\.m?ts$/i
234
+ const typeScriptModule = (file: string): string => stripTypeScriptTypes(fs.readFileSync(file, 'utf8'))
235
+ // the plugins' public folders, as the config last loaded them
236
+ let publicDirs: string[] = []
237
+ const servable = (file: string) => assets.has(file) || publicDirs.some(dir => within(file, dir) && file !== dir)
161
238
 
162
239
  function asset(ref: string | URL): string {
163
240
  const file = toPath(ref)
@@ -187,19 +264,33 @@ export function createServer(project: Project): WhiteboardServer {
187
264
 
188
265
  const isRepoId = (id: string) => id === '-' || id.startsWith('-/')
189
266
 
190
- function frontmatter(source: string): Record<string, string> {
267
+ /** A page's frontmatter, parsed as YAML; empty, with the reason, when it isn't fields. */
268
+ function frontmatter(source: string): { data: Record<string, unknown>; error: string | null } {
191
269
  const m = FRONTMATTER.exec(source)
192
- const out: Record<string, string> = {}
193
- if (m) for (const line of m[1]!.split(/\r?\n/)) {
194
- const kv = /^([\w-]+)\s*:\s*(.*)$/.exec(line)
195
- if (kv) out[kv[1]!] = kv[2]!.trim().replace(/^["']|["']$/g, '')
270
+ if (!m) return { data: {}, error: null }
271
+ let data: unknown
272
+ try {
273
+ data = parseYaml(m[1]!)
274
+ } catch (err) {
275
+ return { data: {}, error: (err as Error).message }
196
276
  }
197
- return out
277
+ if (data == null) return { data: {}, error: null }
278
+ if (typeof data !== 'object' || Array.isArray(data))
279
+ return { data: {}, error: 'it must be fields (`key: value` lines), not a single value or a list' }
280
+ return { data: data as Record<string, unknown>, error: null }
198
281
  }
199
282
 
200
283
  function pageSource(id: string, file: string): PageSource {
201
284
  const source = fs.readFileSync(file, 'utf8')
202
- return { kind: 'page', id, file, mtime: fs.statSync(file).mtimeMs, source, body: source.replace(FRONTMATTER, ''), frontmatter: frontmatter(source) }
285
+ return {
286
+ kind: 'page',
287
+ id,
288
+ file,
289
+ mtime: fs.statSync(file).mtimeMs,
290
+ source,
291
+ body: source.replace(FRONTMATTER, ''),
292
+ ...(({ data, error }) => ({ frontmatter: data, frontmatterError: error }))(frontmatter(source)),
293
+ }
203
294
  }
204
295
 
205
296
  /** The pages in a folder of the pages folder, newest first, with when each was last answered. */
@@ -242,13 +333,15 @@ export function createServer(project: Project): WhiteboardServer {
242
333
  if (isRepoId(id)) {
243
334
  const rel = id.slice(2)
244
335
  const target = inside(project.dir, rel)
245
- if (!target || path.relative(project.dir, target).split(path.sep).includes('.git') || !fs.existsSync(target)) return null
336
+ if (!target || path.relative(project.dir, target).split(path.sep).includes('.git') || !fs.existsSync(target))
337
+ return null
246
338
  const stat = fs.statSync(target)
247
339
  if (stat.isDirectory()) {
248
- const entries = fs.readdirSync(target, { withFileTypes: true })
340
+ const entries = fs
341
+ .readdirSync(target, { withFileTypes: true })
249
342
  .filter(e => !SKIP_DIRS.has(e.name) && e.name !== '.DS_Store')
250
343
  .map(e => ({ name: e.name, dir: e.isDirectory() }))
251
- .sort((a, b) => (Number(b.dir) - Number(a.dir)) || a.name.localeCompare(b.name))
344
+ .sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name))
252
345
  return { kind: 'folder', id, file: target, mtime: stat.mtimeMs, entries }
253
346
  }
254
347
  if (/\.(md|markdown)$/i.test(target)) return pageSource(id, target)
@@ -272,7 +365,12 @@ export function createServer(project: Project): WhiteboardServer {
272
365
  const rel = (dir: string) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join('/')
273
366
  if (within(abs, project.pagesDir)) return `/${rel(project.pagesDir).replace(/\.md$/, '')}`
274
367
  if (FILES && within(abs, project.dir)) {
275
- if (rel(project.dir).split('/').some(part => SKIP_DIRS.has(part))) return null
368
+ if (
369
+ rel(project.dir)
370
+ .split('/')
371
+ .some(part => SKIP_DIRS.has(part))
372
+ )
373
+ return null
276
374
  return `/-/${rel(project.dir)}`
277
375
  }
278
376
  return null
@@ -293,10 +391,19 @@ export function createServer(project: Project): WhiteboardServer {
293
391
 
294
392
  /** A config that failed to load: the page as stored, as text, under the error. */
295
393
  function rawRender(page: StoredPage): Rendered {
296
- const list = (items: [string, string][]) => html`<ul>${items.map(([href, text]) => html`<li><a href="${href}">${text}</a></li>`)}</ul>`
394
+ const list = (items: [string, string][]) =>
395
+ html`<ul>
396
+ ${items.map(([href, text]) => html`<li><a href="${href}">${text}</a></li>`)}
397
+ </ul>`
297
398
  if (page.kind === 'pages') return { html: list(page.pages.map(p => [`/${p.id}`, p.id])) }
298
399
  if (page.kind === 'folder') {
299
- return { html: list(page.entries.map(e => [encodeURIComponent(e.name) + (e.dir ? '/' : ''), e.name + (e.dir ? '/' : '')] as [string, string])) }
400
+ return {
401
+ html: list(
402
+ page.entries.map(
403
+ e => [encodeURIComponent(e.name) + (e.dir ? '/' : ''), e.name + (e.dir ? '/' : '')] as [string, string],
404
+ ),
405
+ ),
406
+ }
300
407
  }
301
408
  return { html: html`<pre>${page.source}</pre>` }
302
409
  }
@@ -310,10 +417,14 @@ export function createServer(project: Project): WhiteboardServer {
310
417
  notices: string[]
311
418
  }
312
419
 
420
+ /** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
421
+ const frontmatterOf = (page: StoredPage): Record<string, unknown> => (page.kind === 'page' ? page.frontmatter : {})
422
+
313
423
  /** Render a stored page as markdown, with the plugins' blocks, and anything the reader should be told. */
314
424
  async function render(page: StoredPage): Promise<Render> {
315
425
  const { pages, errors } = await config()
316
426
  const notices = errors.map(e => `config: ${(e as Error).message}`)
427
+ if (page.kind === 'page' && page.frontmatterError) notices.push(`frontmatter: ${page.frontmatterError}`)
317
428
  let out: Rendered
318
429
  let rendered = !!pages
319
430
  try {
@@ -340,20 +451,33 @@ export function createServer(project: Project): WhiteboardServer {
340
451
  const all = readEvents(project.eventsFile)
341
452
  const picked = pickedUp(all)
342
453
  const owner = new Map<string, string | null>()
343
- for (const e of all) if (e.type === CLAIM && !fromReader(e)) owner.set(e.page, (e.data?.session as string | undefined) ?? null)
454
+ for (const e of all)
455
+ if (e.type === CLAIM && !fromReader(e)) owner.set(e.page, (e.data?.session as string | undefined) ?? null)
344
456
  const out: PageStatus[] = []
345
457
  for (const p of pagesIn(project.pagesDir)) {
346
458
  if (only && p.id !== only && !p.id.startsWith(only + '/')) continue
347
459
  const page = pageSource(p.id, p.file)
348
460
  let asks: string[] = []
349
- try { asks = pages?.questions(page) ?? [] } catch (err) { console.error('questions:', err) }
461
+ try {
462
+ asks = pages?.questions(page) ?? []
463
+ } catch (err) {
464
+ console.error('questions:', err)
465
+ }
350
466
  const events = all.filter(e => e.page === p.id)
351
467
  const listening = listenersFor(p.id)
352
468
  // where each question stands, as the page shows it (see status.ts)
353
- const questions = asks.map(name => ({ name, state: questionState(name, events, listening, id => picked.has(id)).state }))
469
+ const questions = asks.map(name => ({
470
+ name,
471
+ state: questionState(name, events, listening, id => picked.has(id)).state,
472
+ }))
354
473
  const named = (...states: string[]) => questions.filter(q => states.includes(q.state)).map(q => q.name)
355
474
  out.push({
356
- page: p.id, title: titleOf(p.file, path.basename(p.id)), file: p.file, owner: owner.get(p.id) ?? null, asks, questions,
475
+ page: p.id,
476
+ title: titleOf(p.file, path.basename(p.id)),
477
+ file: p.file,
478
+ owner: owner.get(p.id) ?? null,
479
+ asks,
480
+ questions,
357
481
  open: named('open'),
358
482
  unheard: named('open').filter(name => !heard(name, listening)),
359
483
  unread: unreadMessages(events, type => forReader.has(type)),
@@ -369,14 +493,24 @@ export function createServer(project: Project): WhiteboardServer {
369
493
  async function docs() {
370
494
  const { pages, errors } = await config()
371
495
  // what each plugin declares: its routes (for an agent that wants to call them) and commands
372
- const plugins = await Promise.all((await pluginHooks()).map(async h => ({
373
- name: h.name,
374
- error: h.error?.message ?? null,
375
- docs: h.plugin.docs ? await h.plugin.docs() : null,
376
- routes: describeRoutes(h.table),
377
- commands: pluginCommands(h.plugin).map(c => ({ name: c.name, usage: usage(c.command), description: c.command.description })),
378
- events: Object.entries(h.plugin.events ?? {}).map(([type, spec]) => ({ type, handOut: !!spec?.handOut, description: spec?.description ?? '' })),
379
- })))
496
+ const plugins = await Promise.all(
497
+ (await pluginHooks()).map(async h => ({
498
+ name: h.name,
499
+ error: h.error?.message ?? null,
500
+ docs: h.plugin.docs ? await h.plugin.docs() : null,
501
+ routes: describeRoutes(h.table),
502
+ commands: pluginCommands(h.plugin).map(c => ({
503
+ name: c.name,
504
+ usage: usage(c.command),
505
+ description: c.command.description,
506
+ })),
507
+ events: Object.entries(h.plugin.events ?? {}).map(([type, spec]) => ({
508
+ type,
509
+ handOut: !!spec?.handOut,
510
+ description: spec?.description ?? '',
511
+ })),
512
+ })),
513
+ )
380
514
  return { errors: errors.map(e => (e as Error).message), pages: pages?.docs(context()) ?? null, plugins }
381
515
  }
382
516
 
@@ -386,29 +520,59 @@ export function createServer(project: Project): WhiteboardServer {
386
520
  // page's and the plugins' floating buttons and toasts; above what covers the bottom of the window.
387
521
  // Above the page and what floats on it (comment threads: 20), under what fills the window (a
388
522
  // maximized frame: 40, a lightbox or the terminal drawer: 50)
389
- const DOCK_STYLE = '#wb-dock{position:fixed;right:16px;bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:30;display:flex;flex-direction:column;align-items:flex-end;gap:6px}#wb-dock:empty{display:none}'
523
+ const DOCK_STYLE =
524
+ '#wb-dock{position:fixed;right:16px;bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:30;display:flex;flex-direction:column;align-items:flex-end;gap:6px}#wb-dock:empty{display:none}' +
390
525
  // toasts (api.toast): labels in the corner, in the page's theme colours where it has them
391
- + '.wb-toasts{display:flex;flex-direction:column;align-items:flex-end;gap:6px}.wb-toasts:empty{display:none}'
392
- + '.wb-toast{display:inline-flex;align-items:center;gap:8px;cursor:pointer;padding:5px 12px;border-radius:99px;font:600 .8rem/1.4 var(--sans,system-ui,sans-serif);background:var(--accent,#1d5bbf);color:var(--accent-text,#fff);border:1px solid transparent;box-shadow:0 2px 10px rgb(0 0 0/.18)}'
393
- + '.wb-toast[hidden]{display:none}.wb-toast[data-kind=warn]{background:var(--warn,#6b4fc0)}.wb-toast[data-kind=alert]{background:var(--bad,#c4352b);color:#fff}'
526
+ '.wb-toasts{display:flex;flex-direction:column;align-items:flex-end;gap:6px}.wb-toasts:empty{display:none}' +
527
+ '.wb-toast{display:inline-flex;align-items:center;gap:8px;cursor:pointer;padding:5px 12px;border-radius:99px;font:600 .8rem/1.4 var(--sans,system-ui,sans-serif);background:var(--accent,#1d5bbf);color:var(--accent-text,#fff);border:1px solid transparent;box-shadow:0 2px 10px rgb(0 0 0/.18)}' +
528
+ '.wb-toast[hidden]{display:none}.wb-toast[data-kind=warn]{background:var(--warn,#6b4fc0)}.wb-toast[data-kind=alert]{background:var(--bad,#c4352b);color:#fff}' +
394
529
  // where an agent scrolled the page to, lit up a moment
395
- + '@keyframes wb-flash{from{outline-color:var(--accent,#1d5bbf)}to{outline-color:transparent}}.wb-flash{outline:3px solid transparent;outline-offset:6px;border-radius:4px;animation:wb-flash 2s ease-out}'
396
- + '.wb-toast-dismiss{margin-right:-4px;padding:0 4px;border-left:1px solid rgb(255 255 255/.35);opacity:.75}.wb-toast-dismiss:hover{opacity:1}'
530
+ '@keyframes wb-flash{from{outline-color:var(--accent,#1d5bbf)}to{outline-color:transparent}}.wb-flash{outline:3px solid transparent;outline-offset:6px;border-radius:4px;animation:wb-flash 2s ease-out}' +
531
+ '.wb-toast-dismiss{margin-right:-4px;padding:0 4px;border-left:1px solid rgb(255 255 255/.35);opacity:.75}.wb-toast-dismiss:hover{opacity:1}'
397
532
 
398
533
  /** `extras`: what plugins add to <head> and <body> (see shellExtras). */
399
- function shell(page: StoredPage, { page: rendered, out, notices }: Render, extras: Extras = { head: [], body: [], clients: [] }): string {
400
- const handoff = { id: page.id, kind: page.kind, client: rendered ? asset(PAGE_CLIENT) : null, data: out.data ?? null, plugins: extras.clients, messages: extras.messages ?? [] }
534
+ function shell(
535
+ page: StoredPage,
536
+ { page: rendered, out, notices }: Render,
537
+ extras: Extras = { head: [], body: [], clients: [] },
538
+ /** a built page (`whiteboard build`): its files as the build names them, and no server behind it */
539
+ built?: { asset(ref: string | URL): string },
540
+ ): string {
541
+ const handoff = {
542
+ id: page.id,
543
+ kind: page.kind,
544
+ live: !built,
545
+ client: rendered ? (built ?? { asset }).asset(PAGE_CLIENT) : null,
546
+ data: out.data ?? null,
547
+ frontmatter: frontmatterOf(page),
548
+ plugins: extras.clients,
549
+ messages: extras.messages ?? [],
550
+ }
401
551
  // the page's head and html are HTML already; the handoff is JSON made safe for a script tag
402
- return String(html`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
403
- <title>${out.title || page.id || project.name}</title>
404
- <style>${DOCK_STYLE}</style>
405
- ${raw(out.head ?? '')}${extras.head}</head>
406
- <body data-page="${page.id}" data-kind="${page.kind}">
407
- ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
408
- <div id="wb-root">${raw(String(out.html))}</div>
409
- <div id="wb-dock"></div>
410
- <script type="application/json" id="wb-page">${raw(json(handoff))}</script>
411
- <script type="module" src="/_/runtime.js"></script>${extras.body}</body></html>`)
552
+ return String(
553
+ html`<!doctype html>
554
+ <html lang="en">
555
+ <head>
556
+ <meta charset="utf-8" />
557
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
558
+ <title>${out.title || page.id || project.name}</title>
559
+ <style>
560
+ ${DOCK_STYLE}
561
+ </style>
562
+ ${raw(out.head ?? '')}${extras.head}
563
+ </head>
564
+ <body data-page="${page.id}" data-kind="${page.kind}">
565
+ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
566
+ <div id="wb-root">${raw(String(out.html))}</div>
567
+ <div id="wb-dock"></div>
568
+ <script type="application/json" id="wb-page">
569
+ ${raw(json(handoff))}
570
+ </script>
571
+ <script type="module" src="${built ? built.asset(RUNTIME) : '/_/runtime.js'}"></script>
572
+ ${extras.body}
573
+ </body>
574
+ </html>`,
575
+ )
412
576
  }
413
577
 
414
578
  // ---- listeners ---------------------------------------------------------------------------------
@@ -419,8 +583,10 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
419
583
  /** A listener as the server holds it. */
420
584
  const listeners = new Set<Listener>()
421
585
 
422
-
423
- const listenersFor = (page: string | null): Listener[] => [...listeners].filter(l => page == null || covers(l, page)).map(({ page, type, command, fallback }) => ({ page, type, command, ...(fallback && { fallback }) }))
586
+ const listenersFor = (page: string | null): Listener[] =>
587
+ [...listeners]
588
+ .filter(l => page == null || covers(l, page))
589
+ .map(({ page, type, command, fallback }) => ({ page, type, command, ...(fallback && { fallback }) }))
424
590
 
425
591
  // ---- live changes ------------------------------------------------------------------------------
426
592
  // The browser listens at /api/watch. `change`: its page changed; `events`: the log grew;
@@ -438,17 +604,21 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
438
604
  const clients = new Set<WatchClient>()
439
605
  function notify(client: WatchClient, kind: string) {
440
606
  client.pending ??= new Set()
441
- if (client.pending.size === 0) setTimeout(() => {
442
- for (const k of client.pending!) client.res.write(`event: ${k}\ndata: {}\n\n`)
443
- client.pending!.clear()
444
- }, 60)
607
+ if (client.pending.size === 0)
608
+ setTimeout(() => {
609
+ for (const k of client.pending!) client.res.write(`event: ${k}\ndata: {}\n\n`)
610
+ client.pending!.clear()
611
+ }, 60)
445
612
  client.pending.add(kind)
446
613
  }
447
- const notifyAll = (kind: string) => { for (const c of clients) notify(c, kind) }
614
+ const notifyAll = (kind: string) => {
615
+ for (const c of clients) notify(c, kind)
616
+ }
448
617
 
449
618
  function pageChanged(id: string) {
450
619
  for (const c of clients) {
451
- if (c.isDir ? (!c.page || id.startsWith(c.page + '/')) : (c.page === id || c.page + '/index' === id)) notify(c, 'change')
620
+ if (c.isDir ? !c.page || id.startsWith(c.page + '/') : c.page === id || c.page + '/index' === id)
621
+ notify(c, 'change')
452
622
  }
453
623
  // the overview lists every page
454
624
  for (const c of clients) if (c.isDir && !c.page) notify(c, 'change')
@@ -482,7 +652,10 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
482
652
  function setFiles(files: boolean) {
483
653
  if (files === FILES) return
484
654
  FILES = files
485
- if (watcher) { watcher.close(); watchers.delete(watcher) }
655
+ if (watcher) {
656
+ watcher.close()
657
+ watchers.delete(watcher)
658
+ }
486
659
  const base = files ? project.dir : project.wb
487
660
  const prefix = files ? '' : '.whiteboard/'
488
661
  watcher = fs.watch(base, { recursive: true }, (_evt, filename) => {
@@ -522,14 +695,22 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
522
695
  res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' })
523
696
  res.end(body)
524
697
  }
525
- const sendJson = (res: ServerResponse, status: number, data: unknown) => send(res, status, JSON.stringify(data), 'application/json')
526
- const sendFile = (res: ServerResponse, file: string) => send(res, 200, fs.readFileSync(file), MIME[path.extname(file).toLowerCase()] || 'application/octet-stream')
698
+ const sendJson = (res: ServerResponse, status: number, data: unknown) =>
699
+ send(res, status, JSON.stringify(data), 'application/json')
700
+ const sendFile = (res: ServerResponse, file: string) =>
701
+ send(res, 200, fs.readFileSync(file), MIME[path.extname(file).toLowerCase()] || 'application/octet-stream')
527
702
 
528
703
  function readBody(req: IncomingMessage): Promise<string> {
529
704
  return new Promise((resolve, reject) => {
530
705
  const chunks: Buffer[] = []
531
706
  let size = 0
532
- req.on('data', (c: Buffer) => { size += c.length; if (size > 1e6) { reject(new Error('body too large')); req.destroy() } else chunks.push(c) })
707
+ req.on('data', (c: Buffer) => {
708
+ size += c.length
709
+ if (size > 1e6) {
710
+ reject(new Error('body too large'))
711
+ req.destroy()
712
+ } else chunks.push(c)
713
+ })
533
714
  req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
534
715
  req.on('error', reject)
535
716
  })
@@ -540,7 +721,8 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
540
721
 
541
722
  async function resolve(id: string, requested: string): Promise<Resolved> {
542
723
  await config()
543
- if (isRepoId(id) && !FILES) return { notFound: 'This project does not serve its files: its config sets files: false.' }
724
+ if (isRepoId(id) && !FILES)
725
+ return { notFound: 'This project does not serve its files: its config sets files: false.' }
544
726
  if (id === '_/docs') {
545
727
  // how pages are written, then each plugin's own docs, with their examples rendered live
546
728
  const { pages, plugins } = await docs()
@@ -548,13 +730,27 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
548
730
  pages ?? '',
549
731
  ...plugins.filter(p => p.docs).map(p => `<a id="plugin-${p.name}"></a>\n\n${p.docs}`),
550
732
  ].join('\n\n---\n\n')
551
- return { page: { kind: 'page', id, file: path.join(project.pagesDir, '_docs.md'), mtime: null, source, body: source, frontmatter: {} } }
733
+ return {
734
+ page: {
735
+ kind: 'page',
736
+ id,
737
+ file: path.join(project.pagesDir, '_docs.md'),
738
+ mtime: null,
739
+ source,
740
+ body: source,
741
+ frontmatter: {},
742
+ },
743
+ }
552
744
  }
553
745
  const found = stored(id)
554
- if (!found) return { notFound: `${isRepoId(id) ? id.slice(2) : id} does not exist${isRepoId(id) ? '' : ' yet. This page loads as soon as it does'}.` }
746
+ if (!found)
747
+ return {
748
+ notFound: `${isRepoId(id) ? id.slice(2) : id} does not exist${isRepoId(id) ? '' : ' yet. This page loads as soon as it does'}.`,
749
+ }
555
750
  if ('raw' in found) return found
556
751
  // a folder is served at /dir/, so relative links resolve inside it
557
- if ((found.kind === 'folder' || (found.kind === 'pages' && id)) && !requested.endsWith('/')) return { redirect: `/${id}/` }
752
+ if ((found.kind === 'folder' || (found.kind === 'pages' && id)) && !requested.endsWith('/'))
753
+ return { redirect: `/${id}/` }
558
754
  // a list of pages says which await the reader: where their questions stand takes the config
559
755
  if (found.kind === 'pages') {
560
756
  const counts = new Map((await status(found.id || null)).map(s => [s.page, awaiting(s)]))
@@ -570,7 +766,11 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
570
766
  const p = decodeURIComponent(url.pathname)
571
767
  const q = Object.fromEntries(url.searchParams)
572
768
 
573
- if (p === '/favicon.ico') { res.writeHead(204); res.end(); return }
769
+ if (p === '/favicon.ico') {
770
+ res.writeHead(204)
771
+ res.end()
772
+ return
773
+ }
574
774
  if (p === '/_/runtime.js') return sendFile(res, RUNTIME)
575
775
  if (auth.handle(req, res, p, q)) return
576
776
  if (p.startsWith('/api/')) {
@@ -581,8 +781,25 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
581
781
  if (owner) return sendJson(res, 404, { error: `plugin ${owner.name} has no route ${req.method} ${p}` })
582
782
  }
583
783
  if (p.startsWith('/_/file/')) {
784
+ await config()
584
785
  const file = path.resolve(p.slice('/_/file'.length))
585
- if (!servable(file) || !fs.existsSync(file) || !fs.statSync(file).isFile()) return send(res, 404, 'not found', 'text/plain')
786
+ if (!servable(file) || !fs.existsSync(file) || !fs.statSync(file).isFile())
787
+ return send(res, 404, 'not found', 'text/plain')
788
+ // watched from now on, so a change to it reloads the pages that use it
789
+ asset(file)
790
+ if (TYPESCRIPT.test(file)) {
791
+ try {
792
+ return send(res, 200, typeScriptModule(file), 'text/javascript; charset=utf-8')
793
+ } catch (err) {
794
+ // syntax only types can't express (an enum, a namespace) or a mistake: the browser says why
795
+ return send(
796
+ res,
797
+ 200,
798
+ `throw new SyntaxError(${JSON.stringify(`${path.basename(file)}: ${(err as Error).message}`)})`,
799
+ 'text/javascript; charset=utf-8',
800
+ )
801
+ }
802
+ }
586
803
  return sendFile(res, file)
587
804
  }
588
805
  if (p === '/api/health') return sendJson(res, 200, { ok: true, dir: project.dir, pid: process.pid })
@@ -595,7 +812,8 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
595
812
  // ({ page, to }: a heading's text, a form's name or any text) → { tabs }
596
813
  if (p === '/api/scroll' && req.method === 'POST') {
597
814
  const { page: id, to } = JSON.parse(await readBody(req)) as { page?: unknown; to?: unknown }
598
- if (typeof id !== 'string' || typeof to !== 'string' || !to.trim()) return sendJson(res, 400, { error: 'page and to required' })
815
+ if (typeof id !== 'string' || typeof to !== 'string' || !to.trim())
816
+ return sendJson(res, 400, { error: 'page and to required' })
599
817
  let tabs = 0
600
818
  for (const c of clients) {
601
819
  if (c.isDir || (c.page !== id && c.page + '/index' !== id)) continue
@@ -609,13 +827,23 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
609
827
  const { texts } = JSON.parse(await readBody(req)) as { texts?: unknown }
610
828
  if (!Array.isArray(texts)) return sendJson(res, 400, { error: 'texts: an array of strings' })
611
829
  const { pages } = await config()
612
- const out = await Promise.all(texts.map(t => pages ? pages.message(String(t ?? ''), context()) : Promise.resolve({ html: String(html`${String(t ?? '')}`), styles: [] })))
830
+ const out = await Promise.all(
831
+ texts.map(t =>
832
+ pages
833
+ ? pages.message(String(t ?? ''), context())
834
+ : Promise.resolve({ html: String(html`${String(t ?? '')}`), styles: [] }),
835
+ ),
836
+ )
613
837
  return sendJson(res, 200, { html: out.map(o => o.html), styles: [...new Set(out.flatMap(o => o.styles))] })
614
838
  }
615
839
  if (p === '/api/events') {
616
840
  const all = readEvents(project.eventsFile)
617
841
  const picked = pickedUp(all)
618
- return sendJson(res, 200, all.filter(e => matches(e, q)).map(e => (picked.has(e.id) ? { ...e, pickedUp: true } : e)))
842
+ return sendJson(
843
+ res,
844
+ 200,
845
+ all.filter(e => matches(e, q)).map(e => (picked.has(e.id) ? { ...e, pickedUp: true } : e)),
846
+ )
619
847
  }
620
848
  if (p === '/api/docs') return sendJson(res, 200, await docs())
621
849
  if (p === '/api/status') return sendJson(res, 200, await status(q.page || null))
@@ -623,16 +851,36 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
623
851
  if (p === '/api/listen') {
624
852
  const fallback = 'fallback' in q
625
853
  // one fallback per project: two would split what nobody else takes between them
626
- if (fallback && [...listeners].some(l => l.fallback)) return sendJson(res, 409, { error: 'another agent is the fallback already' })
627
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
854
+ if (fallback && [...listeners].some(l => l.fallback))
855
+ return sendJson(res, 409, { error: 'another agent is the fallback already' })
856
+ res.writeHead(200, {
857
+ 'content-type': 'text/event-stream',
858
+ 'cache-control': 'no-store',
859
+ connection: 'keep-alive',
860
+ })
628
861
  res.write(': listening\n\n')
629
- const l: Listener = { page: q.page || '', type: q.type || null, command: q.command === 'wait' ? 'wait' : 'watch', ...(fallback && { fallback }) }
862
+ const l: Listener = {
863
+ page: q.page || '',
864
+ type: q.type || null,
865
+ command: q.command === 'wait' ? 'wait' : 'watch',
866
+ ...(fallback && { fallback }),
867
+ }
630
868
  listeners.add(l)
631
869
  notifyAll('listeners')
632
870
  const ping = setInterval(() => res.write(': ping\n\n'), 25000)
633
- const end = () => { clearInterval(ping); listeners.delete(l); streams.delete(end) }
634
- streams.add(() => { end(); res.end() })
635
- req.on('close', () => { end(); notifyAll('listeners') })
871
+ const end = () => {
872
+ clearInterval(ping)
873
+ listeners.delete(l)
874
+ streams.delete(end)
875
+ }
876
+ streams.add(() => {
877
+ end()
878
+ res.end()
879
+ })
880
+ req.on('close', () => {
881
+ end()
882
+ notifyAll('listeners')
883
+ })
636
884
  return
637
885
  }
638
886
  if (p === '/api/page' || p === '/api/render') {
@@ -640,16 +888,27 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
640
888
  if (!('page' in r)) return sendJson(res, 404, { error: 'notFound' in r ? r.notFound : 'not a page' })
641
889
  if (p === '/api/page') return sendJson(res, 200, r.page)
642
890
  const { out, notices } = await render(r.page)
643
- return sendJson(res, 200, { ...out, notices, mtime: r.page.mtime })
891
+ return sendJson(res, 200, { ...out, notices, mtime: r.page.mtime, frontmatter: frontmatterOf(r.page) })
644
892
  }
645
893
  if (p === '/api/watch') {
646
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
894
+ res.writeHead(200, {
895
+ 'content-type': 'text/event-stream',
896
+ 'cache-control': 'no-store',
897
+ connection: 'keep-alive',
898
+ })
647
899
  res.write(': connected\n\n')
648
900
  const client = { res, page: q.page || '', isDir: 'dir' in q }
649
901
  clients.add(client)
650
902
  const ping = setInterval(() => res.write(': ping\n\n'), 25000)
651
- const end = () => { clearInterval(ping); clients.delete(client); streams.delete(end) }
652
- streams.add(() => { end(); res.end() })
903
+ const end = () => {
904
+ clearInterval(ping)
905
+ clients.delete(client)
906
+ streams.delete(end)
907
+ }
908
+ streams.add(() => {
909
+ end()
910
+ res.end()
911
+ })
653
912
  req.on('close', end)
654
913
  return
655
914
  }
@@ -658,7 +917,11 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
658
917
  // a page is named without .md; a repository path is the file's own
659
918
  const id = isRepoId(path_) ? path_ : path_.replace(/\.md$/, '')
660
919
  const r = await resolve(id, p)
661
- if ('redirect' in r) { res.writeHead(302, { location: r.redirect + url.search }); res.end(); return }
920
+ if ('redirect' in r) {
921
+ res.writeHead(302, { location: r.redirect + url.search })
922
+ res.end()
923
+ return
924
+ }
662
925
  if ('raw' in r) return sendFile(res, r.raw)
663
926
  if ('notFound' in r) {
664
927
  // rendered as a page, with the page's styles and the plugins', and live: it becomes the page
@@ -676,10 +939,228 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
676
939
  }
677
940
  }
678
941
 
942
+ // ---- build: a static site ---------------------------------------------------------------------
943
+ // Pages rendered once (`whiteboard build`), as files: each page's HTML with its links relative, and
944
+ // what it loads copied beside it. See BuildConfig.
945
+
946
+ /** What a build leaves out unless told otherwise: what is for writing a page, not for reading it. */
947
+ const BUILD_SKIP = ['form', 'chat', 'comments', 'draft']
948
+ /** In the folder a build writes, so that a next build knows it may replace it. */
949
+ const BUILD_MARK = '.whiteboard-build'
950
+
951
+ async function build(options: BuildConfig = {}): Promise<BuildResult> {
952
+ const cfg = await config()
953
+ if (cfg.errors.length) throw new Error(`the config failed to load: ${(cfg.errors[0] as Error).message}`)
954
+ if (!cfg.pages) throw new Error('the config has no pages renderer')
955
+ const pages = cfg.pages
956
+ const defined = <T>(...xs: (T | undefined)[]) => xs.find(x => x !== undefined)
957
+ const patterns = defined(options.pages, cfg.build.pages) ?? []
958
+ const skip = new Set(defined(options.skip, cfg.build.skip) ?? BUILD_SKIP)
959
+ const outDir = path.resolve(project.dir, defined(options.out, cfg.build.out) ?? 'site')
960
+ if (!patterns.length)
961
+ throw new Error(
962
+ "nothing to build: name the pages, as globs from the project's folder (whiteboard build 'docs/**/*.md'), or set build.pages in the config",
963
+ )
964
+ const warnings: string[] = []
965
+
966
+ // the pages: markdown files the globs match, but those a `!` glob leaves out
967
+ const include = patterns.filter(p => !p.startsWith('!'))
968
+ const exclude = patterns.filter(p => p.startsWith('!')).map(p => p.slice(1))
969
+ const files = [
970
+ ...new Set(include.flatMap(p => fs.globSync(p, { cwd: project.dir }).map(f => path.resolve(project.dir, f)))),
971
+ ]
972
+ .filter(f => /\.(md|markdown)$/i.test(f) && fs.statSync(f).isFile())
973
+ .filter(f => !exclude.some(g => path.matchesGlob(path.relative(project.dir, f), g)))
974
+ .sort()
975
+ if (!files.length) throw new Error(`no markdown files match ${patterns.join(' ')}`)
976
+ // each at its place below the folder they share; a README or index is its folder's index.html
977
+ const base = files.map(path.dirname).reduce((a, b) => {
978
+ while (!within(b, a)) a = path.dirname(a)
979
+ return a
980
+ })
981
+ const outOf = (file: string) => {
982
+ const rel = path.relative(base, file)
983
+ return path.join(
984
+ outDir,
985
+ /^(readme|index)\.(md|markdown)$/i.test(path.basename(rel))
986
+ ? path.join(path.dirname(rel), 'index.html')
987
+ : rel.replace(/\.(md|markdown)$/i, '.html'),
988
+ )
989
+ }
990
+ const built = new Map(files.map(f => [f, outOf(f)]))
991
+
992
+ // the folder it writes: new, empty, or what an earlier build wrote
993
+ if (fs.existsSync(outDir)) {
994
+ if (fs.readdirSync(outDir).length && !fs.existsSync(path.join(outDir, BUILD_MARK)))
995
+ throw new Error(`${outDir} has files a build didn't write: give another folder (--out), or empty it`)
996
+ fs.rmSync(outDir, { recursive: true })
997
+ }
998
+ fs.mkdirSync(outDir, { recursive: true })
999
+ fs.writeFileSync(
1000
+ path.join(outDir, BUILD_MARK),
1001
+ 'written by whiteboard build; the next build replaces this folder\n',
1002
+ )
1003
+
1004
+ // what a page loads, copied once: the package's files under _/whiteboard/, the project's under
1005
+ // _/project/, at their places there (so a stylesheet's url()s still hold); TypeScript as JavaScript
1006
+ const copied = new Map<string, string>()
1007
+ function copyAsset(file: string): string {
1008
+ const known = copied.get(file)
1009
+ if (known) return known
1010
+ const rel = within(file, ENGINE_DIR)
1011
+ ? path.join('_', 'whiteboard', path.relative(ENGINE_DIR, file))
1012
+ : within(file, project.dir)
1013
+ ? path.join('_', 'project', path.relative(project.dir, file))
1014
+ : path.join('_', 'files', path.basename(path.dirname(file)), path.basename(file))
1015
+ const dest = path.join(outDir, TYPESCRIPT.test(rel) ? rel.replace(/\.m?ts$/i, '.js') : rel)
1016
+ copied.set(file, dest)
1017
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
1018
+ if (TYPESCRIPT.test(file)) fs.writeFileSync(dest, typeScriptModule(file))
1019
+ else fs.copyFileSync(file, dest)
1020
+ // a stylesheet's own files (fonts, images), at the same places beside it
1021
+ if (/\.css$/i.test(file)) {
1022
+ for (const m of fs.readFileSync(file, 'utf8').matchAll(/url\(\s*['"]?([^'")]+)['"]?\s*\)/g)) {
1023
+ const ref = m[1]!
1024
+ if (/^(data:|[a-z][a-z0-9+.-]*:|\/|#)/i.test(ref)) continue
1025
+ const target = path.resolve(path.dirname(file), ref.replace(/[?#].*$/, ''))
1026
+ if (fs.existsSync(target) && fs.statSync(target).isFile()) copyAsset(target)
1027
+ }
1028
+ }
1029
+ return dest
1030
+ }
1031
+ /** a file beside the pages (an image), copied to its place below the site */
1032
+ function copyBeside(file: string): string | null {
1033
+ if (!within(file, base)) return null
1034
+ const dest = path.join(outDir, path.relative(base, file))
1035
+ if (!fs.existsSync(dest)) {
1036
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
1037
+ fs.copyFileSync(file, dest)
1038
+ }
1039
+ return dest
1040
+ }
1041
+
1042
+ const hooks = await pluginHooks()
1043
+ const result: BuildResult = { out: outDir, pages: [], warnings }
1044
+ for (const [file, dest] of built) {
1045
+ const here = path.dirname(dest)
1046
+ const relTo = (target: string) =>
1047
+ path.relative(here, target).split(path.sep).map(encodeURIComponent).join('/') || '.'
1048
+ const assetHere = (ref: string | URL) => relTo(copyAsset(toPath(ref)))
1049
+ const urlFor = (abs: string): string | null => {
1050
+ for (const candidate of [abs, abs + '.md']) {
1051
+ if (!fs.existsSync(candidate)) continue
1052
+ if (fs.statSync(candidate).isDirectory()) {
1053
+ const index = [...built.keys()].find(
1054
+ f => path.dirname(f) === candidate && /^(readme|index)\.(md|markdown)$/i.test(path.basename(f)),
1055
+ )
1056
+ if (index) return relTo(built.get(index)!)
1057
+ continue
1058
+ }
1059
+ if (built.has(candidate)) return relTo(built.get(candidate)!)
1060
+ if (/\.(md|markdown)$/i.test(candidate)) {
1061
+ warnings.push(
1062
+ `${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, which is not in the build`,
1063
+ )
1064
+ return null
1065
+ }
1066
+ const copy = copyBeside(candidate)
1067
+ if (copy) return relTo(copy)
1068
+ warnings.push(
1069
+ `${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, outside the built pages' folder`,
1070
+ )
1071
+ return null
1072
+ }
1073
+ return null
1074
+ }
1075
+ const id = within(file, project.pagesDir)
1076
+ ? path
1077
+ .relative(project.pagesDir, file)
1078
+ .split(path.sep)
1079
+ .join('/')
1080
+ .replace(/\.(md|markdown)$/i, '')
1081
+ : '-/' + path.relative(project.dir, file).split(path.sep).join('/')
1082
+ const stored = pageSource(id, file)
1083
+ if (stored.frontmatterError)
1084
+ warnings.push(`${path.relative(project.dir, file)}: frontmatter: ${stored.frontmatterError}`)
1085
+ const context = {
1086
+ project: { name: project.name, dir: project.dir, files: !!FILES },
1087
+ asset: assetHere,
1088
+ urlFor,
1089
+ live: false,
1090
+ skip,
1091
+ }
1092
+ const rendered = await pages.render(stored, context)
1093
+ // a page without a heading of its own is named by its file (a README by its folder), not by
1094
+ // the id the server knows it by
1095
+ const named = /^(readme|index)\.(md|markdown)$/i.test(path.basename(file))
1096
+ ? path.basename(path.dirname(file))
1097
+ : path.basename(file).replace(/\.(md|markdown)$/i, '')
1098
+ const title = !rendered.title || rendered.title === id ? named : rendered.title
1099
+ const out = { ...rendered, title, html: String(rendered.html ?? ''), head: String(rendered.head ?? '') }
1100
+ // the plugins' browser modules, but those the build leaves out; not what they add to a live
1101
+ // page's shell (the terminal's drawer): that is the server's
1102
+ const included = hooks.filter(h => !h.error && !skip.has(h.name))
1103
+ const clients = included.filter(h => h.client).map(h => ({ name: h.name, client: assetHere(h.client!) }))
1104
+ // what the plugins add to the shell, asked with no request: no browser asked for this page
1105
+ const parts = await Promise.all(
1106
+ included.map(async h => {
1107
+ try {
1108
+ return (await h.shell?.(null)) ?? null
1109
+ } catch (err) {
1110
+ warnings.push(`plugin ${h.name} failed on ${path.relative(project.dir, file)}: ${(err as Error).message}`)
1111
+ return null
1112
+ }
1113
+ }),
1114
+ )
1115
+ const extras = {
1116
+ head: parts.map(x => raw(String(x?.head ?? ''))),
1117
+ body: parts.map(x => raw(String(x?.body ?? ''))),
1118
+ clients,
1119
+ }
1120
+ let doc = shell(stored, { page: true, out, notices: [] }, extras, { asset: assetHere })
1121
+ // a file a plugin named the server's way (its asset URL, /_/file/<path>): its copy
1122
+ doc = doc.replace(/\/_\/file(\/[^"'\s)<>]+)/g, (all, served: string) => {
1123
+ let file: string
1124
+ try {
1125
+ file = path.resolve(served.split('/').map(decodeURIComponent).join(path.sep))
1126
+ } catch {
1127
+ return all
1128
+ }
1129
+ return fs.existsSync(file) && fs.statSync(file).isFile() ? assetHere(file) : all
1130
+ })
1131
+ // what the blocks name relative to the page (an ::image's src, an iframe's page): copied too
1132
+ doc = doc.replace(/\b(src|href|poster)="([^"#?:]+)([^"]*)"/g, (all, _attr, ref: string) => {
1133
+ if (ref.startsWith('/') || ref.startsWith('_/') || ref.startsWith('../')) return all
1134
+ let decoded = ref
1135
+ try {
1136
+ decoded = decodeURIComponent(ref)
1137
+ } catch {
1138
+ /* as written */
1139
+ }
1140
+ const source = path.resolve(path.dirname(file), decoded)
1141
+ if (fs.existsSync(source) && fs.statSync(source).isFile() && !/\.(md|markdown)$/i.test(source)) {
1142
+ const target = path.resolve(here, decoded)
1143
+ if (within(target, outDir) && !fs.existsSync(target)) {
1144
+ fs.mkdirSync(path.dirname(target), { recursive: true })
1145
+ fs.copyFileSync(source, target)
1146
+ }
1147
+ }
1148
+ return all
1149
+ })
1150
+ fs.mkdirSync(here, { recursive: true })
1151
+ fs.writeFileSync(dest, doc)
1152
+ result.pages.push({ file, to: dest })
1153
+ }
1154
+ if (![...built.values()].includes(path.join(outDir, 'index.html')))
1155
+ warnings.push('no README.md or index.md in the top folder: the site has no index.html')
1156
+ return result
1157
+ }
1158
+
679
1159
  return {
680
1160
  handle,
681
1161
  status: (page = null) => status(page),
682
1162
  config,
1163
+ build,
683
1164
  close() {
684
1165
  for (const w of watchers) w.close()
685
1166
  watchers.clear()