@bigmistqke/whiteboard 0.3.0 → 0.4.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 (155) hide show
  1. package/README.md +67 -17
  2. package/bin/whiteboard.ts +268 -71
  3. package/dist/client/runtime.js +88 -41
  4. package/dist/define.js +21 -2
  5. package/dist/plugins/callout/index.js +3 -1
  6. package/dist/plugins/callout/public/style.css +30 -0
  7. package/dist/plugins/chat/index.js +7 -4
  8. package/dist/plugins/chat/{client.js → public/client.js} +1 -1
  9. package/dist/plugins/chat/public/style.css +98 -0
  10. package/dist/plugins/code/index.js +3 -1
  11. package/dist/plugins/code/public/style.css +68 -0
  12. package/dist/plugins/comments/index.js +4 -5
  13. package/dist/plugins/comments/public/client.js +19 -0
  14. package/dist/plugins/comments/public/style.css +185 -0
  15. package/dist/plugins/details/index.js +7 -2
  16. package/dist/plugins/details/public/style.css +7 -0
  17. package/dist/plugins/form/index.js +37 -8
  18. package/dist/plugins/form/public/style.css +126 -0
  19. package/dist/plugins/gallery/index.js +4 -3
  20. package/dist/plugins/gallery/public/client.js +1 -0
  21. package/dist/plugins/gallery/public/style.css +90 -0
  22. package/dist/plugins/grid/index.js +9 -3
  23. package/dist/plugins/grid/public/style.css +71 -0
  24. package/dist/plugins/iframe/index.js +13 -14
  25. package/dist/plugins/iframe/public/style.css +13 -0
  26. package/dist/plugins/index.js +3 -1
  27. package/dist/plugins/mermaid/index.js +3 -1
  28. package/dist/plugins/mermaid/{style.css → public/style.css} +7 -2
  29. package/dist/plugins/terminal/index.js +10 -9
  30. package/dist/plugins/terminal/{style.css → public/style.css} +199 -45
  31. package/dist/plugins/toc/README.md +12 -0
  32. package/dist/plugins/toc/index.js +9 -5
  33. package/dist/plugins/toc/public/client.js +1 -0
  34. package/dist/plugins/toc/public/style.css +93 -0
  35. package/dist/plugins/window/README.md +29 -0
  36. package/dist/plugins/window/index.js +64 -0
  37. package/dist/solid/index.js +14 -11
  38. package/dist/src/client/page/base.css +1078 -199
  39. package/dist/src/client/page/main.js +174 -32
  40. package/dist/src/loader.js +7 -2
  41. package/dist/src/package.js +3 -6
  42. package/dist/src/pages/blocks.js +8 -13
  43. package/dist/src/pages/markdown.js +1 -1
  44. package/dist/src/pages/render.js +73 -13
  45. package/dist/src/pages/window.js +30 -0
  46. package/dist/src/public.js +24 -0
  47. package/dist/src/server.js +37 -15
  48. package/package.json +3 -1
  49. package/plugins/callout/index.ts +3 -1
  50. package/plugins/callout/public/style.css +30 -0
  51. package/plugins/chat/autosize.ts +43 -9
  52. package/plugins/chat/client.tsx +22 -5
  53. package/plugins/chat/index.ts +22 -8
  54. package/plugins/chat/public/style.css +98 -0
  55. package/plugins/claude-code/index.ts +49 -14
  56. package/plugins/code/diff.ts +28 -8
  57. package/plugins/code/index.ts +30 -20
  58. package/plugins/code/public/style.css +68 -0
  59. package/plugins/comments/client.ts +139 -71
  60. package/plugins/comments/index.ts +9 -7
  61. package/plugins/comments/public/style.css +185 -0
  62. package/plugins/details/index.ts +7 -2
  63. package/plugins/details/public/style.css +7 -0
  64. package/plugins/forge/index.ts +16 -3
  65. package/plugins/form/index.ts +75 -27
  66. package/plugins/form/public/style.css +126 -0
  67. package/plugins/gallery/client.tsx +9 -3
  68. package/plugins/gallery/index.ts +31 -9
  69. package/plugins/gallery/public/style.css +90 -0
  70. package/plugins/grid/index.ts +19 -5
  71. package/plugins/grid/public/style.css +71 -0
  72. package/plugins/iframe/index.ts +20 -23
  73. package/plugins/iframe/public/style.css +13 -0
  74. package/plugins/index.ts +16 -1
  75. package/plugins/mermaid/index.ts +3 -1
  76. package/plugins/mermaid/{style.css → public/style.css} +7 -2
  77. package/plugins/terminal/client.ts +105 -48
  78. package/plugins/terminal/host.ts +131 -29
  79. package/plugins/terminal/index.ts +84 -25
  80. package/plugins/terminal/public/style.css +225 -0
  81. package/plugins/terminal/server.ts +64 -13
  82. package/plugins/terminal/sizes.ts +13 -3
  83. package/plugins/toc/README.md +12 -0
  84. package/plugins/toc/client.ts +58 -29
  85. package/plugins/toc/index.ts +22 -5
  86. package/plugins/toc/public/style.css +93 -0
  87. package/plugins/window/README.md +29 -0
  88. package/plugins/window/index.ts +85 -0
  89. package/skills/whiteboard/SKILL.md +3 -1
  90. package/solid/index.tsx +24 -9
  91. package/src/auth.ts +25 -7
  92. package/src/client/forms.ts +74 -28
  93. package/src/client/markdown.ts +15 -4
  94. package/src/client/page/base.css +1078 -199
  95. package/src/client/page/elsewhere.ts +32 -15
  96. package/src/client/page/fresh.ts +91 -23
  97. package/src/client/page/hold.ts +11 -2
  98. package/src/client/page/live.ts +10 -6
  99. package/src/client/page/main.ts +106 -34
  100. package/src/client/page/orphans.ts +25 -10
  101. package/src/client/page/sort.ts +14 -4
  102. package/src/client/page/sticky.ts +11 -3
  103. package/src/client/page/theme.ts +11 -7
  104. package/src/client/page/waiting.ts +141 -34
  105. package/src/client/page/window.ts +40 -0
  106. package/src/client/reactive.ts +19 -0
  107. package/src/client/read.ts +17 -10
  108. package/src/client/runtime.ts +130 -35
  109. package/src/client/scroll.ts +14 -4
  110. package/src/client/toast.ts +19 -5
  111. package/src/config.ts +20 -5
  112. package/src/define.ts +67 -23
  113. package/src/events.ts +111 -24
  114. package/src/html.ts +6 -2
  115. package/src/icons.ts +4 -2
  116. package/src/load.ts +10 -2
  117. package/src/loader.ts +75 -11
  118. package/src/package.ts +9 -8
  119. package/src/pages/blocks.ts +20 -14
  120. package/src/pages/markdown.ts +113 -34
  121. package/src/pages/render.ts +198 -37
  122. package/src/pages/window.ts +71 -0
  123. package/src/plugins.ts +90 -24
  124. package/src/public.ts +39 -0
  125. package/src/running.ts +8 -2
  126. package/src/serve.ts +29 -7
  127. package/src/server.ts +351 -108
  128. package/src/status.ts +15 -9
  129. package/dist/plugins/callout/style.css +0 -12
  130. package/dist/plugins/chat/style.css +0 -24
  131. package/dist/plugins/code/style.css +0 -29
  132. package/dist/plugins/comments/client.js +0 -10
  133. package/dist/plugins/comments/style.css +0 -40
  134. package/dist/plugins/details/style.css +0 -3
  135. package/dist/plugins/form/style.css +0 -44
  136. package/dist/plugins/gallery/client.js +0 -1
  137. package/dist/plugins/gallery/style.css +0 -27
  138. package/dist/plugins/grid/style.css +0 -25
  139. package/dist/plugins/iframe/client.js +0 -1
  140. package/dist/plugins/iframe/style.css +0 -29
  141. package/dist/plugins/toc/client.js +0 -1
  142. package/dist/plugins/toc/style.css +0 -19
  143. package/plugins/callout/style.css +0 -12
  144. package/plugins/chat/style.css +0 -24
  145. package/plugins/code/style.css +0 -29
  146. package/plugins/comments/style.css +0 -40
  147. package/plugins/details/style.css +0 -3
  148. package/plugins/form/style.css +0 -44
  149. package/plugins/gallery/style.css +0 -27
  150. package/plugins/grid/style.css +0 -25
  151. package/plugins/iframe/client.ts +0 -46
  152. package/plugins/iframe/style.css +0 -29
  153. package/plugins/terminal/style.css +0 -71
  154. package/plugins/toc/style.css +0 -19
  155. /package/dist/plugins/terminal/{client.js → public/client.js} +0 -0
