@bigmistqke/whiteboard 0.7.0 → 0.8.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/README.md +10 -209
- package/bin/whiteboard.ts +82 -239
- package/dist/bin/whiteboard.js +70 -200
- package/dist/client/runtime.js +66 -7
- package/dist/plugins/chat/public/style.css +10 -6
- package/dist/plugins/code/README.md +10 -0
- package/dist/plugins/code/index.js +31 -22
- package/dist/plugins/code/public/client.js +1 -0
- package/dist/plugins/code/public/style.css +33 -2
- package/dist/plugins/comments/public/client.js +1 -1
- package/dist/plugins/form/public/style.css +2 -0
- package/dist/plugins/iframe/index.js +2 -2
- package/dist/plugins/lightbox/public/client.js +1 -1
- package/dist/plugins/terminal/index.js +7 -9
- package/dist/plugins/terminal/public/client.js +1 -1
- package/dist/plugins/terminal/public/style.css +3 -3
- package/dist/plugins/toc/index.js +1 -1
- package/dist/plugins/toc/public/client.js +1 -1
- package/dist/plugins/window/index.js +4 -4
- package/dist/src/build.js +159 -0
- package/dist/src/client/page/main.js +1 -1
- package/dist/src/document.js +93 -0
- package/dist/src/events.js +3 -13
- package/dist/src/hub.js +47 -35
- package/dist/src/listen.js +100 -0
- package/dist/src/listeners.js +67 -0
- package/dist/src/pages/index.js +1 -1
- package/dist/src/pages/markdown.js +23 -11
- package/dist/src/pages/render.js +13 -8
- package/dist/src/server.js +166 -514
- package/dist/src/site.js +173 -0
- package/dist/src/status.js +63 -1
- package/package.json +1 -1
- package/plugins/README.md +258 -0
- package/plugins/chat/public/style.css +10 -6
- package/plugins/code/README.md +10 -0
- package/plugins/code/client.ts +73 -0
- package/plugins/code/index.ts +38 -26
- package/plugins/code/public/style.css +33 -2
- package/plugins/comments/client.ts +8 -1
- package/plugins/form/public/style.css +2 -0
- package/plugins/iframe/index.ts +2 -2
- package/plugins/lightbox/client.ts +13 -3
- package/plugins/terminal/client.ts +10 -2
- package/plugins/terminal/index.ts +8 -6
- package/plugins/terminal/public/style.css +3 -3
- package/plugins/toc/client.ts +9 -2
- package/plugins/toc/index.ts +1 -1
- package/plugins/window/index.ts +4 -4
- package/skills/whiteboard/SKILL.md +3 -1
- package/src/build.ts +213 -0
- package/src/client/page/elsewhere.ts +2 -1
- package/src/client/runtime.ts +88 -10
- package/src/client/toast.ts +1 -1
- package/src/define.ts +34 -18
- package/src/document.ts +191 -0
- package/src/events.ts +11 -16
- package/src/hub.ts +48 -34
- package/src/listen.ts +125 -0
- package/src/listeners.ts +95 -0
- package/src/pages/index.ts +1 -1
- package/src/pages/markdown.ts +29 -18
- package/src/pages/render.ts +13 -8
- package/src/server.ts +165 -609
- package/src/site.ts +165 -0
- package/src/status.ts +100 -0
package/src/server.ts
CHANGED
|
@@ -18,26 +18,28 @@
|
|
|
18
18
|
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
19
19
|
import type { Duplex } from 'node:stream'
|
|
20
20
|
import fs from 'node:fs'
|
|
21
|
-
import
|
|
21
|
+
import crypto from 'node:crypto'
|
|
22
22
|
import { stripTypeScriptTypes } from 'node:module'
|
|
23
23
|
import path from 'node:path'
|
|
24
24
|
import type { Project } from './config.ts'
|
|
25
|
-
import { appendEvent, isEventId, readEvents, matches, pickedUp,
|
|
26
|
-
import { html, raw
|
|
25
|
+
import { appendEvent, isEventId, readEvents, matches, pickedUp, forAgent } from './events.ts'
|
|
26
|
+
import { html, raw } from './html.ts'
|
|
27
27
|
import { createConfigLoader, pluginDir, toPath, type LoadedConfig } from './loader.ts'
|
|
28
|
-
import { describeRoutes, dispatch, pluginCommands, mountRoutes, usage
|
|
28
|
+
import { describeRoutes, dispatch, pluginCommands, mountRoutes, usage } from './plugins.ts'
|
|
29
29
|
import { createAuth, sameSite } from './auth.ts'
|
|
30
30
|
import { accept, refuse } from './ws.ts'
|
|
31
31
|
import { FROM_SOURCE, PACKAGE_DIR, VERSION } from './package.ts'
|
|
32
|
-
import {
|
|
32
|
+
import { SCROLL, awaiting, projectStatus, type ProjectStatus } from './status.ts'
|
|
33
33
|
import { titleOf } from './pages/render.ts'
|
|
34
|
+
import { createRegistry, holdStream, listenerOf } from './listeners.ts'
|
|
34
35
|
import { inPublic } from './public.ts'
|
|
36
|
+
import { build, type BuildResult } from './build.ts'
|
|
37
|
+
import { PAGE_CLIENT, RUNTIME, frontmatterOf, pageDocument, pluginParts, type Render, type SetUp } from './document.ts'
|
|
38
|
+
import { SKIP_DIRS, isRepoId, pageSource, servedSite, within } from './site.ts'
|
|
35
39
|
import type {
|
|
36
40
|
Listener,
|
|
37
41
|
PageSource,
|
|
38
42
|
PageStatus,
|
|
39
|
-
Plugin,
|
|
40
|
-
PluginHooks,
|
|
41
43
|
Rendered,
|
|
42
44
|
StoredPage,
|
|
43
45
|
PagesSource,
|
|
@@ -46,10 +48,6 @@ import type {
|
|
|
46
48
|
} from './define.ts'
|
|
47
49
|
|
|
48
50
|
const ENGINE_DIR = PACKAGE_DIR
|
|
49
|
-
// the browser runtime, built by build.ts
|
|
50
|
-
const RUNTIME = path.join(ENGINE_DIR, 'dist', 'client', 'runtime.js')
|
|
51
|
-
// the page in the browser (markdown live: morphing, blocks' islands, forms' marks), built by build.ts
|
|
52
|
-
const PAGE_CLIENT = path.join(ENGINE_DIR, 'dist', 'src', 'client', 'page', 'main.js')
|
|
53
51
|
const MIME: Record<string, string> = {
|
|
54
52
|
'.css': 'text/css',
|
|
55
53
|
'.js': 'text/javascript',
|
|
@@ -74,9 +72,8 @@ const MIME: Record<string, string> = {
|
|
|
74
72
|
}
|
|
75
73
|
// files in .whiteboard/ that are the server's own bookkeeping, not content
|
|
76
74
|
const OWN_FILES = new Set(['events.ndjson', 'server.json', 'server.log', 'server.lock', 'token'])
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/
|
|
75
|
+
|
|
76
|
+
export type { BuildResult }
|
|
80
77
|
|
|
81
78
|
/** A project's server: its request handler, and what it knows. */
|
|
82
79
|
export interface WhiteboardServer {
|
|
@@ -93,9 +90,11 @@ export interface WhiteboardServer {
|
|
|
93
90
|
/**
|
|
94
91
|
* Hold a listener that is not a connection to this server: the shared server's fallback for a
|
|
95
92
|
* whole entry, which covers every page of each of its projects. Pages are told, as for any
|
|
96
|
-
* listener. @returns what removes it
|
|
93
|
+
* listener. @returns what removes it; null when refused (the project has a fallback already)
|
|
97
94
|
*/
|
|
98
|
-
addListener(l: Listener): () => void
|
|
95
|
+
addListener(l: Listener): (() => void) | null
|
|
96
|
+
/** call `fn` whenever a listener comes or goes; returns what stops it */
|
|
97
|
+
onListeners(fn: () => void): () => void
|
|
99
98
|
/** who listens now: the running waits and watches, and a fallback held for it */
|
|
100
99
|
listeners(): Listener[]
|
|
101
100
|
/** the project's pages as its overview lists them, newest first, with what waits on each; whether it serves its files */
|
|
@@ -108,15 +107,6 @@ export interface WhiteboardServer {
|
|
|
108
107
|
close(): void
|
|
109
108
|
}
|
|
110
109
|
|
|
111
|
-
export interface BuildResult {
|
|
112
|
-
/** the folder the site is in */
|
|
113
|
-
out: string
|
|
114
|
-
/** each page, and the file it became */
|
|
115
|
-
pages: { file: string; to: string }[]
|
|
116
|
-
/** what didn't fit: a link to a page outside the build, no index.html */
|
|
117
|
-
warnings: string[]
|
|
118
|
-
}
|
|
119
|
-
|
|
120
110
|
/** How a server is mounted: on a port of its own (the default), or under a path of a shared server. */
|
|
121
111
|
export interface ServerOptions {
|
|
122
112
|
/** the path every URL it makes starts with, without a trailing slash: '' (its own port) or `/rg/develop` */
|
|
@@ -160,14 +150,6 @@ export function createServer(
|
|
|
160
150
|
// ---- plugins --------------------------------------------------------------------------------
|
|
161
151
|
// Behaviour on every page: each one's setup runs once per loaded config.
|
|
162
152
|
|
|
163
|
-
/** A plugin once set up: what its setup returned, its mounted routes, or why it failed. */
|
|
164
|
-
interface SetUp extends PluginHooks {
|
|
165
|
-
name: string
|
|
166
|
-
table: MountedRoute[]
|
|
167
|
-
plugin: Plugin
|
|
168
|
-
error?: Error
|
|
169
|
-
}
|
|
170
|
-
|
|
171
153
|
const setups = new WeakMap<LoadedConfig, Promise<SetUp[]>>()
|
|
172
154
|
// the plugins' own folders in .whiteboard/: changes in them reload nothing
|
|
173
155
|
const pluginDirs = new Set<string>()
|
|
@@ -183,15 +165,13 @@ export function createServer(
|
|
|
183
165
|
try {
|
|
184
166
|
pluginDirs.add(e.name)
|
|
185
167
|
const dataDir = pluginDir(project.wb, e.name)
|
|
186
|
-
// what it serves is in its public folder: its client,
|
|
168
|
+
// what it serves is in its public folder: its client, named in its hooks
|
|
187
169
|
const dir = c.publicDirs.get(e.name)!
|
|
188
|
-
const own = (ref: URL | string) => asset(inPublic(dir, ref, `plugin ${e.name}`))
|
|
189
170
|
const hooks =
|
|
190
171
|
(await e.setup?.({
|
|
191
172
|
project: { name: project.name, dir: project.dir, wb: project.wb },
|
|
192
173
|
dataDir,
|
|
193
174
|
authorized: auth.authorized,
|
|
194
|
-
asset: own,
|
|
195
175
|
})) ?? {}
|
|
196
176
|
const client = hooks.client != null ? inPublic(dir, hooks.client, `plugin ${e.name}: client`) : undefined
|
|
197
177
|
return { name: e.name, ...hooks, client, table: mountRoutes(e.name, hooks.routes), plugin: e }
|
|
@@ -206,51 +186,25 @@ export function createServer(
|
|
|
206
186
|
return setups.get(c)!
|
|
207
187
|
}
|
|
208
188
|
|
|
209
|
-
/**
|
|
210
|
-
* What the plugins add to the page shell for this request, and the notices of those that failed:
|
|
211
|
-
* a failing plugin shows on the page, as a failing config does, instead of quietly leaving its
|
|
212
|
-
* part out.
|
|
213
|
-
*/
|
|
214
|
-
/** What the plugins add to a page: markup for its head and body, their browser modules, and notices. */
|
|
215
|
-
interface Extras {
|
|
216
|
-
head: Html[]
|
|
217
|
-
body: Html[]
|
|
218
|
-
clients: { name: string; client: string }[]
|
|
219
|
-
/** the event types that, from the agent, are messages for the reader (EventSpec.forReader) */
|
|
220
|
-
messages?: string[]
|
|
221
|
-
notices?: string[]
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
async function shellExtras(req: IncomingMessage): Promise<Extras & { notices: string[] }> {
|
|
225
|
-
const hooks = await pluginHooks()
|
|
226
|
-
const notices = hooks.filter(h => h.error).map(h => `plugin "${h.name}" failed to start: ${h.error!.message}`)
|
|
227
|
-
const parts = await Promise.all(
|
|
228
|
-
hooks.map(async h => {
|
|
229
|
-
try {
|
|
230
|
-
return (await h.shell?.(req)) ?? null
|
|
231
|
-
} catch (err) {
|
|
232
|
-
console.error(`plugin ${h.name}:`, err)
|
|
233
|
-
notices.push(`plugin "${h.name}" failed on this page: ${(err as Error).message}`)
|
|
234
|
-
return null
|
|
235
|
-
}
|
|
236
|
-
}),
|
|
237
|
-
)
|
|
238
|
-
// their browser modules, which the runtime imports after the page's
|
|
239
|
-
const clients = hooks.filter(h => h.client && !h.error).map(h => ({ name: h.name, client: asset(h.client!) }))
|
|
240
|
-
const messages = [...(await config()).forReader]
|
|
241
|
-
return {
|
|
242
|
-
head: parts.map(x => raw(String(x?.head ?? ''))),
|
|
243
|
-
body: parts.map(x => raw(String(x?.body ?? ''))),
|
|
244
|
-
clients,
|
|
245
|
-
messages,
|
|
246
|
-
notices,
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
/** A page with what the plugins add, their notices among the page's. */
|
|
189
|
+
/** A page as the server serves it: the render with what the plugins add, their failures among its notices. */
|
|
251
190
|
async function page(req: IncomingMessage, stored: StoredPage, rendered: Render): Promise<string> {
|
|
252
|
-
const
|
|
253
|
-
|
|
191
|
+
const notices = [...rendered.notices]
|
|
192
|
+
const parts = await pluginParts(await pluginHooks(), req, {
|
|
193
|
+
asset,
|
|
194
|
+
messages: [...(await config()).forReader],
|
|
195
|
+
failed: message => {
|
|
196
|
+
console.error(message)
|
|
197
|
+
notices.push(message)
|
|
198
|
+
},
|
|
199
|
+
})
|
|
200
|
+
return pageDocument(stored, { ...rendered, notices }, parts, {
|
|
201
|
+
live: true,
|
|
202
|
+
base,
|
|
203
|
+
asset,
|
|
204
|
+
runtime: `${base}/_/runtime.js`,
|
|
205
|
+
title: projectName(),
|
|
206
|
+
stamps: stamps(),
|
|
207
|
+
})
|
|
254
208
|
}
|
|
255
209
|
|
|
256
210
|
/** The loaded config. Also applies its `files` setting to what is served and watched. */
|
|
@@ -293,140 +247,11 @@ export function createServer(
|
|
|
293
247
|
return `${base}/_/file${file.split(path.sep).map(encodeURIComponent).join('/')}`
|
|
294
248
|
}
|
|
295
249
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
function inside(base: string, rel: string): string | null {
|
|
302
|
-
const p = path.resolve(base, '.' + path.posix.normalize('/' + rel))
|
|
303
|
-
return within(p, base) ? p : null
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
const isRepoId = (id: string) => id === '-' || id.startsWith('-/')
|
|
307
|
-
|
|
308
|
-
/** A page's frontmatter, parsed as YAML; empty, with the reason, when it isn't fields. */
|
|
309
|
-
function frontmatter(source: string): { data: Record<string, unknown>; error: string | null } {
|
|
310
|
-
const m = FRONTMATTER.exec(source)
|
|
311
|
-
if (!m) return { data: {}, error: null }
|
|
312
|
-
let data: unknown
|
|
313
|
-
try {
|
|
314
|
-
data = parseYaml(m[1]!)
|
|
315
|
-
} catch (err) {
|
|
316
|
-
return { data: {}, error: (err as Error).message }
|
|
317
|
-
}
|
|
318
|
-
if (data == null) return { data: {}, error: null }
|
|
319
|
-
if (typeof data !== 'object' || Array.isArray(data))
|
|
320
|
-
return { data: {}, error: 'it must be fields (`key: value` lines), not a single value or a list' }
|
|
321
|
-
return { data: data as Record<string, unknown>, error: null }
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
function pageSource(id: string, file: string): PageSource {
|
|
325
|
-
const source = fs.readFileSync(file, 'utf8')
|
|
326
|
-
return {
|
|
327
|
-
kind: 'page',
|
|
328
|
-
id,
|
|
329
|
-
file,
|
|
330
|
-
mtime: fs.statSync(file).mtimeMs,
|
|
331
|
-
source,
|
|
332
|
-
body: source.replace(FRONTMATTER, ''),
|
|
333
|
-
...(({ data, error }) => ({ frontmatter: data, frontmatterError: error }))(frontmatter(source)),
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
/** The pages in a folder of the pages folder, newest first, with when each was last answered. */
|
|
338
|
-
function pagesIn(dir: string): PagesSource['pages'] {
|
|
339
|
-
const last = new Map<string, string>()
|
|
340
|
-
// the last time the reader sent something: what the agent appended doesn't count
|
|
341
|
-
for (const e of readEvents(project.eventsFile)) if (fromReader(e)) last.set(e.page, e.ts)
|
|
342
|
-
const out: PagesSource['pages'] = []
|
|
343
|
-
const walk = (d: string) => {
|
|
344
|
-
if (!fs.existsSync(d)) return
|
|
345
|
-
for (const ent of fs.readdirSync(d, { withFileTypes: true })) {
|
|
346
|
-
if (ent.name.startsWith('.') || ent.name === 'node_modules') continue
|
|
347
|
-
const full = path.join(d, ent.name)
|
|
348
|
-
if (ent.isDirectory()) walk(full)
|
|
349
|
-
else if (ent.name.endsWith('.md')) {
|
|
350
|
-
const id = path.relative(project.pagesDir, full).split(path.sep).join('/').replace(/\.md$/, '')
|
|
351
|
-
out.push({ id, file: full, mtime: fs.statSync(full).mtimeMs, lastEvent: last.get(id) ?? null, awaiting: 0 })
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
walk(dir)
|
|
356
|
-
return out.sort((a, b) => b.mtime - a.mtime)
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
/** Text files show as files; anything with a NUL byte near the start is binary. */
|
|
360
|
-
function isText(file: string): boolean {
|
|
361
|
-
const fd = fs.openSync(file, 'r')
|
|
362
|
-
const buf = Buffer.alloc(8192)
|
|
363
|
-
const n = fs.readSync(fd, buf, 0, buf.length, 0)
|
|
364
|
-
fs.closeSync(fd)
|
|
365
|
-
return !buf.subarray(0, n).includes(0)
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
/**
|
|
369
|
-
* A page id → the stored page, or one of: { redirect } (a folder asked for without its slash),
|
|
370
|
-
* { raw: file } (serve the bytes), null (nothing there).
|
|
371
|
-
*/
|
|
372
|
-
function stored(id: string): StoredPage | { raw: string } | null {
|
|
373
|
-
if (!id) return { kind: 'pages', id: '', file: project.pagesDir, mtime: null, pages: pagesIn(project.pagesDir) }
|
|
374
|
-
if (isRepoId(id)) {
|
|
375
|
-
const rel = id.slice(2)
|
|
376
|
-
const target = inside(project.dir, rel)
|
|
377
|
-
if (!target || path.relative(project.dir, target).split(path.sep).includes('.git') || !fs.existsSync(target))
|
|
378
|
-
return null
|
|
379
|
-
const stat = fs.statSync(target)
|
|
380
|
-
if (stat.isDirectory()) {
|
|
381
|
-
const entries = fs
|
|
382
|
-
.readdirSync(target, { withFileTypes: true })
|
|
383
|
-
.filter(e => !SKIP_DIRS.has(e.name) && e.name !== '.DS_Store')
|
|
384
|
-
.map(e => ({ name: e.name, dir: e.isDirectory() }))
|
|
385
|
-
.sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name))
|
|
386
|
-
return { kind: 'folder', id, file: target, mtime: stat.mtimeMs, entries }
|
|
387
|
-
}
|
|
388
|
-
if (/\.(md|markdown)$/i.test(target)) return pageSource(id, target)
|
|
389
|
-
if (stat.size > 1e6 || !isText(target)) return { raw: target }
|
|
390
|
-
return { kind: 'file', id, file: target, mtime: stat.mtimeMs, source: fs.readFileSync(target, 'utf8') }
|
|
391
|
-
}
|
|
392
|
-
const target = inside(project.pagesDir, id)
|
|
393
|
-
if (!target) return null
|
|
394
|
-
if (path.extname(id) && fs.existsSync(target) && fs.statSync(target).isFile()) return { raw: target }
|
|
395
|
-
if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
|
|
396
|
-
const index = path.join(target, 'index.md')
|
|
397
|
-
if (fs.existsSync(index)) return pageSource(id, index)
|
|
398
|
-
return { kind: 'pages', id, file: target, mtime: null, pages: pagesIn(target) }
|
|
399
|
-
}
|
|
400
|
-
const file = target + '.md'
|
|
401
|
-
return fs.existsSync(file) ? pageSource(id, file) : null
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
/** The URL that serves a file or folder on disk, or null when nothing here serves it. */
|
|
405
|
-
function urlOf(abs: string): string | null {
|
|
406
|
-
const rel = (dir: string) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join('/')
|
|
407
|
-
if (within(abs, project.pagesDir)) return `${base}/${rel(project.pagesDir).replace(/\.md$/, '')}`
|
|
408
|
-
if (FILES && within(abs, project.dir)) {
|
|
409
|
-
if (
|
|
410
|
-
rel(project.dir)
|
|
411
|
-
.split('/')
|
|
412
|
-
.some(part => SKIP_DIRS.has(part))
|
|
413
|
-
)
|
|
414
|
-
return null
|
|
415
|
-
return `${base}/-/${rel(project.dir)}`
|
|
416
|
-
}
|
|
417
|
-
return null
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
/** For links: the target if it exists (also with .md added), mapped to its URL. */
|
|
421
|
-
function urlFor(abs: string): string | null {
|
|
422
|
-
for (const candidate of [abs, abs + '.md']) {
|
|
423
|
-
if (fs.existsSync(candidate)) {
|
|
424
|
-
const url = urlOf(candidate)
|
|
425
|
-
if (url) return url + (fs.statSync(candidate).isDirectory() && !url.endsWith('/') ? '/' : '')
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
return null
|
|
429
|
-
}
|
|
250
|
+
// ---- stored pages: the site (site.ts) --------------------------------------------------------------
|
|
251
|
+
const site = servedSite(project, { base, files: () => !!FILES })
|
|
252
|
+
const stored = site.page
|
|
253
|
+
const pagesIn = site.pagesIn
|
|
254
|
+
const urlFor = site.urlFor
|
|
430
255
|
|
|
431
256
|
// ---- rendering ---------------------------------------------------------------------------------
|
|
432
257
|
|
|
@@ -457,16 +282,6 @@ export function createServer(
|
|
|
457
282
|
...(entry && { entry: { name: entry, label } }),
|
|
458
283
|
})
|
|
459
284
|
|
|
460
|
-
/** A render as the shell takes it. `page`: whether the page's browser part runs (not on raw text). */
|
|
461
|
-
interface Render {
|
|
462
|
-
page: boolean
|
|
463
|
-
out: Rendered
|
|
464
|
-
notices: string[]
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
/** A stored page's frontmatter, for the browser (PageHandle.frontmatter): a markdown page's, else none. */
|
|
468
|
-
const frontmatterOf = (page: StoredPage): Record<string, unknown> => (page.kind === 'page' ? page.frontmatter : {})
|
|
469
|
-
|
|
470
285
|
/** Render a stored page as markdown, with the plugins' blocks, and anything the reader should be told. */
|
|
471
286
|
async function render(page: StoredPage): Promise<Render> {
|
|
472
287
|
const { pages, errors } = await config()
|
|
@@ -488,52 +303,67 @@ export function createServer(
|
|
|
488
303
|
}
|
|
489
304
|
|
|
490
305
|
/**
|
|
491
|
-
*
|
|
492
|
-
*
|
|
493
|
-
*
|
|
306
|
+
* The project's status (status.ts): the pages, below `only` when given, with their questions, the
|
|
307
|
+
* log read once, and who listens. What `whiteboard status`, the hooks, the page lists and the log's
|
|
308
|
+
* picked-up marks take.
|
|
494
309
|
*/
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
let asks: string[] = []
|
|
508
|
-
try {
|
|
509
|
-
asks = pages?.questions(page) ?? []
|
|
510
|
-
} catch (err) {
|
|
511
|
-
console.error('questions:', err)
|
|
512
|
-
}
|
|
513
|
-
const events = all.filter(e => e.page === p.id)
|
|
514
|
-
const listening = listenersFor(p.id)
|
|
515
|
-
// where each question stands, as the page shows it (see status.ts)
|
|
516
|
-
const questions = asks.map(name => ({
|
|
517
|
-
name,
|
|
518
|
-
state: questionState(name, events, listening, id => picked.has(id)).state,
|
|
519
|
-
}))
|
|
520
|
-
const named = (...states: string[]) => questions.filter(q => states.includes(q.state)).map(q => q.name)
|
|
521
|
-
out.push({
|
|
522
|
-
page: p.id,
|
|
523
|
-
title: titleOf(p.file, path.basename(p.id)),
|
|
524
|
-
file: p.file,
|
|
525
|
-
owner: owner.get(p.id) ?? null,
|
|
526
|
-
asks,
|
|
527
|
-
questions,
|
|
528
|
-
open: named('open'),
|
|
529
|
-
unheard: named('open').filter(name => !heard(name, listening)),
|
|
530
|
-
unread: unreadMessages(events, type => forReader.has(type)),
|
|
531
|
-
// the reader's events for an agent: a form's answers, and plugin events declared handOut
|
|
532
|
-
unpicked: events.filter(e => fromReader(e) && isForAgent(e.type) && !picked.has(e.id)),
|
|
533
|
-
listeners: listening,
|
|
534
|
-
})
|
|
310
|
+
// Each page's questions and title, kept while its file and the config stay as they are: parsing
|
|
311
|
+
// every page's markdown on each ask was most of what a status cost.
|
|
312
|
+
const asked = new Map<
|
|
313
|
+
string,
|
|
314
|
+
{ file: string; mtime: number; size: number; renderer: unknown; title: string; asks: string[] }
|
|
315
|
+
>()
|
|
316
|
+
function questionsOf(renderer: LoadedConfig['pages'], id: string, file: string): { title: string; asks: string[] } {
|
|
317
|
+
let stat: fs.Stats
|
|
318
|
+
try {
|
|
319
|
+
stat = fs.statSync(file)
|
|
320
|
+
} catch {
|
|
321
|
+
return { title: path.basename(id), asks: [] }
|
|
535
322
|
}
|
|
536
|
-
|
|
323
|
+
const kept = asked.get(id)
|
|
324
|
+
if (
|
|
325
|
+
kept &&
|
|
326
|
+
kept.file === file &&
|
|
327
|
+
kept.mtime === stat.mtimeMs &&
|
|
328
|
+
kept.size === stat.size &&
|
|
329
|
+
kept.renderer === renderer
|
|
330
|
+
)
|
|
331
|
+
return kept
|
|
332
|
+
let asks: string[] = []
|
|
333
|
+
try {
|
|
334
|
+
asks = renderer?.questions(pageSource(id, file)) ?? []
|
|
335
|
+
} catch (err) {
|
|
336
|
+
console.error('questions:', err)
|
|
337
|
+
}
|
|
338
|
+
const now = { file, mtime: stat.mtimeMs, size: stat.size, renderer, title: titleOf(file, path.basename(id)), asks }
|
|
339
|
+
asked.set(id, now)
|
|
340
|
+
return now
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async function snapshot(listed: PagesSource['pages']): Promise<ProjectStatus> {
|
|
344
|
+
const { pages: renderer, handedOut, forReader } = await config()
|
|
345
|
+
const pages = listed.map(p => ({ id: p.id, file: p.file, ...questionsOf(renderer, p.id, p.file) }))
|
|
346
|
+
return projectStatus({
|
|
347
|
+
pages,
|
|
348
|
+
events: readEvents(project.eventsFile),
|
|
349
|
+
listeners: listenersFor,
|
|
350
|
+
forAgent: forAgent(handedOut),
|
|
351
|
+
forReader: type => forReader.has(type),
|
|
352
|
+
})
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Per page, below `only` when given: what `whiteboard status` and the hooks report (see snapshot). */
|
|
356
|
+
const status = async (only: string | null): Promise<PageStatus[]> =>
|
|
357
|
+
(await snapshot(pagesIn(project.pagesDir).filter(p => !only || p.id === only || p.id.startsWith(only + '/')))).pages
|
|
358
|
+
|
|
359
|
+
/** A list of pages, with when each was last answered and how much waits on it, from one status. */
|
|
360
|
+
async function withStatus(pages: PagesSource['pages']): Promise<PagesSource['pages']> {
|
|
361
|
+
const s = await snapshot(pages)
|
|
362
|
+
pages.forEach((p, i) => {
|
|
363
|
+
p.awaiting = awaiting(s.pages[i]!)
|
|
364
|
+
p.lastEvent = s.lastAnswered(p.id)
|
|
365
|
+
})
|
|
366
|
+
return pages
|
|
537
367
|
}
|
|
538
368
|
|
|
539
369
|
/** How to write pages here, as markdown: the pages' own docs, then each plugin's. */
|
|
@@ -561,84 +391,53 @@ export function createServer(
|
|
|
561
391
|
return { errors: errors.map(e => (e as Error).message), pages: pages?.docs(context()) ?? null, plugins }
|
|
562
392
|
}
|
|
563
393
|
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
extras: Extras = { head: [], body: [], clients: [] },
|
|
588
|
-
/** a built page (`whiteboard build`): its files as the build names them, and no server behind it */
|
|
589
|
-
built?: { asset(ref: string | URL): string },
|
|
590
|
-
): string {
|
|
591
|
-
const handoff = {
|
|
592
|
-
id: page.id,
|
|
593
|
-
kind: page.kind,
|
|
594
|
-
live: !built,
|
|
595
|
-
// what the page's own requests start with (see ServerOptions.base)
|
|
596
|
-
base: built ? '' : base,
|
|
597
|
-
client: rendered ? (built ?? { asset }).asset(PAGE_CLIENT) : null,
|
|
598
|
-
data: out.data ?? null,
|
|
599
|
-
frontmatter: frontmatterOf(page),
|
|
600
|
-
plugins: extras.clients,
|
|
601
|
-
messages: extras.messages ?? [],
|
|
394
|
+
/**
|
|
395
|
+
* What the browser runs and how it looks, as two stamps: one over its code (the runtime, the page's
|
|
396
|
+
* module, the plugins' scripts), one over its stylesheets (the engine's, the plugins', the
|
|
397
|
+
* project's in .whiteboard/). A page gets them with its HTML and asks again when its live channel
|
|
398
|
+
* is back: what changed while it was away (a restart, a background tab whose browser held its
|
|
399
|
+
* timers), it would otherwise never hear of. Made from the files themselves, not from what was
|
|
400
|
+
* served since the server started, so a fresh server gives the same stamps for the same files.
|
|
401
|
+
*/
|
|
402
|
+
function stamps(): { code: string; style: string } {
|
|
403
|
+
const files: string[] = [RUNTIME]
|
|
404
|
+
const add = (dir: string, deep: boolean) => {
|
|
405
|
+
let entries: fs.Dirent[]
|
|
406
|
+
try {
|
|
407
|
+
entries = fs.readdirSync(dir, { withFileTypes: true })
|
|
408
|
+
} catch {
|
|
409
|
+
return
|
|
410
|
+
}
|
|
411
|
+
for (const e of entries) {
|
|
412
|
+
const full = path.join(dir, e.name)
|
|
413
|
+
if (e.isDirectory()) {
|
|
414
|
+
if (deep) add(full, deep)
|
|
415
|
+
} else files.push(full)
|
|
416
|
+
}
|
|
602
417
|
}
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
<div id="wb-dock"></div>
|
|
620
|
-
<script type="application/json" id="wb-page">
|
|
621
|
-
${raw(json(handoff))}
|
|
622
|
-
</script>
|
|
623
|
-
<script type="module" src="${built ? built.asset(RUNTIME) : `${base}/_/runtime.js`}"></script>
|
|
624
|
-
${extras.body}
|
|
625
|
-
</body>
|
|
626
|
-
</html>`,
|
|
627
|
-
)
|
|
418
|
+
add(path.dirname(PAGE_CLIENT), false)
|
|
419
|
+
for (const dir of publicDirs) add(dir, true)
|
|
420
|
+
for (const f of fs.readdirSync(project.wb).filter(f => f.endsWith('.css'))) files.push(path.join(project.wb, f))
|
|
421
|
+
const of = (list: string[]) => {
|
|
422
|
+
const hash = crypto.createHash('sha1')
|
|
423
|
+
for (const f of [...new Set(list)].toSorted()) {
|
|
424
|
+
try {
|
|
425
|
+
const st = fs.statSync(f)
|
|
426
|
+
hash.update(`${f}\0${st.mtimeMs}\0${st.size}\n`)
|
|
427
|
+
} catch {
|
|
428
|
+
/* gone */
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return hash.digest('hex').slice(0, 16)
|
|
432
|
+
}
|
|
433
|
+
return { code: of(files.filter(f => !f.endsWith('.css'))), style: of(files.filter(f => f.endsWith('.css'))) }
|
|
628
434
|
}
|
|
629
435
|
|
|
630
436
|
// ---- listeners ---------------------------------------------------------------------------------
|
|
631
|
-
// An agent waiting for answers
|
|
632
|
-
// as long as it runs: that connection is the listener, gone when the command is. Pages show what an
|
|
437
|
+
// An agent waiting for answers holds a connection to /api/listen (listeners.ts). Pages show what an
|
|
633
438
|
// agent is waiting for from these, so nothing depends on the agent marking it.
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
const listeners = new Set<Listener>()
|
|
637
|
-
|
|
638
|
-
const listenersFor = (page: string | null): Listener[] =>
|
|
639
|
-
[...listeners]
|
|
640
|
-
.filter(l => page == null || covers(l, page))
|
|
641
|
-
.map(({ page, type, command, fallback }) => ({ page, type, command, ...(fallback && { fallback }) }))
|
|
439
|
+
const registry = createRegistry()
|
|
440
|
+
const listenersFor = (page: string | null): Listener[] => registry.list(page)
|
|
642
441
|
|
|
643
442
|
// ---- live changes ------------------------------------------------------------------------------
|
|
644
443
|
// The browser listens on a WebSocket at /api/live, each message `{ event, data }`. `change`: its
|
|
@@ -672,10 +471,10 @@ export function createServer(
|
|
|
672
471
|
for (const c of clients) notify(c, kind)
|
|
673
472
|
}
|
|
674
473
|
// who listens shows on this project's pages, and, under a shared server, on the others' (onChange)
|
|
675
|
-
|
|
474
|
+
registry.onChange(() => {
|
|
676
475
|
notifyAll('listeners')
|
|
677
476
|
onChange?.()
|
|
678
|
-
}
|
|
477
|
+
})
|
|
679
478
|
|
|
680
479
|
function pageChanged(id: string) {
|
|
681
480
|
onChange?.()
|
|
@@ -819,8 +618,7 @@ export function createServer(
|
|
|
819
618
|
return { redirect: `${base}/${id}/` }
|
|
820
619
|
// a list of pages says which await the reader: where their questions stand takes the config
|
|
821
620
|
if (found.kind === 'pages') {
|
|
822
|
-
|
|
823
|
-
for (const p of found.pages) p.awaiting = counts.get(p.id) ?? 0
|
|
621
|
+
await withStatus(found.pages)
|
|
824
622
|
if (!found.id && overview) Object.assign(found, await overview())
|
|
825
623
|
}
|
|
826
624
|
return { page: found }
|
|
@@ -888,12 +686,12 @@ export function createServer(
|
|
|
888
686
|
const { page: id, to } = JSON.parse(await readBody(req)) as { page?: unknown; to?: unknown }
|
|
889
687
|
if (typeof id !== 'string' || typeof to !== 'string' || !to.trim())
|
|
890
688
|
return sendJson(res, 400, { error: 'page and to required' })
|
|
689
|
+
// in the log, so a tab that isn't connected now (a server restarting, a background tab
|
|
690
|
+
// whose browser holds its timers) still scrolls there once it is back; a page loaded later
|
|
691
|
+
// doesn't (see the runtime)
|
|
692
|
+
appendEvent(project.eventsFile, { page: id, type: SCROLL, data: { to } }, 'cli')
|
|
891
693
|
let tabs = 0
|
|
892
|
-
for (const c of clients)
|
|
893
|
-
if (c.isDir || (c.page !== id && c.page + '/index' !== id)) continue
|
|
894
|
-
c.send('scroll', { to })
|
|
895
|
-
tabs++
|
|
896
|
-
}
|
|
694
|
+
for (const c of clients) if (!c.isDir && (c.page === id || c.page + '/index' === id)) tabs++
|
|
897
695
|
return sendJson(res, 200, { tabs })
|
|
898
696
|
}
|
|
899
697
|
// messages (comments, chat) written in markdown, as HTML: { texts } → { html, styles }
|
|
@@ -922,39 +720,21 @@ export function createServer(
|
|
|
922
720
|
if (p === '/api/docs') return sendJson(res, 200, await docs())
|
|
923
721
|
if (p === '/api/status') return sendJson(res, 200, await status(q.page || null))
|
|
924
722
|
if (p === '/api/listeners') return sendJson(res, 200, listenersFor(q.page ?? null))
|
|
723
|
+
if (p === '/api/stamps') return sendJson(res, 200, stamps())
|
|
925
724
|
if (p === '/api/listen') {
|
|
926
|
-
const
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
})
|
|
935
|
-
res.write(': listening\n\n')
|
|
936
|
-
const l: Listener = {
|
|
937
|
-
page: q.page || '',
|
|
938
|
-
type: q.type || null,
|
|
939
|
-
command: q.command === 'wait' ? 'wait' : 'watch',
|
|
940
|
-
...(fallback && { fallback }),
|
|
941
|
-
}
|
|
942
|
-
listeners.add(l)
|
|
943
|
-
listenersChanged()
|
|
944
|
-
const ping = setInterval(() => res.write(': ping\n\n'), 25000)
|
|
945
|
-
const end = () => {
|
|
946
|
-
clearInterval(ping)
|
|
947
|
-
listeners.delete(l)
|
|
948
|
-
streams.delete(end)
|
|
949
|
-
}
|
|
950
|
-
streams.add(() => {
|
|
951
|
-
end()
|
|
952
|
-
res.end()
|
|
953
|
-
})
|
|
954
|
-
req.on('close', () => {
|
|
955
|
-
end()
|
|
956
|
-
listenersChanged()
|
|
725
|
+
const remove = registry.add(listenerOf(url.searchParams))
|
|
726
|
+
if (!remove) return sendJson(res, 409, { error: 'another agent is the fallback already' })
|
|
727
|
+
// a fallback is told who else listens, at once and on every change
|
|
728
|
+
const off = 'fallback' in q ? registry.onChange(() => tell()) : () => {}
|
|
729
|
+
const stream = holdStream(req, res, () => {
|
|
730
|
+
off()
|
|
731
|
+
remove()
|
|
732
|
+
streams.delete(stream.end)
|
|
957
733
|
})
|
|
734
|
+
const tell = () =>
|
|
735
|
+
stream.send('listeners', { projects: [{ dir: project.dir, base, listeners: registry.list() }] })
|
|
736
|
+
if ('fallback' in q) tell()
|
|
737
|
+
streams.add(stream.end)
|
|
958
738
|
return
|
|
959
739
|
}
|
|
960
740
|
if (p === '/api/page' || p === '/api/render') {
|
|
@@ -1019,223 +799,6 @@ export function createServer(
|
|
|
1019
799
|
}
|
|
1020
800
|
}
|
|
1021
801
|
|
|
1022
|
-
// ---- build: a static site ---------------------------------------------------------------------
|
|
1023
|
-
// Pages rendered once (`whiteboard build`), as files: each page's HTML with its links relative, and
|
|
1024
|
-
// what it loads copied beside it. See BuildConfig.
|
|
1025
|
-
|
|
1026
|
-
/** What a build leaves out unless told otherwise: what is for writing a page, not for reading it. */
|
|
1027
|
-
const BUILD_SKIP = ['form', 'chat', 'comments', 'draft']
|
|
1028
|
-
/** In the folder a build writes, so that a next build knows it may replace it. */
|
|
1029
|
-
const BUILD_MARK = '.whiteboard-build'
|
|
1030
|
-
|
|
1031
|
-
async function build(options: BuildConfig = {}): Promise<BuildResult> {
|
|
1032
|
-
const cfg = await config()
|
|
1033
|
-
if (cfg.errors.length) throw new Error(`the config failed to load: ${(cfg.errors[0] as Error).message}`)
|
|
1034
|
-
if (!cfg.pages) throw new Error('the config has no pages renderer')
|
|
1035
|
-
const pages = cfg.pages
|
|
1036
|
-
const defined = <T>(...xs: (T | undefined)[]) => xs.find(x => x !== undefined)
|
|
1037
|
-
const patterns = defined(options.pages, cfg.build.pages) ?? []
|
|
1038
|
-
const skip = new Set(defined(options.skip, cfg.build.skip) ?? BUILD_SKIP)
|
|
1039
|
-
const outDir = path.resolve(project.dir, defined(options.out, cfg.build.out) ?? 'site')
|
|
1040
|
-
if (!patterns.length)
|
|
1041
|
-
throw new Error(
|
|
1042
|
-
"nothing to build: name the pages, as globs from the project's folder (whiteboard build 'docs/**/*.md'), or set build.pages in the config",
|
|
1043
|
-
)
|
|
1044
|
-
const warnings: string[] = []
|
|
1045
|
-
|
|
1046
|
-
// the pages: markdown files the globs match, but those a `!` glob leaves out
|
|
1047
|
-
const include = patterns.filter(p => !p.startsWith('!'))
|
|
1048
|
-
const exclude = patterns.filter(p => p.startsWith('!')).map(p => p.slice(1))
|
|
1049
|
-
const files = [
|
|
1050
|
-
...new Set(include.flatMap(p => fs.globSync(p, { cwd: project.dir }).map(f => path.resolve(project.dir, f)))),
|
|
1051
|
-
]
|
|
1052
|
-
.filter(f => /\.(md|markdown)$/i.test(f) && fs.statSync(f).isFile())
|
|
1053
|
-
.filter(f => !exclude.some(g => path.matchesGlob(path.relative(project.dir, f), g)))
|
|
1054
|
-
.sort()
|
|
1055
|
-
if (!files.length) throw new Error(`no markdown files match ${patterns.join(' ')}`)
|
|
1056
|
-
// each at its place below the folder they share; a README or index is its folder's index.html
|
|
1057
|
-
const base = files.map(path.dirname).reduce((a, b) => {
|
|
1058
|
-
while (!within(b, a)) a = path.dirname(a)
|
|
1059
|
-
return a
|
|
1060
|
-
})
|
|
1061
|
-
const outOf = (file: string) => {
|
|
1062
|
-
const rel = path.relative(base, file)
|
|
1063
|
-
return path.join(
|
|
1064
|
-
outDir,
|
|
1065
|
-
/^(readme|index)\.(md|markdown)$/i.test(path.basename(rel))
|
|
1066
|
-
? path.join(path.dirname(rel), 'index.html')
|
|
1067
|
-
: rel.replace(/\.(md|markdown)$/i, '.html'),
|
|
1068
|
-
)
|
|
1069
|
-
}
|
|
1070
|
-
const built = new Map(files.map(f => [f, outOf(f)]))
|
|
1071
|
-
|
|
1072
|
-
// the folder it writes: new, empty, or what an earlier build wrote
|
|
1073
|
-
if (fs.existsSync(outDir)) {
|
|
1074
|
-
if (fs.readdirSync(outDir).length && !fs.existsSync(path.join(outDir, BUILD_MARK)))
|
|
1075
|
-
throw new Error(`${outDir} has files a build didn't write: give another folder (--out), or empty it`)
|
|
1076
|
-
fs.rmSync(outDir, { recursive: true })
|
|
1077
|
-
}
|
|
1078
|
-
fs.mkdirSync(outDir, { recursive: true })
|
|
1079
|
-
fs.writeFileSync(
|
|
1080
|
-
path.join(outDir, BUILD_MARK),
|
|
1081
|
-
'written by whiteboard build; the next build replaces this folder\n',
|
|
1082
|
-
)
|
|
1083
|
-
|
|
1084
|
-
// what a page loads, copied once: the package's files under _/whiteboard/, the project's under
|
|
1085
|
-
// _/project/, at their places there (so a stylesheet's url()s still hold); TypeScript as JavaScript
|
|
1086
|
-
const copied = new Map<string, string>()
|
|
1087
|
-
function copyAsset(file: string): string {
|
|
1088
|
-
const known = copied.get(file)
|
|
1089
|
-
if (known) return known
|
|
1090
|
-
const rel = within(file, ENGINE_DIR)
|
|
1091
|
-
? path.join('_', 'whiteboard', path.relative(ENGINE_DIR, file))
|
|
1092
|
-
: within(file, project.dir)
|
|
1093
|
-
? path.join('_', 'project', path.relative(project.dir, file))
|
|
1094
|
-
: path.join('_', 'files', path.basename(path.dirname(file)), path.basename(file))
|
|
1095
|
-
const dest = path.join(outDir, TYPESCRIPT.test(rel) ? rel.replace(/\.m?ts$/i, '.js') : rel)
|
|
1096
|
-
copied.set(file, dest)
|
|
1097
|
-
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
1098
|
-
if (TYPESCRIPT.test(file)) fs.writeFileSync(dest, typeScriptModule(file))
|
|
1099
|
-
else fs.copyFileSync(file, dest)
|
|
1100
|
-
// a stylesheet's own files (fonts, images), at the same places beside it
|
|
1101
|
-
if (/\.css$/i.test(file)) {
|
|
1102
|
-
for (const m of fs.readFileSync(file, 'utf8').matchAll(/url\(\s*['"]?([^'")]+)['"]?\s*\)/g)) {
|
|
1103
|
-
const ref = m[1]!
|
|
1104
|
-
if (/^(data:|[a-z][a-z0-9+.-]*:|\/|#)/i.test(ref)) continue
|
|
1105
|
-
const target = path.resolve(path.dirname(file), ref.replace(/[?#].*$/, ''))
|
|
1106
|
-
if (fs.existsSync(target) && fs.statSync(target).isFile()) copyAsset(target)
|
|
1107
|
-
}
|
|
1108
|
-
}
|
|
1109
|
-
return dest
|
|
1110
|
-
}
|
|
1111
|
-
/** a file beside the pages (an image), copied to its place below the site */
|
|
1112
|
-
function copyBeside(file: string): string | null {
|
|
1113
|
-
if (!within(file, base)) return null
|
|
1114
|
-
const dest = path.join(outDir, path.relative(base, file))
|
|
1115
|
-
if (!fs.existsSync(dest)) {
|
|
1116
|
-
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
1117
|
-
fs.copyFileSync(file, dest)
|
|
1118
|
-
}
|
|
1119
|
-
return dest
|
|
1120
|
-
}
|
|
1121
|
-
|
|
1122
|
-
const hooks = await pluginHooks()
|
|
1123
|
-
const result: BuildResult = { out: outDir, pages: [], warnings }
|
|
1124
|
-
for (const [file, dest] of built) {
|
|
1125
|
-
const here = path.dirname(dest)
|
|
1126
|
-
const relTo = (target: string) =>
|
|
1127
|
-
path.relative(here, target).split(path.sep).map(encodeURIComponent).join('/') || '.'
|
|
1128
|
-
const assetHere = (ref: string | URL) => relTo(copyAsset(toPath(ref)))
|
|
1129
|
-
const urlFor = (abs: string): string | null => {
|
|
1130
|
-
for (const candidate of [abs, abs + '.md']) {
|
|
1131
|
-
if (!fs.existsSync(candidate)) continue
|
|
1132
|
-
if (fs.statSync(candidate).isDirectory()) {
|
|
1133
|
-
const index = [...built.keys()].find(
|
|
1134
|
-
f => path.dirname(f) === candidate && /^(readme|index)\.(md|markdown)$/i.test(path.basename(f)),
|
|
1135
|
-
)
|
|
1136
|
-
if (index) return relTo(built.get(index)!)
|
|
1137
|
-
continue
|
|
1138
|
-
}
|
|
1139
|
-
if (built.has(candidate)) return relTo(built.get(candidate)!)
|
|
1140
|
-
if (/\.(md|markdown)$/i.test(candidate)) {
|
|
1141
|
-
warnings.push(
|
|
1142
|
-
`${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, which is not in the build`,
|
|
1143
|
-
)
|
|
1144
|
-
return null
|
|
1145
|
-
}
|
|
1146
|
-
const copy = copyBeside(candidate)
|
|
1147
|
-
if (copy) return relTo(copy)
|
|
1148
|
-
warnings.push(
|
|
1149
|
-
`${path.relative(project.dir, file)} links to ${path.relative(project.dir, candidate)}, outside the built pages' folder`,
|
|
1150
|
-
)
|
|
1151
|
-
return null
|
|
1152
|
-
}
|
|
1153
|
-
return null
|
|
1154
|
-
}
|
|
1155
|
-
const id = within(file, project.pagesDir)
|
|
1156
|
-
? path
|
|
1157
|
-
.relative(project.pagesDir, file)
|
|
1158
|
-
.split(path.sep)
|
|
1159
|
-
.join('/')
|
|
1160
|
-
.replace(/\.(md|markdown)$/i, '')
|
|
1161
|
-
: '-/' + path.relative(project.dir, file).split(path.sep).join('/')
|
|
1162
|
-
const stored = pageSource(id, file)
|
|
1163
|
-
if (stored.frontmatterError)
|
|
1164
|
-
warnings.push(`${path.relative(project.dir, file)}: frontmatter: ${stored.frontmatterError}`)
|
|
1165
|
-
const context = {
|
|
1166
|
-
project: { name: project.name, dir: project.dir, files: !!FILES },
|
|
1167
|
-
asset: assetHere,
|
|
1168
|
-
urlFor,
|
|
1169
|
-
live: false,
|
|
1170
|
-
skip,
|
|
1171
|
-
}
|
|
1172
|
-
const rendered = await pages.render(stored, context)
|
|
1173
|
-
// a page without a heading of its own is named by its file (a README by its folder), not by
|
|
1174
|
-
// the id the server knows it by
|
|
1175
|
-
const named = /^(readme|index)\.(md|markdown)$/i.test(path.basename(file))
|
|
1176
|
-
? path.basename(path.dirname(file))
|
|
1177
|
-
: path.basename(file).replace(/\.(md|markdown)$/i, '')
|
|
1178
|
-
const title = !rendered.title || rendered.title === id ? named : rendered.title
|
|
1179
|
-
const out = { ...rendered, title, html: String(rendered.html ?? ''), head: String(rendered.head ?? '') }
|
|
1180
|
-
// the plugins' browser modules, but those the build leaves out; not what they add to a live
|
|
1181
|
-
// page's shell (the terminal's drawer): that is the server's
|
|
1182
|
-
const included = hooks.filter(h => !h.error && !skip.has(h.name))
|
|
1183
|
-
const clients = included.filter(h => h.client).map(h => ({ name: h.name, client: assetHere(h.client!) }))
|
|
1184
|
-
// what the plugins add to the shell, asked with no request: no browser asked for this page
|
|
1185
|
-
const parts = await Promise.all(
|
|
1186
|
-
included.map(async h => {
|
|
1187
|
-
try {
|
|
1188
|
-
return (await h.shell?.(null)) ?? null
|
|
1189
|
-
} catch (err) {
|
|
1190
|
-
warnings.push(`plugin ${h.name} failed on ${path.relative(project.dir, file)}: ${(err as Error).message}`)
|
|
1191
|
-
return null
|
|
1192
|
-
}
|
|
1193
|
-
}),
|
|
1194
|
-
)
|
|
1195
|
-
const extras = {
|
|
1196
|
-
head: parts.map(x => raw(String(x?.head ?? ''))),
|
|
1197
|
-
body: parts.map(x => raw(String(x?.body ?? ''))),
|
|
1198
|
-
clients,
|
|
1199
|
-
}
|
|
1200
|
-
let doc = shell(stored, { page: true, out, notices: [] }, extras, { asset: assetHere })
|
|
1201
|
-
// a file a plugin named the server's way (its asset URL, /_/file/<path>): its copy
|
|
1202
|
-
doc = doc.replace(/\/_\/file(\/[^"'\s)<>]+)/g, (all, served: string) => {
|
|
1203
|
-
let file: string
|
|
1204
|
-
try {
|
|
1205
|
-
file = path.resolve(served.split('/').map(decodeURIComponent).join(path.sep))
|
|
1206
|
-
} catch {
|
|
1207
|
-
return all
|
|
1208
|
-
}
|
|
1209
|
-
return fs.existsSync(file) && fs.statSync(file).isFile() ? assetHere(file) : all
|
|
1210
|
-
})
|
|
1211
|
-
// what the blocks name relative to the page (an ::image's src, an iframe's page): copied too
|
|
1212
|
-
doc = doc.replace(/\b(src|href|poster)="([^"#?:]+)([^"]*)"/g, (all, _attr, ref: string) => {
|
|
1213
|
-
if (ref.startsWith('/') || ref.startsWith('_/') || ref.startsWith('../')) return all
|
|
1214
|
-
let decoded = ref
|
|
1215
|
-
try {
|
|
1216
|
-
decoded = decodeURIComponent(ref)
|
|
1217
|
-
} catch {
|
|
1218
|
-
/* as written */
|
|
1219
|
-
}
|
|
1220
|
-
const source = path.resolve(path.dirname(file), decoded)
|
|
1221
|
-
if (fs.existsSync(source) && fs.statSync(source).isFile() && !/\.(md|markdown)$/i.test(source)) {
|
|
1222
|
-
const target = path.resolve(here, decoded)
|
|
1223
|
-
if (within(target, outDir) && !fs.existsSync(target)) {
|
|
1224
|
-
fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
1225
|
-
fs.copyFileSync(source, target)
|
|
1226
|
-
}
|
|
1227
|
-
}
|
|
1228
|
-
return all
|
|
1229
|
-
})
|
|
1230
|
-
fs.mkdirSync(here, { recursive: true })
|
|
1231
|
-
fs.writeFileSync(dest, doc)
|
|
1232
|
-
result.pages.push({ file, to: dest })
|
|
1233
|
-
}
|
|
1234
|
-
if (![...built.values()].includes(path.join(outDir, 'index.html')))
|
|
1235
|
-
warnings.push('no README.md or index.md in the top folder: the site has no index.html')
|
|
1236
|
-
return result
|
|
1237
|
-
}
|
|
1238
|
-
|
|
1239
802
|
/** The live channel: /api/live, a WebSocket from a page of this server's (see ws.ts). */
|
|
1240
803
|
function upgrade(req: IncomingMessage, conn: Duplex, _head: Buffer) {
|
|
1241
804
|
const url = new URL((req.url ?? '/').replace(/^\/+/, '/'), 'http://localhost')
|
|
@@ -1264,25 +827,18 @@ export function createServer(
|
|
|
1264
827
|
listeners: () => listenersFor(null),
|
|
1265
828
|
async overview() {
|
|
1266
829
|
await config()
|
|
1267
|
-
const pages = pagesIn(project.pagesDir)
|
|
1268
|
-
const counts = new Map((await status(null)).map(s => [s.page, awaiting(s)]))
|
|
1269
|
-
for (const p of pages) p.awaiting = counts.get(p.id) ?? 0
|
|
830
|
+
const pages = await withStatus(pagesIn(project.pagesDir))
|
|
1270
831
|
return { pages, files: !!FILES }
|
|
1271
832
|
},
|
|
1272
833
|
touch() {
|
|
1273
834
|
for (const c of clients) if (c.isDir && !c.page) notify(c, 'change')
|
|
1274
835
|
},
|
|
1275
836
|
elsewhere: () => notifyAll('elsewhere'),
|
|
1276
|
-
addListener(l)
|
|
1277
|
-
|
|
1278
|
-
listenersChanged()
|
|
1279
|
-
return () => {
|
|
1280
|
-
if (listeners.delete(l)) listenersChanged()
|
|
1281
|
-
}
|
|
1282
|
-
},
|
|
837
|
+
addListener: l => registry.add(l),
|
|
838
|
+
onListeners: fn => registry.onChange(fn),
|
|
1283
839
|
status: (page = null) => status(page),
|
|
1284
840
|
config,
|
|
1285
|
-
build,
|
|
841
|
+
build: options => build({ project, config, hooks: pluginHooks, files: () => !!FILES }, options),
|
|
1286
842
|
close() {
|
|
1287
843
|
for (const w of watchers) w.close()
|
|
1288
844
|
watchers.clear()
|