@bigmistqke/whiteboard 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -17
- package/bin/whiteboard.ts +268 -71
- package/dist/client/runtime.js +88 -41
- package/dist/define.js +21 -2
- package/dist/plugins/callout/index.js +3 -1
- package/dist/plugins/callout/public/style.css +30 -0
- package/dist/plugins/chat/index.js +7 -4
- package/dist/plugins/chat/{client.js → public/client.js} +1 -1
- package/dist/plugins/chat/public/style.css +98 -0
- package/dist/plugins/code/index.js +3 -1
- package/dist/plugins/code/public/style.css +68 -0
- package/dist/plugins/comments/index.js +4 -5
- package/dist/plugins/comments/public/client.js +19 -0
- package/dist/plugins/comments/public/style.css +185 -0
- package/dist/plugins/details/index.js +7 -2
- package/dist/plugins/details/public/style.css +7 -0
- package/dist/plugins/form/index.js +37 -8
- package/dist/plugins/form/public/style.css +126 -0
- package/dist/plugins/gallery/index.js +4 -3
- package/dist/plugins/gallery/public/client.js +1 -0
- package/dist/plugins/gallery/public/style.css +90 -0
- package/dist/plugins/grid/index.js +9 -3
- package/dist/plugins/grid/public/style.css +71 -0
- package/dist/plugins/iframe/index.js +13 -14
- package/dist/plugins/iframe/public/style.css +13 -0
- package/dist/plugins/index.js +3 -1
- package/dist/plugins/mermaid/index.js +3 -1
- package/dist/plugins/mermaid/{style.css → public/style.css} +7 -2
- package/dist/plugins/terminal/index.js +10 -9
- package/dist/plugins/terminal/{style.css → public/style.css} +199 -45
- package/dist/plugins/toc/index.js +4 -3
- package/dist/plugins/toc/public/client.js +1 -0
- package/dist/plugins/toc/public/style.css +93 -0
- package/dist/plugins/window/README.md +29 -0
- package/dist/plugins/window/index.js +64 -0
- package/dist/solid/index.js +14 -11
- package/dist/src/client/page/base.css +1078 -199
- package/dist/src/client/page/main.js +174 -33
- package/dist/src/loader.js +7 -2
- package/dist/src/package.js +3 -6
- package/dist/src/pages/blocks.js +8 -13
- package/dist/src/pages/markdown.js +1 -1
- package/dist/src/pages/render.js +74 -15
- package/dist/src/pages/window.js +30 -0
- package/dist/src/public.js +24 -0
- package/dist/src/server.js +36 -14
- package/package.json +3 -1
- package/plugins/callout/index.ts +3 -1
- package/plugins/callout/public/style.css +30 -0
- package/plugins/chat/autosize.ts +43 -9
- package/plugins/chat/client.tsx +22 -5
- package/plugins/chat/index.ts +22 -8
- package/plugins/chat/public/style.css +98 -0
- package/plugins/claude-code/index.ts +49 -14
- package/plugins/code/diff.ts +28 -8
- package/plugins/code/index.ts +30 -20
- package/plugins/code/public/style.css +68 -0
- package/plugins/comments/client.ts +139 -71
- package/plugins/comments/index.ts +9 -7
- package/plugins/comments/public/style.css +185 -0
- package/plugins/details/index.ts +7 -2
- package/plugins/details/public/style.css +7 -0
- package/plugins/forge/index.ts +16 -3
- package/plugins/form/index.ts +75 -27
- package/plugins/form/public/style.css +126 -0
- package/plugins/gallery/client.tsx +9 -3
- package/plugins/gallery/index.ts +31 -9
- package/plugins/gallery/public/style.css +90 -0
- package/plugins/grid/index.ts +19 -5
- package/plugins/grid/public/style.css +71 -0
- package/plugins/iframe/index.ts +20 -23
- package/plugins/iframe/public/style.css +13 -0
- package/plugins/index.ts +16 -1
- package/plugins/mermaid/index.ts +3 -1
- package/plugins/mermaid/{style.css → public/style.css} +7 -2
- package/plugins/terminal/client.ts +105 -48
- package/plugins/terminal/host.ts +131 -29
- package/plugins/terminal/index.ts +84 -25
- package/plugins/terminal/public/style.css +225 -0
- package/plugins/terminal/server.ts +64 -13
- package/plugins/terminal/sizes.ts +13 -3
- package/plugins/toc/client.ts +45 -26
- package/plugins/toc/index.ts +9 -6
- package/plugins/toc/public/style.css +93 -0
- package/plugins/window/README.md +29 -0
- package/plugins/window/index.ts +85 -0
- package/skills/whiteboard/SKILL.md +3 -1
- package/solid/index.tsx +24 -9
- package/src/auth.ts +25 -7
- package/src/client/forms.ts +74 -28
- package/src/client/markdown.ts +15 -4
- package/src/client/page/base.css +1078 -199
- package/src/client/page/elsewhere.ts +32 -15
- package/src/client/page/fresh.ts +91 -23
- package/src/client/page/hold.ts +11 -2
- package/src/client/page/live.ts +10 -6
- package/src/client/page/main.ts +106 -36
- package/src/client/page/orphans.ts +25 -10
- package/src/client/page/sort.ts +14 -4
- package/src/client/page/sticky.ts +11 -3
- package/src/client/page/theme.ts +11 -7
- package/src/client/page/waiting.ts +141 -34
- package/src/client/page/window.ts +40 -0
- package/src/client/reactive.ts +19 -0
- package/src/client/read.ts +17 -10
- package/src/client/runtime.ts +130 -35
- package/src/client/scroll.ts +14 -4
- package/src/client/toast.ts +19 -5
- package/src/config.ts +20 -5
- package/src/define.ts +65 -25
- package/src/events.ts +111 -24
- package/src/html.ts +6 -2
- package/src/icons.ts +4 -2
- package/src/load.ts +10 -2
- package/src/loader.ts +75 -11
- package/src/package.ts +9 -8
- package/src/pages/blocks.ts +20 -14
- package/src/pages/markdown.ts +113 -34
- package/src/pages/render.ts +199 -39
- package/src/pages/window.ts +71 -0
- package/src/plugins.ts +90 -24
- package/src/public.ts +39 -0
- package/src/running.ts +8 -2
- package/src/serve.ts +29 -7
- package/src/server.ts +348 -107
- package/src/status.ts +15 -9
- package/dist/plugins/callout/style.css +0 -12
- package/dist/plugins/chat/style.css +0 -24
- package/dist/plugins/code/style.css +0 -29
- package/dist/plugins/comments/client.js +0 -10
- package/dist/plugins/comments/style.css +0 -40
- package/dist/plugins/details/style.css +0 -3
- package/dist/plugins/form/style.css +0 -44
- package/dist/plugins/gallery/client.js +0 -1
- package/dist/plugins/gallery/style.css +0 -27
- package/dist/plugins/grid/style.css +0 -25
- package/dist/plugins/iframe/client.js +0 -1
- package/dist/plugins/iframe/style.css +0 -29
- package/dist/plugins/toc/client.js +0 -1
- package/dist/plugins/toc/style.css +0 -19
- package/plugins/callout/style.css +0 -12
- package/plugins/chat/style.css +0 -24
- package/plugins/code/style.css +0 -29
- package/plugins/comments/style.css +0 -40
- package/plugins/details/style.css +0 -3
- package/plugins/form/style.css +0 -44
- package/plugins/gallery/style.css +0 -27
- package/plugins/grid/style.css +0 -25
- package/plugins/iframe/client.ts +0 -46
- package/plugins/iframe/style.css +0 -29
- package/plugins/terminal/style.css +0 -71
- package/plugins/toc/style.css +0 -19
- /package/dist/plugins/terminal/{client.js → public/client.js} +0 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// A window around a block: a header with its label (or an address), a button that opens what it
|
|
2
|
+
// shows on its own (an address, an image), and one that fills the browser window with it (the page
|
|
3
|
+
// does that: src/client/page/window.ts; the same button, or Esc, puts it back). The iframe block
|
|
4
|
+
// is one around a page, `:::window` one around any markdown; any block can draw one.
|
|
5
|
+
import { html, raw, type Html } from '../html.ts'
|
|
6
|
+
|
|
7
|
+
// the header's buttons, as icons
|
|
8
|
+
const svg = (d: string) =>
|
|
9
|
+
raw(
|
|
10
|
+
`<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${d}</svg>`,
|
|
11
|
+
)
|
|
12
|
+
const OPEN = svg(
|
|
13
|
+
'<path d="M9 2.5h4.5V7M13.5 2.5 7.5 8.5M11.5 9.5v3a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1h3"/>',
|
|
14
|
+
)
|
|
15
|
+
const MAXIMIZE = svg('<path d="M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10"/>')
|
|
16
|
+
const RESTORE = svg('<path d="M6 2.5V6H2.5M13.5 6H10V2.5M10 13.5V10h3.5M2.5 10H6v3.5"/>')
|
|
17
|
+
|
|
18
|
+
export interface WindowOptions {
|
|
19
|
+
/** what the window shows, as HTML */
|
|
20
|
+
body: Html | string
|
|
21
|
+
/** its label, as HTML (a block's label); without one, the header shows `address` */
|
|
22
|
+
label?: Html | string | null
|
|
23
|
+
/** what it shows on its own: an address, an image's; the ↗ button opens it, and hovering the label shows it */
|
|
24
|
+
open?: string | null
|
|
25
|
+
/** wider than the text column */
|
|
26
|
+
wide?: boolean
|
|
27
|
+
/** no header: the window alone, without its buttons */
|
|
28
|
+
bare?: boolean
|
|
29
|
+
/** a class for its body, and a height for it (a CSS length), for what has none of its own (an iframe) */
|
|
30
|
+
bodyClass?: string
|
|
31
|
+
height?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A window around a block's HTML: see the top of this file. */
|
|
35
|
+
export function windowFrame({
|
|
36
|
+
body,
|
|
37
|
+
label = null,
|
|
38
|
+
open = null,
|
|
39
|
+
wide = false,
|
|
40
|
+
bare = false,
|
|
41
|
+
bodyClass = '',
|
|
42
|
+
height,
|
|
43
|
+
}: WindowOptions): Html {
|
|
44
|
+
const name =
|
|
45
|
+
label != null && String(label) !== ''
|
|
46
|
+
? html`<span class="wb-window-title">${raw(String(label))}</span>`
|
|
47
|
+
: open
|
|
48
|
+
? html`<span class="wb-window-address">${open}</span>`
|
|
49
|
+
: html``
|
|
50
|
+
const header =
|
|
51
|
+
!bare &&
|
|
52
|
+
html`<div class="wb-window-bar">
|
|
53
|
+
<span class="wb-window-name" ${open ? html` title="${open}"` : ''}>${name}</span>
|
|
54
|
+
${open && html`<a class="wb-window-button" href="${open}" target="_blank" rel="noopener" title="Open on its own" aria-label="Open on its own">${OPEN}</a>`}
|
|
55
|
+
<button
|
|
56
|
+
type="button"
|
|
57
|
+
class="wb-window-button"
|
|
58
|
+
data-wb-maximize
|
|
59
|
+
title="Fill the window"
|
|
60
|
+
aria-label="Fill the window"
|
|
61
|
+
>
|
|
62
|
+
<span class="wb-window-max">${MAXIMIZE}</span><span class="wb-window-restore">${RESTORE}</span>
|
|
63
|
+
</button>
|
|
64
|
+
</div>`
|
|
65
|
+
return html`<div class="wb-window${wide && raw(' wb-wide')}">
|
|
66
|
+
${header}
|
|
67
|
+
<div class="wb-window-body${bodyClass && raw(' ' + bodyClass)}" ${height ? html` style="height: ${height}"` : ''}>
|
|
68
|
+
${raw(String(body))}
|
|
69
|
+
</div>
|
|
70
|
+
</div>`
|
|
71
|
+
}
|
package/src/plugins.ts
CHANGED
|
@@ -42,7 +42,8 @@ const TYPES: Record<BaseType, (v: unknown) => boolean> = {
|
|
|
42
42
|
function parseType(spec: FieldType | string, where: string): { type: BaseType; optional: boolean } {
|
|
43
43
|
const optional = spec.endsWith('?')
|
|
44
44
|
const type = optional ? spec.slice(0, -1) : spec
|
|
45
|
-
if (!(type in TYPES))
|
|
45
|
+
if (!(type in TYPES))
|
|
46
|
+
throw new Error(`${where}: unknown type "${spec}" (one of ${Object.keys(TYPES).join(', ')}, with ? when optional)`)
|
|
46
47
|
return { type: type as BaseType, optional }
|
|
47
48
|
}
|
|
48
49
|
|
|
@@ -52,7 +53,10 @@ function checkFields(spec: Record<string, FieldType> = {}, input: unknown = {},
|
|
|
52
53
|
const value = input as Record<string, unknown>
|
|
53
54
|
for (const [name, s] of Object.entries(spec)) {
|
|
54
55
|
const { type, optional } = parseType(s, where)
|
|
55
|
-
if (value[name] === undefined) {
|
|
56
|
+
if (value[name] === undefined) {
|
|
57
|
+
if (!optional) return `${where}: ${name} is missing`
|
|
58
|
+
continue
|
|
59
|
+
}
|
|
56
60
|
if (!TYPES[type](value[name])) return `${where}: ${name} must be ${type}`
|
|
57
61
|
}
|
|
58
62
|
for (const name of Object.keys(value)) if (!(name in spec)) return `${where}: unknown field ${name}`
|
|
@@ -81,10 +85,12 @@ export function mountRoutes(name: string, routes: Record<string, Route> = {}): M
|
|
|
81
85
|
const m = ROUTE.exec(key)
|
|
82
86
|
if (!m) throw new Error(`plugin ${name}: route "${key}" must look like "GET /path"`)
|
|
83
87
|
if (typeof route?.run !== 'function') throw new Error(`plugin ${name}: route "${key}" has no run function`)
|
|
84
|
-
for (const [field, spec] of Object.entries({ ...route.body, ...route.query }))
|
|
88
|
+
for (const [field, spec] of Object.entries({ ...route.body, ...route.query }))
|
|
89
|
+
parseType(spec, `plugin ${name}, route "${key}", ${field}`)
|
|
85
90
|
const [, method, at] = m as unknown as [string, string, string]
|
|
86
91
|
const path = `/api/${name}${at === '/' ? '' : at.replace(/\/$/, '')}`
|
|
87
|
-
if (table.some(r => r.method === method && r.path === path))
|
|
92
|
+
if (table.some(r => r.method === method && r.path === path))
|
|
93
|
+
throw new Error(`plugin ${name}: route "${key}" is declared twice`)
|
|
88
94
|
table.push({ method, path, route, plugin: name })
|
|
89
95
|
}
|
|
90
96
|
return table
|
|
@@ -93,8 +99,20 @@ export function mountRoutes(name: string, routes: Record<string, Route> = {}): M
|
|
|
93
99
|
function readJson(req: IncomingMessage): Promise<unknown> {
|
|
94
100
|
return new Promise((resolve, reject) => {
|
|
95
101
|
let body = ''
|
|
96
|
-
req.on('data', (c: Buffer) => {
|
|
97
|
-
|
|
102
|
+
req.on('data', (c: Buffer) => {
|
|
103
|
+
body += c
|
|
104
|
+
if (body.length > 1e6) {
|
|
105
|
+
reject(new Error('body too large'))
|
|
106
|
+
req.destroy()
|
|
107
|
+
}
|
|
108
|
+
})
|
|
109
|
+
req.on('end', () => {
|
|
110
|
+
try {
|
|
111
|
+
resolve(body ? JSON.parse(body) : {})
|
|
112
|
+
} catch {
|
|
113
|
+
reject(new Error('the body is not JSON'))
|
|
114
|
+
}
|
|
115
|
+
})
|
|
98
116
|
req.on('error', reject)
|
|
99
117
|
})
|
|
100
118
|
}
|
|
@@ -110,29 +128,56 @@ const json = (res: ServerResponse, status: number, data: unknown) => {
|
|
|
110
128
|
* JSON; a stream route (`stream: true`) writes to `res` itself. An error it throws is sent with its
|
|
111
129
|
* `status` (default 500).
|
|
112
130
|
*/
|
|
113
|
-
export async function dispatch(
|
|
131
|
+
export async function dispatch(
|
|
132
|
+
table: MountedRoute[],
|
|
133
|
+
req: IncomingMessage,
|
|
134
|
+
res: ServerResponse,
|
|
135
|
+
url: URL,
|
|
136
|
+
authorized: (req: IncomingMessage) => boolean,
|
|
137
|
+
): Promise<boolean> {
|
|
114
138
|
const forPath = table.filter(r => r.path === url.pathname)
|
|
115
139
|
if (!forPath.length) return false
|
|
116
140
|
const hit = forPath.find(r => r.method === req.method)
|
|
117
|
-
if (!hit) {
|
|
141
|
+
if (!hit) {
|
|
142
|
+
res.setHeader('allow', forPath.map(r => r.method).join(', '))
|
|
143
|
+
json(res, 405, { error: `use ${forPath.map(r => r.method).join(' or ')}` })
|
|
144
|
+
return true
|
|
145
|
+
}
|
|
118
146
|
const { route } = hit
|
|
119
|
-
if (route.auth && !authorized(req)) {
|
|
147
|
+
if (route.auth && !authorized(req)) {
|
|
148
|
+
json(res, 403, {
|
|
149
|
+
error: "this needs the project's token: open a link from the command line, or send x-whiteboard-token",
|
|
150
|
+
})
|
|
151
|
+
return true
|
|
152
|
+
}
|
|
120
153
|
try {
|
|
121
154
|
const query = fromQuery(route.query, url.searchParams)
|
|
122
155
|
const queryError = route.query ? checkFields(route.query, query, 'query') : null
|
|
123
|
-
if (queryError) {
|
|
156
|
+
if (queryError) {
|
|
157
|
+
json(res, 400, { error: queryError })
|
|
158
|
+
return true
|
|
159
|
+
}
|
|
124
160
|
let body: Record<string, unknown> = {}
|
|
125
161
|
if (hit.method !== 'GET' && hit.method !== 'DELETE') {
|
|
126
162
|
const input = await readJson(req)
|
|
127
163
|
const bodyError = checkFields(route.body, input, 'body')
|
|
128
|
-
if (bodyError) {
|
|
164
|
+
if (bodyError) {
|
|
165
|
+
json(res, 400, { error: bodyError })
|
|
166
|
+
return true
|
|
167
|
+
}
|
|
129
168
|
body = input as Record<string, unknown>
|
|
130
169
|
}
|
|
131
|
-
if (route.stream) {
|
|
170
|
+
if (route.stream) {
|
|
171
|
+
await route.run({ body, query, req, res })
|
|
172
|
+
return true
|
|
173
|
+
}
|
|
132
174
|
const out = await route.run({ body, query, req })
|
|
133
175
|
json(res, 200, out ?? { ok: true })
|
|
134
176
|
} catch (err) {
|
|
135
|
-
if (res.headersSent) {
|
|
177
|
+
if (res.headersSent) {
|
|
178
|
+
res.end()
|
|
179
|
+
return true
|
|
180
|
+
}
|
|
136
181
|
const e = err as { status?: number; message?: string } | null
|
|
137
182
|
json(res, e?.status ?? 500, { error: e?.message ?? String(err) })
|
|
138
183
|
}
|
|
@@ -140,10 +185,16 @@ export async function dispatch(table: MountedRoute[], req: IncomingMessage, res:
|
|
|
140
185
|
}
|
|
141
186
|
|
|
142
187
|
/** The routes for the docs: method, path, what it does, what it takes. */
|
|
143
|
-
export const describeRoutes = (table: MountedRoute[]) =>
|
|
144
|
-
method, path,
|
|
145
|
-
|
|
146
|
-
|
|
188
|
+
export const describeRoutes = (table: MountedRoute[]) =>
|
|
189
|
+
table.map(({ method, path, route }) => ({
|
|
190
|
+
method,
|
|
191
|
+
path,
|
|
192
|
+
description: route.description ?? '',
|
|
193
|
+
auth: !!route.auth,
|
|
194
|
+
stream: !!route.stream,
|
|
195
|
+
body: route.body ?? null,
|
|
196
|
+
query: route.query ?? null,
|
|
197
|
+
}))
|
|
147
198
|
|
|
148
199
|
// ---- commands ----------------------------------------------------------------------------------
|
|
149
200
|
|
|
@@ -175,19 +226,34 @@ export function parseCommandArgs(command: Command, all: string[], name: string)
|
|
|
175
226
|
const cut = all.indexOf('--')
|
|
176
227
|
const args = cut < 0 ? all : all.slice(0, cut)
|
|
177
228
|
const rest = cut < 0 ? [] : all.slice(cut + 1)
|
|
178
|
-
if (rest.length && !command.rest)
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
229
|
+
if (rest.length && !command.rest)
|
|
230
|
+
throw new Error(`whiteboard ${name} takes nothing after --\nusage: whiteboard ${name} ${usage(command)}`)
|
|
231
|
+
const options: ParseArgsOptionsConfig = Object.fromEntries(
|
|
232
|
+
Object.entries(command.options ?? {}).map(([key, o]) => {
|
|
233
|
+
const { type } = parseType(o.type, key)
|
|
234
|
+
return [
|
|
235
|
+
key,
|
|
236
|
+
{
|
|
237
|
+
type: type === 'boolean' ? ('boolean' as const) : ('string' as const),
|
|
238
|
+
...(o.short ? { short: o.short } : {}),
|
|
239
|
+
},
|
|
240
|
+
]
|
|
241
|
+
}),
|
|
242
|
+
)
|
|
183
243
|
let parsed
|
|
184
|
-
try {
|
|
244
|
+
try {
|
|
245
|
+
parsed = parseArgs({ args, options, allowPositionals: true, strict: true })
|
|
246
|
+
} catch (err) {
|
|
185
247
|
throw new Error(`${(err as Error).message}\nusage: whiteboard ${name} ${usage(command)}`)
|
|
186
248
|
}
|
|
187
249
|
const values: Record<string, unknown> = { ...parsed.values }
|
|
188
250
|
for (const [key, o] of Object.entries(command.options ?? {})) {
|
|
189
251
|
const { type, optional } = parseType(o.type, key)
|
|
190
|
-
if (values[key] === undefined) {
|
|
252
|
+
if (values[key] === undefined) {
|
|
253
|
+
if (!optional && type !== 'boolean')
|
|
254
|
+
throw new Error(`--${key} is missing\nusage: whiteboard ${name} ${usage(command)}`)
|
|
255
|
+
continue
|
|
256
|
+
}
|
|
191
257
|
if (type === 'number') {
|
|
192
258
|
values[key] = Number(values[key])
|
|
193
259
|
if (!Number.isFinite(values[key])) throw new Error(`--${key} must be a number`)
|
package/src/public.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// A plugin's public folder: the one place its browser files are served from (its client modules,
|
|
2
|
+
// stylesheets, images, fonts; TypeScript there is served with its types stripped). The server
|
|
3
|
+
// serves what is inside a plugin's public folder, and nothing else of the plugin: not its server
|
|
4
|
+
// code, not the project's files beside it.
|
|
5
|
+
//
|
|
6
|
+
// A plugin says where (`public`); definePlugin defaults it to `public/` next to the module that
|
|
7
|
+
// calls it; a plugin that is a plain object (one written inline in the config, say) has the
|
|
8
|
+
// project's `.whiteboard/public/`. Its files (`client`, `style`, a block's) are named within it.
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
import { fileURLToPath } from 'node:url'
|
|
11
|
+
import type { Plugin } from './define.ts'
|
|
12
|
+
|
|
13
|
+
const asPath = (ref: URL | string): string => (ref instanceof URL || ref.startsWith('file:') ? fileURLToPath(ref) : ref)
|
|
14
|
+
|
|
15
|
+
/** The folder a plugin's browser files are served from. */
|
|
16
|
+
export function publicDirOf(plugin: Plugin, wb: string): string {
|
|
17
|
+
return path.resolve(plugin.public != null ? asPath(plugin.public) : path.join(wb, 'public'))
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Is `file` inside `dir`? */
|
|
21
|
+
export const within = (file: string, dir: string): boolean => {
|
|
22
|
+
const rel = path.relative(dir, file)
|
|
23
|
+
return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A file a plugin names, as a path: a name within its public folder (`style.css`,
|
|
28
|
+
* `client/main.js`), or a URL or absolute path, which must be inside it. Anything else is an
|
|
29
|
+
* error, said when the config loads, rather than a file that quietly isn't served.
|
|
30
|
+
*/
|
|
31
|
+
export function inPublic(dir: string, ref: URL | string, what: string): string {
|
|
32
|
+
const file =
|
|
33
|
+
typeof ref === 'string' && !ref.startsWith('file:') && !path.isAbsolute(ref)
|
|
34
|
+
? path.resolve(dir, ref)
|
|
35
|
+
: path.resolve(asPath(ref))
|
|
36
|
+
if (!within(file, dir))
|
|
37
|
+
throw new Error(`${what}: ${file} is not in its public folder (${dir}); a plugin's browser files live there`)
|
|
38
|
+
return file
|
|
39
|
+
}
|
package/src/running.ts
CHANGED
|
@@ -6,7 +6,11 @@ import type { Project } from './config.ts'
|
|
|
6
6
|
|
|
7
7
|
/** The port the last server of this project recorded, or null. */
|
|
8
8
|
export function recordedPort(project: Project): number | null {
|
|
9
|
-
try {
|
|
9
|
+
try {
|
|
10
|
+
return Number(JSON.parse(fs.readFileSync(project.serverFile, 'utf8')).port) || null
|
|
11
|
+
} catch {
|
|
12
|
+
return null
|
|
13
|
+
}
|
|
10
14
|
}
|
|
11
15
|
|
|
12
16
|
/** The base URL of this project's running server, or null. `except`: a process to not count (the asking server itself). */
|
|
@@ -18,5 +22,7 @@ export async function runningServer(project: Project, { except }: { except?: num
|
|
|
18
22
|
const res = await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(800) })
|
|
19
23
|
const health = res.ok ? await res.json() : null
|
|
20
24
|
return health?.dir === project.dir && health.pid !== except ? base : null
|
|
21
|
-
} catch {
|
|
25
|
+
} catch {
|
|
26
|
+
return null
|
|
27
|
+
}
|
|
22
28
|
}
|
package/src/serve.ts
CHANGED
|
@@ -19,12 +19,26 @@ export async function start(project: Project): Promise<number> {
|
|
|
19
19
|
fs.mkdirSync(project.pagesDir, { recursive: true })
|
|
20
20
|
const wb = createServer(project)
|
|
21
21
|
await wb.config()
|
|
22
|
-
const server = http.createServer((req, res) => {
|
|
23
|
-
|
|
22
|
+
const server = http.createServer((req, res) => {
|
|
23
|
+
void wb.handle(req, res)
|
|
24
|
+
})
|
|
25
|
+
const candidates = [
|
|
26
|
+
...new Set(
|
|
27
|
+
[recordedPort(project), DEFAULT_PORT, ...Array.from({ length: 50 }, (_, i) => DEFAULT_PORT + 1 + i)].filter(
|
|
28
|
+
(p): p is number => !!p,
|
|
29
|
+
),
|
|
30
|
+
),
|
|
31
|
+
]
|
|
24
32
|
for (const port of candidates) {
|
|
25
33
|
const ok = await new Promise<boolean>((resolve, reject) => {
|
|
26
|
-
const onError = (err: NodeJS.ErrnoException) => {
|
|
27
|
-
|
|
34
|
+
const onError = (err: NodeJS.ErrnoException) => {
|
|
35
|
+
server.off('listening', onListening)
|
|
36
|
+
err.code === 'EADDRINUSE' ? resolve(false) : reject(err)
|
|
37
|
+
}
|
|
38
|
+
const onListening = () => {
|
|
39
|
+
server.off('error', onError)
|
|
40
|
+
resolve(true)
|
|
41
|
+
}
|
|
28
42
|
server.once('error', onError)
|
|
29
43
|
server.once('listening', onListening)
|
|
30
44
|
server.listen(port, '127.0.0.1')
|
|
@@ -32,15 +46,23 @@ export async function start(project: Project): Promise<number> {
|
|
|
32
46
|
if (!ok) continue
|
|
33
47
|
fs.writeFileSync(project.serverFile, JSON.stringify({ port, pid: process.pid }, null, 2) + '\n')
|
|
34
48
|
// the command that started this server waits for it; others can now find it
|
|
35
|
-
try {
|
|
49
|
+
try {
|
|
50
|
+
fs.unlinkSync(path.join(project.wb, 'server.lock'))
|
|
51
|
+
} catch {}
|
|
36
52
|
const cleanup = () => {
|
|
37
|
-
try {
|
|
53
|
+
try {
|
|
54
|
+
if (JSON.parse(fs.readFileSync(project.serverFile, 'utf8')).pid === process.pid)
|
|
55
|
+
fs.unlinkSync(project.serverFile)
|
|
56
|
+
} catch {}
|
|
38
57
|
}
|
|
39
58
|
process.on('exit', cleanup)
|
|
40
59
|
// one server per project: should another have started at the same moment, whichever one
|
|
41
60
|
// server.json names last stays, and the others leave (their clients reconnect to it)
|
|
42
61
|
const yieldToOther = async () => {
|
|
43
|
-
if (await runningServer(project, { except: process.pid })) {
|
|
62
|
+
if (await runningServer(project, { except: process.pid })) {
|
|
63
|
+
console.log('whiteboard: another server of this project took over')
|
|
64
|
+
process.exit(0)
|
|
65
|
+
}
|
|
44
66
|
}
|
|
45
67
|
setTimeout(yieldToOther, 1500).unref()
|
|
46
68
|
setInterval(yieldToOther, 30000).unref()
|