package/src/server.ts CHANGED
@@ -17,6 +17,7 @@
17
17
  // text.
18
18
  import type { IncomingMessage, ServerResponse } from 'node:http'
19
19
  import fs from 'node:fs'
20
+ import { stripTypeScriptTypes } from 'node:module'
20
21
  import path from 'node:path'
21
22
  import type { Project } from './config.ts'
22
23
  import { appendEvent, readEvents, matches, pickedUp, fromReader, forAgent, CLAIM } from './events.ts'
@@ -27,7 +28,17 @@ import { createAuth } from './auth.ts'
27
28
  import { FROM_SOURCE, PACKAGE_DIR } from './package.ts'
28
29
  import { awaiting, covers, heard, questionState, unreadMessages } from './status.ts'
29
30
  import { titleOf } from './pages/render.ts'
30
- import type { Listener, PageSource, PageStatus, Plugin, PluginHooks, Rendered, StoredPage, PagesSource } from './define.ts'
31
+ import { inPublic } from './public.ts'
32
+ import type {
33
+ Listener,
34
+ PageSource,
35
+ PageStatus,
36
+ Plugin,
37
+ PluginHooks,
38
+ Rendered,
39
+ StoredPage,
40
+ PagesSource,
41
+ } from './define.ts'
31
42
 
32
43
  const ENGINE_DIR = PACKAGE_DIR
33
44
  // the browser runtime, built by build.ts
@@ -35,11 +46,26 @@ const RUNTIME = path.join(ENGINE_DIR, 'dist', 'client', 'runtime.js')
35
46
  // the page in the browser (markdown live: morphing, blocks' islands, forms' marks), built by build.ts
36
47
  const PAGE_CLIENT = path.join(ENGINE_DIR, 'dist', 'src', 'client', 'page', 'main.js')
37
48
  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',
