fascicle 0.12.0 → 0.12.3

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +148 -32
  2. package/README.md +25 -15
  3. package/dist/{adapters-hmnJOOgf.js → adapters-CutexJd3.js} +12 -12
  4. package/dist/adapters-CutexJd3.js.map +1 -0
  5. package/dist/adapters.d.ts +10 -10
  6. package/dist/adapters.js +1 -1
  7. package/dist/agents.d.ts +22 -3
  8. package/dist/agents.js +74 -24
  9. package/dist/agents.js.map +1 -1
  10. package/dist/bin/fascicle-viewer.js +2 -2
  11. package/dist/{core-BkB2l1-e.js → core-DdJEhyQc.js} +314 -501
  12. package/dist/core-DdJEhyQc.js.map +1 -0
  13. package/dist/engine-J4lIxpw5.js +7000 -0
  14. package/dist/engine-J4lIxpw5.js.map +1 -0
  15. package/dist/index.d.ts +237 -178
  16. package/dist/index.js +617 -7771
  17. package/dist/index.js.map +1 -1
  18. package/dist/{invoke-JkzNf7-Y.js → invoke-CH_eJZeS.js} +8 -8
  19. package/dist/{invoke-JkzNf7-Y.js.map → invoke-CH_eJZeS.js.map} +1 -1
  20. package/dist/{leading_system-BVtGMweY.js → leading_system-BUCT-PwD.js} +31 -8
  21. package/dist/leading_system-BUCT-PwD.js.map +1 -0
  22. package/dist/mcp.d.ts +5 -5
  23. package/dist/mcp.js +10 -9
  24. package/dist/mcp.js.map +1 -1
  25. package/dist/otel.d.ts +1 -1
  26. package/dist/otel.js +4 -4
  27. package/dist/otel.js.map +1 -1
  28. package/dist/static/viewer.html +2 -1
  29. package/dist/stdio.d.ts +2 -2
  30. package/dist/stdio.js +2 -2
  31. package/dist/testing.d.ts +66 -15
  32. package/dist/testing.js +200 -34
  33. package/dist/testing.js.map +1 -1
  34. package/dist/trajectory-ByoOQZ6T.d.ts +114 -0
  35. package/dist/trajectory-D1eq9eue.js +81 -0
  36. package/dist/trajectory-D1eq9eue.js.map +1 -0
  37. package/dist/{types-BCtKsxrX.d.ts → types-BK0UW28o.d.ts} +3 -3
  38. package/dist/{types-CVdTBXE_.d.ts → types-DBpU27sQ.d.ts} +20 -3
  39. package/dist/{types-4l54cexm.d.ts → types-DU6cvoA4.d.ts} +9 -5
  40. package/dist/ui.d.ts +2 -2
  41. package/dist/ui.js +1 -1
  42. package/dist/ui.js.map +1 -1
  43. package/dist/viewer.d.ts +117 -0
  44. package/dist/viewer.js +659 -0
  45. package/dist/viewer.js.map +1 -0
  46. package/package.json +26 -12
  47. package/dist/adapters-hmnJOOgf.js.map +0 -1
  48. package/dist/core-BkB2l1-e.js.map +0 -1
  49. package/dist/leading_system-BVtGMweY.js.map +0 -1
