@venizia/vulcan 0.4.10-0 → 0.4.10-2
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/base/claude/events.json +0 -1
- package/base/hooks/event.ts +4 -3
- package/base/hooks/guard-outside.ts +34 -15
- package/base/hooks/guard-remote-hosts.ts +13 -4
- package/base/rules.md +1 -1
- package/base/skills/build-a-feature/SKILL.md +11 -2
- package/base/skills/review-a-change/SKILL.md +10 -6
- package/base/skills/ship/SKILL.md +9 -4
- package/base/templates/board.html +844 -4240
- package/base/templates/pull-request.md +31 -0
- package/base/templates/trusted-hosts.local.example +11 -0
- package/base/templates/vulcan.config.mts +1 -0
- package/package.json +6 -4
- package/src/board/agent-setting.ts +43 -0
- package/src/board/command.ts +138 -17
- package/src/board/common/constants.ts +38 -1
- package/src/board/common/types.ts +40 -1
- package/src/board/fold.ts +106 -12
- package/src/board/github.ts +6 -3
- package/src/board/index.ts +2 -0
- package/src/board/schema.ts +32 -0
- package/src/board/server.ts +325 -0
- package/src/board/settings.ts +99 -17
- package/src/board/watch.ts +88 -0
- package/src/commands/help.command.ts +4 -3
- package/src/commands/init.command.ts +26 -1
- package/src/common/constants.ts +8 -0
- package/src/common/git-files.ts +11 -0
- package/src/common/index.ts +1 -0
- package/src/common/layout-folder.ts +1 -1
- package/src/config/schema.ts +33 -19
- package/src/create/common/constants.ts +1 -0
- package/src/create/dockerignore.ts +5 -3
- package/src/create/init-monorepo.ts +28 -4
- package/src/create/project-key.ts +60 -0
- package/src/create/workspace.ts +2 -1
- package/src/doctor/checks.ts +89 -2
- package/src/doctor/common/constants.ts +48 -0
- package/src/doctor/common/types.ts +2 -1
- package/src/doctor/index.ts +2 -0
- package/src/doctor/private-values.ts +108 -0
- package/src/doctor/runner.ts +4 -0
- package/src/doctor/schema.ts +29 -0
- package/src/events/actor.ts +10 -5
- package/src/events/command.ts +225 -22
- package/src/events/common/constants.ts +100 -6
- package/src/events/common/types.ts +22 -0
- package/src/events/flow-id.ts +89 -0
- package/src/events/flow.ts +4 -4
- package/src/events/hook.ts +53 -6
- package/src/events/index.ts +2 -0
- package/src/events/log.ts +115 -7
- package/src/events/project-key.ts +22 -0
- package/src/events/retention.ts +2 -4
- package/src/events/settings.ts +16 -0
- package/src/events/text.ts +23 -0
- package/src/hooks/host-pattern.ts +17 -0
- package/src/hooks/remote-hosts.ts +39 -7
- package/src/init/common/constants.ts +1 -0
- package/src/init/scaffold.ts +39 -7
- package/src/manifest/render.ts +5 -1
- package/src/router.ts +11 -2
- package/src/sync/claude-launch.ts +62 -7
- package/src/wiki/source-links.ts +5 -4
package/src/board/fold.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
EventActorNames,
|
|
3
|
+
EventKinds,
|
|
4
|
+
EventSources,
|
|
5
|
+
EventStatuses,
|
|
6
|
+
} from '../events/common/index.ts';
|
|
2
7
|
import type { IEvent } from '../events/common/index.ts';
|
|
3
8
|
import {
|
|
4
9
|
BoardConstants,
|
|
@@ -13,6 +18,7 @@ import type {
|
|
|
13
18
|
IBoardDecision,
|
|
14
19
|
IBoardEvent,
|
|
15
20
|
IBoardFlow,
|
|
21
|
+
IBoardItem,
|
|
16
22
|
TBoardState,
|
|
17
23
|
} from './common/index.ts';
|
|
18
24
|
|
|
@@ -20,6 +26,7 @@ const PR_NUMBER = /^#?(\d+)$/;
|
|
|
20
26
|
/** A `pr` line with this ref says the pull request was merged: `--ref merged:12`. */
|
|
21
27
|
const MERGED_REF = /^merged:#?(\d+)$/;
|
|
22
28
|
const TO_PREFIX = 'to:';
|
|
29
|
+
const FROM_PREFIX = 'from:';
|
|
23
30
|
/** Kinds that take the stage the flow is at when they happen: a message belongs to the stage it was sent in. */
|
|
24
31
|
const CARRY_KINDS: string[] = [BoardKinds.MSG, BoardKinds.NOTE];
|
|
25
32
|
|
|
@@ -159,9 +166,25 @@ export class BoardFold {
|
|
|
159
166
|
|
|
160
167
|
case EventKinds.MSG_SENT:
|
|
161
168
|
case EventKinds.MSG_RECEIVED: {
|
|
162
|
-
const
|
|
169
|
+
const isIncoming = line.kind === EventKinds.MSG_RECEIVED;
|
|
170
|
+
// A received line has a sender, never a recipient: the page reads `to` as who the message went to.
|
|
171
|
+
const to =
|
|
172
|
+
!isIncoming && line.ref?.startsWith(TO_PREFIX)
|
|
173
|
+
? line.ref.slice(TO_PREFIX.length)
|
|
174
|
+
: undefined;
|
|
175
|
+
const from =
|
|
176
|
+
isIncoming && line.ref?.startsWith(FROM_PREFIX)
|
|
177
|
+
? line.ref.slice(FROM_PREFIX.length)
|
|
178
|
+
: undefined;
|
|
163
179
|
|
|
164
|
-
return {
|
|
180
|
+
return {
|
|
181
|
+
...base,
|
|
182
|
+
kind: BoardKinds.MSG,
|
|
183
|
+
stage: -1,
|
|
184
|
+
...(to === undefined ? {} : { to }),
|
|
185
|
+
...(isIncoming ? { incoming: true } : {}),
|
|
186
|
+
...(from === undefined || from === '' ? {} : { from }),
|
|
187
|
+
};
|
|
165
188
|
}
|
|
166
189
|
|
|
167
190
|
case EventKinds.NEEDS_OWNER: {
|
|
@@ -178,9 +201,20 @@ export class BoardFold {
|
|
|
178
201
|
stage: BoardStages.REQUEST,
|
|
179
202
|
isTitle: true,
|
|
180
203
|
...(line.why === undefined ? {} : { why: line.why }),
|
|
204
|
+
...(line.context === undefined ? {} : { context: line.context }),
|
|
205
|
+
...(line.next === undefined ? {} : { next: line.next }),
|
|
206
|
+
...(line.steps === undefined ? {} : { steps: line.steps }),
|
|
207
|
+
...(line.checks === undefined ? {} : { checks: line.checks }),
|
|
208
|
+
...(line.apps === undefined ? {} : { apps: line.apps }),
|
|
209
|
+
...(line.due === undefined ? {} : { due: line.due }),
|
|
210
|
+
...(line.ref === undefined ? {} : { tracker: line.ref }),
|
|
181
211
|
};
|
|
182
212
|
}
|
|
183
213
|
|
|
214
|
+
case EventKinds.DEPLOY: {
|
|
215
|
+
return { ...base, kind: BoardKinds.RELEASE, stage: BoardStages.RELEASE };
|
|
216
|
+
}
|
|
217
|
+
|
|
184
218
|
case EventKinds.SESSION_START:
|
|
185
219
|
case EventKinds.SESSION_STOP:
|
|
186
220
|
case EventKinds.SUBAGENT_STOP: {
|
|
@@ -204,34 +238,77 @@ export class BoardFold {
|
|
|
204
238
|
}
|
|
205
239
|
}
|
|
206
240
|
|
|
241
|
+
/** When the agent's current stretch in `state` began: kept while it stays in the state and the lines come within the active gap. */
|
|
242
|
+
private static sinceOf(opts: {
|
|
243
|
+
known: IBoardAgent | undefined;
|
|
244
|
+
state: IBoardAgent['state'] | undefined;
|
|
245
|
+
ts: string;
|
|
246
|
+
}): string {
|
|
247
|
+
const { known } = opts;
|
|
248
|
+
|
|
249
|
+
if (
|
|
250
|
+
known === undefined ||
|
|
251
|
+
known.state !== opts.state ||
|
|
252
|
+
Date.parse(opts.ts) - Date.parse(known.checkedAt) > BoardConstants.ACTIVE_GAP_MS
|
|
253
|
+
) {
|
|
254
|
+
return opts.ts;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return known.since;
|
|
258
|
+
}
|
|
259
|
+
|
|
207
260
|
private static moveAgent(opts: { agents: Record<string, IBoardAgent>; line: IEvent }): void {
|
|
208
261
|
const { agents, line } = opts;
|
|
209
262
|
const known = agents[line.actor];
|
|
210
263
|
|
|
211
|
-
|
|
264
|
+
// A session with no name of its own is no agent: its lines stay in their flows, and it has no card.
|
|
265
|
+
// A message the agent got is not a line of its own: it moves neither its state nor its time.
|
|
266
|
+
if (
|
|
267
|
+
!EventActorNames.isNamed({ actor: line.actor }) ||
|
|
268
|
+
line.kind === EventKinds.SUBAGENT_STOP ||
|
|
269
|
+
line.kind === EventKinds.MSG_RECEIVED ||
|
|
270
|
+
BoardFold.isHarnessAsk({ line })
|
|
271
|
+
) {
|
|
212
272
|
return;
|
|
213
273
|
}
|
|
214
274
|
|
|
215
|
-
if (
|
|
216
|
-
|
|
275
|
+
if (
|
|
276
|
+
line.kind === EventKinds.SESSION_START ||
|
|
277
|
+
line.kind === EventKinds.SESSION_STOP ||
|
|
278
|
+
line.kind === EventKinds.TOOL_TICK
|
|
279
|
+
) {
|
|
280
|
+
const state = line.kind === EventKinds.SESSION_STOP ? 'idle' : 'working';
|
|
281
|
+
|
|
282
|
+
// The model is what the session start said, and the harness is the hook that wrote it; both stay until a start says another.
|
|
283
|
+
const isHook = line.source === EventSources.CLAUDE_HOOK;
|
|
284
|
+
const model =
|
|
285
|
+
line.kind === EventKinds.SESSION_START ? (line.model ?? known?.model) : known?.model;
|
|
286
|
+
const harness = isHook ? BoardConstants.HARNESS_CLAUDE : known?.harness;
|
|
217
287
|
|
|
218
288
|
agents[line.actor] = {
|
|
219
289
|
name: line.actor,
|
|
220
290
|
state,
|
|
221
291
|
current: known?.current ?? '',
|
|
222
|
-
since: known
|
|
292
|
+
since: BoardFold.sinceOf({ known, state, ts: line.ts }),
|
|
223
293
|
checkedAt: line.ts,
|
|
294
|
+
...(model === undefined ? {} : { model }),
|
|
295
|
+
...(harness === undefined ? {} : { harness }),
|
|
224
296
|
};
|
|
225
297
|
|
|
226
298
|
return;
|
|
227
299
|
}
|
|
228
300
|
|
|
301
|
+
// A line of work after a stop means the agent is at it again.
|
|
302
|
+
const wakes = known?.state === 'idle';
|
|
303
|
+
|
|
229
304
|
agents[line.actor] = {
|
|
230
305
|
name: line.actor,
|
|
231
|
-
state: known?.state ?? 'working',
|
|
306
|
+
state: wakes ? 'working' : (known?.state ?? 'working'),
|
|
232
307
|
current: line.summary,
|
|
233
|
-
since: known?.
|
|
308
|
+
since: BoardFold.sinceOf({ known, state: wakes ? 'working' : known?.state, ts: line.ts }),
|
|
234
309
|
checkedAt: line.ts,
|
|
310
|
+
...(known?.model === undefined ? {} : { model: known.model }),
|
|
311
|
+
...(known?.harness === undefined ? {} : { harness: known.harness }),
|
|
235
312
|
};
|
|
236
313
|
}
|
|
237
314
|
|
|
@@ -331,11 +408,18 @@ export class BoardFold {
|
|
|
331
408
|
};
|
|
332
409
|
}
|
|
333
410
|
|
|
334
|
-
/** The
|
|
411
|
+
/** The heading a `flow` line gives: title, reason, context and next step. The newest line wins as a whole: a newer line that leaves a field out drops the old one, so no stale text outlives the line that wrote it. */
|
|
335
412
|
private static headingOf(opts: { named: IBoardEvent | undefined }): {
|
|
336
413
|
title?: string;
|
|
337
414
|
named: boolean;
|
|
338
415
|
why?: string;
|
|
416
|
+
context?: string;
|
|
417
|
+
next?: string;
|
|
418
|
+
steps?: IBoardItem[];
|
|
419
|
+
checks?: IBoardItem[];
|
|
420
|
+
apps?: string[];
|
|
421
|
+
due?: string;
|
|
422
|
+
tracker?: string;
|
|
339
423
|
} {
|
|
340
424
|
const { named } = opts;
|
|
341
425
|
|
|
@@ -345,6 +429,13 @@ export class BoardFold {
|
|
|
345
429
|
title: named.summary,
|
|
346
430
|
named: true,
|
|
347
431
|
...(named.why === undefined ? {} : { why: named.why }),
|
|
432
|
+
...(named.context === undefined ? {} : { context: named.context }),
|
|
433
|
+
...(named.next === undefined ? {} : { next: named.next }),
|
|
434
|
+
...(named.steps === undefined ? {} : { steps: named.steps }),
|
|
435
|
+
...(named.checks === undefined ? {} : { checks: named.checks }),
|
|
436
|
+
...(named.apps === undefined ? {} : { apps: named.apps }),
|
|
437
|
+
...(named.due === undefined ? {} : { due: named.due }),
|
|
438
|
+
...(named.tracker === undefined ? {} : { tracker: named.tracker }),
|
|
348
439
|
};
|
|
349
440
|
}
|
|
350
441
|
|
|
@@ -410,9 +501,12 @@ export class BoardFold {
|
|
|
410
501
|
}
|
|
411
502
|
}
|
|
412
503
|
|
|
413
|
-
// A merge is Done until something reopens it: a commit, a fix or another pull request after it.
|
|
504
|
+
// A merge or a deploy is Done until something reopens it: a commit, a fix or another pull request after it.
|
|
414
505
|
const merged = events.findLastIndex(
|
|
415
|
-
(event) =>
|
|
506
|
+
(event) =>
|
|
507
|
+
event.kind === BoardKinds.MERGE ||
|
|
508
|
+
event.kind === BoardKinds.RELEASE ||
|
|
509
|
+
event.status === BoardStatuses.DONE,
|
|
416
510
|
);
|
|
417
511
|
|
|
418
512
|
if (merged >= 0 && !events.slice(merged + 1).some((event) => BoardFold.reopens({ event }))) {
|
package/src/board/github.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { spawnSync } from 'node:child_process';
|
|
2
2
|
import { RecordValue } from '../common/record.ts';
|
|
3
|
+
import { EventConstants } from '../events/common/index.ts';
|
|
3
4
|
import { EventFlow } from '../events/flow.ts';
|
|
4
5
|
import {
|
|
5
6
|
BoardConstants,
|
|
@@ -21,7 +22,6 @@ const FAILED = new Set([
|
|
|
21
22
|
'STARTUP_FAILURE',
|
|
22
23
|
'ERROR',
|
|
23
24
|
]);
|
|
24
|
-
const BODY_FLOW = /\bFlow:\s*(F-\d+)\b/;
|
|
25
25
|
|
|
26
26
|
const text = (opts: { value: unknown }): string =>
|
|
27
27
|
typeof opts.value === 'string' ? opts.value : '';
|
|
@@ -104,9 +104,12 @@ export class BoardGithub {
|
|
|
104
104
|
return { events, note: `github: ${notes.join(', ')}` };
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
-
/** `Flow:
|
|
107
|
+
/** `Flow: <id>` in the body of a pull request, else a flow id as a segment of its branch, else none. */
|
|
108
108
|
static flowOf(opts: { body: string; branch: string }): string | undefined {
|
|
109
|
-
return
|
|
109
|
+
return (
|
|
110
|
+
EventConstants.FLOW_LINE.exec(opts.body)?.[1] ??
|
|
111
|
+
EventFlow.fromBranchName({ branch: opts.branch })
|
|
112
|
+
);
|
|
110
113
|
}
|
|
111
114
|
|
|
112
115
|
/** The lines one pull request stands for: opened, each check, each review, merged or closed. */
|
package/src/board/index.ts
CHANGED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { BoardAgentSetting } from './agent-setting.ts';
|
|
3
|
+
import { BoardConstants, BoardShapes } from './common/index.ts';
|
|
4
|
+
|
|
5
|
+
const SHAPE = z.custom<string>((value) => typeof value === 'string' && BoardShapes.isValid(value), {
|
|
6
|
+
message: `one of ${[...BoardShapes.SCHEME_SET].join(', ')}`,
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
/** A face, or `{ shape?, lane?, role? }`: the lane rolls the agent into the row of another listed agent; the role is what the card says it is. */
|
|
10
|
+
export const BOARD_AGENT = z.union([
|
|
11
|
+
SHAPE,
|
|
12
|
+
z.strictObject({
|
|
13
|
+
shape: SHAPE.optional(),
|
|
14
|
+
lane: z.string().min(1).optional(),
|
|
15
|
+
role: z.string().trim().min(1).max(BoardConstants.ROLE_MAX).optional(),
|
|
16
|
+
}),
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
/** The agents of a board by name. */
|
|
20
|
+
export const BOARD_AGENTS = z
|
|
21
|
+
.record(z.string().min(1), BOARD_AGENT)
|
|
22
|
+
.superRefine((settings, context) => {
|
|
23
|
+
for (const name of Object.keys(settings)) {
|
|
24
|
+
const message = BoardAgentSetting.problemOf({ settings, name });
|
|
25
|
+
|
|
26
|
+
if (message !== undefined) {
|
|
27
|
+
context.addIssue({ code: 'custom', message, path: [name, 'lane'] });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
export type TBoardAgentSetting = z.output<typeof BOARD_AGENT>;
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import type { Server } from 'bun';
|
|
3
|
+
import { BoardRoutes, BoardServe } from './common/index.ts';
|
|
4
|
+
import type { IBoardData, TBoardRoute } from './common/index.ts';
|
|
5
|
+
import { BoardPage } from './page.ts';
|
|
6
|
+
import { BoardWatch } from './watch.ts';
|
|
7
|
+
|
|
8
|
+
interface IBoardServerOptions {
|
|
9
|
+
port: number;
|
|
10
|
+
/** The name of the address; default `BoardServe.DEFAULT_HOSTNAME`. The server still listens on 127.0.0.1 only. */
|
|
11
|
+
hostname?: string;
|
|
12
|
+
/** The events folder to watch; a read of the board happens when it changes. */
|
|
13
|
+
dir: string;
|
|
14
|
+
/** The folded board, as `vulcan board` makes it. */
|
|
15
|
+
collect: () => IBoardData;
|
|
16
|
+
maxSnapshotBytes?: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface IBoardServerRun {
|
|
20
|
+
server: Server<undefined>;
|
|
21
|
+
token: string;
|
|
22
|
+
clients: Set<ReadableStreamDefaultController<Uint8Array>>;
|
|
23
|
+
latest: string;
|
|
24
|
+
max: number;
|
|
25
|
+
stopWatch: () => void;
|
|
26
|
+
timers: ReturnType<typeof setInterval>[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const PAGE_HEADERS = {
|
|
30
|
+
'content-type': 'text/html; charset=utf-8',
|
|
31
|
+
'content-security-policy':
|
|
32
|
+
"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
|
|
33
|
+
'cache-control': 'no-store',
|
|
34
|
+
'referrer-policy': 'no-referrer',
|
|
35
|
+
'x-content-type-options': 'nosniff',
|
|
36
|
+
};
|
|
37
|
+
const STREAM_HEADERS = {
|
|
38
|
+
'content-type': 'text/event-stream',
|
|
39
|
+
'cache-control': 'no-store',
|
|
40
|
+
'x-content-type-options': 'nosniff',
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const encoder = new TextEncoder();
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* `vulcan board serve`: the board on 127.0.0.1, and a stream that sends the next snapshot when the event log changes.
|
|
47
|
+
* It writes nothing of the project; every request must carry this run's token and a local Host and Origin.
|
|
48
|
+
*/
|
|
49
|
+
export class BoardServer {
|
|
50
|
+
private static run: IBoardServerRun | undefined;
|
|
51
|
+
|
|
52
|
+
/** Whether a request may be answered, and which route it asks for. Pure: no socket, so every refusal is tested alone. */
|
|
53
|
+
static check(opts: {
|
|
54
|
+
method: string;
|
|
55
|
+
url: string;
|
|
56
|
+
host: string | null;
|
|
57
|
+
origin: string | null;
|
|
58
|
+
port: number;
|
|
59
|
+
token: string;
|
|
60
|
+
hostname: string;
|
|
61
|
+
}): { status: number; route?: TBoardRoute } {
|
|
62
|
+
const names = [
|
|
63
|
+
`127.0.0.1:${opts.port}`,
|
|
64
|
+
`localhost:${opts.port}`,
|
|
65
|
+
`${opts.hostname.toLowerCase()}:${opts.port}`,
|
|
66
|
+
];
|
|
67
|
+
const host = opts.host?.toLowerCase() ?? null;
|
|
68
|
+
const origin = opts.origin?.toLowerCase() ?? null;
|
|
69
|
+
|
|
70
|
+
if (host === null || !names.includes(host)) {
|
|
71
|
+
return { status: 403 };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (origin !== null && !names.some((name) => origin === `http://${name}`)) {
|
|
75
|
+
return { status: 403 };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const url = new URL(opts.url);
|
|
79
|
+
const given = url.searchParams.get(BoardServe.TOKEN_PARAM);
|
|
80
|
+
|
|
81
|
+
if (given === null || !BoardServer.isToken({ given, token: opts.token })) {
|
|
82
|
+
return { status: 403 };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (opts.method !== 'GET') {
|
|
86
|
+
return { status: 405 };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (url.pathname === BoardServe.PAGE_PATH) {
|
|
90
|
+
return { status: 200, route: BoardRoutes.PAGE };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return url.pathname === BoardServe.STREAM_PATH
|
|
94
|
+
? { status: 200, route: BoardRoutes.STREAM }
|
|
95
|
+
: { status: 404 };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Starts the server on `port`, or on a free one when it is busy. */
|
|
99
|
+
static async start(
|
|
100
|
+
opts: IBoardServerOptions,
|
|
101
|
+
): Promise<{ url: string; fallback: string; note?: string }> {
|
|
102
|
+
await BoardServer.stop();
|
|
103
|
+
|
|
104
|
+
const token = randomBytes(BoardServe.TOKEN_BYTES).toString('hex');
|
|
105
|
+
const max = opts.maxSnapshotBytes ?? BoardServe.MAX_SNAPSHOT_BYTES;
|
|
106
|
+
const hostname = opts.hostname ?? BoardServe.DEFAULT_HOSTNAME;
|
|
107
|
+
const listen = (port: number): Server<undefined> =>
|
|
108
|
+
Bun.serve({
|
|
109
|
+
hostname: BoardServe.HOST,
|
|
110
|
+
port,
|
|
111
|
+
development: false,
|
|
112
|
+
fetch: (request, server) =>
|
|
113
|
+
BoardServer.answer({ request, server, token, hostname, collect: opts.collect }),
|
|
114
|
+
error: (error) => {
|
|
115
|
+
process.stderr.write(`board: a request failed: ${error.message}\n`);
|
|
116
|
+
|
|
117
|
+
return new Response(null, { status: 500 });
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
let note: string | undefined;
|
|
121
|
+
let server: Server<undefined>;
|
|
122
|
+
|
|
123
|
+
try {
|
|
124
|
+
server = listen(opts.port);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (
|
|
127
|
+
opts.port === 0 ||
|
|
128
|
+
!(error instanceof Error) ||
|
|
129
|
+
!('code' in error) ||
|
|
130
|
+
error.code !== 'EADDRINUSE'
|
|
131
|
+
) {
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
server = listen(0);
|
|
136
|
+
note = `port ${opts.port} is busy: using ${server.port}`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const run: IBoardServerRun = {
|
|
140
|
+
server,
|
|
141
|
+
token,
|
|
142
|
+
clients: new Set(),
|
|
143
|
+
latest: BoardServer.frameOf({ data: opts.collect(), max }),
|
|
144
|
+
max,
|
|
145
|
+
stopWatch: () => undefined,
|
|
146
|
+
timers: [],
|
|
147
|
+
};
|
|
148
|
+
const publish = (): void => {
|
|
149
|
+
const data = BoardServer.snapshotOf({ collect: opts.collect });
|
|
150
|
+
|
|
151
|
+
if (data === undefined) {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
run.latest = BoardServer.frameOf({ data, max });
|
|
156
|
+
|
|
157
|
+
for (const client of run.clients) {
|
|
158
|
+
BoardServer.send({ clients: run.clients, client, text: run.latest });
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
BoardServer.run = run;
|
|
163
|
+
run.stopWatch = BoardWatch.start({ dir: opts.dir, onChange: publish });
|
|
164
|
+
run.timers.push(
|
|
165
|
+
setInterval(publish, BoardServe.REFRESH_MS),
|
|
166
|
+
setInterval(() => {
|
|
167
|
+
for (const client of run.clients) {
|
|
168
|
+
BoardServer.send({ clients: run.clients, client, text: ': ping\n\n' });
|
|
169
|
+
}
|
|
170
|
+
}, BoardServe.HEARTBEAT_MS),
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
const path = BoardServer.pathWithToken({ path: BoardServe.PAGE_PATH, token });
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
url: `http://${hostname}:${server.port}${path}`,
|
|
177
|
+
fallback: `http://${BoardServe.HOST}:${server.port}${path}`,
|
|
178
|
+
...(note === undefined ? {} : { note }),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Stops the server, the watch and the timers, and ends every open stream. */
|
|
183
|
+
static async stop(): Promise<void> {
|
|
184
|
+
const { run } = BoardServer;
|
|
185
|
+
|
|
186
|
+
if (run === undefined) {
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
BoardServer.run = undefined;
|
|
191
|
+
run.stopWatch();
|
|
192
|
+
|
|
193
|
+
for (const timer of run.timers) {
|
|
194
|
+
clearInterval(timer);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
for (const client of run.clients) {
|
|
198
|
+
client.close();
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
await run.server.stop(true);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Both sides are hashed, so the comparison is over 32 bytes each whatever the token text is, multibyte included. */
|
|
205
|
+
private static isToken(opts: { given: string; token: string }): boolean {
|
|
206
|
+
const digest = (text: string): Buffer => createHash('sha256').update(text).digest();
|
|
207
|
+
|
|
208
|
+
return timingSafeEqual(digest(opts.given), digest(opts.token));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private static pathWithToken(opts: { path: string; token: string }): string {
|
|
212
|
+
return `${opts.path}?${BoardServe.TOKEN_PARAM}=${opts.token}`;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** The folded board, or `undefined` with one line on stderr when it cannot be read (a log file the user cannot open, say). */
|
|
216
|
+
private static snapshotOf(opts: { collect: () => IBoardData }): IBoardData | undefined {
|
|
217
|
+
try {
|
|
218
|
+
return opts.collect();
|
|
219
|
+
} catch (error) {
|
|
220
|
+
process.stderr.write(
|
|
221
|
+
`board: cannot read the board: ${error instanceof Error ? error.message : String(error)}\n`,
|
|
222
|
+
);
|
|
223
|
+
|
|
224
|
+
return undefined;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** One SSE message: the snapshot, or a notice that it is over the cap in bytes. A JSON text has no raw line break, so it is one `data:` line. */
|
|
229
|
+
private static frameOf(opts: { data: IBoardData; max: number }): string {
|
|
230
|
+
const json = JSON.stringify(opts.data);
|
|
231
|
+
|
|
232
|
+
return Buffer.byteLength(json) > opts.max ? 'data: {"tooLarge":true}\n\n' : `data: ${json}\n\n`;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** A client whose stream errored is dropped; one that has not read what it was sent (a full queue) skips this message instead of piling up. */
|
|
236
|
+
static send(opts: {
|
|
237
|
+
clients: Set<ReadableStreamDefaultController<Uint8Array>>;
|
|
238
|
+
client: ReadableStreamDefaultController<Uint8Array>;
|
|
239
|
+
text: string;
|
|
240
|
+
}): void {
|
|
241
|
+
const { desiredSize } = opts.client;
|
|
242
|
+
|
|
243
|
+
if (desiredSize === null) {
|
|
244
|
+
opts.clients.delete(opts.client);
|
|
245
|
+
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (desiredSize > 0) {
|
|
250
|
+
opts.client.enqueue(encoder.encode(opts.text));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private static answer(opts: {
|
|
255
|
+
request: Request;
|
|
256
|
+
server: Server<undefined>;
|
|
257
|
+
token: string;
|
|
258
|
+
hostname: string;
|
|
259
|
+
collect: () => IBoardData;
|
|
260
|
+
}): Response {
|
|
261
|
+
const { request, server, token } = opts;
|
|
262
|
+
const verdict = BoardServer.check({
|
|
263
|
+
method: request.method,
|
|
264
|
+
url: request.url,
|
|
265
|
+
host: request.headers.get('host'),
|
|
266
|
+
origin: request.headers.get('origin'),
|
|
267
|
+
port: server.port ?? 0,
|
|
268
|
+
token,
|
|
269
|
+
hostname: opts.hostname,
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
if (verdict.route === BoardRoutes.PAGE) {
|
|
273
|
+
const data = BoardServer.snapshotOf({ collect: opts.collect });
|
|
274
|
+
|
|
275
|
+
if (data === undefined) {
|
|
276
|
+
return new Response(null, { status: 503 });
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const live = { stream: BoardServer.pathWithToken({ path: BoardServe.STREAM_PATH, token }) };
|
|
280
|
+
|
|
281
|
+
return new Response(BoardPage.render({ data: { ...data, live } }), {
|
|
282
|
+
headers: PAGE_HEADERS,
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
if (verdict.route === BoardRoutes.STREAM) {
|
|
287
|
+
return BoardServer.openStream({ request, server });
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
return new Response(null, { status: verdict.status });
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private static openStream(opts: { request: Request; server: Server<undefined> }): Response {
|
|
294
|
+
const { run } = BoardServer;
|
|
295
|
+
|
|
296
|
+
if (run === undefined || run.clients.size >= BoardServe.MAX_STREAMS) {
|
|
297
|
+
return new Response(null, { status: 503 });
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
opts.server.timeout(opts.request, 0);
|
|
301
|
+
|
|
302
|
+
let controller: ReadableStreamDefaultController<Uint8Array> | undefined;
|
|
303
|
+
const body = new ReadableStream<Uint8Array>(
|
|
304
|
+
{
|
|
305
|
+
start: (started) => {
|
|
306
|
+
controller = started;
|
|
307
|
+
run.clients.add(started);
|
|
308
|
+
BoardServer.send({
|
|
309
|
+
clients: run.clients,
|
|
310
|
+
client: started,
|
|
311
|
+
text: `retry: 3000\n\n${run.latest}`,
|
|
312
|
+
});
|
|
313
|
+
},
|
|
314
|
+
cancel: () => {
|
|
315
|
+
if (controller !== undefined) {
|
|
316
|
+
run.clients.delete(controller);
|
|
317
|
+
}
|
|
318
|
+
},
|
|
319
|
+
},
|
|
320
|
+
new ByteLengthQueuingStrategy({ highWaterMark: 2 * run.max }),
|
|
321
|
+
);
|
|
322
|
+
|
|
323
|
+
return new Response(body, { headers: STREAM_HEADERS });
|
|
324
|
+
}
|
|
325
|
+
}
|