49
+ '.css': 'text/css',
50
+ '.js': 'text/javascript',
51
+ '.mjs': 'text/javascript',
52
+ '.json': 'application/json',
53
+ '.png': 'image/png',
54
+ '.jpg': 'image/jpeg',
55
+ '.jpeg': 'image/jpeg',
56
+ '.gif': 'image/gif',
57
+ '.webp': 'image/webp',
58
+ '.avif': 'image/avif',
59
+ '.svg': 'image/svg+xml',
60
+ '.pdf': 'application/pdf',
61
+ '.mp4': 'video/mp4',
62
+ '.webm': 'video/webm',
63
+ '.woff': 'font/woff',
64
+ '.woff2': 'font/woff2',
65
+ '.txt': 'text/plain; charset=utf-8',
66
+ '.md': 'text/markdown; charset=utf-8',
67
+ '.csv': 'text/csv; charset=utf-8',
68
+ '.html': 'text/html; charset=utf-8',
43
69
  }
44
70
  // files in .whiteboard/ that are the server's own bookkeeping, not content
45
71
  const OWN_FILES = new Set(['events.ndjson', 'server.json', 'server.log', 'server.lock', 'token'])
@@ -47,7 +73,6 @@ const SKIP_DIRS = new Set(['node_modules', '.git'])
47
73
  // a page's frontmatter: `---` lines around `key: value` lines, at the very start
48
74
  const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/
49
75
 
50
-
51
76
  /** A project's server: its request handler, and what it knows. */
52
77
  export interface WhiteboardServer {
53
78
  /** answer one request */
@@ -67,7 +92,15 @@ export function createServer(project: Project): WhiteboardServer {
67
92
  const watchers = new Set<fs.FSWatcher>()
68
93
  const streams = new Set<() => void>()
69
94
  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 */ }
95
+ try {
96
+ watchers.add(
97
+ fs.watch(dir, options, (_evt, name) => {
98
+ if (name) fn(String(name))
99
+ }),
100
+ )
101
+ } catch {
102
+ /* gone, or not built */
103
+ }
71
104
  }
72
105
 
73
106
  // ---- plugins --------------------------------------------------------------------------------
@@ -89,17 +122,32 @@ export function createServer(project: Project): WhiteboardServer {
89
122
  async function pluginHooks(): Promise<SetUp[]> {
90
123
  const c = await config()
91
124
  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
- })))
125
+ setups.set(
126
+ c,
127
+ Promise.all(
128
+ c.plugins.map(async (e): Promise<SetUp> => {
129
+ try {
130
+ pluginDirs.add(e.name)
131
+ const dataDir = pluginDir(project.wb, e.name)
132
+ // what it serves is in its public folder: its client, and what it asks ctx.asset for
133
+ const dir = c.publicDirs.get(e.name)!
134
+ const own = (ref: URL | string) => asset(inPublic(dir, ref, `plugin ${e.name}`))
135
+ const hooks =
136
+ (await e.setup?.({
137
+ project: { name: project.name, dir: project.dir, wb: project.wb },
138
+ dataDir,
139
+ authorized: auth.authorized,
140
+ asset: own,
141
+ })) ?? {}
142
+ const client = hooks.client != null ? inPublic(dir, hooks.client, `plugin ${e.name}: client`) : undefined
143
+ return { name: e.name, ...hooks, client, table: mountRoutes(e.name, hooks.routes), plugin: e }
144
+ } catch (err) {
145
+ console.error(`plugin ${e.name}:`, err)
146
+ return { name: e.name, table: [], plugin: e, error: err as Error }
147
+ }
148
+ }),
149
+ ),
150
+ )
103
151
  }
104
152
  return setups.get(c)!
105
153
  }
@@ -122,17 +170,27 @@ export function createServer(project: Project): WhiteboardServer {
122
170
  async function shellExtras(req: IncomingMessage): Promise<Extras & { notices: string[] }> {
123
171
  const hooks = await pluginHooks()
124
172
  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
- }))
173
+ const parts = await Promise.all(
174
+ hooks.map(async h => {
175
+ try {
176
+ return (await h.shell?.(req)) ?? null
177
+ } catch (err) {
178
+ console.error(`plugin ${h.name}:`, err)
179
+ notices.push(`plugin "${h.name}" failed on this page: ${(err as Error).message}`)
180
+ return null
181
+ }
182
+ }),
183
+ )
132
184
  // their browser modules, which the runtime imports after the page's
133
185
  const clients = hooks.filter(h => h.client && !h.error).map(h => ({ name: h.name, client: asset(h.client!) }))
134
186
  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 }
187
+ return {
188
+ head: parts.map(x => raw(String(x?.head ?? ''))),
189
+ body: parts.map(x => raw(String(x?.body ?? ''))),
190
+ clients,
191
+ messages,
192
+ notices,
193
+ }
136
194
  }
137
195
 
138
196
  /** A page with what the plugins add, their notices among the page's. */
@@ -145,19 +203,25 @@ export function createServer(project: Project): WhiteboardServer {
145
203
  async function config(): Promise<LoadedConfig> {
146
204
  const c = await loader.config()
147
205
  setFiles(c.files)
206
+ publicDirs = [...c.publicDirs.values()]
148
207
  return c
149
208
  }
150
209
 
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.
210
+ // ---- assets: the browser's files ----------------------------------------------------------------
211
+ // Served at /_/file/<absolute path>, and only these: the files the core names (its page module and
212
+ // styles, the project's stylesheet), and what is inside a plugin's public folder (public.ts): its
213
+ // client modules, styles, images, fonts. Nothing else of a plugin, and nothing beside its public
214
+ // folder: not its server code, not the project's token, log or config. TypeScript there is
215
+ // served with its types stripped (Node's own type stripping, as for server code: erasable syntax
216
+ // only, positions kept). The folders of what is served are watched from then on.
156
217
 
157
218
  const assets = new Set<string>()
158
219
  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))