package/dist/viewer.js ADDED
@@ -0,0 +1,659 @@
1
+ import "./core-DdJEhyQc.js";
2
+ import { s as parse_trajectory_event } from "./trajectory-D1eq9eue.js";
3
+ import { open, stat } from "node:fs/promises";
4
+ import { dirname, resolve } from "node:path";
5
+ import { createReadStream, existsSync, statSync, watch } from "node:fs";
6
+ import { spawn } from "node:child_process";
7
+ import { fileURLToPath } from "node:url";
8
+ import { createServer } from "node:http";
9
+ import { parseArgs } from "node:util";
10
+ //#region src/viewer/broadcast.ts
11
+ /**
12
+ * Creates a broadcaster: a bounded ring buffer plus subscriber fan-out.
13
+ *
14
+ * Each event gets a monotonic `id` so SSE clients can replay from a known
15
+ * cursor on reconnect (`snapshot_after`). `emit` does not await delivery, so
16
+ * slow-client backpressure is the subscriber's responsibility. A subscriber
17
+ * that throws is unsubscribed, and the `on_subscriber_error` callback fires
18
+ * once with the captured error so the server can log it.
19
+ */
20
+ function create_broadcaster(config) {
21
+ const max = Math.max(1, config.buffer | 0);
22
+ const ring = [];
23
+ const subscribers = /* @__PURE__ */ new Set();
24
+ let next_id = 1;
25
+ const emit = (event) => {
26
+ const entry = {
27
+ id: next_id++,
28
+ event
29
+ };
30
+ ring.push(entry);
31
+ if (ring.length > max) ring.splice(0, ring.length - max);
32
+ for (const fn of Array.from(subscribers)) try {
33
+ fn(entry);
34
+ } catch (err) {
35
+ subscribers.delete(fn);
36
+ if (config.on_subscriber_error) config.on_subscriber_error(err);
37
+ }
38
+ return entry;
39
+ };
40
+ const subscribe = (fn) => {
41
+ subscribers.add(fn);
42
+ return () => {
43
+ subscribers.delete(fn);
44
+ };
45
+ };
46
+ const snapshot = () => [...ring];
47
+ const snapshot_after = (last_id) => ring.filter((e) => e.id > last_id);
48
+ const size = () => ring.length;
49
+ return {
50
+ emit,
51
+ subscribe,
52
+ snapshot,
53
+ snapshot_after,
54
+ size
55
+ };
56
+ }
57
+ //#endregion
58
+ //#region src/viewer/server.ts
59
+ /**
60
+ * Tiny HTTP server: 5 routes, SSE fan-out, NDJSON ingest.
61
+ *
62
+ * GET / -> static viewer.html
63
+ * GET /api/events -> text/event-stream replaying the ring buffer
64
+ * GET /api/snapshot -> JSON dump of the ring buffer
65
+ * POST /api/ingest -> newline-delimited trajectory events (http_logger)
66
+ * GET /api/health -> { ok: true }
67
+ *
68
+ * The server owns nothing but the socket. The broadcaster owns the event
69
+ * history; the static html lives on disk. SSE clients reconnect with
70
+ * `Last-Event-ID` and the server replays anything past their cursor from
71
+ * the ring buffer; older events are gone (bounded memory by design).
72
+ */
73
+ const SSE_HEARTBEAT_MS = 15e3;
74
+ const STATIC_HTML = resolve(dirname(fileURLToPath(import.meta.url)), "static", "viewer.html");
75
+ /**
76
+ * Starts the HTTP server and resolves once it is listening.
77
+ *
78
+ * Wires the five routes (static HTML, health, snapshot, SSE, ingest) to a
79
+ * single request handler and resolves with the bound URL and a `close`
80
+ * that shuts the socket down.
81
+ */
82
+ function start_server(config) {
83
+ const { broadcaster, host, port, on_parse_error } = config;
84
+ const handler = (req, res) => {
85
+ const route = resolve_route(req, host, port);
86
+ if (route === "GET /" || route === "GET /index.html") {
87
+ serve_static_html(res);
88
+ return;
89
+ }
90
+ if (route === "GET /api/health") {
91
+ send_json(res, 200, { ok: true });
92
+ return;
93
+ }
94
+ if (route === "GET /api/snapshot") {
95
+ send_json(res, 200, { events: broadcaster.snapshot() });
96
+ return;
97
+ }
98
+ if (route === "GET /api/events") {
99
+ handle_sse(req, res, broadcaster);
100
+ return;
101
+ }
102
+ if (route === "POST /api/ingest") {
103
+ handle_ingest(req, res, broadcaster, on_parse_error);
104
+ return;
105
+ }
106
+ res.statusCode = 404;
107
+ res.setHeader("content-type", "application/json");
108
+ res.end(JSON.stringify({
109
+ error: "not_found",
110
+ route
111
+ }));
112
+ };
113
+ const http_server = createServer(handler);
114
+ return new Promise((res_ok, res_err) => {
115
+ http_server.once("error", res_err);
116
+ http_server.listen(port, host, () => {
117
+ http_server.removeListener("error", res_err);
118
+ const addr = http_server.address();
119
+ const bound_port = addr !== null && typeof addr === "object" && "port" in addr ? addr.port : port;
120
+ res_ok({
121
+ url: `http://${host}:${bound_port}`,
122
+ close: () => close_server(http_server)
123
+ });
124
+ });
125
+ });
126
+ }
127
+ /**
128
+ * Builds a `"METHOD /path"` route key from a request.
129
+ *
130
+ * Falls back to the server's own `host`/`port` when the request has no
131
+ * `Host` header, so a malformed or missing header never throws inside
132
+ * `new URL`.
133
+ */
134
+ function resolve_route(req, host, port) {
135
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? `${host}:${port}`}`);
136
+ return `${req.method ?? "GET"} ${url.pathname}`;
137
+ }
138
+ /**
139
+ * Closes the HTTP server and resolves once every connection is torn down.
140
+ */
141
+ function close_server(server) {
142
+ return new Promise((res_ok, res_err) => {
143
+ server.close((err) => {
144
+ if (err) res_err(err);
145
+ else res_ok();
146
+ });
147
+ server.closeAllConnections?.();
148
+ });
149
+ }
150
+ /**
151
+ * Writes a JSON response with the given status code.
152
+ */
153
+ function send_json(res, status, body) {
154
+ res.statusCode = status;
155
+ res.setHeader("content-type", "application/json");
156
+ res.end(JSON.stringify(body));
157
+ }
158
+ /**
159
+ * Streams the bundled `viewer.html` as the response body.
160
+ */
161
+ function serve_static_html(res) {
162
+ let size;
163
+ try {
164
+ size = statSync(STATIC_HTML).size;
165
+ } catch {
166
+ res.statusCode = 500;
167
+ res.setHeader("content-type", "text/plain");
168
+ res.end("viewer.html missing");
169
+ return;
170
+ }
171
+ res.statusCode = 200;
172
+ res.setHeader("content-type", "text/html; charset=utf-8");
173
+ res.setHeader("cache-control", "no-store");
174
+ res.setHeader("content-length", String(size));
175
+ createReadStream(STATIC_HTML).pipe(res);
176
+ }
177
+ /**
178
+ * Handles `GET /api/events` by turning the connection into an SSE stream.
179
+ *
180
+ * Replays whatever the client missed since its `Last-Event-ID` cursor,
181
+ * subscribes it to the broadcaster for new events, and keeps the
182
+ * connection alive with a periodic heartbeat comment.
183
+ */
184
+ function handle_sse(req, res, broadcaster) {
185
+ res.statusCode = 200;
186
+ res.setHeader("content-type", "text/event-stream");
187
+ res.setHeader("cache-control", "no-store");
188
+ res.setHeader("connection", "keep-alive");
189
+ res.setHeader("x-accel-buffering", "no");
190
+ const last_event_id = parse_last_event_id(req.headers["last-event-id"]);
191
+ for (const entry of broadcaster.snapshot_after(last_event_id)) write_event(res, entry.id, entry.event);
192
+ const heartbeat = setInterval(() => {
193
+ res.write(": heartbeat\n\n");
194
+ }, SSE_HEARTBEAT_MS);
195
+ const unsubscribe = broadcaster.subscribe((entry) => {
196
+ write_event(res, entry.id, entry.event);
197
+ });
198
+ const close = () => {
199
+ clearInterval(heartbeat);
200
+ unsubscribe();
201
+ if (!res.writableEnded) {
202
+ res.write("event: close\ndata: {}\n\n");
203
+ res.end();
204
+ }
205
+ };
206
+ req.on("close", close);
207
+ req.on("error", close);
208
+ }
209
+ /**
210
+ * Parses the `Last-Event-ID` header into a replay cursor, defaulting to 0.
211
+ *
212
+ * Treats a missing header or a non-numeric or non-positive value as "no
213
+ * cursor", which makes `handle_sse` replay the full ring buffer.
214
+ */
215
+ function parse_last_event_id(value) {
216
+ if (typeof value !== "string") return 0;
217
+ const n = Number.parseInt(value, 10);
218
+ return Number.isFinite(n) && n > 0 ? n : 0;
219
+ }
220
+ /**
221
+ * Writes one SSE `trajectory` event frame to the response stream.
222
+ */
223
+ function write_event(res, id, event) {
224
+ res.write(`id: ${id}\nevent: trajectory\ndata: ${JSON.stringify(event)}\n\n`);
225
+ }
226
+ /**
227
+ * Handles `POST /api/ingest`: parses newline-delimited trajectory events
228
+ * from the request body and feeds valid ones into the broadcaster.
229
+ *
230
+ * Reports how many lines were accepted vs rejected in the response body;
231
+ * a malformed line is skipped and reported via `on_parse_error`, not
232
+ * treated as a fatal request error.
233
+ */
234
+ function handle_ingest(req, res, broadcaster, on_parse_error) {
235
+ let buf = "";
236
+ let accepted = 0;
237
+ let rejected = 0;
238
+ const consume_line = (line) => {
239
+ if (line.length === 0) return;
240
+ let parsed;
241
+ try {
242
+ parsed = JSON.parse(line);
243
+ } catch (err) {
244
+ rejected++;
245
+ if (on_parse_error) on_parse_error(err, line);
246
+ return;
247
+ }
248
+ const result = parse_trajectory_event(parsed);
249
+ if (!result.success) {
250
+ rejected++;
251
+ if (on_parse_error) on_parse_error(result.error, line);
252
+ return;
253
+ }
254
+ broadcaster.emit(result.data);
255
+ accepted++;
256
+ };
257
+ req.setEncoding("utf8");
258
+ req.on("data", (chunk) => {
259
+ buf += chunk;
260
+ let nl = buf.indexOf("\n");
261
+ while (nl !== -1) {
262
+ consume_line(buf.slice(0, nl));
263
+ buf = buf.slice(nl + 1);
264
+ nl = buf.indexOf("\n");
265
+ }
266
+ });
267
+ req.on("end", () => {
268
+ if (buf.length > 0) consume_line(buf);
269
+ send_json(res, 200, {
270
+ accepted,
271
+ rejected
272
+ });
273
+ });
274
+ req.on("error", (err) => {
275
+ if (on_parse_error) on_parse_error(err, "");
276
+ send_json(res, 400, { error: "bad_request" });
277
+ });
278
+ }
279
+ //#endregion
280
+ //#region src/viewer/tail.ts
281
+ /**
282
+ * JSONL file tailer.
283
+ *
284
+ * Watches a file for appends and emits one parsed trajectory event per
285
+ * complete line. Handles three pathological cases:
286
+ *
287
+ * - Truncation / rotation: a watcher event whose stat is shorter than the
288
+ * current offset means the file shrunk. Reset offset to 0 and re-stream.
289
+ * - Partial last line: if the trailing chunk has no `\n`, buffer it and
290
+ * wait. Never parse a half-written line.
291
+ * - Schema failures: a line that fails `parse_trajectory_event` is
292
+ * dropped and surfaced to `on_parse_error`. The stream keeps going.
293
+ *
294
+ * The watcher is fs.watch-based; reads are serialized and change events
295
+ * that arrive mid-read are coalesced into one extra pass rather than
296
+ * dropped, so a burst of appends never starts overlapping reads. Each pass
297
+ * re-stats and re-reads from the saved offset, which also covers platforms
298
+ * where fs.watch misses some append notifications: the next successful
299
+ * change event catches the file up regardless.
300
+ */
301
+ /**
302
+ * Starts tailing `path` and returns a handle to stop or drain it.
303
+ *
304
+ * Watches the file with `fs.watch` and re-reads from the last known offset
305
+ * on every change, buffering an incomplete trailing line until the rest
306
+ * arrives. Overlapping change events are coalesced: a read already in
307
+ * flight absorbs any events that fire while it runs instead of starting a
308
+ * second concurrent read.
309
+ */
310
+ function start_tail(config) {
311
+ const { path, on_event, on_parse_error, on_io_error } = config;
312
+ let offset = 0;
313
+ let buffer = "";
314
+ let busy = false;
315
+ let pending = false;
316
+ let closed = false;
317
+ let watcher = null;
318
+ let last_drain = Promise.resolve();
319
+ const handle_line = (line) => {
320
+ if (line.length === 0) return;
321
+ let parsed;
322
+ try {
323
+ parsed = JSON.parse(line);
324
+ } catch (err) {
325
+ if (on_parse_error) on_parse_error(err, line);
326
+ return;
327
+ }
328
+ const result = parse_trajectory_event(parsed);
329
+ if (!result.success) {
330
+ if (on_parse_error) on_parse_error(result.error, line);
331
+ return;
332
+ }
333
+ on_event(result.data);
334
+ };
335
+ const read_more = async () => {
336
+ let st;
337
+ try {
338
+ st = await stat(path);
339
+ } catch (err) {
340
+ if (on_io_error) on_io_error(err);
341
+ return;
342
+ }
343
+ if (st.size < offset) {
344
+ offset = 0;
345
+ buffer = "";
346
+ }
347
+ if (st.size === offset) return;
348
+ const fh = await open(path, "r").catch((err) => {
349
+ if (on_io_error) on_io_error(err);
350
+ return null;
351
+ });
352
+ if (!fh) return;
353
+ try {
354
+ const length = st.size - offset;
355
+ const buf = Buffer.alloc(length);
356
+ const { bytesRead } = await fh.read(buf, 0, length, offset);
357
+ offset += bytesRead;
358
+ buffer += buf.subarray(0, bytesRead).toString("utf8");
359
+ } finally {
360
+ await fh.close();
361
+ }
362
+ let nl = buffer.indexOf("\n");
363
+ while (nl !== -1) {
364
+ const line = buffer.slice(0, nl);
365
+ buffer = buffer.slice(nl + 1);
366
+ handle_line(line);
367
+ nl = buffer.indexOf("\n");
368
+ }
369
+ };
370
+ const schedule = () => {
371
+ if (closed) return;
372
+ if (busy) {
373
+ pending = true;
374
+ return;
375
+ }
376
+ busy = true;
377
+ last_drain = (async () => {
378
+ try {
379
+ let keep_going = true;
380
+ while (keep_going) {
381
+ pending = false;
382
+ await read_more();
383
+ keep_going = pending && !closed;
384
+ }
385
+ } finally {
386
+ busy = false;
387
+ }
388
+ })();
389
+ };
390
+ schedule();
391
+ try {
392
+ watcher = watch(path, { persistent: true }, () => {
393
+ schedule();
394
+ });
395
+ } catch (err) {
396
+ if (on_io_error) on_io_error(err);
397
+ }
398
+ const stop = () => {
399
+ closed = true;
400
+ if (watcher) {
401
+ watcher.close();
402
+ watcher = null;
403
+ }
404
+ };
405
+ const drain = async () => {
406
+ schedule();
407
+ await last_drain;
408
+ };
409
+ return {
410
+ stop,
411
+ drain
412
+ };
413
+ }
414
+ //#endregion
415
+ //#region src/viewer/start_viewer.ts
416
+ /**
417
+ * `start_viewer` programmatic embed implementation.
418
+ *
419
+ * Spin up the server, optionally start tailing a JSONL file, and return a
420
+ * handle that can stop both. `start_viewer` only depends on core's wire-format
421
+ * schema; it never reaches into the engine, composites, or any provider.
422
+ */
423
+ /**
424
+ * Starts the viewer: brings up the HTTP/SSE server and, if `options.path`
425
+ * is set, a file tail that feeds the same broadcaster.
426
+ *
427
+ * Defaults to `127.0.0.1:4242` with a 1000-event ring buffer. HTTP ingest
428
+ * and SSE are always available; tailing is opt-in via `path`.
429
+ */
430
+ async function start_viewer(options = {}) {
431
+ const host = options.host ?? "127.0.0.1";
432
+ const port = options.port ?? 4242;
433
+ const broadcaster = create_broadcaster({
434
+ buffer: options.buffer ?? 1e3,
435
+ ...options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}
436
+ });
437
+ const server = await start_server({
438
+ broadcaster,
439
+ host,
440
+ port,
441
+ ...options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}
442
+ });
443
+ let tail = null;
444
+ if (options.path !== void 0) tail = start_tail({
445
+ path: options.path,
446
+ on_event: (event) => {
447
+ broadcaster.emit(event);
448
+ },
449
+ ...options.on_parse_error ? { on_parse_error: options.on_parse_error } : {},
450
+ ...options.on_io_error ? { on_io_error: options.on_io_error } : {}
451
+ });
452
+ return wrap_handle(server, tail, host);
453
+ }
454
+ /**
455
+ * Combines the server and optional tail into a single `ViewerHandle`.
456
+ *
457
+ * `close` stops the tail first, then closes the server, mirroring the
458
+ * startup order (server first, tail second) in reverse. The port is read
459
+ * back from `server.url` rather than the requested `port` option, since
460
+ * a caller that passes `0` gets whatever port the OS actually bound.
461
+ */
462
+ function wrap_handle(server, tail, host) {
463
+ return {
464
+ url: server.url,
465
+ host,
466
+ port: Number(new URL(server.url).port),
467
+ close: async () => {
468
+ if (tail) tail.stop();
469
+ await server.close();
470
+ }
471
+ };
472
+ }
473
+ //#endregion
474
+ //#region src/viewer/cli.ts
475
+ /**
476
+ * fascicle-viewer CLI.
477
+ *
478
+ * fascicle-viewer <path> # tail a JSONL file (primary)
479
+ * fascicle-viewer --listen # accept HTTP push only
480
+ * fascicle-viewer <path> --listen # both producers feed the same broadcaster
481
+ *
482
+ * Flags: --port <n> --host <h> --buffer <n> --no-open --help
483
+ *
484
+ * Defaults bind 127.0.0.1:4242 and open the user's default browser. SIGINT
485
+ * shuts everything down cleanly. The CLI body is exposed as `run_viewer_cli`
486
+ * so the umbrella's bin shim can drive it from a bundled `dist/index.js`.
487
+ */
488
+ const HELP = `\
489
+ fascicle-viewer — minimal in-repo dashboard for fascicle trajectory streams.
490
+
491
+ Usage:
492
+ fascicle-viewer <path> tail a JSONL file
493
+ fascicle-viewer --listen accept HTTP push only
494
+ fascicle-viewer <path> --listen both producers feed the same broadcaster
495
+
496
+ Options:
497
+ --port <n> port (default 4242)
498
+ --host <h> bind host (default 127.0.0.1; --host 0.0.0.0 warns)
499
+ --buffer <n> ring-buffer size (default 1000)
500
+ --no-open do not open the browser
501
+ --help show this message
502
+ `;
503
+ /**
504
+ * Parses CLI argv into a validated `CliArgs`, exiting on bad input.
505
+ *
506
+ * `--help` prints usage and exits 0. Invalid numeric flags, or a missing
507
+ * <path> without `--listen`, write to stderr and exit 2.
508
+ */
509
+ function parse(argv) {
510
+ const { values, positionals } = parseArgs({
511
+ args: [...argv],
512
+ allowPositionals: true,
513
+ options: {
514
+ port: {
515
+ type: "string",
516
+ default: "4242"
517
+ },
518
+ host: {
519
+ type: "string",
520
+ default: "127.0.0.1"
521
+ },
522
+ buffer: {
523
+ type: "string",
524
+ default: "1000"
525
+ },
526
+ listen: {
527
+ type: "boolean",
528
+ default: false
529
+ },
530
+ open: {
531
+ type: "boolean",
532
+ default: true
533
+ },
534
+ "no-open": {
535
+ type: "boolean",
536
+ default: false
537
+ },
538
+ help: {
539
+ type: "boolean",
540
+ default: false
541
+ }
542
+ }
543
+ });
544
+ if (values.help) {
545
+ process.stdout.write(HELP);
546
+ process.exit(0);
547
+ }
548
+ const port_raw = values.port ?? "4242";
549
+ const buffer_raw = values.buffer ?? "1000";
550
+ const port = Number.parseInt(port_raw, 10);
551
+ const buffer = Number.parseInt(buffer_raw, 10);
552
+ if (!Number.isFinite(port) || port <= 0) {
553
+ process.stderr.write(`fascicle-viewer: invalid --port '${port_raw}': expected a positive integer\n`);
554
+ process.exit(2);
555
+ }
556
+ if (!Number.isFinite(buffer) || buffer <= 0) {
557
+ process.stderr.write(`fascicle-viewer: invalid --buffer '${buffer_raw}': expected a positive integer\n`);
558
+ process.exit(2);
559
+ }
560
+ const path = positionals[0];
561
+ const listen = values.listen ?? false;
562
+ if (path === void 0 && !listen) {
563
+ process.stderr.write("fascicle-viewer: a <path> is required unless --listen is set\n");
564
+ process.stderr.write(HELP);
565
+ process.exit(2);
566
+ }
567
+ return {
568
+ ...path !== void 0 ? { path } : {},
569
+ host: values.host ?? "127.0.0.1",
570
+ port,
571
+ buffer,
572
+ listen,
573
+ open: !values["no-open"] && (values.open ?? true)
574
+ };
575
+ }
576
+ /**
577
+ * Opens `url` in the platform's default browser, best-effort.
578
+ *
579
+ * Spawns the platform opener (`open`, `cmd /c start`, or `xdg-open`)
580
+ * detached and swallows failures; the CLI prints the URL either way.
581
+ */
582
+ function open_browser(url) {
583
+ const platform = process.platform;
584
+ const cmd = platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
585
+ const args = platform === "win32" ? [
586
+ "/c",
587
+ "start",
588
+ "\"\"",
589
+ url
590
+ ] : [url];
591
+ try {
592
+ const child = spawn(cmd, args, {
593
+ stdio: "ignore",
594
+ detached: true
595
+ });
596
+ child.on("error", () => {});
597
+ child.unref();
598
+ } catch {}
599
+ }
600
+ /**
601
+ * CLI entry point: parses argv, starts the viewer, and wires shutdown.
602
+ *
603
+ * Warns but proceeds when the tailed path does not exist yet or when the
604
+ * bind host is 0.0.0.0 (the dashboard has no auth). Optionally opens the
605
+ * browser, then installs SIGINT/SIGTERM handlers that close the viewer
606
+ * before exiting.
607
+ */
608
+ async function run_viewer_cli(argv) {
609
+ const args = parse(argv);
610
+ if (args.path !== void 0 && !existsSync(args.path)) process.stderr.write(`fascicle-viewer: warning: ${args.path} does not exist yet — will pick up events once it is created\n`);
611
+ if (args.host === "0.0.0.0") process.stderr.write("fascicle-viewer: warning: binding 0.0.0.0 — this dashboard has no auth and exposes whatever is in your trajectory stream\n");
612
+ const handle = await start_viewer({
613
+ ...args.path !== void 0 ? { path: args.path } : {},
614
+ host: args.host,
615
+ port: args.port,
616
+ buffer: args.buffer,
617
+ on_parse_error: (err, line) => {
618
+ const preview = line.length > 120 ? `${line.slice(0, 120)}…` : line;
619
+ process.stderr.write(`fascicle-viewer: skipped malformed line: ${preview}\n ${describe_error(err)}\n`);
620
+ },
621
+ on_io_error: (err) => {
622
+ process.stderr.write(`fascicle-viewer: io error: ${describe_error(err)}\n`);
623
+ }
624
+ });
625
+ if (args.path !== void 0) process.stderr.write(`fascicle-viewer: watching ${args.path}\n`);
626
+ if (args.listen || args.path === void 0) process.stderr.write(`fascicle-viewer: listening for HTTP push on ${handle.url}/api/ingest\n`);
627
+ process.stderr.write(`fascicle-viewer: viewer at ${handle.url}\n`);
628
+ if (args.open) open_browser(handle.url);
629
+ const shutdown = async () => {
630
+ process.stderr.write("\nfascicle-viewer: shutting down\n");
631
+ await handle.close();
632
+ process.exit(0);
633
+ };
634
+ process.on("SIGINT", () => {
635
+ shutdown();
636
+ });
637
+ process.on("SIGTERM", () => {
638
+ shutdown();
639
+ });
640
+ }
641
+ /**
642
+ * Renders an unknown thrown value as a human-readable message.
643
+ */
644
+ function describe_error(err) {
645
+ if (err instanceof Error) return err.message;
646
+ try {
647
+ return JSON.stringify(err);
648
+ } catch {
649
+ return String(err);
650
+ }
651
+ }
652
+ if (process.argv[1] !== void 0 && process.argv[1] === fileURLToPath(import.meta.url)) run_viewer_cli(process.argv.slice(2)).catch((err) => {
653
+ process.stderr.write(`fascicle-viewer: ${describe_error(err)}\n`);
654
+ process.exit(1);
655
+ });
656
+ //#endregion
657
+ export { create_broadcaster, run_viewer_cli, start_server, start_tail, start_viewer };
658
+
659
+ //# sourceMappingURL=viewer.js.map