fascicle 0.12.5 → 0.12.8
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/CHANGELOG.md +48 -0
- package/dist/agents.js +1 -1
- package/dist/{core-DdJEhyQc.js → core-CFdEjtiT.js} +281 -270
- package/dist/core-CFdEjtiT.js.map +1 -0
- package/dist/{engine-CdXegeqC.js → engine-DQiQHiy8.js} +23 -13
- package/dist/{engine-CdXegeqC.js.map → engine-DQiQHiy8.js.map} +1 -1
- package/dist/index.js +3 -3
- package/dist/{invoke-CH_eJZeS.js → invoke-eEYMZmWg.js} +3 -3
- package/dist/{invoke-CH_eJZeS.js.map → invoke-eEYMZmWg.js.map} +1 -1
- package/dist/{leading_system-BUCT-PwD.js → leading_system-DQmlA6Fs.js} +2 -2
- package/dist/{leading_system-BUCT-PwD.js.map → leading_system-DQmlA6Fs.js.map} +1 -1
- package/dist/mcp.js +1 -1
- package/dist/stdio.js +1 -1
- package/dist/testing.js +3 -3
- package/dist/viewer-app/assets/index-BBEYkjnQ.js +2 -0
- package/dist/viewer-app/assets/index-Cev83tcH.css +1 -0
- package/dist/viewer-app/fonts/sora-OFL.txt +93 -0
- package/dist/viewer-app/fonts/sora-latin.woff2 +0 -0
- package/dist/viewer-app/fonts/spline-sans-mono-OFL.txt +93 -0
- package/dist/viewer-app/fonts/spline-sans-mono-latin.woff2 +0 -0
- package/dist/viewer-app/index.html +13 -0
- package/dist/viewer.d.ts +17 -3
- package/dist/viewer.js +210 -50
- package/dist/viewer.js.map +1 -1
- package/package.json +9 -2
- package/dist/core-DdJEhyQc.js.map +0 -1
- package/dist/static/viewer.html +0 -375
package/dist/viewer.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"viewer.js","names":["fs_watch"],"sources":["../src/viewer/broadcast.ts","../src/viewer/server.ts","../src/viewer/tail.ts","../src/viewer/start_viewer.ts","../src/viewer/cli.ts"],"sourcesContent":["/**\n * In-process pub/sub for trajectory events.\n *\n * One ring buffer of the last N events plus a Set of subscriber callbacks.\n * Both producers (file tail and HTTP ingest) push into the same broadcaster;\n * SSE writers fan out via `subscribe`.\n */\n\nimport type { ParsedTrajectoryEvent } from '#core'\n\nexport type BroadcastEvent = {\n readonly id: number\n readonly event: ParsedTrajectoryEvent\n}\n\nexport type Subscriber = (entry: BroadcastEvent) => void\n\nexport type Broadcaster = {\n readonly emit: (event: ParsedTrajectoryEvent) => BroadcastEvent\n readonly subscribe: (fn: Subscriber) => () => void\n readonly snapshot: () => readonly BroadcastEvent[]\n readonly snapshot_after: (last_id: number) => readonly BroadcastEvent[]\n readonly size: () => number\n}\n\nexport type BroadcasterConfig = {\n readonly buffer: number\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\n/**\n * Creates a broadcaster: a bounded ring buffer plus subscriber fan-out.\n *\n * Each event gets a monotonic `id` so SSE clients can replay from a known\n * cursor on reconnect (`snapshot_after`). `emit` does not await delivery, so\n * slow-client backpressure is the subscriber's responsibility. A subscriber\n * that throws is unsubscribed, and the `on_subscriber_error` callback fires\n * once with the captured error so the server can log it.\n */\nexport function create_broadcaster(config: BroadcasterConfig): Broadcaster {\n // `| 0` truncates fractional sizes; clamp so the ring keeps at least one\n // event.\n const max = Math.max(1, config.buffer | 0)\n const ring: BroadcastEvent[] = []\n const subscribers = new Set<Subscriber>()\n let next_id = 1\n\n const emit = (event: ParsedTrajectoryEvent): BroadcastEvent => {\n const entry: BroadcastEvent = { id: next_id++, event }\n ring.push(entry)\n if (ring.length > max) ring.splice(0, ring.length - max)\n // Iterate a copy so deleting a throwing subscriber (or an unsubscribe\n // triggered from inside a callback) cannot upset the live Set.\n for (const fn of Array.from(subscribers)) {\n try {\n fn(entry)\n } catch (err) {\n subscribers.delete(fn)\n if (config.on_subscriber_error) config.on_subscriber_error(err)\n }\n }\n return entry\n }\n\n const subscribe = (fn: Subscriber): (() => void) => {\n subscribers.add(fn)\n return () => { subscribers.delete(fn) }\n }\n\n const snapshot = (): readonly BroadcastEvent[] => [...ring]\n\n const snapshot_after = (last_id: number): readonly BroadcastEvent[] =>\n ring.filter((e) => e.id > last_id)\n\n const size = (): number => ring.length\n\n return { emit, subscribe, snapshot, snapshot_after, size }\n}\n","/**\n * Tiny HTTP server: 5 routes, SSE fan-out, NDJSON ingest.\n *\n * GET / -> static viewer.html\n * GET /api/events -> text/event-stream replaying the ring buffer\n * GET /api/snapshot -> JSON dump of the ring buffer\n * POST /api/ingest -> newline-delimited trajectory events (http_logger)\n * GET /api/health -> { ok: true }\n *\n * The server owns nothing but the socket. The broadcaster owns the event\n * history; the static html lives on disk. SSE clients reconnect with\n * `Last-Event-ID` and the server replays anything past their cursor from\n * the ring buffer; older events are gone (bounded memory by design).\n */\n\nimport { createReadStream, statSync } from 'node:fs'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport { dirname, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { parse_trajectory_event, type ParsedTrajectoryEvent } from '#core'\nimport type { Broadcaster } from './broadcast.js'\n\nconst SSE_HEARTBEAT_MS = 15_000\nconst HERE = dirname(fileURLToPath(import.meta.url))\nconst STATIC_HTML = resolve(HERE, 'static', 'viewer.html')\n\nexport type ServerConfig = {\n readonly broadcaster: Broadcaster\n readonly host: string\n readonly port: number\n readonly on_parse_error?: (err: unknown, line: string) => void\n}\n\nexport type ViewerServer = {\n readonly url: string\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the HTTP server and resolves once it is listening.\n *\n * Wires the five routes (static HTML, health, snapshot, SSE, ingest) to a\n * single request handler and resolves with the bound URL and a `close`\n * that shuts the socket down.\n */\nexport function start_server(config: ServerConfig): Promise<ViewerServer> {\n const { broadcaster, host, port, on_parse_error } = config\n\n const handler = (req: IncomingMessage, res: ServerResponse): void => {\n const route = resolve_route(req, host, port)\n\n if (route === 'GET /' || route === 'GET /index.html') {\n serve_static_html(res)\n return\n }\n if (route === 'GET /api/health') {\n send_json(res, 200, { ok: true })\n return\n }\n if (route === 'GET /api/snapshot') {\n send_json(res, 200, { events: broadcaster.snapshot() })\n return\n }\n if (route === 'GET /api/events') {\n handle_sse(req, res, broadcaster)\n return\n }\n if (route === 'POST /api/ingest') {\n handle_ingest(req, res, broadcaster, on_parse_error)\n return\n }\n res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify({ error: 'not_found', route }))\n }\n\n const http_server = createServer(handler)\n\n return new Promise((res_ok, res_err) => {\n // `listen` can fail (for example, port already in use); reject instead of\n // leaving the returned promise pending forever.\n http_server.once('error', res_err)\n http_server.listen(port, host, () => {\n http_server.removeListener('error', res_err)\n // `address().port` is the port actually bound. It only differs from\n // the requested `port` when the caller passed 0 and asked the OS to\n // pick a free port.\n const addr = http_server.address()\n const bound_port =\n addr !== null && typeof addr === 'object' && 'port' in addr ? addr.port : port\n const url = `http://${host}:${bound_port}`\n res_ok({\n url,\n close: () => close_server(http_server),\n })\n })\n })\n}\n\n/**\n * Builds a `\"METHOD /path\"` route key from a request.\n *\n * Falls back to the server's own `host`/`port` when the request has no\n * `Host` header, so a malformed or missing header never throws inside\n * `new URL`.\n */\nexport function resolve_route(\n req: {\n url?: string | undefined\n method?: string | undefined\n headers: { host?: string | undefined }\n },\n host: string,\n port: number,\n): string {\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? `${host}:${port}`}`)\n return `${req.method ?? 'GET'} ${url.pathname}`\n}\n\n/**\n * Closes the HTTP server and resolves once every connection is torn down.\n */\nfunction close_server(server: Server): Promise<void> {\n return new Promise((res_ok, res_err) => {\n server.close((err) => {\n if (err) res_err(err)\n else res_ok()\n })\n // `close` alone only stops new connections and waits for existing ones\n // (including open SSE streams) to end on their own, which can hang\n // indefinitely. Force them closed so shutdown actually completes.\n server.closeAllConnections?.()\n })\n}\n\n/**\n * Writes a JSON response with the given status code.\n */\nfunction send_json(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify(body))\n}\n\n/**\n * Streams the bundled `viewer.html` as the response body.\n */\nfunction serve_static_html(res: ServerResponse): void {\n let size: number\n try {\n // Stat first so a missing file produces a clean 500 response instead\n // of a stream error after headers have already been sent.\n size = statSync(STATIC_HTML).size\n } catch {\n res.statusCode = 500\n res.setHeader('content-type', 'text/plain')\n res.end('viewer.html missing')\n return\n }\n res.statusCode = 200\n res.setHeader('content-type', 'text/html; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('content-length', String(size))\n createReadStream(STATIC_HTML).pipe(res)\n}\n\n/**\n * Handles `GET /api/events` by turning the connection into an SSE stream.\n *\n * Replays whatever the client missed since its `Last-Event-ID` cursor,\n * subscribes it to the broadcaster for new events, and keeps the\n * connection alive with a periodic heartbeat comment.\n */\nfunction handle_sse(req: IncomingMessage, res: ServerResponse, broadcaster: Broadcaster): void {\n res.statusCode = 200\n res.setHeader('content-type', 'text/event-stream')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('connection', 'keep-alive')\n // Disables response buffering in nginx so SSE frames reach the client as\n // soon as they are written instead of sitting in a proxy buffer.\n res.setHeader('x-accel-buffering', 'no')\n\n // Replay everything after the client's cursor before subscribing. Both\n // calls run synchronously back to back, so there is no window in which\n // an event could land between the replay and the live subscription.\n const last_event_id = parse_last_event_id(req.headers['last-event-id'])\n for (const entry of broadcaster.snapshot_after(last_event_id)) {\n write_event(res, entry.id, entry.event)\n }\n\n // Comment frames keep the connection alive through idle proxies and\n // load balancers that would otherwise time out a quiet SSE stream.\n const heartbeat = setInterval(() => {\n res.write(': heartbeat\\n\\n')\n }, SSE_HEARTBEAT_MS)\n\n const unsubscribe = broadcaster.subscribe((entry) => {\n write_event(res, entry.id, entry.event)\n })\n\n const close = (): void => {\n clearInterval(heartbeat)\n unsubscribe()\n if (!res.writableEnded) {\n res.write('event: close\\ndata: {}\\n\\n')\n res.end()\n }\n }\n\n // A clean disconnect and a socket error both need the same cleanup.\n req.on('close', close)\n req.on('error', close)\n}\n\n/**\n * Parses the `Last-Event-ID` header into a replay cursor, defaulting to 0.\n *\n * Treats a missing header or a non-numeric or non-positive value as \"no\n * cursor\", which makes `handle_sse` replay the full ring buffer.\n */\nfunction parse_last_event_id(value: string | string[] | undefined): number {\n if (typeof value !== 'string') return 0\n const n = Number.parseInt(value, 10)\n return Number.isFinite(n) && n > 0 ? n : 0\n}\n\n/**\n * Writes one SSE `trajectory` event frame to the response stream.\n */\nfunction write_event(res: ServerResponse, id: number, event: ParsedTrajectoryEvent): void {\n res.write(`id: ${id}\\nevent: trajectory\\ndata: ${JSON.stringify(event)}\\n\\n`)\n}\n\n/**\n * Handles `POST /api/ingest`: parses newline-delimited trajectory events\n * from the request body and feeds valid ones into the broadcaster.\n *\n * Reports how many lines were accepted vs rejected in the response body;\n * a malformed line is skipped and reported via `on_parse_error`, not\n * treated as a fatal request error.\n */\nfunction handle_ingest(\n req: IncomingMessage,\n res: ServerResponse,\n broadcaster: Broadcaster,\n on_parse_error?: (err: unknown, line: string) => void,\n): void {\n let buf = ''\n let accepted = 0\n let rejected = 0\n\n const consume_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n rejected++\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = parse_trajectory_event(parsed)\n if (!result.success) {\n rejected++\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n broadcaster.emit(result.data)\n accepted++\n }\n\n req.setEncoding('utf8')\n req.on('data', (chunk: string) => {\n buf += chunk\n // Consume every complete line in the buffer so far; a trailing partial\n // line (no `\\n` yet) stays in `buf` until a later chunk completes it.\n let nl = buf.indexOf('\\n')\n while (nl !== -1) {\n consume_line(buf.slice(0, nl))\n buf = buf.slice(nl + 1)\n nl = buf.indexOf('\\n')\n }\n })\n req.on('end', () => {\n // Flush a final line that arrived without a trailing newline.\n if (buf.length > 0) consume_line(buf)\n send_json(res, 200, { accepted, rejected })\n })\n req.on('error', (err: unknown) => {\n if (on_parse_error) on_parse_error(err, '')\n send_json(res, 400, { error: 'bad_request' })\n })\n}\n\nexport const internals_for_test = { STATIC_HTML, SSE_HEARTBEAT_MS, parse_last_event_id }\n","/**\n * JSONL file tailer.\n *\n * Watches a file for appends and emits one parsed trajectory event per\n * complete line. Handles three pathological cases:\n *\n * - Truncation / rotation: a watcher event whose stat is shorter than the\n * current offset means the file shrunk. Reset offset to 0 and re-stream.\n * - Partial last line: if the trailing chunk has no `\\n`, buffer it and\n * wait. Never parse a half-written line.\n * - Schema failures: a line that fails `parse_trajectory_event` is\n * dropped and surfaced to `on_parse_error`. The stream keeps going.\n *\n * The watcher is fs.watch-based; reads are serialized and change events\n * that arrive mid-read are coalesced into one extra pass rather than\n * dropped, so a burst of appends never starts overlapping reads. Each pass\n * re-stats and re-reads from the saved offset, which also covers platforms\n * where fs.watch misses some append notifications: the next successful\n * change event catches the file up regardless.\n */\n\nimport { type FSWatcher, watch as fs_watch } from 'node:fs'\nimport { open, stat } from 'node:fs/promises'\nimport { parse_trajectory_event, type ParsedTrajectoryEvent } from '#core'\n\nexport type TailConfig = {\n readonly path: string\n readonly on_event: (event: ParsedTrajectoryEvent) => void\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n}\n\nexport type Tail = {\n readonly stop: () => void\n readonly drain: () => Promise<void>\n}\n\n/**\n * Starts tailing `path` and returns a handle to stop or drain it.\n *\n * Watches the file with `fs.watch` and re-reads from the last known offset\n * on every change, buffering an incomplete trailing line until the rest\n * arrives. Overlapping change events are coalesced: a read already in\n * flight absorbs any events that fire while it runs instead of starting a\n * second concurrent read.\n */\nexport function start_tail(config: TailConfig): Tail {\n const { path, on_event, on_parse_error, on_io_error } = config\n let offset = 0\n let buffer = ''\n let busy = false\n let pending = false\n let closed = false\n let watcher: FSWatcher | null = null\n let last_drain: Promise<void> = Promise.resolve()\n\n const handle_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = parse_trajectory_event(parsed)\n if (!result.success) {\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n on_event(result.data)\n }\n\n const read_more = async (): Promise<void> => {\n let st\n try {\n st = await stat(path)\n } catch (err) {\n if (on_io_error) on_io_error(err)\n return\n }\n if (st.size < offset) {\n // File is shorter than our offset: it was truncated or rotated.\n // Restart from the top instead of seeking to a now-invalid offset.\n offset = 0\n buffer = ''\n }\n if (st.size === offset) return\n\n const fh = await open(path, 'r').catch((err: unknown) => {\n if (on_io_error) on_io_error(err)\n return null\n })\n if (!fh) return\n try {\n const length = st.size - offset\n const buf = Buffer.alloc(length)\n const { bytesRead } = await fh.read(buf, 0, length, offset)\n offset += bytesRead\n buffer += buf.subarray(0, bytesRead).toString('utf8')\n } finally {\n await fh.close()\n }\n\n let nl = buffer.indexOf('\\n')\n while (nl !== -1) {\n const line = buffer.slice(0, nl)\n buffer = buffer.slice(nl + 1)\n handle_line(line)\n nl = buffer.indexOf('\\n')\n }\n // Anything left in `buffer` has no trailing newline yet; keep it for\n // the next read instead of parsing a half-written line.\n }\n\n // Coalesces watcher bursts: if `schedule` fires while a read is already\n // running, it just flags `pending` and returns. The running loop below\n // checks `pending` after each pass and does one more pass if it was set,\n // so a burst of change events never starts overlapping reads.\n const schedule = (): void => {\n if (closed) return\n if (busy) {\n pending = true\n return\n }\n busy = true\n last_drain = (async (): Promise<void> => {\n try {\n let keep_going = true\n while (keep_going) {\n pending = false\n await read_more()\n keep_going = pending && !closed\n }\n } finally {\n busy = false\n }\n })()\n }\n\n schedule()\n\n try {\n watcher = fs_watch(path, { persistent: true }, () => { schedule() })\n } catch (err) {\n if (on_io_error) on_io_error(err)\n }\n\n const stop = (): void => {\n closed = true\n if (watcher) {\n watcher.close()\n watcher = null\n }\n }\n\n const drain = async (): Promise<void> => {\n schedule()\n await last_drain\n }\n\n return { stop, drain }\n}\n","/**\n * `start_viewer` programmatic embed implementation.\n *\n * Spin up the server, optionally start tailing a JSONL file, and return a\n * handle that can stop both. `start_viewer` only depends on core's wire-format\n * schema; it never reaches into the engine, composites, or any provider.\n */\n\nimport { create_broadcaster } from './broadcast.js'\nimport { start_server, type ViewerServer } from './server.js'\nimport { start_tail, type Tail } from './tail.js'\n\nexport type StartViewerOptions = {\n readonly path?: string\n readonly host?: string\n readonly port?: number\n readonly buffer?: number\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\nexport type ViewerHandle = {\n readonly url: string\n readonly host: string\n readonly port: number\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the viewer: brings up the HTTP/SSE server and, if `options.path`\n * is set, a file tail that feeds the same broadcaster.\n *\n * Defaults to `127.0.0.1:4242` with a 1000-event ring buffer. HTTP ingest\n * and SSE are always available; tailing is opt-in via `path`.\n */\nexport async function start_viewer(options: StartViewerOptions = {}): Promise<ViewerHandle> {\n const host = options.host ?? '127.0.0.1'\n const port = options.port ?? 4242\n const buffer = options.buffer ?? 1000\n const broadcaster = create_broadcaster({\n buffer,\n ...(options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}),\n })\n const server = await start_server({\n broadcaster,\n host,\n port,\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n })\n\n let tail: Tail | null = null\n if (options.path !== undefined) {\n tail = start_tail({\n path: options.path,\n on_event: (event) => { broadcaster.emit(event) },\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n ...(options.on_io_error ? { on_io_error: options.on_io_error } : {}),\n })\n }\n\n return wrap_handle(server, tail, host)\n}\n\n/**\n * Combines the server and optional tail into a single `ViewerHandle`.\n *\n * `close` stops the tail first, then closes the server, mirroring the\n * startup order (server first, tail second) in reverse. The port is read\n * back from `server.url` rather than the requested `port` option, since\n * a caller that passes `0` gets whatever port the OS actually bound.\n */\nfunction wrap_handle(server: ViewerServer, tail: Tail | null, host: string): ViewerHandle {\n return {\n url: server.url,\n host,\n port: Number(new URL(server.url).port),\n close: async () => {\n if (tail) tail.stop()\n await server.close()\n },\n }\n}\n","#!/usr/bin/env tsx\n/**\n * fascicle-viewer CLI.\n *\n * fascicle-viewer <path> # tail a JSONL file (primary)\n * fascicle-viewer --listen # accept HTTP push only\n * fascicle-viewer <path> --listen # both producers feed the same broadcaster\n *\n * Flags: --port <n> --host <h> --buffer <n> --no-open --help\n *\n * Defaults bind 127.0.0.1:4242 and open the user's default browser. SIGINT\n * shuts everything down cleanly. The CLI body is exposed as `run_viewer_cli`\n * so the umbrella's bin shim can drive it from a bundled `dist/index.js`.\n */\n\nimport { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { parseArgs } from 'node:util'\nimport { fileURLToPath } from 'node:url'\nimport { start_viewer } from './start_viewer.js'\n\ntype CliArgs = {\n readonly path?: string\n readonly host: string\n readonly port: number\n readonly buffer: number\n readonly listen: boolean\n readonly open: boolean\n}\n\nconst HELP = `\\\nfascicle-viewer — minimal in-repo dashboard for fascicle trajectory streams.\n\nUsage:\n fascicle-viewer <path> tail a JSONL file\n fascicle-viewer --listen accept HTTP push only\n fascicle-viewer <path> --listen both producers feed the same broadcaster\n\nOptions:\n --port <n> port (default 4242)\n --host <h> bind host (default 127.0.0.1; --host 0.0.0.0 warns)\n --buffer <n> ring-buffer size (default 1000)\n --no-open do not open the browser\n --help show this message\n`\n\n/**\n * Parses CLI argv into a validated `CliArgs`, exiting on bad input.\n *\n * `--help` prints usage and exits 0. Invalid numeric flags, or a missing\n * <path> without `--listen`, write to stderr and exit 2.\n */\nexport function parse(argv: readonly string[]): CliArgs {\n const { values, positionals } = parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: {\n port: { type: 'string', default: '4242' },\n host: { type: 'string', default: '127.0.0.1' },\n buffer: { type: 'string', default: '1000' },\n listen: { type: 'boolean', default: false },\n open: { type: 'boolean', default: true },\n 'no-open': { type: 'boolean', default: false },\n help: { type: 'boolean', default: false },\n },\n })\n if (values.help) {\n process.stdout.write(HELP)\n process.exit(0)\n }\n const port_raw = values.port ?? '4242'\n const buffer_raw = values.buffer ?? '1000'\n const port = Number.parseInt(port_raw, 10)\n const buffer = Number.parseInt(buffer_raw, 10)\n if (!Number.isFinite(port) || port <= 0) {\n process.stderr.write(\n `fascicle-viewer: invalid --port '${port_raw}': expected a positive integer\\n`,\n )\n process.exit(2)\n }\n if (!Number.isFinite(buffer) || buffer <= 0) {\n process.stderr.write(\n `fascicle-viewer: invalid --buffer '${buffer_raw}': expected a positive integer\\n`,\n )\n process.exit(2)\n }\n const path = positionals[0]\n const listen = values.listen ?? false\n if (path === undefined && !listen) {\n process.stderr.write('fascicle-viewer: a <path> is required unless --listen is set\\n')\n process.stderr.write(HELP)\n process.exit(2)\n }\n return {\n ...(path !== undefined ? { path } : {}),\n host: values.host ?? '127.0.0.1',\n port,\n buffer,\n listen,\n open: !values['no-open'] && (values.open ?? true),\n }\n}\n\n/**\n * Opens `url` in the platform's default browser, best-effort.\n *\n * Spawns the platform opener (`open`, `cmd /c start`, or `xdg-open`)\n * detached and swallows failures; the CLI prints the URL either way.\n */\nexport function open_browser(url: string): void {\n const platform = process.platform\n const cmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open'\n const args = platform === 'win32' ? ['/c', 'start', '\"\"', url] : [url]\n try {\n const child = spawn(cmd, args, { stdio: 'ignore', detached: true })\n child.on('error', () => {})\n child.unref()\n } catch {\n // Best-effort. The CLI logs the URL anyway.\n }\n}\n\n/**\n * CLI entry point: parses argv, starts the viewer, and wires shutdown.\n *\n * Warns but proceeds when the tailed path does not exist yet or when the\n * bind host is 0.0.0.0 (the dashboard has no auth). Optionally opens the\n * browser, then installs SIGINT/SIGTERM handlers that close the viewer\n * before exiting.\n */\nexport async function run_viewer_cli(argv: readonly string[]): Promise<void> {\n const args = parse(argv)\n\n if (args.path !== undefined && !existsSync(args.path)) {\n process.stderr.write(\n `fascicle-viewer: warning: ${args.path} does not exist yet — will pick up events once it is created\\n`,\n )\n }\n if (args.host === '0.0.0.0') {\n process.stderr.write(\n 'fascicle-viewer: warning: binding 0.0.0.0 — this dashboard has no auth and exposes whatever is in your trajectory stream\\n',\n )\n }\n\n const handle = await start_viewer({\n ...(args.path !== undefined ? { path: args.path } : {}),\n host: args.host,\n port: args.port,\n buffer: args.buffer,\n on_parse_error: (err, line) => {\n const preview = line.length > 120 ? `${line.slice(0, 120)}…` : line\n process.stderr.write(\n `fascicle-viewer: skipped malformed line: ${preview}\\n ${describe_error(err)}\\n`,\n )\n },\n on_io_error: (err) => {\n process.stderr.write(`fascicle-viewer: io error: ${describe_error(err)}\\n`)\n },\n })\n\n if (args.path !== undefined) process.stderr.write(`fascicle-viewer: watching ${args.path}\\n`)\n if (args.listen || args.path === undefined) process.stderr.write(`fascicle-viewer: listening for HTTP push on ${handle.url}/api/ingest\\n`)\n process.stderr.write(`fascicle-viewer: viewer at ${handle.url}\\n`)\n\n if (args.open) open_browser(handle.url)\n\n const shutdown = async (): Promise<void> => {\n process.stderr.write('\\nfascicle-viewer: shutting down\\n')\n await handle.close()\n process.exit(0)\n }\n process.on('SIGINT', () => { void shutdown() })\n process.on('SIGTERM', () => { void shutdown() })\n}\n\n/**\n * Renders an unknown thrown value as a human-readable message.\n */\nfunction describe_error(err: unknown): string {\n if (err instanceof Error) return err.message\n try {\n return JSON.stringify(err)\n } catch {\n return String(err)\n }\n}\n\n// ESM main-module detection. The bundler inlines this file into dist/index.js,\n// so a fragile suffix check (`endsWith('/cli.js')`) would fire whenever a\n// consumer's own entry script happened to be named cli.js, see\n// https://nodejs.org/api/esm.html#importmetaurl. Compare the resolved path of\n// this module against argv[1] so the auto-execute only fires when the file is\n// run directly (for example, `tsx src/viewer/cli.ts`), not when imported.\nconst invoked_directly =\n process.argv[1] !== undefined &&\n process.argv[1] === fileURLToPath(import.meta.url)\n\nif (invoked_directly) {\n void run_viewer_cli(process.argv.slice(2)).catch((err: unkn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;CAChE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
|
1
|
+
{"version":3,"file":"viewer.js","names":["fs_watch"],"sources":["../src/viewer/broadcast.ts","../src/viewer/server.ts","../src/viewer/tail.ts","../src/viewer/start_viewer.ts","../src/viewer/cli.ts"],"sourcesContent":["/**\n * In-process pub/sub for trajectory events.\n *\n * One ring buffer of the last N events plus a Set of subscriber callbacks.\n * Both producers (file tail and HTTP ingest) push into the same broadcaster;\n * SSE writers fan out via `subscribe`.\n */\n\nimport type { ParsedTrajectoryEvent } from '#core'\n\nexport type BroadcastEvent = {\n readonly id: number\n readonly event: ParsedTrajectoryEvent\n}\n\nexport type Subscriber = (entry: BroadcastEvent) => void\n\nexport type Broadcaster = {\n readonly emit: (event: ParsedTrajectoryEvent) => BroadcastEvent\n readonly subscribe: (fn: Subscriber) => () => void\n readonly snapshot: () => readonly BroadcastEvent[]\n readonly snapshot_after: (last_id: number) => readonly BroadcastEvent[]\n readonly size: () => number\n}\n\nexport type BroadcasterConfig = {\n readonly buffer: number\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\n/**\n * Creates a broadcaster: a bounded ring buffer plus subscriber fan-out.\n *\n * Each event gets a monotonic `id` so SSE clients can replay from a known\n * cursor on reconnect (`snapshot_after`). `emit` does not await delivery, so\n * slow-client backpressure is the subscriber's responsibility. A subscriber\n * that throws is unsubscribed, and the `on_subscriber_error` callback fires\n * once with the captured error so the server can log it.\n */\nexport function create_broadcaster(config: BroadcasterConfig): Broadcaster {\n // `| 0` truncates fractional sizes; clamp so the ring keeps at least one\n // event.\n const max = Math.max(1, config.buffer | 0)\n const ring: BroadcastEvent[] = []\n const subscribers = new Set<Subscriber>()\n let next_id = 1\n\n const emit = (event: ParsedTrajectoryEvent): BroadcastEvent => {\n const entry: BroadcastEvent = { id: next_id++, event }\n ring.push(entry)\n if (ring.length > max) ring.splice(0, ring.length - max)\n // Iterate a copy so deleting a throwing subscriber (or an unsubscribe\n // triggered from inside a callback) cannot upset the live Set.\n for (const fn of Array.from(subscribers)) {\n try {\n fn(entry)\n } catch (err) {\n subscribers.delete(fn)\n if (config.on_subscriber_error) config.on_subscriber_error(err)\n }\n }\n return entry\n }\n\n const subscribe = (fn: Subscriber): (() => void) => {\n subscribers.add(fn)\n return () => { subscribers.delete(fn) }\n }\n\n const snapshot = (): readonly BroadcastEvent[] => [...ring]\n\n const snapshot_after = (last_id: number): readonly BroadcastEvent[] =>\n ring.filter((e) => e.id > last_id)\n\n const size = (): number => ring.length\n\n return { emit, subscribe, snapshot, snapshot_after, size }\n}\n","/**\n * Tiny HTTP server: 5 API routes, SSE fan-out, NDJSON ingest, plus the\n * compiled run canvas served as static files.\n *\n * GET /api/events -> text/event-stream, replaying past the client cursor\n * GET /api/trajectory -> the full run history as NDJSON (file, or ring)\n * GET /api/snapshot -> JSON dump of the ring buffer\n * POST /api/ingest -> newline-delimited trajectory events (http_logger)\n * GET /api/health -> { ok: true }\n * GET /<anything> -> a file from the compiled app, `/` being index.html\n *\n * The server owns nothing but the socket. The broadcaster owns the recent\n * event ring; the tailed file owns the full history; the canvas is a vite build\n * on disk. A client folds `/api/trajectory` for the whole run and then follows\n * `/api/events`, which replays anything past the cursor it names and streams\n * new events live. The ring is bounded memory by design, so history older than\n * it is served from the file the tail already reads (D7).\n */\n\nimport { createReadStream, statSync, type Stats } from 'node:fs'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport { dirname, extname, resolve, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { parse_trajectory_event, type ParsedTrajectoryEvent } from '#core'\nimport type { Broadcaster } from './broadcast.js'\n\nconst SSE_HEARTBEAT_MS = 15_000\nconst HERE = dirname(fileURLToPath(import.meta.url))\n\n/**\n * The header `/api/trajectory` stamps with the broadcaster's newest id: the\n * seam the client resumes SSE from after folding the history dump. The client\n * carries the same literal (`app/history.ts`); the two ends cannot share a\n * module because the browser bundle must not pull in node builtins.\n */\nconst CURSOR_HEADER = 'x-fascicle-cursor'\n\n/**\n * Content types for everything the compiled app ships. Anything outside the\n * map is served as an opaque download rather than guessed at, which keeps a\n * stray file from being executed as script by a browser.\n */\nconst CONTENT_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css; charset=utf-8',\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain; charset=utf-8',\n '.woff2': 'font/woff2',\n}\n\nconst FALLBACK_CONTENT_TYPE = 'application/octet-stream'\n\nexport type ServerConfig = {\n readonly broadcaster: Broadcaster\n readonly host: string\n readonly port: number\n /**\n * Where the compiled canvas lives, defaulting to the bundled\n * `dist/viewer-app`. The tests point it at a fixture directory so the suite\n * never depends on a build having run.\n */\n readonly app_dir?: string\n /**\n * The trajectory file `/api/trajectory` streams as full history. Absent when\n * the server is ingest-fed only, where that route falls back to the ring\n * (D7). Threaded from the tailed `path` by `start_viewer`.\n */\n readonly trajectory_path?: string\n readonly on_parse_error?: (err: unknown, line: string) => void\n}\n\nexport type ViewerServer = {\n readonly url: string\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the HTTP server and resolves once it is listening.\n *\n * Wires the four API routes (health, snapshot, SSE, ingest) plus the compiled\n * app's static files to a single request handler, and resolves with the bound\n * URL and a `close` that shuts the socket down. The API routes are matched\n * first and exactly, so no file the canvas ships can ever shadow one.\n */\nexport function start_server(config: ServerConfig): Promise<ViewerServer> {\n const { broadcaster, host, port, app_dir, trajectory_path, on_parse_error } = config\n\n const handler = (req: IncomingMessage, res: ServerResponse): void => {\n const route = resolve_route(req, host, port)\n\n if (route === 'GET /api/health') {\n send_json(res, 200, { ok: true })\n return\n }\n if (route === 'GET /api/snapshot') {\n send_json(res, 200, { events: broadcaster.snapshot() })\n return\n }\n if (route === 'GET /api/trajectory') {\n serve_trajectory(res, broadcaster, trajectory_path)\n return\n }\n if (route === 'GET /api/events') {\n handle_sse(req, res, broadcaster)\n return\n }\n if (route === 'POST /api/ingest') {\n handle_ingest(req, res, broadcaster, on_parse_error)\n return\n }\n if (route.startsWith('GET /')) {\n serve_app_asset(res, route, app_dir)\n return\n }\n send_not_found(res, route)\n }\n\n const http_server = createServer(handler)\n\n return new Promise((res_ok, res_err) => {\n // `listen` can fail (for example, port already in use); reject instead of\n // leaving the returned promise pending forever.\n http_server.once('error', res_err)\n http_server.listen(port, host, () => {\n http_server.removeListener('error', res_err)\n const url = `http://${host}:${bound_port_of(http_server.address(), port)}`\n res_ok({\n url,\n close: () => close_server(http_server),\n })\n })\n })\n}\n\n/**\n * Resolves the port a listening server actually bound to.\n *\n * `address()` is only an `AddressInfo` for a TCP listen; it is a path string\n * for a unix socket and `null` before listening, so the fallback covers both.\n * The bound port differs from the requested one only when the caller passed 0\n * and asked the OS to pick a free port.\n */\nexport function bound_port_of(addr: ReturnType<Server['address']>, fallback: number): number {\n return addr !== null && typeof addr === 'object' && 'port' in addr ? addr.port : fallback\n}\n\n/**\n * Builds a `\"METHOD /path\"` route key from a request.\n *\n * Resolves the path against the client's `Host` header when it parses, and\n * against the server's own `host`/`port` otherwise. A header can be present yet\n * malformed (`'in valid'`), which `??` cannot catch because it is neither null\n * nor undefined; fed to `new URL` it throws. Trying the header inside a\n * try/catch and falling back to the server's authority keeps route resolution\n * total for any header a client sends.\n */\nexport function resolve_route(\n req: {\n url?: string | undefined\n method?: string | undefined\n headers: { host?: string | undefined }\n },\n host: string,\n port: number,\n): string {\n const method = req.method ?? 'GET'\n const path = req.url ?? '/'\n const header = req.headers.host\n if (header !== undefined) {\n try {\n return `${method} ${new URL(path, `http://${header}`).pathname}`\n } catch {\n // A malformed Host header falls through to the server's own authority.\n }\n }\n return `${method} ${new URL(path, `http://${host}:${port}`).pathname}`\n}\n\n/**\n * Closes the HTTP server and resolves once every connection is torn down.\n */\nfunction close_server(server: Server): Promise<void> {\n return new Promise((res_ok, res_err) => {\n server.close((err) => {\n if (err) res_err(err)\n else res_ok()\n })\n // `close` alone only stops new connections and waits for existing ones\n // (including open SSE streams) to end on their own, which can hang\n // indefinitely. Force them closed so shutdown actually completes.\n // `closeAllConnections` has existed since node 18.2 and `engines.node` is\n // `>=24`, so the call is unconditional.\n server.closeAllConnections()\n })\n}\n\n/**\n * Writes a JSON response with the given status code.\n */\nfunction send_json(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify(body))\n}\n\n/**\n * Writes the JSON 404 that names the route that missed.\n */\nfunction send_not_found(res: ServerResponse, route: string): void {\n send_json(res, 404, { error: 'not_found', route })\n}\n\n/**\n * Handles `GET /api/trajectory` by streaming the whole run history as NDJSON,\n * one event per line, so the client folds the full run before it follows the\n * live tail (D7).\n *\n * The tailed file is the source of truth: its bytes stream straight through,\n * which keeps memory bounded no matter how long the run grew, and a finished\n * `.jsonl` opened with no live producer becomes the same client path as live.\n * An ingest-fed server has no file, so it falls back to the ring buffer, the\n * only history it holds. Either way the response is stamped with the\n * broadcaster's newest id, the seam the client resumes SSE from; the client\n * still takes the larger of that and its own folded count, so a file that ran\n * ahead of the broadcaster is not re-folded.\n */\nfunction serve_trajectory(\n res: ServerResponse,\n broadcaster: Broadcaster,\n trajectory_path: string | undefined,\n): void {\n const ring = broadcaster.snapshot()\n res.statusCode = 200\n res.setHeader('content-type', 'application/x-ndjson; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n res.setHeader(CURSOR_HEADER, String(ring.at(-1)?.id ?? 0))\n\n // The two guards are nested rather than joined with `&&` on purpose: only a\n // present file reaches `createReadStream`, so a path that is undefined (ingest\n // mode) or set-but-uncreated (a run not yet started) falls through to the\n // ring, the only history such a server holds (D7). `stat_file` returns null\n // for a missing path either way, which keeps the fallthrough total.\n if (trajectory_path !== undefined) {\n if (stat_file(trajectory_path) !== null) {\n createReadStream(trajectory_path).pipe(res)\n return\n }\n }\n res.end(ring.map((entry) => `${JSON.stringify(entry.event)}\\n`).join(''))\n}\n\n/**\n * Where the compiled canvas can be, relative to this module.\n *\n * Published, `viewer.js` sits in `dist/` beside `dist/viewer-app/`. Running\n * from source, this module is `src/viewer/server.ts` and the same build output\n * is two levels up in the repo's `dist/`. The two candidates never both exist\n * for the same install, so probing them in order is unambiguous.\n */\nfunction app_dir_candidates(here: string): readonly string[] {\n return [resolve(here, 'viewer-app'), resolve(here, '..', '..', 'dist', 'viewer-app')]\n}\n\n/**\n * The compiled app directory, or `null` when the canvas has not been built.\n *\n * A directory only counts once its `index.html` is really there, so a\n * half-written build reads as absent rather than as a directory that 404s\n * every asset.\n */\nfunction resolve_app_dir(override: string | undefined): string | null {\n const candidates = override === undefined ? app_dir_candidates(HERE) : [override]\n return candidates.find((dir) => stat_file(resolve(dir, 'index.html')) !== null) ?? null\n}\n\n/**\n * The stats of an existing regular file, or `null` for anything else.\n *\n * One syscall answers both questions the asset route asks: whether to serve\n * the path at all, and what `content-length` to declare. Reading the stats\n * before the stream opens is what keeps a missing file a clean 404 rather\n * than a stream error raised after the headers have gone out.\n */\nfunction stat_file(path: string): Stats | null {\n try {\n const stats = statSync(path)\n return stats.isFile() ? stats : null\n } catch {\n return null\n }\n}\n\n/**\n * Resolves a URL path inside the compiled app directory, or `null` when it\n * escapes it.\n *\n * The server is bound to localhost by default, but a browser will happily\n * send `/../../etc/passwd`, so containment is checked on the resolved path\n * rather than trusted from the URL text.\n */\nfunction resolve_app_file(dir: string, url_path: string): string | null {\n const file = resolve(dir, `.${url_path}`)\n if (file !== dir && !file.startsWith(dir + sep)) return null\n return file === dir ? resolve(dir, 'index.html') : file\n}\n\n/**\n * Streams one file of the compiled canvas as the response body.\n *\n * A missing app directory is a 500 naming the build step, because the server\n * is fine and the operator forgot to compile; a missing file inside a present\n * app is an ordinary 404.\n */\nfunction serve_app_asset(res: ServerResponse, route: string, override: string | undefined): void {\n const dir = resolve_app_dir(override)\n if (dir === null) {\n res.statusCode = 500\n res.setHeader('content-type', 'text/plain')\n res.end('viewer app not built; run `pnpm build`')\n return\n }\n\n // The route key is `\"<METHOD> <path>\"`; splitting on the space keeps the\n // path independent of which method got here, so the GET guard above stays\n // the only thing deciding whether a non-GET reaches the filesystem.\n const file = resolve_app_file(dir, route.slice(route.indexOf(' ') + 1))\n const stats = file === null ? null : stat_file(file)\n if (file === null || stats === null) {\n send_not_found(res, route)\n return\n }\n\n res.statusCode = 200\n res.setHeader('content-type', CONTENT_TYPES[extname(file)] ?? FALLBACK_CONTENT_TYPE)\n // A localhost dev tool is rebuilt while its tab is open, so nothing it\n // serves may be cached: a stale bundle would look like a broken canvas.\n res.setHeader('cache-control', 'no-store')\n res.setHeader('content-length', String(stats.size))\n createReadStream(file).pipe(res)\n}\n\n/**\n * Handles `GET /api/events` by turning the connection into an SSE stream.\n *\n * Replays whatever the client missed since its cursor, subscribes it to the\n * broadcaster for new events, and keeps the connection alive with a periodic\n * heartbeat comment. The cursor is the furthest the client can name: the\n * `Last-Event-ID` a reconnecting browser sends, or the `?since=` a fresh load\n * sets after folding `/api/trajectory`, because native `EventSource` cannot set\n * the header on a first connect. That same cursor guards the live subscription,\n * so an event the history dump already carried is never delivered twice when\n * the file ran ahead of the broadcaster at dump time.\n */\nfunction handle_sse(req: IncomingMessage, res: ServerResponse, broadcaster: Broadcaster): void {\n res.statusCode = 200\n res.setHeader('content-type', 'text/event-stream')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('connection', 'keep-alive')\n // Disables response buffering in nginx so SSE frames reach the client as\n // soon as they are written instead of sitting in a proxy buffer.\n res.setHeader('x-accel-buffering', 'no')\n\n // Node holds the response head back until something is written, so a stream\n // that opens on an empty ring buffer would sit headerless until the first\n // heartbeat 15 seconds later, and `EventSource` would not raise `open` until\n // then. One comment frame flushes the head immediately and is ignored by\n // every SSE client.\n res.write(': connected\\n\\n')\n\n // Replay everything after the client's cursor before subscribing. Both\n // calls run synchronously back to back, so there is no window in which\n // an event could land between the replay and the live subscription.\n const cursor = Math.max(\n parse_last_event_id(req.headers['last-event-id']),\n parse_since(req.url),\n )\n for (const entry of broadcaster.snapshot_after(cursor)) {\n write_event(res, entry.id, entry.event)\n }\n\n // Comment frames keep the connection alive through idle proxies and\n // load balancers that would otherwise time out a quiet SSE stream.\n const heartbeat = setInterval(() => {\n res.write(': heartbeat\\n\\n')\n }, SSE_HEARTBEAT_MS)\n\n // The live guard matters only when the cursor sits ahead of the ring: a fresh\n // load that folded a file the broadcaster had not caught up to. In the common\n // reconnect case every live id is already past the cursor, so nothing drops.\n const unsubscribe = broadcaster.subscribe((entry) => {\n if (entry.id > cursor) write_event(res, entry.id, entry.event)\n })\n\n const close = (): void => {\n clearInterval(heartbeat)\n unsubscribe()\n if (!res.writableEnded) {\n res.write('event: close\\ndata: {}\\n\\n')\n res.end()\n }\n }\n\n // A clean disconnect and a socket error both need the same cleanup.\n req.on('close', close)\n req.on('error', close)\n}\n\n/**\n * Parses the `Last-Event-ID` header into a replay cursor, defaulting to 0.\n *\n * Treats a missing header or a non-numeric or non-positive value as \"no\n * cursor\", which makes `handle_sse` replay the full ring buffer.\n */\nfunction parse_last_event_id(value: string | string[] | undefined): number {\n if (typeof value !== 'string') return 0\n const n = Number.parseInt(value, 10)\n return Number.isFinite(n) && n > 0 ? n : 0\n}\n\n/**\n * Parses the `?since=` cursor off a request URL, defaulting to 0.\n *\n * A fresh load sets it after folding `/api/trajectory`, since native\n * `EventSource` cannot send a `Last-Event-ID` header on a first connect. The\n * value reuses `parse_last_event_id`'s number rule, so a missing, absent, or\n * unusable `since` reads as \"no cursor\" exactly as the header does.\n */\nfunction parse_since(url: string | undefined): number {\n if (typeof url !== 'string') return 0\n const query = url.indexOf('?')\n if (query === -1) return 0\n return parse_last_event_id(new URLSearchParams(url.slice(query + 1)).get('since') ?? undefined)\n}\n\n/**\n * Writes one SSE `trajectory` event frame to the response stream.\n */\nfunction write_event(res: ServerResponse, id: number, event: ParsedTrajectoryEvent): void {\n res.write(`id: ${id}\\nevent: trajectory\\ndata: ${JSON.stringify(event)}\\n\\n`)\n}\n\n/**\n * Handles `POST /api/ingest`: parses newline-delimited trajectory events\n * from the request body and feeds valid ones into the broadcaster.\n *\n * Reports how many lines were accepted vs rejected in the response body;\n * a malformed line is skipped and reported via `on_parse_error`, not\n * treated as a fatal request error.\n */\nfunction handle_ingest(\n req: IncomingMessage,\n res: ServerResponse,\n broadcaster: Broadcaster,\n on_parse_error?: (err: unknown, line: string) => void,\n): void {\n let buf = ''\n let accepted = 0\n let rejected = 0\n\n const consume_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n rejected++\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = parse_trajectory_event(parsed)\n if (!result.success) {\n rejected++\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n broadcaster.emit(result.data)\n accepted++\n }\n\n req.setEncoding('utf8')\n req.on('data', (chunk: string) => {\n buf += chunk\n // Consume every complete line in the buffer so far; a trailing partial\n // line (no `\\n` yet) stays in `buf` until a later chunk completes it.\n let nl = buf.indexOf('\\n')\n while (nl !== -1) {\n consume_line(buf.slice(0, nl))\n buf = buf.slice(nl + 1)\n nl = buf.indexOf('\\n')\n }\n })\n req.on('end', () => {\n // Flush a final line that arrived without a trailing newline.\n if (buf.length > 0) consume_line(buf)\n send_json(res, 200, { accepted, rejected })\n })\n req.on('error', (err: unknown) => {\n if (on_parse_error) on_parse_error(err, '')\n send_json(res, 400, { error: 'bad_request' })\n })\n}\n\nexport const internals_for_test = {\n SSE_HEARTBEAT_MS,\n CURSOR_HEADER,\n app_dir_candidates,\n resolve_app_dir,\n resolve_app_file,\n parse_last_event_id,\n parse_since,\n serve_trajectory,\n handle_sse,\n handle_ingest,\n}\n","/**\n * JSONL file tailer.\n *\n * Watches a file for appends and emits one parsed trajectory event per\n * complete line. Handles three pathological cases:\n *\n * - Truncation / rotation: a watcher event whose stat is shorter than the\n * current offset means the file shrunk. Reset offset to 0 and re-stream.\n * - Partial last line: if the trailing chunk has no `\\n`, buffer it and\n * wait. Never parse a half-written line.\n * - Schema failures: a line that fails `parse_trajectory_event` is\n * dropped and surfaced to `on_parse_error`. The stream keeps going.\n *\n * The watcher is fs.watch-based; reads are serialized and change events\n * that arrive mid-read are coalesced into one extra pass rather than\n * dropped, so a burst of appends never starts overlapping reads. Each pass\n * re-stats and re-reads from the saved offset, which also covers platforms\n * where fs.watch misses some append notifications: the next successful\n * change event catches the file up regardless.\n */\n\nimport { type FSWatcher, watch as fs_watch } from 'node:fs'\nimport { open, stat } from 'node:fs/promises'\nimport { parse_trajectory_event, type ParsedTrajectoryEvent } from '#core'\n\nexport type TailConfig = {\n readonly path: string\n readonly on_event: (event: ParsedTrajectoryEvent) => void\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n}\n\nexport type Tail = {\n readonly stop: () => void\n readonly drain: () => Promise<void>\n}\n\n/**\n * Starts tailing `path` and returns a handle to stop or drain it.\n *\n * Watches the file with `fs.watch` and re-reads from the last known offset\n * on every change, buffering an incomplete trailing line until the rest\n * arrives. Overlapping change events are coalesced: a read already in\n * flight absorbs any events that fire while it runs instead of starting a\n * second concurrent read.\n */\nexport function start_tail(config: TailConfig): Tail {\n const { path, on_event, on_parse_error, on_io_error } = config\n let offset = 0\n let buffer = ''\n let busy = false\n let pending = false\n let closed = false\n let watcher: FSWatcher | null = null\n let last_drain: Promise<void> = Promise.resolve()\n\n const handle_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = parse_trajectory_event(parsed)\n if (!result.success) {\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n on_event(result.data)\n }\n\n const read_more = async (): Promise<void> => {\n let st\n try {\n st = await stat(path)\n } catch (err) {\n if (on_io_error) on_io_error(err)\n return\n }\n if (st.size < offset) {\n // File is shorter than our offset: it was truncated or rotated.\n // Restart from the top instead of seeking to a now-invalid offset.\n offset = 0\n buffer = ''\n }\n if (st.size === offset) return\n\n const fh = await open(path, 'r').catch((err: unknown) => {\n if (on_io_error) on_io_error(err)\n return null\n })\n if (!fh) return\n try {\n const length = st.size - offset\n const buf = Buffer.alloc(length)\n const { bytesRead } = await fh.read(buf, 0, length, offset)\n offset += bytesRead\n buffer += buf.subarray(0, bytesRead).toString('utf8')\n } finally {\n await fh.close()\n }\n\n let nl = buffer.indexOf('\\n')\n while (nl !== -1) {\n const line = buffer.slice(0, nl)\n buffer = buffer.slice(nl + 1)\n handle_line(line)\n nl = buffer.indexOf('\\n')\n }\n // Anything left in `buffer` has no trailing newline yet; keep it for\n // the next read instead of parsing a half-written line.\n }\n\n // Coalesces watcher bursts: if `schedule` fires while a read is already\n // running, it just flags `pending` and returns. The running loop below\n // checks `pending` after each pass and does one more pass if it was set,\n // so a burst of change events never starts overlapping reads.\n const schedule = (): void => {\n if (closed) return\n if (busy) {\n pending = true\n return\n }\n busy = true\n last_drain = (async (): Promise<void> => {\n try {\n let keep_going = true\n while (keep_going) {\n pending = false\n await read_more()\n keep_going = pending && !closed\n }\n } finally {\n busy = false\n }\n })()\n }\n\n schedule()\n\n try {\n watcher = fs_watch(path, { persistent: true }, () => { schedule() })\n } catch (err) {\n if (on_io_error) on_io_error(err)\n }\n\n const stop = (): void => {\n closed = true\n if (watcher) {\n watcher.close()\n watcher = null\n }\n }\n\n const drain = async (): Promise<void> => {\n schedule()\n await last_drain\n }\n\n return { stop, drain }\n}\n","/**\n * `start_viewer` programmatic embed implementation.\n *\n * Spin up the server, optionally start tailing a JSONL file, and return a\n * handle that can stop both. `start_viewer` only depends on core's wire-format\n * schema; it never reaches into the engine, composites, or any provider.\n */\n\nimport { create_broadcaster } from './broadcast.js'\nimport { start_server, type ViewerServer } from './server.js'\nimport { start_tail, type Tail } from './tail.js'\n\nexport type StartViewerOptions = {\n readonly path?: string\n readonly host?: string\n readonly port?: number\n readonly buffer?: number\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\nexport type ViewerHandle = {\n readonly url: string\n readonly host: string\n readonly port: number\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the viewer: brings up the HTTP/SSE server and, if `options.path`\n * is set, a file tail that feeds the same broadcaster.\n *\n * Defaults to `127.0.0.1:4242` with a 1000-event ring buffer. HTTP ingest\n * and SSE are always available; tailing is opt-in via `path`.\n */\nexport async function start_viewer(options: StartViewerOptions = {}): Promise<ViewerHandle> {\n const host = options.host ?? '127.0.0.1'\n const port = options.port ?? 4242\n const buffer = options.buffer ?? 1000\n const broadcaster = create_broadcaster({\n buffer,\n ...(options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}),\n })\n const server = await start_server({\n broadcaster,\n host,\n port,\n // The tailed file is `/api/trajectory`'s full-history source (D7); an\n // ingest-only viewer leaves it unset and that route serves the ring.\n ...(options.path !== undefined ? { trajectory_path: options.path } : {}),\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n })\n\n let tail: Tail | null = null\n if (options.path !== undefined) {\n tail = start_tail({\n path: options.path,\n on_event: (event) => { broadcaster.emit(event) },\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n ...(options.on_io_error ? { on_io_error: options.on_io_error } : {}),\n })\n }\n\n return wrap_handle(server, tail, host)\n}\n\n/**\n * Combines the server and optional tail into a single `ViewerHandle`.\n *\n * `close` stops the tail first, then closes the server, mirroring the\n * startup order (server first, tail second) in reverse. The port is read\n * back from `server.url` rather than the requested `port` option, since\n * a caller that passes `0` gets whatever port the OS actually bound.\n */\nfunction wrap_handle(server: ViewerServer, tail: Tail | null, host: string): ViewerHandle {\n return {\n url: server.url,\n host,\n port: Number(new URL(server.url).port),\n close: async () => {\n if (tail) tail.stop()\n await server.close()\n },\n }\n}\n","#!/usr/bin/env tsx\n/**\n * fascicle-viewer CLI.\n *\n * fascicle-viewer <path> # tail a JSONL file (primary)\n * fascicle-viewer --listen # accept HTTP push only\n * fascicle-viewer <path> --listen # both producers feed the same broadcaster\n *\n * Flags: --port <n> --host <h> --buffer <n> --no-open --help\n *\n * Defaults bind 127.0.0.1:4242 and open the user's default browser. SIGINT\n * shuts everything down cleanly. The CLI body is exposed as `run_viewer_cli`\n * so the umbrella's bin shim can drive it from a bundled `dist/index.js`.\n */\n\nimport { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { parseArgs } from 'node:util'\nimport { fileURLToPath } from 'node:url'\nimport { start_viewer } from './start_viewer.js'\n\ntype CliArgs = {\n readonly path?: string\n readonly host: string\n readonly port: number\n readonly buffer: number\n readonly listen: boolean\n readonly open: boolean\n}\n\nconst HELP = `\\\nfascicle-viewer — minimal in-repo dashboard for fascicle trajectory streams.\n\nUsage:\n fascicle-viewer <path> tail a JSONL file\n fascicle-viewer --listen accept HTTP push only\n fascicle-viewer <path> --listen both producers feed the same broadcaster\n\nOptions:\n --port <n> port (default 4242)\n --host <h> bind host (default 127.0.0.1; --host 0.0.0.0 warns)\n --buffer <n> ring-buffer size (default 1000)\n --no-open do not open the browser\n --help show this message\n`\n\n/**\n * Parses CLI argv into a validated `CliArgs`, exiting on bad input.\n *\n * `--help` prints usage and exits 0. Invalid numeric flags, or a missing\n * <path> without `--listen`, write to stderr and exit 2.\n */\nexport function parse(argv: readonly string[]): CliArgs {\n const { values, positionals } = parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: {\n port: { type: 'string', default: '4242' },\n host: { type: 'string', default: '127.0.0.1' },\n buffer: { type: 'string', default: '1000' },\n listen: { type: 'boolean', default: false },\n open: { type: 'boolean', default: true },\n 'no-open': { type: 'boolean', default: false },\n help: { type: 'boolean', default: false },\n },\n })\n if (values.help) {\n process.stdout.write(HELP)\n process.exit(0)\n }\n const port_raw = values.port ?? '4242'\n const buffer_raw = values.buffer ?? '1000'\n const port = Number.parseInt(port_raw, 10)\n const buffer = Number.parseInt(buffer_raw, 10)\n if (!Number.isFinite(port) || port <= 0) {\n process.stderr.write(\n `fascicle-viewer: invalid --port '${port_raw}': expected a positive integer\\n`,\n )\n process.exit(2)\n }\n if (!Number.isFinite(buffer) || buffer <= 0) {\n process.stderr.write(\n `fascicle-viewer: invalid --buffer '${buffer_raw}': expected a positive integer\\n`,\n )\n process.exit(2)\n }\n const path = positionals[0]\n const listen = values.listen ?? false\n if (path === undefined && !listen) {\n process.stderr.write('fascicle-viewer: a <path> is required unless --listen is set\\n')\n process.stderr.write(HELP)\n process.exit(2)\n }\n return {\n ...(path !== undefined ? { path } : {}),\n host: values.host ?? '127.0.0.1',\n port,\n buffer,\n listen,\n open: !values['no-open'] && (values.open ?? true),\n }\n}\n\n/**\n * Opens `url` in the platform's default browser, best-effort.\n *\n * Spawns the platform opener (`open`, `cmd /c start`, or `xdg-open`)\n * detached and swallows failures; the CLI prints the URL either way.\n */\nexport function open_browser(url: string): void {\n const platform = process.platform\n const cmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open'\n const args = platform === 'win32' ? ['/c', 'start', '\"\"', url] : [url]\n try {\n const child = spawn(cmd, args, { stdio: 'ignore', detached: true })\n child.on('error', () => {})\n child.unref()\n } catch {\n // Best-effort. The CLI logs the URL anyway.\n }\n}\n\n/**\n * CLI entry point: parses argv, starts the viewer, and wires shutdown.\n *\n * Warns but proceeds when the tailed path does not exist yet or when the\n * bind host is 0.0.0.0 (the dashboard has no auth). Optionally opens the\n * browser, then installs SIGINT/SIGTERM handlers that close the viewer\n * before exiting.\n */\nexport async function run_viewer_cli(argv: readonly string[]): Promise<void> {\n const args = parse(argv)\n\n if (args.path !== undefined && !existsSync(args.path)) {\n process.stderr.write(\n `fascicle-viewer: warning: ${args.path} does not exist yet — will pick up events once it is created\\n`,\n )\n }\n if (args.host === '0.0.0.0') {\n process.stderr.write(\n 'fascicle-viewer: warning: binding 0.0.0.0 — this dashboard has no auth and exposes whatever is in your trajectory stream\\n',\n )\n }\n\n const handle = await start_viewer({\n ...(args.path !== undefined ? { path: args.path } : {}),\n host: args.host,\n port: args.port,\n buffer: args.buffer,\n on_parse_error: (err, line) => {\n const preview = line.length > 120 ? `${line.slice(0, 120)}…` : line\n process.stderr.write(\n `fascicle-viewer: skipped malformed line: ${preview}\\n ${describe_error(err)}\\n`,\n )\n },\n on_io_error: (err) => {\n process.stderr.write(`fascicle-viewer: io error: ${describe_error(err)}\\n`)\n },\n })\n\n if (args.path !== undefined) process.stderr.write(`fascicle-viewer: watching ${args.path}\\n`)\n if (args.listen || args.path === undefined) process.stderr.write(`fascicle-viewer: listening for HTTP push on ${handle.url}/api/ingest\\n`)\n process.stderr.write(`fascicle-viewer: viewer at ${handle.url}\\n`)\n\n if (args.open) open_browser(handle.url)\n\n const shutdown = async (): Promise<void> => {\n process.stderr.write('\\nfascicle-viewer: shutting down\\n')\n await handle.close()\n process.exit(0)\n }\n process.on('SIGINT', () => { void shutdown() })\n process.on('SIGTERM', () => { void shutdown() })\n}\n\n/**\n * Renders an unknown thrown value as a human-readable message.\n */\nfunction describe_error(err: unknown): string {\n if (err instanceof Error) return err.message\n try {\n return JSON.stringify(err)\n } catch {\n return String(err)\n }\n}\n\n// ESM main-module detection. The bundler inlines this file into dist/index.js,\n// so a fragile suffix check (`endsWith('/cli.js')`) would fire whenever a\n// consumer's own entry script happened to be named cli.js, see\n// https://nodejs.org/api/esm.html#importmetaurl. Compare the resolved path of\n// this module against argv[1] so the auto-execute only fires when the file is\n// run directly (for example, `tsx src/viewer/cli.ts`), not when imported.\nconst invoked_directly =\n process.argv[1] !== undefined &&\n process.argv[1] === fileURLToPath(import.meta.url)\n\nif (invoked_directly) {\n void run_viewer_cli(process.argv.slice(2)).catch((err: unknown) => {\n process.stderr.write(`fascicle-viewer: ${describe_error(err)}\\n`)\n process.exit(1)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,mBAAmB,QAAwC;CAGzE,MAAM,MAAM,KAAK,IAAI,GAAG,OAAO,SAAS,CAAC;CACzC,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,KAAK,SAAS,KAAA,GAAW,QAAQ,OAAO,MAAM,6BAA6B,KAAK,KAAK,GAAG;CAC5F,IAAI,KAAK,UAAU,KAAK,SAAS,KAAA,GAAW,QAAQ,OAAO,MAAM,+CAA+C,OAAO,IAAI,cAAc;CACzI,QAAQ,OAAO,MAAM,8BAA8B,OAAO,IAAI,GAAG;CAEjE,IAAI,KAAK,MAAM,aAAa,OAAO,GAAG;CAEtC,MAAM,WAAW,YAA2B;EAC1C,QAAQ,OAAO,MAAM,oCAAoC;EACzD,MAAM,OAAO,MAAM;EACnB,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,GAAG,gBAAgB;EAAE,SAAc;CAAE,CAAC;CAC9C,QAAQ,GAAG,iBAAiB;EAAE,SAAc;CAAE,CAAC;AACjD;;;;AAKA,SAAS,eAAe,KAAsB;CAC5C,IAAI,eAAe,OAAO,OAAO,IAAI;CACrC,IAAI;EACF,OAAO,KAAK,UAAU,GAAG;CAC3B,QAAQ;EACN,OAAO,OAAO,GAAG;CACnB;AACF;AAYA,IAHE,QAAQ,KAAK,OAAO,KAAA,KACpB,QAAQ,KAAK,OAAO,cAAc,OAAO,KAAK,GAAG,GAGjD,eAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,QAAiB;CACjE,QAAQ,OAAO,MAAM,oBAAoB,eAAe,GAAG,EAAE,GAAG;CAChE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fascicle",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.8",
|
|
4
4
|
"description": "Compose agents like plain values. A TypeScript toolkit that wires LLM calls, tools, and functions into typed steps over eight providers. No framework, no ambient state.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agents",
|
|
@@ -131,13 +131,16 @@
|
|
|
131
131
|
"check:changed": "checkride --changed",
|
|
132
132
|
"check:fix": "pnpm exec oxlint --type-aware --fix && node scripts/strip-semicolons.mjs && pnpm exec fallow fix",
|
|
133
133
|
"check:mutation": "stryker run",
|
|
134
|
+
"check:e2e": "playwright test",
|
|
134
135
|
"check:publish": "checkride --only publint,attw,pack,smoke,snippets",
|
|
135
136
|
"check:security": "checkride --only security",
|
|
136
137
|
"prepublishOnly": "pnpm check && pnpm build && pnpm check:publish",
|
|
137
138
|
"test": "vitest run",
|
|
138
139
|
"test:watch": "vitest",
|
|
139
140
|
"types": "tsc --noEmit",
|
|
140
|
-
"fascicle-viewer": "tsx src/viewer/cli.ts"
|
|
141
|
+
"fascicle-viewer": "tsx src/viewer/cli.ts",
|
|
142
|
+
"viewer:app": "vite build --config vite.viewer.config.ts",
|
|
143
|
+
"viewer:app:watch": "vite build --watch --config vite.viewer.config.ts"
|
|
141
144
|
},
|
|
142
145
|
"peerDependencies": {
|
|
143
146
|
"@ai-sdk/amazon-bedrock": "^5.0.0",
|
|
@@ -204,6 +207,7 @@
|
|
|
204
207
|
"@opentelemetry/resources": "^2.10.0",
|
|
205
208
|
"@opentelemetry/sdk-metrics": "2.10.0",
|
|
206
209
|
"@opentelemetry/sdk-trace-base": "2.10.0",
|
|
210
|
+
"@playwright/test": "1.62.1",
|
|
207
211
|
"@standard-schema/spec": "1.1.0",
|
|
208
212
|
"@stryker-mutator/core": "9.6.1",
|
|
209
213
|
"@stryker-mutator/vitest-runner": "9.6.1",
|
|
@@ -219,9 +223,12 @@
|
|
|
219
223
|
"oxlint": "1.73.0",
|
|
220
224
|
"oxlint-tsgolint": "0.24.0",
|
|
221
225
|
"publint": "0.3.21",
|
|
226
|
+
"solid-js": "1.9.15",
|
|
222
227
|
"tsdown": "0.22.3",
|
|
223
228
|
"tsx": "4.23.0",
|
|
224
229
|
"typescript": "6.0.3",
|
|
230
|
+
"vite": "8.2.2",
|
|
231
|
+
"vite-plugin-solid": "2.11.14",
|
|
225
232
|
"vitest": "4.1.10",
|
|
226
233
|
"zod": "4.4.3"
|
|
227
234
|
}
|