220
+ const TYPESCRIPT = /\.m?ts$/i
221
+ const typeScriptModule = (file: string): string => stripTypeScriptTypes(fs.readFileSync(file, 'utf8'))
222
+ // the plugins' public folders, as the config last loaded them
223
+ let publicDirs: string[] = []
224
+ const servable = (file: string) => assets.has(file) || publicDirs.some(dir => within(file, dir) && file !== dir)
161
225
 
162
226
  function asset(ref: string | URL): string {
163
227
  const file = toPath(ref)
@@ -190,16 +254,25 @@ export function createServer(project: Project): WhiteboardServer {
190
254
  function frontmatter(source: string): Record<string, string> {
191
255
  const m = FRONTMATTER.exec(source)
192
256
  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, '')
196
- }
257
+ if (m)
258
+ for (const line of m[1]!.split(/\r?\n/)) {
259
+ const kv = /^([\w-]+)\s*:\s*(.*)$/.exec(line)
260
+ if (kv) out[kv[1]!] = kv[2]!.trim().replace(/^["']|["']$/g, '')
261
+ }
197
262
  return out
198
263
  }
199
264
 
200
265
  function pageSource(id: string, file: string): PageSource {
201
266
  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) }
267
+ return {
268
+ kind: 'page',
269
+ id,
270
+ file,
271
+ mtime: fs.statSync(file).mtimeMs,
272
+ source,
273
+ body: source.replace(FRONTMATTER, ''),
274
+ frontmatter: frontmatter(source),
275
+ }
203
276
  }
204
277
 
205
278
  /** The pages in a folder of the pages folder, newest first, with when each was last answered. */
@@ -242,13 +315,15 @@ export function createServer(project: Project): WhiteboardServer {
242
315
  if (isRepoId(id)) {
243
316
  const rel = id.slice(2)
244
317
  const target = inside(project.dir, rel)
245
- if (!target || path.relative(project.dir, target).split(path.sep).includes('.git') || !fs.existsSync(target)) return null
318
+ if (!target || path.relative(project.dir, target).split(path.sep).includes('.git') || !fs.existsSync(target))
319
+ return null
246
320
  const stat = fs.statSync(target)
247
321
  if (stat.isDirectory()) {
248
- const entries = fs.readdirSync(target, { withFileTypes: true })
322
+ const entries = fs
323
+ .readdirSync(target, { withFileTypes: true })
249
324
  .filter(e => !SKIP_DIRS.has(e.name) && e.name !== '.DS_Store')
250
325
  .map(e => ({ name: e.name, dir: e.isDirectory() }))
251
- .sort((a, b) => (Number(b.dir) - Number(a.dir)) || a.name.localeCompare(b.name))
326
+ .sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name))
252
327
  return { kind: 'folder', id, file: target, mtime: stat.mtimeMs, entries }
253
328
  }
254
329
  if (/\.(md|markdown)$/i.test(target)) return pageSource(id, target)
