@bigmistqke/whiteboard 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +609 -2
- package/bin/whiteboard.ts +431 -0
- package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
- package/dist/bin/whiteboard.js +471 -0
- package/dist/client/runtime.js +391 -0
- package/dist/define.js +7 -0
- package/dist/plugins/callout/README.md +13 -0
- package/dist/plugins/callout/index.js +27 -0
- package/dist/plugins/callout/style.css +12 -0
- package/dist/plugins/chat/README.md +45 -0
- package/dist/plugins/chat/client.js +3 -0
- package/dist/plugins/chat/index.js +46 -0
- package/dist/plugins/chat/style.css +17 -0
- package/dist/plugins/claude-code/index.js +120 -0
- package/dist/plugins/code/README.md +42 -0
- package/dist/plugins/code/diff.js +64 -0
- package/dist/plugins/code/index.js +77 -0
- package/dist/plugins/code/style.css +29 -0
- package/dist/plugins/comments/client.js +10 -0
- package/dist/plugins/comments/index.js +51 -0
- package/dist/plugins/comments/style.css +32 -0
- package/dist/plugins/details/README.md +17 -0
- package/dist/plugins/details/index.js +17 -0
- package/dist/plugins/details/style.css +3 -0
- package/dist/plugins/form/README.md +111 -0
- package/dist/plugins/form/index.js +102 -0
- package/dist/plugins/form/style.css +41 -0
- package/dist/plugins/gallery/README.md +30 -0
- package/dist/plugins/gallery/client.js +1 -0
- package/dist/plugins/gallery/index.js +74 -0
- package/dist/plugins/gallery/style.css +27 -0
- package/dist/plugins/grid/README.md +33 -0
- package/dist/plugins/grid/index.js +33 -0
- package/dist/plugins/grid/style.css +25 -0
- package/dist/plugins/index.js +26 -0
- package/dist/plugins/mermaid/README.md +21 -0
- package/dist/plugins/mermaid/index.js +34 -0
- package/dist/plugins/mermaid/style.css +16 -0
- package/dist/plugins/quiet/README.md +26 -0
- package/dist/plugins/quiet/index.js +17 -0
- package/dist/plugins/terminal/client.js +41 -0
- package/dist/plugins/terminal/host.js +332 -0
- package/dist/plugins/terminal/index.js +171 -0
- package/dist/plugins/terminal/modes.js +32 -0
- package/dist/plugins/terminal/server.js +256 -0
- package/dist/plugins/terminal/sizes.js +57 -0
- package/dist/plugins/terminal/style.css +357 -0
- package/dist/solid/index.js +35 -0
- package/dist/src/auth.js +54 -0
- package/dist/src/client/page/base.css +274 -0
- package/dist/src/client/page/main.js +1004 -0
- package/dist/src/config.js +76 -0
- package/dist/src/events.js +162 -0
- package/dist/src/html.js +34 -0
- package/dist/src/load.js +77 -0
- package/dist/src/loader.js +120 -0
- package/dist/src/package.js +33 -0
- package/dist/src/pages/blocks.js +49 -0
- package/dist/src/pages/index.js +14 -0
- package/dist/src/pages/markdown.js +307 -0
- package/dist/src/pages/render.js +257 -0
- package/dist/src/plugins.js +238 -0
- package/dist/src/running.js +24 -0
- package/dist/src/serve.js +71 -0
- package/dist/src/server.js +700 -0
- package/dist/src/status.js +43 -0
- package/package.json +131 -4
- package/plugins/callout/README.md +13 -0
- package/plugins/callout/index.ts +25 -0
- package/plugins/callout/style.css +12 -0
- package/plugins/chat/README.md +45 -0
- package/plugins/chat/autosize.ts +101 -0
- package/plugins/chat/client.tsx +81 -0
- package/plugins/chat/index.ts +61 -0
- package/plugins/chat/style.css +17 -0
- package/plugins/claude-code/index.ts +136 -0
- package/plugins/code/README.md +42 -0
- package/plugins/code/diff.ts +58 -0
- package/plugins/code/index.ts +94 -0
- package/plugins/code/style.css +29 -0
- package/plugins/comments/client.ts +448 -0
- package/plugins/comments/index.ts +52 -0
- package/plugins/comments/style.css +32 -0
- package/plugins/details/README.md +17 -0
- package/plugins/details/index.ts +21 -0
- package/plugins/details/style.css +3 -0
- package/plugins/form/README.md +111 -0
- package/plugins/form/index.ts +104 -0
- package/plugins/form/style.css +41 -0
- package/plugins/gallery/README.md +30 -0
- package/plugins/gallery/client.tsx +64 -0
- package/plugins/gallery/index.ts +67 -0
- package/plugins/gallery/style.css +27 -0
- package/plugins/grid/README.md +33 -0
- package/plugins/grid/index.ts +36 -0
- package/plugins/grid/style.css +25 -0
- package/plugins/index.ts +19 -0
- package/plugins/mermaid/README.md +21 -0
- package/plugins/mermaid/index.ts +39 -0
- package/plugins/mermaid/style.css +16 -0
- package/plugins/quiet/README.md +26 -0
- package/plugins/quiet/index.ts +27 -0
- package/plugins/terminal/client.ts +317 -0
- package/plugins/terminal/host.ts +326 -0
- package/plugins/terminal/index.ts +138 -0
- package/plugins/terminal/modes.ts +30 -0
- package/plugins/terminal/server.ts +215 -0
- package/plugins/terminal/sizes.ts +60 -0
- package/plugins/terminal/style.css +71 -0
- package/skills/whiteboard/SKILL.md +292 -0
- package/solid/index.tsx +56 -0
- package/src/auth.ts +66 -0
- package/src/client/forms.ts +186 -0
- package/src/client/page/base.css +274 -0
- package/src/client/page/fresh.ts +205 -0
- package/src/client/page/main.ts +249 -0
- package/src/client/page/orphans.ts +46 -0
- package/src/client/page/theme.ts +32 -0
- package/src/client/page/view.ts +9 -0
- package/src/client/page/waiting.ts +109 -0
- package/src/client/runtime.ts +170 -0
- package/src/config.ts +96 -0
- package/src/define.ts +546 -0
- package/src/events.ts +194 -0
- package/src/html.ts +40 -0
- package/src/load.ts +89 -0
- package/src/loader.ts +109 -0
- package/src/package.ts +39 -0
- package/src/pages/blocks.ts +67 -0
- package/src/pages/index.ts +36 -0
- package/src/pages/markdown.ts +276 -0
- package/src/pages/render.ts +196 -0
- package/src/plugins.ts +197 -0
- package/src/running.ts +22 -0
- package/src/serve.ts +52 -0
- package/src/server.ts +644 -0
- package/src/status.ts +69 -0
package/src/server.ts
ADDED
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
// The server of one project, as a request handler: `createServer(project)` gives one, and
|
|
2
|
+
// `start` in serve.ts makes it listen on a port. Nothing happens on import, and a server's state
|
|
3
|
+
// (listeners, open pages, watchers) lives in it, so tests can make one for a throwaway project and
|
|
4
|
+
// send it requests.
|
|
5
|
+
//
|
|
6
|
+
// / the overview: the project's pages
|
|
7
|
+
// /<page> a page from .whiteboard/pages/<page>.md
|
|
8
|
+
// /-/<path> a file of the project, from the repository (unless the config sets files: false)
|
|
9
|
+
// /_/docs how to write pages here: markdown, and each plugin's docs
|
|
10
|
+
// /_/file/<path> a file a plugin asked to serve (its client, a stylesheet)
|
|
11
|
+
// /_/auth sets the project's token as a cookie (see auth.ts)
|
|
12
|
+
// /api/<ext>/… a plugin's own routes (see Plugin in define.ts)
|
|
13
|
+
// /api/… the stored page, its render, events, live changes
|
|
14
|
+
//
|
|
15
|
+
// The core reads pages as they are stored and renders them as markdown, with the blocks the project's
|
|
16
|
+
// plugins bring (pages.ts). When the config fails to load, a page shows as its raw
|
|
17
|
+
// text.
|
|
18
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
19
|
+
import fs from 'node:fs'
|
|
20
|
+
import path from 'node:path'
|
|
21
|
+
import type { Project } from './config.ts'
|
|
22
|
+
import { appendEvent, readEvents, matches, pickedUp, fromReader, forAgent, CLAIM } from './events.ts'
|
|
23
|
+
import { html, raw, type Html } from './html.ts'
|
|
24
|
+
import { createConfigLoader, pluginDir, toPath, type LoadedConfig } from './loader.ts'
|
|
25
|
+
import { describeRoutes, dispatch, pluginCommands, mountRoutes, usage, type MountedRoute } from './plugins.ts'
|
|
26
|
+
import { createAuth } from './auth.ts'
|
|
27
|
+
import { FROM_SOURCE, PACKAGE_DIR } from './package.ts'
|
|
28
|
+
import { questionState } from './status.ts'
|
|
29
|
+
import type { Listener, PageSource, PageStatus, Plugin, PluginHooks, Rendered, StoredPage, PagesSource } from './define.ts'
|
|
30
|
+
|
|
31
|
+
const ENGINE_DIR = PACKAGE_DIR
|
|
32
|
+
// the browser runtime, built by build.ts
|
|
33
|
+
const RUNTIME = path.join(ENGINE_DIR, 'dist', 'client', 'runtime.js')
|
|
34
|
+
// the page in the browser (markdown live: morphing, blocks' islands, forms' marks), built by build.ts
|
|
35
|
+
const PAGE_CLIENT = path.join(ENGINE_DIR, 'dist', 'src', 'client', 'page', 'main.js')
|
|
36
|
+
const MIME: Record<string, string> = {
|
|
37
|
+
'.css': 'text/css', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json', '.png': 'image/png',
|
|
38
|
+
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif',
|
|
39
|
+
'.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.mp4': 'video/mp4', '.webm': 'video/webm', '.woff': 'font/woff',
|
|
40
|
+
'.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8', '.md': 'text/markdown; charset=utf-8',
|
|
41
|
+
'.csv': 'text/csv; charset=utf-8', '.html': 'text/html; charset=utf-8',
|
|
42
|
+
}
|
|
43
|
+
// files in .whiteboard/ that are the server's own bookkeeping, not content
|
|
44
|
+
const OWN_FILES = new Set(['events.ndjson', 'server.json', 'server.log', 'server.lock', 'token'])
|
|
45
|
+
const SKIP_DIRS = new Set(['node_modules', '.git'])
|
|
46
|
+
// a page's frontmatter: `---` lines around `key: value` lines, at the very start
|
|
47
|
+
const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
/** A project's server: its request handler, and what it knows. */
|
|
51
|
+
export interface WhiteboardServer {
|
|
52
|
+
/** answer one request */
|
|
53
|
+
handle(req: IncomingMessage, res: ServerResponse): Promise<void>
|
|
54
|
+
/** what is open on each page (or on `page` and below), as /api/status gives it */
|
|
55
|
+
status(page?: string | null): Promise<PageStatus[]>
|
|
56
|
+
/** the project's config, loaded */
|
|
57
|
+
config(): Promise<LoadedConfig>
|
|
58
|
+
/** stop watching and end the live connections; the server answers nothing after */
|
|
59
|
+
close(): void
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function createServer(project: Project): WhiteboardServer {
|
|
63
|
+
const loader = createConfigLoader(project)
|
|
64
|
+
const auth = createAuth(project.wb)
|
|
65
|
+
// what close() stops: watchers, and the live connections' pings and responses
|
|
66
|
+
const watchers = new Set<fs.FSWatcher>()
|
|
67
|
+
const streams = new Set<() => void>()
|
|
68
|
+
const watch = (dir: string, options: fs.WatchOptions, fn: (name: string) => void) => {
|
|
69
|
+
try { watchers.add(fs.watch(dir, options, (_evt, name) => { if (name) fn(String(name)) })) } catch { /* gone, or not built */ }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ---- plugins --------------------------------------------------------------------------------
|
|
73
|
+
// Behaviour on every page: each one's setup runs once per loaded config.
|
|
74
|
+
|
|
75
|
+
/** A plugin once set up: what its setup returned, its mounted routes, or why it failed. */
|
|
76
|
+
interface SetUp extends PluginHooks {
|
|
77
|
+
name: string
|
|
78
|
+
table: MountedRoute[]
|
|
79
|
+
plugin: Plugin
|
|
80
|
+
error?: Error
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const setups = new WeakMap<LoadedConfig, Promise<SetUp[]>>()
|
|
84
|
+
// the plugins' own folders in .whiteboard/: changes in them reload nothing
|
|
85
|
+
const pluginDirs = new Set<string>()
|
|
86
|
+
|
|
87
|
+
/** The hooks of the loaded config's plugins, set up once per config. */
|
|
88
|
+
async function pluginHooks(): Promise<SetUp[]> {
|
|
89
|
+
const c = await config()
|
|
90
|
+
if (!setups.has(c)) {
|
|
91
|
+
setups.set(c, Promise.all(c.plugins.map(async (e): Promise<SetUp> => {
|
|
92
|
+
try {
|
|
93
|
+
pluginDirs.add(e.name)
|
|
94
|
+
const dataDir = pluginDir(project.wb, e.name)
|
|
95
|
+
const hooks = (await e.setup?.({ project: { name: project.name, dir: project.dir, wb: project.wb }, dataDir, authorized: auth.authorized, asset })) ?? {}
|
|
96
|
+
return { name: e.name, ...hooks, table: mountRoutes(e.name, hooks.routes), plugin: e }
|
|
97
|
+
} catch (err) {
|
|
98
|
+
console.error(`plugin ${e.name}:`, err)
|
|
99
|
+
return { name: e.name, table: [], plugin: e, error: err as Error }
|
|
100
|
+
}
|
|
101
|
+
})))
|
|
102
|
+
}
|
|
103
|
+
return setups.get(c)!
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* What the plugins add to the page shell for this request, and the notices of those that failed:
|
|
108
|
+
* a failing plugin shows on the page, as a failing config does, instead of quietly leaving its
|
|
109
|
+
* part out.
|
|
110
|
+
*/
|
|
111
|
+
/** What the plugins add to a page: markup for its head and body, their browser modules, and notices. */
|
|
112
|
+
interface Extras {
|
|
113
|
+
head: Html[]
|
|
114
|
+
body: Html[]
|
|
115
|
+
clients: { name: string; client: string }[]
|
|
116
|
+
notices?: string[]
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function shellExtras(req: IncomingMessage): Promise<Extras & { notices: string[] }> {
|
|
120
|
+
const hooks = await pluginHooks()
|
|
121
|
+
const notices = hooks.filter(h => h.error).map(h => `plugin "${h.name}" failed to start: ${h.error!.message}`)
|
|
122
|
+
const parts = await Promise.all(hooks.map(async h => {
|
|
123
|
+
try { return (await h.shell?.(req)) ?? null } catch (err) {
|
|
124
|
+
console.error(`plugin ${h.name}:`, err)
|
|
125
|
+
notices.push(`plugin "${h.name}" failed on this page: ${(err as Error).message}`)
|
|
126
|
+
return null
|
|
127
|
+
}
|
|
128
|
+
}))
|
|
129
|
+
// their browser modules, which the runtime imports after the page's
|
|
130
|
+
const clients = hooks.filter(h => h.client && !h.error).map(h => ({ name: h.name, client: asset(h.client!) }))
|
|
131
|
+
return { head: parts.map(x => raw(String(x?.head ?? ''))), body: parts.map(x => raw(String(x?.body ?? ''))), clients, notices }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A page with what the plugins add, their notices among the page's. */
|
|
135
|
+
async function page(req: IncomingMessage, stored: StoredPage, rendered: Render): Promise<string> {
|
|
136
|
+
const extras = await shellExtras(req)
|
|
137
|
+
return shell(stored, { ...rendered, notices: [...rendered.notices, ...extras.notices] }, extras)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The loaded config. Also applies its `files` setting to what is served and watched. */
|
|
141
|
+
async function config(): Promise<LoadedConfig> {
|
|
142
|
+
const c = await loader.config()
|
|
143
|
+
setFiles(c.files)
|
|
144
|
+
return c
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// ---- assets: files a plugin asks to serve -------------------------------------------------------
|
|
148
|
+
// Served at /_/file/<absolute path>, only once asked for. Beside a file asked for, its neighbours
|
|
149
|
+
// too, since a client module may import them, but only browser assets (scripts, styles, images,
|
|
150
|
+
// fonts): a plugin's module in .whiteboard/ must not open up the project's token, log or config.
|
|
151
|
+
// Those folders are watched from then on.
|
|
152
|
+
|
|
153
|
+
const assets = new Set<string>()
|
|
154
|
+
const assetDirs = new Set<string>()
|
|
155
|
+
const BROWSER_ASSET = /\.(m?js|css|map|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|wasm)$/i
|
|
156
|
+
const servable = (file: string) => assets.has(file) || (assetDirs.has(path.dirname(file)) && BROWSER_ASSET.test(file))
|
|
157
|
+
|
|
158
|
+
function asset(ref: string | URL): string {
|
|
159
|
+
const file = toPath(ref)
|
|
160
|
+
if (!assets.has(file)) {
|
|
161
|
+
assets.add(file)
|
|
162
|
+
const dir = path.dirname(file)
|
|
163
|
+
if (!assetDirs.has(dir)) {
|
|
164
|
+
assetDirs.add(dir)
|
|
165
|
+
// .whiteboard/ itself is watched already (setFiles), and so are the engine's own files
|
|
166
|
+
if (!within(dir, project.wb) && !ENGINE_WATCHED.some(d => within(dir, d))) {
|
|
167
|
+
watch(dir, {}, name => onSourceChange(path.join(dir, name)))
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return `/_/file${file.split(path.sep).map(encodeURIComponent).join('/')}`
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const within = (file: string, dir: string) => file === dir || file.startsWith(dir + path.sep)
|
|
175
|
+
|
|
176
|
+
// ---- stored pages ------------------------------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
/** Resolve a path inside a base folder, refusing anything that escapes it. */
|
|
179
|
+
function inside(base: string, rel: string): string | null {
|
|
180
|
+
const p = path.resolve(base, '.' + path.posix.normalize('/' + rel))
|
|
181
|
+
return within(p, base) ? p : null
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const isRepoId = (id: string) => id === '-' || id.startsWith('-/')
|
|
185
|
+
|
|
186
|
+
function frontmatter(source: string): Record<string, string> {
|
|
187
|
+
const m = FRONTMATTER.exec(source)
|
|
188
|
+
const out: Record<string, string> = {}
|
|
189
|
+
if (m) for (const line of m[1]!.split(/\r?\n/)) {
|
|
190
|
+
const kv = /^([\w-]+)\s*:\s*(.*)$/.exec(line)
|
|
191
|
+
if (kv) out[kv[1]!] = kv[2]!.trim().replace(/^["']|["']$/g, '')
|
|
192
|
+
}
|
|
193
|
+
return out
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function pageSource(id: string, file: string): PageSource {
|
|
197
|
+
const source = fs.readFileSync(file, 'utf8')
|
|
198
|
+
return { kind: 'page', id, file, mtime: fs.statSync(file).mtimeMs, source, body: source.replace(FRONTMATTER, ''), frontmatter: frontmatter(source) }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** The pages in a folder of the pages folder, newest first, with when each was last answered. */
|
|
202
|
+
function pagesIn(dir: string): PagesSource['pages'] {
|
|
203
|
+
const last = new Map<string, string>()
|
|
204
|
+
// the last time the reader sent something: what the agent appended doesn't count
|
|
205
|
+
for (const e of readEvents(project.eventsFile)) if (fromReader(e)) last.set(e.page, e.ts)
|
|
206
|
+
const out: PagesSource['pages'] = []
|
|
207
|
+
const walk = (d: string) => {
|
|
208
|
+
if (!fs.existsSync(d)) return
|
|
209
|
+
for (const ent of fs.readdirSync(d, { withFileTypes: true })) {
|
|
210
|
+
if (ent.name.startsWith('.') || ent.name === 'node_modules') continue
|
|
211
|
+
const full = path.join(d, ent.name)
|
|
212
|
+
if (ent.isDirectory()) walk(full)
|
|
213
|
+
else if (ent.name.endsWith('.md')) {
|
|
214
|
+
const id = path.relative(project.pagesDir, full).split(path.sep).join('/').replace(/\.md$/, '')
|
|
215
|
+
out.push({ id, file: full, mtime: fs.statSync(full).mtimeMs, lastEvent: last.get(id) ?? null, listeners: listenersFor(id).length })
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
walk(dir)
|
|
220
|
+
return out.sort((a, b) => b.mtime - a.mtime)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Text files show as files; anything with a NUL byte near the start is binary. */
|
|
224
|
+
function isText(file: string): boolean {
|
|
225
|
+
const fd = fs.openSync(file, 'r')
|
|
226
|
+
const buf = Buffer.alloc(8192)
|
|
227
|
+
const n = fs.readSync(fd, buf, 0, buf.length, 0)
|
|
228
|
+
fs.closeSync(fd)
|
|
229
|
+
return !buf.subarray(0, n).includes(0)
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* A page id → the stored page, or one of: { redirect } (a folder asked for without its slash),
|
|
234
|
+
* { raw: file } (serve the bytes), null (nothing there).
|
|
235
|
+
*/
|
|
236
|
+
function stored(id: string): StoredPage | { raw: string } | null {
|
|
237
|
+
if (!id) return { kind: 'pages', id: '', file: project.pagesDir, mtime: null, pages: pagesIn(project.pagesDir) }
|
|
238
|
+
if (isRepoId(id)) {
|
|
239
|
+
const rel = id.slice(2)
|
|
240
|
+
const target = inside(project.dir, rel)
|
|
241
|
+
if (!target || path.relative(project.dir, target).split(path.sep).includes('.git') || !fs.existsSync(target)) return null
|
|
242
|
+
const stat = fs.statSync(target)
|
|
243
|
+
if (stat.isDirectory()) {
|
|
244
|
+
const entries = fs.readdirSync(target, { withFileTypes: true })
|
|
245
|
+
.filter(e => !SKIP_DIRS.has(e.name) && e.name !== '.DS_Store')
|
|
246
|
+
.map(e => ({ name: e.name, dir: e.isDirectory() }))
|
|
247
|
+
.sort((a, b) => (Number(b.dir) - Number(a.dir)) || a.name.localeCompare(b.name))
|
|
248
|
+
return { kind: 'folder', id, file: target, mtime: stat.mtimeMs, entries }
|
|
249
|
+
}
|
|
250
|
+
if (/\.(md|markdown)$/i.test(target)) return pageSource(id, target)
|
|
251
|
+
if (stat.size > 1e6 || !isText(target)) return { raw: target }
|
|
252
|
+
return { kind: 'file', id, file: target, mtime: stat.mtimeMs, source: fs.readFileSync(target, 'utf8') }
|
|
253
|
+
}
|
|
254
|
+
const target = inside(project.pagesDir, id)
|
|
255
|
+
if (!target) return null
|
|
256
|
+
if (path.extname(id) && fs.existsSync(target) && fs.statSync(target).isFile()) return { raw: target }
|
|
257
|
+
if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
|
|
258
|
+
const index = path.join(target, 'index.md')
|
|
259
|
+
if (fs.existsSync(index)) return pageSource(id, index)
|
|
260
|
+
return { kind: 'pages', id, file: target, mtime: null, pages: pagesIn(target) }
|
|
261
|
+
}
|
|
262
|
+
const file = target + '.md'
|
|
263
|
+
return fs.existsSync(file) ? pageSource(id, file) : null
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** The URL that serves a file or folder on disk, or null when nothing here serves it. */
|
|
267
|
+
function urlOf(abs: string): string | null {
|
|
268
|
+
const rel = (dir: string) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join('/')
|
|
269
|
+
if (within(abs, project.pagesDir)) return `/${rel(project.pagesDir).replace(/\.md$/, '')}`
|
|
270
|
+
if (FILES && within(abs, project.dir)) {
|
|
271
|
+
if (rel(project.dir).split('/').some(part => SKIP_DIRS.has(part))) return null
|
|
272
|
+
return `/-/${rel(project.dir)}`
|
|
273
|
+
}
|
|
274
|
+
return null
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** For links: the target if it exists (also with .md added), mapped to its URL. */
|
|
278
|
+
function urlFor(abs: string): string | null {
|
|
279
|
+
for (const candidate of [abs, abs + '.md']) {
|
|
280
|
+
if (fs.existsSync(candidate)) {
|
|
281
|
+
const url = urlOf(candidate)
|
|
282
|
+
if (url) return url + (fs.statSync(candidate).isDirectory() && !url.endsWith('/') ? '/' : '')
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return null
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// ---- rendering ---------------------------------------------------------------------------------
|
|
289
|
+
|
|
290
|
+
/** A config that failed to load: the page as stored, as text, under the error. */
|
|
291
|
+
function rawRender(page: StoredPage): Rendered {
|
|
292
|
+
const list = (items: [string, string][]) => html`<ul>${items.map(([href, text]) => html`<li><a href="${href}">${text}</a></li>`)}</ul>`
|
|
293
|
+
if (page.kind === 'pages') return { html: list(page.pages.map(p => [`/${p.id}`, p.id])) }
|
|
294
|
+
if (page.kind === 'folder') {
|
|
295
|
+
return { html: list(page.entries.map(e => [encodeURIComponent(e.name) + (e.dir ? '/' : ''), e.name + (e.dir ? '/' : '')] as [string, string])) }
|
|
296
|
+
}
|
|
297
|
+
return { html: html`<pre>${page.source}</pre>` }
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const context = () => ({ project: { name: project.name, dir: project.dir, files: !!FILES }, asset, urlFor })
|
|
301
|
+
|
|
302
|
+
/** A render as the shell takes it. `page`: whether the page's browser part runs (not on raw text). */
|
|
303
|
+
interface Render {
|
|
304
|
+
page: boolean
|
|
305
|
+
out: Rendered
|
|
306
|
+
notices: string[]
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Render a stored page as markdown, with the plugins' blocks, and anything the reader should be told. */
|
|
310
|
+
async function render(page: StoredPage): Promise<Render> {
|
|
311
|
+
const { pages, errors } = await config()
|
|
312
|
+
const notices = errors.map(e => `config: ${(e as Error).message}`)
|
|
313
|
+
let out: Rendered
|
|
314
|
+
let rendered = !!pages
|
|
315
|
+
try {
|
|
316
|
+
out = pages ? await pages.render(page, context()) : rawRender(page)
|
|
317
|
+
} catch (err) {
|
|
318
|
+
console.error('render:', err)
|
|
319
|
+
notices.push(`the page failed to render: ${(err as Error).message}`)
|
|
320
|
+
out = rawRender(page)
|
|
321
|
+
rendered = false
|
|
322
|
+
}
|
|
323
|
+
// HTML built with `html`: from here on it is a string, for the shell and for /api/render's JSON alike
|
|
324
|
+
const strings = { ...out, html: String(out.html ?? ''), ...(out.head != null ? { head: String(out.head) } : {}) }
|
|
325
|
+
return { page: rendered, out: strings, notices }
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Per page: the questions it asks that have no answer yet, the reader's events no wait or watch
|
|
330
|
+
* picked up, who is listening, and the session that claimed it. What `whiteboard status` and the
|
|
331
|
+
* hooks report. The questions are a page's named forms.
|
|
332
|
+
*/
|
|
333
|
+
async function status(only: string | null): Promise<PageStatus[]> {
|
|
334
|
+
const { pages, handedOut } = await config()
|
|
335
|
+
const isForAgent = forAgent(handedOut)
|
|
336
|
+
const all = readEvents(project.eventsFile)
|
|
337
|
+
const picked = pickedUp(all)
|
|
338
|
+
const owner = new Map<string, string | null>()
|
|
339
|
+
for (const e of all) if (e.type === CLAIM && !fromReader(e)) owner.set(e.page, (e.data?.session as string | undefined) ?? null)
|
|
340
|
+
const out: PageStatus[] = []
|
|
341
|
+
for (const p of pagesIn(project.pagesDir)) {
|
|
342
|
+
if (only && p.id !== only && !p.id.startsWith(only + '/')) continue
|
|
343
|
+
const page = pageSource(p.id, p.file)
|
|
344
|
+
let asks: string[] = []
|
|
345
|
+
try { asks = pages?.questions(page) ?? [] } catch (err) { console.error('questions:', err) }
|
|
346
|
+
const events = all.filter(e => e.page === p.id)
|
|
347
|
+
const listening = listenersFor(p.id)
|
|
348
|
+
// where each question stands, as the page shows it (see status.ts)
|
|
349
|
+
const questions = asks.map(name => ({ name, state: questionState(name, events, listening, id => picked.has(id)).state }))
|
|
350
|
+
const named = (...states: string[]) => questions.filter(q => states.includes(q.state)).map(q => q.name)
|
|
351
|
+
out.push({
|
|
352
|
+
page: p.id, file: p.file, owner: owner.get(p.id) ?? null, asks, questions,
|
|
353
|
+
open: named('waiting', 'unheard'),
|
|
354
|
+
unheard: named('unheard'),
|
|
355
|
+
// the reader's events for an agent: a form's answers, and plugin events declared handOut
|
|
356
|
+
unpicked: events.filter(e => fromReader(e) && isForAgent(e.type) && !picked.has(e.id)),
|
|
357
|
+
listeners: listening,
|
|
358
|
+
})
|
|
359
|
+
}
|
|
360
|
+
return out
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** How to write pages here, as markdown: the pages' own docs, then each plugin's. */
|
|
364
|
+
async function docs() {
|
|
365
|
+
const { pages, errors } = await config()
|
|
366
|
+
// what each plugin declares: its routes (for an agent that wants to call them) and commands
|
|
367
|
+
const plugins = await Promise.all((await pluginHooks()).map(async h => ({
|
|
368
|
+
name: h.name,
|
|
369
|
+
error: h.error?.message ?? null,
|
|
370
|
+
docs: h.plugin.docs ? await h.plugin.docs() : null,
|
|
371
|
+
routes: describeRoutes(h.table),
|
|
372
|
+
commands: pluginCommands(h.plugin).map(c => ({ name: c.name, usage: usage(c.command), description: c.command.description })),
|
|
373
|
+
events: Object.entries(h.plugin.events ?? {}).map(([type, spec]) => ({ type, handOut: !!spec?.handOut, description: spec?.description ?? '' })),
|
|
374
|
+
})))
|
|
375
|
+
return { errors: errors.map(e => (e as Error).message), pages: pages?.docs(context()) ?? null, plugins }
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const json = (s: unknown) => JSON.stringify(s).replace(/</g, '\\u003c')
|
|
379
|
+
|
|
380
|
+
// the page's corner (api.corner()): the one thing the core puts on every page, empty, for the
|
|
381
|
+
// page's and the plugins' floating buttons; above what covers the bottom of the window
|
|
382
|
+
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}'
|
|
383
|
+
|
|
384
|
+
/** `extras`: what plugins add to <head> and <body> (see shellExtras). */
|
|
385
|
+
function shell(page: StoredPage, { page: rendered, out, notices }: Render, extras: Extras = { head: [], body: [], clients: [] }): string {
|
|
386
|
+
const handoff = { id: page.id, kind: page.kind, client: rendered ? asset(PAGE_CLIENT) : null, data: out.data ?? null, plugins: extras.clients }
|
|
387
|
+
// the page's head and html are HTML already; the handoff is JSON made safe for a script tag
|
|
388
|
+
return String(html`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
389
|
+
<title>${out.title || page.id || project.name}</title>
|
|
390
|
+
<style>${DOCK_STYLE}</style>
|
|
391
|
+
${raw(out.head ?? '')}${extras.head}</head>
|
|
392
|
+
<body data-page="${page.id}" data-kind="${page.kind}">
|
|
393
|
+
${notices.map(n => html`<pre class="wb-error" role="alert">${n}</pre>`)}
|
|
394
|
+
<div id="wb-root">${raw(String(out.html))}</div>
|
|
395
|
+
<div id="wb-dock"></div>
|
|
396
|
+
<script type="application/json" id="wb-page">${raw(json(handoff))}</script>
|
|
397
|
+
<script type="module" src="/_/runtime.js"></script>${extras.body}</body></html>`)
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// ---- listeners ---------------------------------------------------------------------------------
|
|
401
|
+
// An agent waiting for answers (`whiteboard wait` or `watch`) holds a connection to /api/listen for
|
|
402
|
+
// as long as it runs: that connection is the listener, gone when the command is. Pages show what an
|
|
403
|
+
// agent is waiting for from these, so nothing depends on the agent marking it.
|
|
404
|
+
|
|
405
|
+
/** A listener as the server holds it. */
|
|
406
|
+
const listeners = new Set<Listener>()
|
|
407
|
+
|
|
408
|
+
/** Does a listener's page filter cover `page`? An empty filter covers every page. */
|
|
409
|
+
const covers = (l: Listener, page: string) => !l.page || page === l.page || page.startsWith(l.page + '/')
|
|
410
|
+
|
|
411
|
+
const listenersFor = (page: string | null): Listener[] => [...listeners].filter(l => page == null || covers(l, page)).map(({ page, type, command }) => ({ page, type, command }))
|
|
412
|
+
|
|
413
|
+
// ---- live changes ------------------------------------------------------------------------------
|
|
414
|
+
// The browser listens at /api/watch. `change`: its page changed; `events`: the log grew;
|
|
415
|
+
// `listeners`: an agent started or stopped waiting; `style`: a stylesheet changed; `reload`:
|
|
416
|
+
// browser code changed.
|
|
417
|
+
|
|
418
|
+
/** A browser following its page at /api/watch; `pending`: what it will be told in a moment. */
|
|
419
|
+
interface WatchClient {
|
|
420
|
+
res: ServerResponse
|
|
421
|
+
page: string
|
|
422
|
+
isDir: boolean
|
|
423
|
+
pending?: Set<string>
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
const clients = new Set<WatchClient>()
|
|
427
|
+
function notify(client: WatchClient, kind: string) {
|
|
428
|
+
client.pending ??= new Set()
|
|
429
|
+
if (client.pending.size === 0) setTimeout(() => {
|
|
430
|
+
for (const k of client.pending!) client.res.write(`event: ${k}\ndata: {}\n\n`)
|
|
431
|
+
client.pending!.clear()
|
|
432
|
+
}, 60)
|
|
433
|
+
client.pending.add(kind)
|
|
434
|
+
}
|
|
435
|
+
const notifyAll = (kind: string) => { for (const c of clients) notify(c, kind) }
|
|
436
|
+
|
|
437
|
+
function pageChanged(id: string) {
|
|
438
|
+
for (const c of clients) {
|
|
439
|
+
if (c.isDir ? (!c.page || id.startsWith(c.page + '/')) : (c.page === id || c.page + '/index' === id)) notify(c, 'change')
|
|
440
|
+
}
|
|
441
|
+
// the overview lists every page
|
|
442
|
+
for (const c of clients) if (c.isDir && !c.page) notify(c, 'change')
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** A file in the project changed; `f` is its path relative to the project folder, with / separators. */
|
|
446
|
+
function fileChanged(f: string) {
|
|
447
|
+
if (f.split('/').some(part => SKIP_DIRS.has(part))) return
|
|
448
|
+
if (f.startsWith('.whiteboard/')) {
|
|
449
|
+
const inner = f.slice('.whiteboard/'.length)
|
|
450
|
+
if (inner === 'events.ndjson') return notifyAll('events')
|
|
451
|
+
if (inner.startsWith('pages/')) {
|
|
452
|
+
if (inner.endsWith('.md')) pageChanged(inner.slice('pages/'.length).replace(/\.md$/, ''))
|
|
453
|
+
return
|
|
454
|
+
}
|
|
455
|
+
if (OWN_FILES.has(inner) || pluginDirs.has(inner.split('/')[0]!)) return
|
|
456
|
+
// the config, or something it imports
|
|
457
|
+
return onSourceChange(path.join(project.dir, f))
|
|
458
|
+
}
|
|
459
|
+
if (!FILES) return
|
|
460
|
+
// a repository file; its folder's listing shows it too
|
|
461
|
+
pageChanged(`-/${f}`)
|
|
462
|
+
const parent = f.includes('/') ? f.slice(0, f.lastIndexOf('/')) : ''
|
|
463
|
+
pageChanged(`-${parent ? '/' + parent : ''}`)
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// With files on, the whole project folder is watched (repository views stay live); with files off,
|
|
467
|
+
// only .whiteboard/, so a project in a large folder such as the home folder stays cheap.
|
|
468
|
+
let FILES: boolean | null = null
|
|
469
|
+
let watcher: fs.FSWatcher | null = null
|
|
470
|
+
function setFiles(files: boolean) {
|
|
471
|
+
if (files === FILES) return
|
|
472
|
+
FILES = files
|
|
473
|
+
if (watcher) { watcher.close(); watchers.delete(watcher) }
|
|
474
|
+
const base = files ? project.dir : project.wb
|
|
475
|
+
const prefix = files ? '' : '.whiteboard/'
|
|
476
|
+
watcher = fs.watch(base, { recursive: true }, (_evt, filename) => {
|
|
477
|
+
if (filename) fileChanged(prefix + filename.replace(/\\/g, '/'))
|
|
478
|
+
})
|
|
479
|
+
watchers.add(watcher)
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// What a plugin or the config is made of changed. A stylesheet reloads in place; a browser module
|
|
483
|
+
// reloads the pages; anything else loads the config afresh and re-renders open pages.
|
|
484
|
+
let reloadTimer: ReturnType<typeof setTimeout> | undefined
|
|
485
|
+
async function onSourceChange(file: string) {
|
|
486
|
+
if (within(file, project.pagesDir)) return
|
|
487
|
+
if (path.dirname(file) === project.wb && OWN_FILES.has(path.basename(file))) return
|
|
488
|
+
if ([...pluginDirs].some(name => within(file, path.join(project.wb, name)))) return
|
|
489
|
+
if (file.endsWith('.css')) return notifyAll('style')
|
|
490
|
+
if (file.endsWith('.md')) return notifyAll('change')
|
|
491
|
+
if (file === RUNTIME || assets.has(file)) return notifyAll('reload')
|
|
492
|
+
// a build writes several files at once: load the config once they are all there
|
|
493
|
+
clearTimeout(reloadTimer)
|
|
494
|
+
reloadTimer = setTimeout(() => {
|
|
495
|
+
loader.invalidate()
|
|
496
|
+
config().then(() => notifyAll('change'))
|
|
497
|
+
}, 80)
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// The engine's own files, when it runs from source: what a config loads from it runs from source
|
|
501
|
+
// too (the plugins), and the browser code from its build (npm run dev). A change to
|
|
502
|
+
// either reloads what it is made of, like a project's own files.
|
|
503
|
+
const ENGINE_BUILD = path.join(ENGINE_DIR, 'dist')
|
|
504
|
+
const ENGINE_WATCHED = !FROM_SOURCE ? [] : [ENGINE_BUILD, ...['plugins'].map(d => path.join(ENGINE_DIR, d))]
|
|
505
|
+
for (const dir of ENGINE_WATCHED) watch(dir, { recursive: true }, name => onSourceChange(path.join(dir, name)))
|
|
506
|
+
|
|
507
|
+
// ---- http --------------------------------------------------------------------------------------
|
|
508
|
+
|
|
509
|
+
function send(res: ServerResponse, status: number, body: string | Buffer, type = 'text/html; charset=utf-8') {
|
|
510
|
+
res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' })
|
|
511
|
+
res.end(body)
|
|
512
|
+
}
|
|
513
|
+
const sendJson = (res: ServerResponse, status: number, data: unknown) => send(res, status, JSON.stringify(data), 'application/json')
|
|
514
|
+
const sendFile = (res: ServerResponse, file: string) => send(res, 200, fs.readFileSync(file), MIME[path.extname(file).toLowerCase()] || 'application/octet-stream')
|
|
515
|
+
|
|
516
|
+
function readBody(req: IncomingMessage): Promise<string> {
|
|
517
|
+
return new Promise((resolve, reject) => {
|
|
518
|
+
const chunks: Buffer[] = []
|
|
519
|
+
let size = 0
|
|
520
|
+
req.on('data', (c: Buffer) => { size += c.length; if (size > 1e6) { reject(new Error('body too large')); req.destroy() } else chunks.push(c) })
|
|
521
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
|
|
522
|
+
req.on('error', reject)
|
|
523
|
+
})
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** What a page id resolves to, or why it does not: the response to send instead. */
|
|
527
|
+
type Resolved = { page: StoredPage } | { raw: string } | { redirect: string } | { notFound: string }
|
|
528
|
+
|
|
529
|
+
async function resolve(id: string, requested: string): Promise<Resolved> {
|
|
530
|
+
await config()
|
|
531
|
+
if (isRepoId(id) && !FILES) return { notFound: 'This project does not serve its files: its config sets files: false.' }
|
|
532
|
+
if (id === '_/docs') {
|
|
533
|
+
// how pages are written, then each plugin's own docs, with their examples rendered live
|
|
534
|
+
const { pages, plugins } = await docs()
|
|
535
|
+
const source = [
|
|
536
|
+
pages ?? '',
|
|
537
|
+
...plugins.filter(p => p.docs).map(p => `<a id="plugin-${p.name}"></a>\n\n${p.docs}`),
|
|
538
|
+
].join('\n\n---\n\n')
|
|
539
|
+
return { page: { kind: 'page', id, file: path.join(project.pagesDir, '_docs.md'), mtime: null, source, body: source, frontmatter: {} } }
|
|
540
|
+
}
|
|
541
|
+
const found = stored(id)
|
|
542
|
+
if (!found) return { notFound: `${isRepoId(id) ? id.slice(2) : id} does not exist${isRepoId(id) ? '' : ' yet. This page loads as soon as it does'}.` }
|
|
543
|
+
if ('raw' in found) return found
|
|
544
|
+
// a folder is served at /dir/, so relative links resolve inside it
|
|
545
|
+
if ((found.kind === 'folder' || (found.kind === 'pages' && id)) && !requested.endsWith('/')) return { redirect: `/${id}/` }
|
|
546
|
+
return { page: found }
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
550
|
+
try {
|
|
551
|
+
// a path like //x would otherwise read as a host
|
|
552
|
+
const url = new URL((req.url ?? '/').replace(/^\/+/, '/'), 'http://localhost')
|
|
553
|
+
const p = decodeURIComponent(url.pathname)
|
|
554
|
+
const q = Object.fromEntries(url.searchParams)
|
|
555
|
+
|
|
556
|
+
if (p === '/favicon.ico') { res.writeHead(204); res.end(); return }
|
|
557
|
+
if (p === '/_/runtime.js') return sendFile(res, RUNTIME)
|
|
558
|
+
if (auth.handle(req, res, p, q)) return
|
|
559
|
+
if (p.startsWith('/api/')) {
|
|
560
|
+
const hooks = await pluginHooks()
|
|
561
|
+
for (const h of hooks) if (await dispatch(h.table, req, res, url, auth.authorized)) return
|
|
562
|
+
// under a plugin's name, but none of its routes
|
|
563
|
+
const owner = hooks.find(h => p.startsWith(`/api/${h.name}/`) || p === `/api/${h.name}`)
|
|
564
|
+
if (owner) return sendJson(res, 404, { error: `plugin ${owner.name} has no route ${req.method} ${p}` })
|
|
565
|
+
}
|
|
566
|
+
if (p.startsWith('/_/file/')) {
|
|
567
|
+
const file = path.resolve(p.slice('/_/file'.length))
|
|
568
|
+
if (!servable(file) || !fs.existsSync(file) || !fs.statSync(file).isFile()) return send(res, 404, 'not found', 'text/plain')
|
|
569
|
+
return sendFile(res, file)
|
|
570
|
+
}
|
|
571
|
+
if (p === '/api/health') return sendJson(res, 200, { ok: true, dir: project.dir, pid: process.pid })
|
|
572
|
+
if (p === '/api/events' && req.method === 'POST') {
|
|
573
|
+
const body = JSON.parse(await readBody(req))
|
|
574
|
+
if (!body.type) return sendJson(res, 400, { error: 'event type required' })
|
|
575
|
+
return sendJson(res, 200, appendEvent(project.eventsFile, body))
|
|
576
|
+
}
|
|
577
|
+
if (p === '/api/events') {
|
|
578
|
+
const all = readEvents(project.eventsFile)
|
|
579
|
+
const picked = pickedUp(all)
|
|
580
|
+
return sendJson(res, 200, all.filter(e => matches(e, q)).map(e => (picked.has(e.id) ? { ...e, pickedUp: true } : e)))
|
|
581
|
+
}
|
|
582
|
+
if (p === '/api/docs') return sendJson(res, 200, await docs())
|
|
583
|
+
if (p === '/api/status') return sendJson(res, 200, await status(q.page || null))
|
|
584
|
+
if (p === '/api/listeners') return sendJson(res, 200, listenersFor(q.page ?? null))
|
|
585
|
+
if (p === '/api/listen') {
|
|
586
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
|
|
587
|
+
res.write(': listening\n\n')
|
|
588
|
+
const l: Listener = { page: q.page || '', type: q.type || null, command: q.command === 'wait' ? 'wait' : 'watch' }
|
|
589
|
+
listeners.add(l)
|
|
590
|
+
notifyAll('listeners')
|
|
591
|
+
const ping = setInterval(() => res.write(': ping\n\n'), 25000)
|
|
592
|
+
const end = () => { clearInterval(ping); listeners.delete(l); streams.delete(end) }
|
|
593
|
+
streams.add(() => { end(); res.end() })
|
|
594
|
+
req.on('close', () => { end(); notifyAll('listeners') })
|
|
595
|
+
return
|
|
596
|
+
}
|
|
597
|
+
if (p === '/api/page' || p === '/api/render') {
|
|
598
|
+
const r = await resolve(q.page ?? '', '/')
|
|
599
|
+
if (!('page' in r)) return sendJson(res, 404, { error: 'notFound' in r ? r.notFound : 'not a page' })
|
|
600
|
+
if (p === '/api/page') return sendJson(res, 200, r.page)
|
|
601
|
+
const { out, notices } = await render(r.page)
|
|
602
|
+
return sendJson(res, 200, { ...out, notices, mtime: r.page.mtime })
|
|
603
|
+
}
|
|
604
|
+
if (p === '/api/watch') {
|
|
605
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
|
|
606
|
+
res.write(': connected\n\n')
|
|
607
|
+
const client = { res, page: q.page || '', isDir: 'dir' in q }
|
|
608
|
+
clients.add(client)
|
|
609
|
+
const ping = setInterval(() => res.write(': ping\n\n'), 25000)
|
|
610
|
+
const end = () => { clearInterval(ping); clients.delete(client); streams.delete(end) }
|
|
611
|
+
streams.add(() => { end(); res.end() })
|
|
612
|
+
req.on('close', end)
|
|
613
|
+
return
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
const path_ = p.replace(/^\/+/, '').replace(/\/+$/, '')
|
|
617
|
+
// a page is named without .md; a repository path is the file's own
|
|
618
|
+
const id = isRepoId(path_) ? path_ : path_.replace(/\.md$/, '')
|
|
619
|
+
const r = await resolve(id, p)
|
|
620
|
+
if ('redirect' in r) { res.writeHead(302, { location: r.redirect + url.search }); res.end(); return }
|
|
621
|
+
if ('raw' in r) return sendFile(res, r.raw)
|
|
622
|
+
if ('notFound' in r) {
|
|
623
|
+
const missing: PageSource = { kind: 'page', id, file: '', mtime: null, source: r.notFound, body: r.notFound, frontmatter: {} }
|
|
624
|
+
return send(res, 404, await page(req, missing, { page: false, out: { title: 'Not found', html: html`<h1>Not found</h1><p>${r.notFound}</p>` }, notices: [] }))
|
|
625
|
+
}
|
|
626
|
+
return send(res, 200, await page(req, r.page, await render(r.page)))
|
|
627
|
+
} catch (err) {
|
|
628
|
+
console.error(err)
|
|
629
|
+
send(res, 500, String((err as Error)?.stack || err), 'text/plain')
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
return {
|
|
634
|
+
handle,
|
|
635
|
+
status: (page = null) => status(page),
|
|
636
|
+
config,
|
|
637
|
+
close() {
|
|
638
|
+
for (const w of watchers) w.close()
|
|
639
|
+
watchers.clear()
|
|
640
|
+
for (const stop of [...streams]) stop()
|
|
641
|
+
clearTimeout(reloadTimer)
|
|
642
|
+
},
|
|
643
|
+
}
|
|
644
|
+
}
|