@@ -272,7 +347,12 @@ export function createServer(project: Project): WhiteboardServer {
272
347
  const rel = (dir: string) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join('/')
273
348
  if (within(abs, project.pagesDir)) return `/${rel(project.pagesDir).replace(/\.md$/, '')}`
274
349
  if (FILES && within(abs, project.dir)) {
275
- if (rel(project.dir).split('/').some(part => SKIP_DIRS.has(part))) return null
350
+ if (
351
+ rel(project.dir)
352
+ .split('/')
353
+ .some(part => SKIP_DIRS.has(part))
354
+ )
355
+ return null
276
356
  return `/-/${rel(project.dir)}`
277
357
  }
278
358
  return null
@@ -293,10 +373,19 @@ export function createServer(project: Project): WhiteboardServer {
293
373
 
294
374
  /** A config that failed to load: the page as stored, as text, under the error. */
295
375
  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>`
376
+ const list = (items: [string, string][]) =>
377
+ html`<ul>
378
+ ${items.map(([href, text]) => html`<li><a href="${href}">${text}</a></li>`)}
379
+ </ul>`
297
380
  if (page.kind === 'pages') return { html: list(page.pages.map(p => [`/${p.id}`, p.id])) }
298
381
  if (page.kind === 'folder') {
299
- return { html: list(page.entries.map(e => [encodeURIComponent(e.name) + (e.dir ? '/' : ''), e.name + (e.dir ? '/' : '')] as [string, string])) }
382
+ return {
383
+ html: list(
384
+ page.entries.map(
385
+ e => [encodeURIComponent(e.name) + (e.dir ? '/' : ''), e.name + (e.dir ? '/' : '')] as [string, string],
386
+ ),
387
+ ),
388
+ }
300
389
  }
301
390
  return { html: html`<pre>${page.source}</pre>` }
302
391
  }
@@ -310,6 +399,9 @@ export function createServer(project: Project): WhiteboardServer {
310
399
  notices: string[]
311
400
  }
312
401
 
402
+ /** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
403
+ const frontmatterOf = (page: StoredPage): Record<string, string> => (page.kind === 'page' ? page.frontmatter : {})
404
+
313
405
  /** Render a stored page as markdown, with the plugins' blocks, and anything the reader should be told. */
314
406
  async function render(page: StoredPage): Promise<Render> {
315
407
  const { pages, errors } = await config()
@@ -340,20 +432,33 @@ export function createServer(project: Project): WhiteboardServer {
340
432
  const all = readEvents(project.eventsFile)
341
433
  const picked = pickedUp(all)
342
434
  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)
435
+ for (const e of all)
436
+ if (e.type === CLAIM && !fromReader(e)) owner.set(e.page, (e.data?.session as string | undefined) ?? null)
344
437
  const out: PageStatus[] = []
345
438
  for (const p of pagesIn(project.pagesDir)) {
346
439
  if (only && p.id !== only && !p.id.startsWith(only + '/')) continue
347
440
  const page = pageSource(p.id, p.file)
348
441
  let asks: string[] = []
349
- try { asks = pages?.questions(page) ?? [] } catch (err) { console.error('questions:', err) }
442
+ try {
443
+ asks = pages?.questions(page) ?? []
444
+ } catch (err) {
445
+ console.error('questions:', err)
446
+ }
350
447
  const events = all.filter(e => e.page === p.id)
351
448
  const listening = listenersFor(p.id)
352
449
  // 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 }))
450
+ const questions = asks.map(name => ({
451
+ name,
452
+ state: questionState(name, events, listening, id => picked.has(id)).state,
453
+ }))
354
454
  const named = (...states: string[]) => questions.filter(q => states.includes(q.state)).map(q => q.name)
355
455
  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,
456
+ page: p.id,
457
+ title: titleOf(p.file, path.basename(p.id)),
458
+ file: p.file,
459
+ owner: owner.get(p.id) ?? null,
460
+ asks,
461
+ questions,
357
462
  open: named('open'),
358
463
  unheard: named('open').filter(name => !heard(name, listening)),
359
464
  unread: unreadMessages(events, type => forReader.has(type)),
@@ -369,44 +474,83 @@ export function createServer(project: Project): WhiteboardServer {
369
474
  async function docs() {
370
475
  const { pages, errors } = await config()
371
476
  // 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
- })))
477
+ const plugins = await Promise.all(
478
+ (await pluginHooks()).map(async h => ({
479
+ name: h.name,
480
+ error: h.error?.message ?? null,
481
+ docs: h.plugin.docs ? await h.plugin.docs() : null,
482
+ routes: describeRoutes(h.table),
483
+ commands: pluginCommands(h.plugin).map(c => ({
484
+ name: c.name,
485
+ usage: usage(c.command),
486
+ description: c.command.description,
487
+ })),
488
+ events: Object.entries(h.plugin.events ?? {}).map(([type, spec]) => ({
489
+ type,
490
+ handOut: !!spec?.handOut,
491
+ description: spec?.description ?? '',
492
+ })),
493
+ })),
494
+ )
380
495
  return { errors: errors.map(e => (e as Error).message), pages: pages?.docs(context()) ?? null, plugins }
381
496
  }
382
497
 
383
498
  const json = (s: unknown) => JSON.stringify(s).replace(/</g, '\\u003c')
384
499
 
385
500
  // the page's corner (api.corner()): the one thing the core puts on every page, empty, for the
386
- // page's and the plugins' floating buttons; above what covers the bottom of the window
387
- const DOCK_STYLE = '#wb-dock{position:fixed;right:16px;bottom:calc(16px + var(--wb-inset-bottom,0px));z-index:10;display:flex;flex-direction:column;align-items:flex-end;gap:6px}#wb-dock:empty{display:none}'
501
+ // page's and the plugins' floating buttons and toasts; above what covers the bottom of the window.
502
+ // Above the page and what floats on it (comment threads: 20), under what fills the window (a
503
+ // maximized frame: 40, a lightbox or the terminal drawer: 50)
504
+ const DOCK_STYLE =
505
+ '#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}' +
388
506
  // toasts (api.toast): labels in the corner, in the page's theme colours where it has them
389
- + '.wb-toasts{display:flex;flex-direction:column;align-items:flex-end;gap:6px}.wb-toasts:empty{display:none}'
390
- + '.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)}'
391
- + '.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}'
507
+ '.wb-toasts{display:flex;flex-direction:column;align-items:flex-end;gap:6px}.wb-toasts:empty{display:none}' +
508
+ '.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)}' +
509
+ '.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}' +
392
510
  // where an agent scrolled the page to, lit up a moment
393
- + '@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}'
394
- + '.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}'
511
+ '@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}' +
512
+ '.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}'
395
513
 
396
514
  /** `extras`: what plugins add to <head> and <body> (see shellExtras). */
397
- function shell(page: StoredPage, { page: rendered, out, notices }: Render, extras: Extras = { head: [], body: [], clients: [] }): string {
398
- const handoff = { id: page.id, kind: page.kind, client: rendered ? asset(PAGE_CLIENT) : null, data: out.data ?? null, plugins: extras.clients, messages: extras.messages ?? [] }
515
+ function shell(
516
+ page: StoredPage,
517
+ { page: rendered, out, notices }: Render,
518
+ extras: Extras = { head: [], body: [], clients: [] },
519
+ ): string {
520
+ const handoff = {
521
+ id: page.id,
522
+ kind: page.kind,
523
+ client: rendered ? asset(PAGE_CLIENT) : null,
524
+ data: out.data ?? null,
525
+ frontmatter: frontmatterOf(page),
526
+ plugins: extras.clients,
527
+ messages: extras.messages ?? [],
528
+ }
399
529
  // the page's head and html are HTML already; the handoff is JSON made safe for a script tag
400
- return String(html`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
401
- <title>${out.title || page.id || project.name}</title>
402
- <style>${DOCK_STYLE}</style>
403
- ${raw(out.head ?? '')}${extras.head}</head>
404
- <body data-page="${page.id}" data-kind="${page.kind}">
405
- ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
406
- <div id="wb-root">${raw(String(out.html))}</div>
407
- <div id="wb-dock"></div>
408
- <script type="application/json" id="wb-page">${raw(json(handoff))}</script>
409
- <script type="module" src="/_/runtime.js"></script>${extras.body}</body></html>`)
530
+ return String(
531
+ html`<!doctype html>
532
+ <html lang="en">
533
+ <head>
534
+ <meta charset="utf-8" />
535
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
536
+ <title>${out.title || page.id || project.name}</title>
537
+ <style>
538
+ ${DOCK_STYLE}
539
+ </style>
540
+ ${raw(out.head ?? '')}${extras.head}
541
+ </head>
542
+ <body data-page="${page.id}" data-kind="${page.kind}">
543
+ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
544
+ <div id="wb-root">${raw(String(out.html))}</div>
545
+ <div id="wb-dock"></div>
546
+ <script type="application/json" id="wb-page">
547
+ ${raw(json(handoff))}
548
+ </script>
549
+ <script type="module" src="/_/runtime.js"></script>
550
+ ${extras.body}
551
+ </body>
552
+ </html>`,
553
+ )
410
554
  }
411
555
 
412
556
  // ---- listeners ---------------------------------------------------------------------------------
@@ -417,8 +561,10 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
417
561
  /** A listener as the server holds it. */
418
562
  const listeners = new Set<Listener>()
419
563
 
420
-
421
- const listenersFor = (page: string | null): Listener[] => [...listeners].filter(l => page == null || covers(l, page)).map(({ page, type, command, fallback }) => ({ page, type, command, ...(fallback && { fallback }) }))
564
+ const listenersFor = (page: string | null): Listener[] =>
565
+ [...listeners]
566
+ .filter(l => page == null || covers(l, page))
567
+ .map(({ page, type, command, fallback }) => ({ page, type, command, ...(fallback && { fallback }) }))
422
568
 
423
569
  // ---- live changes ------------------------------------------------------------------------------
424
570
  // The browser listens at /api/watch. `change`: its page changed; `events`: the log grew;
@@ -436,17 +582,21 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
436
582
  const clients = new Set<WatchClient>()
437
583
  function notify(client: WatchClient, kind: string) {
438
584
  client.pending ??= new Set()
439
- if (client.pending.size === 0) setTimeout(() => {
440
- for (const k of client.pending!) client.res.write(`event: ${k}\ndata: {}\n\n`)
441
- client.pending!.clear()
442
- }, 60)
585
+ if (client.pending.size === 0)
586
+ setTimeout(() => {
587
+ for (const k of client.pending!) client.res.write(`event: ${k}\ndata: {}\n\n`)
588
+ client.pending!.clear()
589
+ }, 60)
443
590
  client.pending.add(kind)
444
591
  }
445
- const notifyAll = (kind: string) => { for (const c of clients) notify(c, kind) }
592
+ const notifyAll = (kind: string) => {
593
+ for (const c of clients) notify(c, kind)
594
+ }
446
595
 
447
596
  function pageChanged(id: string) {
448
597
  for (const c of clients) {
449
- if (c.isDir ? (!c.page || id.startsWith(c.page + '/')) : (c.page === id || c.page + '/index' === id)) notify(c, 'change')
598
+ if (c.isDir ? !c.page || id.startsWith(c.page + '/') : c.page === id || c.page + '/index' === id)
599
+ notify(c, 'change')
450
600
  }
451
601
  // the overview lists every page
452
602
  for (const c of clients) if (c.isDir && !c.page) notify(c, 'change')
@@ -480,7 +630,10 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
480
630
  function setFiles(files: boolean) {
481
631
  if (files === FILES) return
482
632
  FILES = files
483
- if (watcher) { watcher.close(); watchers.delete(watcher) }
633
+ if (watcher) {
634
+ watcher.close()
635
+ watchers.delete(watcher)
636
+ }
484
637
  const base = files ? project.dir : project.wb
485
638
  const prefix = files ? '' : '.whiteboard/'
486
639
  watcher = fs.watch(base, { recursive: true }, (_evt, filename) => {
@@ -520,14 +673,22 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
520
673
  res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' })
521
674
  res.end(body)
522
675
  }
523
- const sendJson = (res: ServerResponse, status: number, data: unknown) => send(res, status, JSON.stringify(data), 'application/json')
524
- const sendFile = (res: ServerResponse, file: string) => send(res, 200, fs.readFileSync(file), MIME[path.extname(file).toLowerCase()] || 'application/octet-stream')
676
+ const sendJson = (res: ServerResponse, status: number, data: unknown) =>
677
+ send(res, status, JSON.stringify(data), 'application/json')
678
+ const sendFile = (res: ServerResponse, file: string) =>
679
+ send(res, 200, fs.readFileSync(file), MIME[path.extname(file).toLowerCase()] || 'application/octet-stream')
525
680
 
526
681
  function readBody(req: IncomingMessage): Promise<string> {
527
682
  return new Promise((resolve, reject) => {
528
683
  const chunks: Buffer[] = []
529
684
  let size = 0
530
- req.on('data', (c: Buffer) => { size += c.length; if (size > 1e6) { reject(new Error('body too large')); req.destroy() } else chunks.push(c) })
685
+ req.on('data', (c: Buffer) => {
686
+ size += c.length
687
+ if (size > 1e6) {
688
+ reject(new Error('body too large'))
689
+ req.destroy()
690
+ } else chunks.push(c)
691
+ })
531
692
  req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
532
693
  req.on('error', reject)
533
694
  })
@@ -538,7 +699,8 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
538
699
 
539
700
  async function resolve(id: string, requested: string): Promise<Resolved> {
540
701
  await config()
541
- if (isRepoId(id) && !FILES) return { notFound: 'This project does not serve its files: its config sets files: false.' }
702
+ if (isRepoId(id) && !FILES)
703
+ return { notFound: 'This project does not serve its files: its config sets files: false.' }
542
704
  if (id === '_/docs') {
543
705
  // how pages are written, then each plugin's own docs, with their examples rendered live
544
706
  const { pages, plugins } = await docs()
@@ -546,13 +708,27 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
546
708
  pages ?? '',
547
709
  ...plugins.filter(p => p.docs).map(p => `<a id="plugin-${p.name}"></a>\n\n${p.docs}`),
548
710
  ].join('\n\n---\n\n')
549
- return { page: { kind: 'page', id, file: path.join(project.pagesDir, '_docs.md'), mtime: null, source, body: source, frontmatter: {} } }
711
+ return {
712
+ page: {
713
+ kind: 'page',
714
+ id,
715
+ file: path.join(project.pagesDir, '_docs.md'),
716
+ mtime: null,
717
+ source,
718
+ body: source,
719
+ frontmatter: {},
720
+ },
721
+ }
550
722
  }
551
723
  const found = stored(id)
552
- if (!found) return { notFound: `${isRepoId(id) ? id.slice(2) : id} does not exist${isRepoId(id) ? '' : ' yet. This page loads as soon as it does'}.` }
724
+ if (!found)
725
+ return {
726
+ notFound: `${isRepoId(id) ? id.slice(2) : id} does not exist${isRepoId(id) ? '' : ' yet. This page loads as soon as it does'}.`,
727
+ }
553
728
  if ('raw' in found) return found
554
729
  // a folder is served at /dir/, so relative links resolve inside it
555
- if ((found.kind === 'folder' || (found.kind === 'pages' && id)) && !requested.endsWith('/')) return { redirect: `/${id}/` }
730
+ if ((found.kind === 'folder' || (found.kind === 'pages' && id)) && !requested.endsWith('/'))
731
+ return { redirect: `/${id}/` }
556
732
  // a list of pages says which await the reader: where their questions stand takes the config
557
733
  if (found.kind === 'pages') {
558
734
  const counts = new Map((await status(found.id || null)).map(s => [s.page, awaiting(s)]))
@@ -568,7 +744,11 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
568
744
  const p = decodeURIComponent(url.pathname)
569
745
  const q = Object.fromEntries(url.searchParams)
570
746
 
571
- if (p === '/favicon.ico') { res.writeHead(204); res.end(); return }
747
+ if (p === '/favicon.ico') {
748
+ res.writeHead(204)
749
+ res.end()
750
+ return
751
+ }
572
752
  if (p === '/_/runtime.js') return sendFile(res, RUNTIME)
573
753
  if (auth.handle(req, res, p, q)) return
574
754
  if (p.startsWith('/api/')) {
@@ -579,8 +759,25 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
579
759
  if (owner) return sendJson(res, 404, { error: `plugin ${owner.name} has no route ${req.method} ${p}` })
580
760
  }
581
761
  if (p.startsWith('/_/file/')) {
762
+ await config()
582
763
  const file = path.resolve(p.slice('/_/file'.length))
583
- if (!servable(file) || !fs.existsSync(file) || !fs.statSync(file).isFile()) return send(res, 404, 'not found', 'text/plain')
764
+ if (!servable(file) || !fs.existsSync(file) || !fs.statSync(file).isFile())
765
+ return send(res, 404, 'not found', 'text/plain')
766
+ // watched from now on, so a change to it reloads the pages that use it
767
+ asset(file)
768
+ if (TYPESCRIPT.test(file)) {
769
+ try {
770
+ return send(res, 200, typeScriptModule(file), 'text/javascript; charset=utf-8')
771
+ } catch (err) {
772
+ // syntax only types can't express (an enum, a namespace) or a mistake: the browser says why
773
+ return send(
774
+ res,
775
+ 200,
776
+ `throw new SyntaxError(${JSON.stringify(`${path.basename(file)}: ${(err as Error).message}`)})`,
777
+ 'text/javascript; charset=utf-8',
778
+ )
779
+ }
780
+ }
584
781
  return sendFile(res, file)
585
782
  }
586
783
  if (p === '/api/health') return sendJson(res, 200, { ok: true, dir: project.dir, pid: process.pid })
@@ -593,7 +790,8 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
593
790
  // ({ page, to }: a heading's text, a form's name or any text) → { tabs }
594
791
  if (p === '/api/scroll' && req.method === 'POST') {
595
792
  const { page: id, to } = JSON.parse(await readBody(req)) as { page?: unknown; to?: unknown }
596
- if (typeof id !== 'string' || typeof to !== 'string' || !to.trim()) return sendJson(res, 400, { error: 'page and to required' })
793
+ if (typeof id !== 'string' || typeof to !== 'string' || !to.trim())
794
+ return sendJson(res, 400, { error: 'page and to required' })
597
795
  let tabs = 0
598
796
  for (const c of clients) {
599
797
  if (c.isDir || (c.page !== id && c.page + '/index' !== id)) continue
@@ -607,13 +805,23 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
607
805
  const { texts } = JSON.parse(await readBody(req)) as { texts?: unknown }
608
806
  if (!Array.isArray(texts)) return sendJson(res, 400, { error: 'texts: an array of strings' })
609
807
  const { pages } = await config()
610
- const out = await Promise.all(texts.map(t => pages ? pages.message(String(t ?? ''), context()) : Promise.resolve({ html: String(html`${String(t ?? '')}`), styles: [] })))
808
+ const out = await Promise.all(
809
+ texts.map(t =>
810
+ pages
811
+ ? pages.message(String(t ?? ''), context())
812
+ : Promise.resolve({ html: String(html`${String(t ?? '')}`), styles: [] }),
813
+ ),
814
+ )
611
815
  return sendJson(res, 200, { html: out.map(o => o.html), styles: [...new Set(out.flatMap(o => o.styles))] })
612
816
  }
613
817
  if (p === '/api/events') {
614
818
  const all = readEvents(project.eventsFile)
615
819
  const picked = pickedUp(all)
616
- return sendJson(res, 200, all.filter(e => matches(e, q)).map(e => (picked.has(e.id) ? { ...e, pickedUp: true } : e)))
820
+ return sendJson(
821
+ res,
822
+ 200,
823
+ all.filter(e => matches(e, q)).map(e => (picked.has(e.id) ? { ...e, pickedUp: true } : e)),
824
+ )
617
825
  }
618
826
  if (p === '/api/docs') return sendJson(res, 200, await docs())
619
827
  if (p === '/api/status') return sendJson(res, 200, await status(q.page || null))
@@ -621,16 +829,36 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
621
829
  if (p === '/api/listen') {
622
830
  const fallback = 'fallback' in q
623
831
  // one fallback per project: two would split what nobody else takes between them
624
- if (fallback && [...listeners].some(l => l.fallback)) return sendJson(res, 409, { error: 'another agent is the fallback already' })
625
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
832
+ if (fallback && [...listeners].some(l => l.fallback))
833
+ return sendJson(res, 409, { error: 'another agent is the fallback already' })
834
+ res.writeHead(200, {
835
+ 'content-type': 'text/event-stream',
836
+ 'cache-control': 'no-store',
837
+ connection: 'keep-alive',
838
+ })
626
839
  res.write(': listening\n\n')
627
- const l: Listener = { page: q.page || '', type: q.type || null, command: q.command === 'wait' ? 'wait' : 'watch', ...(fallback && { fallback }) }
840
+ const l: Listener = {
841
+ page: q.page || '',
842
+ type: q.type || null,
843
+ command: q.command === 'wait' ? 'wait' : 'watch',
844
+ ...(fallback && { fallback }),
845
+ }
628
846
  listeners.add(l)
629
847
  notifyAll('listeners')
630
848
  const ping = setInterval(() => res.write(': ping\n\n'), 25000)
631
- const end = () => { clearInterval(ping); listeners.delete(l); streams.delete(end) }
632
- streams.add(() => { end(); res.end() })
633
- req.on('close', () => { end(); notifyAll('listeners') })
849
+ const end = () => {
850
+ clearInterval(ping)
851
+ listeners.delete(l)
852
+ streams.delete(end)
853
+ }
854
+ streams.add(() => {
855
+ end()
856
+ res.end()
857
+ })
858
+ req.on('close', () => {
859
+ end()
860
+ notifyAll('listeners')
861
+ })
634
862
  return
635
863
  }
636
864
  if (p === '/api/page' || p === '/api/render') {
@@ -638,16 +866,27 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
638
866
  if (!('page' in r)) return sendJson(res, 404, { error: 'notFound' in r ? r.notFound : 'not a page' })
639
867
  if (p === '/api/page') return sendJson(res, 200, r.page)
640
868
  const { out, notices } = await render(r.page)
641
- return sendJson(res, 200, { ...out, notices, mtime: r.page.mtime })
869
+ return sendJson(res, 200, { ...out, notices, mtime: r.page.mtime, frontmatter: frontmatterOf(r.page) })
642
870
  }
643
871
  if (p === '/api/watch') {
644
- res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
872
+ res.writeHead(200, {
873
+ 'content-type': 'text/event-stream',
874
+ 'cache-control': 'no-store',
875
+ connection: 'keep-alive',
876
+ })
645
877
  res.write(': connected\n\n')
646
878
  const client = { res, page: q.page || '', isDir: 'dir' in q }
647
879
  clients.add(client)
648
880
  const ping = setInterval(() => res.write(': ping\n\n'), 25000)
649
- const end = () => { clearInterval(ping); clients.delete(client); streams.delete(end) }
650
- streams.add(() => { end(); res.end() })
881
+ const end = () => {
882
+ clearInterval(ping)
883
+ clients.delete(client)
884
+ streams.delete(end)
885
+ }
886
+ streams.add(() => {
887
+ end()
888
+ res.end()
889
+ })
651
890
  req.on('close', end)
652
891
  return
653
892
  }
@@ -656,7 +895,11 @@ ${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
656
895
  // a page is named without .md; a repository path is the file's own
657
896
  const id = isRepoId(path_) ? path_ : path_.replace(/\.md$/, '')
658
897
  const r = await resolve(id, p)
659
- if ('redirect' in r) { res.writeHead(302, { location: r.redirect + url.search }); res.end(); return }
898
+ if ('redirect' in r) {
899
+ res.writeHead(302, { location: r.redirect + url.search })
900
+ res.end()
901
+ return
902
+ }
660
903
  if ('raw' in r) return sendFile(res, r.raw)
661
904
  if ('notFound' in r) {
662
905
  // rendered as a page, with the page's styles and the plugins', and live: it becomes the page