@brickkit/cli 0.7.4 → 0.8.1

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 (39) hide show
  1. package/README.md +173 -1
  2. package/dashboard-dist/CollapsiblePanel-DM8J3g8m.js +2 -0
  3. package/dashboard-dist/Geist-Variable.woff2 +0 -0
  4. package/dashboard-dist/GeistMono-Variable.woff2 +0 -0
  5. package/dashboard-dist/PopoverPopup-B6eMOlOC.js +1 -0
  6. package/dashboard-dist/api-reference-wTdT1AVt.js +260 -0
  7. package/dashboard-dist/app.css +2 -0
  8. package/dashboard-dist/app.js +18 -0
  9. package/dashboard-dist/core-CHWYtApw.js +1 -0
  10. package/dashboard-dist/docs-DflzpIIh.js +4 -0
  11. package/dashboard-dist/docs.css +1 -0
  12. package/dashboard-dist/preload-helper-CVJ-D494.js +1 -0
  13. package/dashboard-dist/react-jsx-runtime.js +4 -0
  14. package/dashboard-dist/react.js +3 -0
  15. package/dashboard-dist/rolldown-runtime-XKyaHtl9.js +1 -0
  16. package/dist/bin.d.ts.map +1 -1
  17. package/dist/bin.js +17 -6
  18. package/dist/bin.js.map +1 -1
  19. package/dist/dev-reporter.d.ts +15 -0
  20. package/dist/dev-reporter.d.ts.map +1 -0
  21. package/dist/dev-reporter.js +28 -0
  22. package/dist/dev-reporter.js.map +1 -0
  23. package/dist/dev-telemetry-store.js +1897 -0
  24. package/dist/dev-telemetry-store.js.map +1 -0
  25. package/dist/dev-telemetry.js +199 -0
  26. package/dist/dev-telemetry.js.map +1 -0
  27. package/dist/dev-worker.js +54 -9
  28. package/dist/dev-worker.js.map +1 -1
  29. package/dist/index.d.ts +24 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/runner.js +157 -8
  32. package/dist/runner.js.map +1 -1
  33. package/dist/vite.d.ts +11 -0
  34. package/dist/vite.d.ts.map +1 -1
  35. package/dist/vite.js +104 -6
  36. package/dist/vite.js.map +1 -1
  37. package/package.json +42 -4
  38. package/dist/port-utils.js +0 -13
  39. package/dist/port-utils.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-telemetry-store.js","names":[],"sources":["../src/dev-history-csv.ts","../src/dev-history.ts","../src/dev-dashboard-shell.ts","../src/dashboard-access.ts","../src/dev-dashboard.ts","../src/dev-docs.ts","../src/dev-telemetry-store.ts"],"sourcesContent":["import type { HistoryTrace } from \"./dev-history\";\n\n// Kept apart from dev-history so the dashboard can export what it shows without\n// pulling in the database code.\n\nconst CSV_COLUMNS = [\n \"time\",\n \"method\",\n \"route\",\n \"path\",\n \"status\",\n \"outcome\",\n \"duration_ms\",\n \"service\",\n \"action\",\n \"message\",\n \"trace_id\",\n] as const;\n\nfunction csvCell(value: string | number | undefined): string {\n if (value === undefined) return \"\";\n const text = String(value);\n // Quote anything a spreadsheet could split on, and defuse formulas.\n const safe = /^[=+\\-@\\t\\r]/.test(text) ? `'${text}` : text;\n return /[\",\\n\\r]/.test(safe) ? `\"${safe.replace(/\"/g, '\"\"')}\"` : safe;\n}\n\n/** Requests as CSV with a header row, for the dashboard's export. */\nexport function tracesToCsv(traces: HistoryTrace[]): string {\n const lines = traces.map((trace) => {\n const failed = trace.status === \"error\" || (trace.httpStatus ?? 0) >= 500;\n const client = (trace.httpStatus ?? 0) >= 400;\n return [\n new Date(trace.startMs).toISOString(),\n trace.method,\n trace.route,\n trace.path,\n trace.httpStatus ?? trace.status,\n failed ? \"server\" : client ? \"client\" : \"ok\",\n trace.durationMs === undefined ? undefined : trace.durationMs.toFixed(3),\n trace.service,\n trace.action,\n trace.message,\n trace.traceId,\n ]\n .map(csvCell)\n .join(\",\");\n });\n return [CSV_COLUMNS.join(\",\"), ...lines].join(\"\\n\") + \"\\n\";\n}\n","import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { tracesToCsv } from \"./dev-history-csv\";\nimport type { SpanOutcome, TraceSummary } from \"./dev-telemetry-store\";\n\nexport { tracesToCsv };\n\nexport const DEFAULT_HISTORY_DAYS = 90;\n\nconst DAY_MS = 86_400_000;\nconst MAX_TRACES = 100_000;\nconst FLUSH_MS = 250;\nconst PRUNE_MS = 30 * 60_000;\nconst VOLUME_BUCKETS = 48;\nconst DEFAULT_LIMIT = 100;\nconst MAX_LIMIT = 500;\nconst MAX_FACET_VALUES = 30;\nconst MAX_EXPORT_ROWS = 100_000;\n\n/** A finished request without its spans; fetch the full trace by id. */\nexport interface HistoryTrace {\n traceId: string;\n name: string;\n /** \"GET /api/page/:id\" when the method and route are known, else the span name. */\n endpoint: string;\n method?: string;\n route?: string;\n path?: string;\n httpStatus?: number;\n generation: number;\n startMs: number;\n endMs?: number;\n durationMs?: number;\n status: SpanOutcome;\n truncated: boolean;\n /** The service and action that handled the request, when it ran one. */\n service?: string;\n action?: string;\n /** Why it failed, when it did. */\n message?: string;\n}\n\n/** How a request ended: a 5xx or crash, a 4xx, or neither. */\nexport type Outcome = \"ok\" | \"client\" | \"server\";\nconst OUTCOMES = new Set<string>([\"ok\", \"client\", \"server\"]);\n\n/** A filter groups values with OR; separate filters combine with AND. */\nexport interface HistoryQuery {\n from: number;\n to: number;\n endpoints?: string[];\n methods?: string[];\n services?: string[];\n outcomes?: Outcome[];\n /** Only requests at least this slow. */\n minMs?: number;\n /** Matches the endpoint or the request path. */\n query?: string;\n sort?: \"recent\" | \"slowest\";\n limit?: number;\n offset?: number;\n}\n\nexport interface VolumeBucket {\n start: number;\n ok: number;\n client: number;\n server: number;\n}\n\n/** The numbers behind the cards at the top of the log, for what matches. */\nexport interface HistorySummary {\n total: number;\n clientErrors: number;\n serverErrors: number;\n medianMs: number;\n p95Ms: number;\n}\n\nexport interface FacetValue {\n value: string;\n count: number;\n}\n\n/** What is in the range, counted for each filter as if it were not applied. */\nexport interface HistoryFacets {\n outcome: FacetValue[];\n method: FacetValue[];\n service: FacetValue[];\n endpoint: FacetValue[];\n}\n\nexport interface HistoryInfo {\n days: number;\n count: number;\n oldestMs?: number;\n}\n\ninterface Statement {\n run(...params: unknown[]): unknown;\n all(...params: unknown[]): Record<string, unknown>[];\n get(...params: unknown[]): Record<string, unknown> | undefined;\n}\n\ninterface Database {\n exec(sql: string): void;\n prepare(sql: string): Statement;\n close(): void;\n}\n\n/**\n * SQLite from whichever runtime is running: `bun:sqlite` under Bun, and\n * `node:sqlite` under Node, which is what runs Vite's dev server. Both are\n * imported by a variable name so bundlers leave them alone.\n */\nasync function openDatabase(file: string): Promise<Database> {\n if (typeof Bun !== \"undefined\") {\n const specifier = \"bun:sqlite\";\n const { Database } = (await import(specifier)) as {\n Database: new (file: string, options: { create: boolean }) => Database;\n };\n return new Database(file, { create: true });\n }\n const specifier = \"node:sqlite\";\n // Node prints an experimental-feature warning when this module loads. It is\n // stable enough for a local log, and the warning would only confuse.\n const emit = process.emitWarning;\n process.emitWarning = ((warning: unknown, ...rest: unknown[]) => {\n if (typeof warning === \"string\" && warning.includes(\"SQLite\")) return;\n return (emit as (...args: unknown[]) => void).call(\n process,\n warning,\n ...rest,\n );\n }) as typeof process.emitWarning;\n try {\n const { DatabaseSync } = (await import(specifier)) as {\n DatabaseSync: new (file: string) => Database;\n };\n return new DatabaseSync(file);\n } finally {\n process.emitWarning = emit;\n }\n}\n\nexport interface OpenHistoryOptions {\n /** The project folder; the database lives in `.brick/` inside it. */\n directory: string;\n /** How long to keep requests. Zero or less turns history off. */\n days: number;\n warn?: (message: string) => void;\n}\n\n/**\n * Open the request history, or return undefined when it is turned off or this\n * runtime has no SQLite. Never throws: the dashboard works without history.\n */\nexport async function openHistory(\n options: OpenHistoryOptions,\n): Promise<DevHistory | undefined> {\n if (!(options.days > 0)) return undefined;\n try {\n const folder = join(options.directory, \".brick\");\n mkdirSync(folder, { recursive: true });\n // Requests can hold SQL text and error details, so never let them be\n // committed by accident.\n const ignore = join(folder, \".gitignore\");\n if (!existsSync(ignore)) writeFileSync(ignore, \"*\\n\");\n const database = await openDatabase(join(folder, \"telemetry.sqlite\"));\n return new DevHistory(database, options.days);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n options.warn?.(\n `[Brick-TS] Request history is unavailable (${reason}). It needs Bun, or Node 22.5 or later. Continuing without it.`,\n );\n return undefined;\n }\n}\n\nconst text = (value: unknown): string | undefined =>\n value === null || value === undefined ? undefined : String(value);\nconst number = (value: unknown): number | undefined =>\n value === null || value === undefined ? undefined : Number(value);\n\nfunction percentile(sorted: number[], fraction: number): number {\n if (sorted.length === 0) return 0;\n const position = (sorted.length - 1) * fraction;\n const lower = Math.floor(position);\n const upper = Math.ceil(position);\n return sorted[lower] + (sorted[upper] - sorted[lower]) * (position - lower);\n}\n\nconst OUTCOME_SQL: Record<Outcome, string> = {\n server: \"(status = 'error' OR http_status >= 500)\",\n client: \"(status != 'error' AND http_status >= 400 AND http_status < 500)\",\n ok: \"(status != 'error' AND (http_status IS NULL OR http_status < 400))\",\n};\n\n/** The outcome of each row, for counting; agrees with OUTCOME_SQL. */\nconst OUTCOME_CASE = `CASE\n WHEN status = 'error' OR http_status >= 500 THEN 'server'\n WHEN http_status >= 400 AND http_status < 500 THEN 'client'\n ELSE 'ok' END`;\n\ntype Facet = \"outcome\" | \"method\" | \"service\" | \"endpoint\";\n\nconst FACET_COLUMNS: Record<Facet, string> = {\n outcome: OUTCOME_CASE,\n method: \"method\",\n service: \"service\",\n endpoint: \"endpoint\",\n};\n\n/** The WHERE clause for a query, leaving out one filter when counting its facet. */\nfunction filterSql(\n query: HistoryQuery,\n skip?: Facet,\n): { sql: string; params: unknown[] } {\n const clauses = [\"start_ms >= ?\", \"start_ms <= ?\"];\n const params: unknown[] = [query.from, query.to];\n const anyOf = (column: string, values: string[] | undefined) => {\n if (!values || values.length === 0) return;\n clauses.push(`${column} IN (${values.map(() => \"?\").join(\", \")})`);\n params.push(...values);\n };\n if (skip !== \"endpoint\") anyOf(\"endpoint\", query.endpoints);\n if (skip !== \"method\") anyOf(\"method\", query.methods);\n if (skip !== \"service\") anyOf(\"service\", query.services);\n if (skip !== \"outcome\" && query.outcomes && query.outcomes.length > 0) {\n clauses.push(\n `(${query.outcomes.map((outcome) => OUTCOME_SQL[outcome]).join(\" OR \")})`,\n );\n }\n if (query.minMs !== undefined && query.minMs > 0) {\n clauses.push(\"duration_ms >= ?\");\n params.push(query.minMs);\n }\n const needle = query.query?.trim();\n if (needle) {\n const pattern = `%${needle.replace(/[\\\\%_]/g, \"\\\\$&\")}%`;\n clauses.push(\n \"(endpoint LIKE ? ESCAPE '\\\\' OR path LIKE ? ESCAPE '\\\\' OR name LIKE ? ESCAPE '\\\\' OR action LIKE ? ESCAPE '\\\\' OR message LIKE ? ESCAPE '\\\\')\",\n );\n params.push(pattern, pattern, pattern, pattern, pattern);\n }\n return { sql: clauses.join(\" AND \"), params };\n}\n\nconst LIST_COLUMNS = `trace_id, name, endpoint, method, route, path, http_status, generation,\n start_ms, end_ms, duration_ms, status, truncated, service, action, message`;\n\nfunction toHistoryTrace(row: Record<string, unknown>): HistoryTrace {\n return {\n traceId: String(row.trace_id),\n name: String(row.name),\n endpoint: String(row.endpoint),\n method: text(row.method),\n route: text(row.route),\n path: text(row.path),\n httpStatus: number(row.http_status),\n generation: Number(row.generation),\n startMs: Number(row.start_ms),\n endMs: number(row.end_ms),\n durationMs: number(row.duration_ms),\n status: String(row.status) as SpanOutcome,\n truncated: Number(row.truncated) === 1,\n service: text(row.service),\n action: text(row.action),\n message: text(row.message),\n };\n}\n\n/**\n * Requests kept on disk between runs, for looking back over weeks\n * instead of the last few minutes. Writes are batched; reads see them.\n */\nexport class DevHistory {\n readonly days: number;\n readonly #database: Database;\n readonly #pendingTraces = new Map<string, TraceSummary>();\n #flushTimer: ReturnType<typeof setTimeout> | undefined;\n readonly #pruneTimer: ReturnType<typeof setInterval>;\n #closed = false;\n\n constructor(database: Database, days: number) {\n this.#database = database;\n this.days = days;\n database.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n PRAGMA busy_timeout = 2000;\n CREATE TABLE IF NOT EXISTS traces (\n trace_id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n endpoint TEXT NOT NULL,\n method TEXT,\n route TEXT,\n path TEXT,\n http_status INTEGER,\n generation INTEGER NOT NULL,\n start_ms INTEGER NOT NULL,\n end_ms INTEGER,\n duration_ms REAL,\n status TEXT NOT NULL,\n truncated INTEGER NOT NULL,\n spans TEXT NOT NULL,\n service TEXT,\n action TEXT,\n message TEXT\n );\n CREATE INDEX IF NOT EXISTS traces_start ON traces (start_ms);\n CREATE INDEX IF NOT EXISTS traces_endpoint ON traces (endpoint, start_ms);\n -- Earlier versions kept failures here; nothing reads them now.\n DROP TABLE IF EXISTS failures;\n `);\n this.#addMissingColumns();\n this.prune();\n this.#pruneTimer = setInterval(() => this.prune(), PRUNE_MS);\n this.#pruneTimer.unref?.();\n }\n\n /** A folder from an earlier version has the table without the newer columns. */\n #addMissingColumns(): void {\n const present = new Set(\n this.#database\n .prepare(\"PRAGMA table_info(traces)\")\n .all()\n .map((column) => String(column.name)),\n );\n for (const column of [\"service\", \"action\", \"message\"]) {\n if (!present.has(column)) {\n this.#database.exec(`ALTER TABLE traces ADD COLUMN ${column} TEXT`);\n }\n }\n }\n\n /** Queue a finished request. A later save of the same request replaces it. */\n saveTrace(trace: TraceSummary): void {\n if (this.#closed) return;\n this.#pendingTraces.set(trace.traceId, trace);\n this.#scheduleFlush();\n }\n\n #scheduleFlush(): void {\n if (this.#flushTimer) return;\n this.#flushTimer = setTimeout(() => this.flush(), FLUSH_MS);\n this.#flushTimer.unref?.();\n }\n\n /** Write queued requests now. */\n flush(): void {\n if (this.#flushTimer) {\n clearTimeout(this.#flushTimer);\n this.#flushTimer = undefined;\n }\n if (this.#closed || this.#pendingTraces.size === 0) return;\n const traces = [...this.#pendingTraces.values()];\n this.#pendingTraces.clear();\n try {\n this.#database.exec(\"BEGIN\");\n const saveTrace = this.#database.prepare(\n `INSERT OR REPLACE INTO traces (trace_id, name, endpoint, method, route, path,\n http_status, generation, start_ms, end_ms, duration_ms, status, truncated, spans,\n service, action, message)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n );\n for (const trace of traces) {\n saveTrace.run(\n trace.traceId,\n trace.name,\n trace.method && trace.route\n ? `${trace.method} ${trace.route}`\n : trace.name,\n trace.method ?? null,\n trace.route ?? null,\n trace.path ?? null,\n trace.httpStatus ?? null,\n trace.generation,\n trace.startMs,\n trace.endMs ?? null,\n trace.durationMs ?? null,\n trace.status,\n trace.truncated ? 1 : 0,\n JSON.stringify(trace.spans),\n trace.service ?? null,\n trace.action ?? null,\n trace.message ?? null,\n );\n }\n this.#database.exec(\"COMMIT\");\n } catch {\n // A failed write loses a batch of history; it must not break the app.\n try {\n this.#database.exec(\"ROLLBACK\");\n } catch {\n // Nothing was open.\n }\n }\n }\n\n /** Drop what is past retention, then the oldest beyond the size cap. */\n prune(now = Date.now()): void {\n if (this.#closed) return;\n try {\n const cutoff = now - this.days * DAY_MS;\n this.#database\n .prepare(\"DELETE FROM traces WHERE start_ms < ?\")\n .run(cutoff);\n const count = Number(\n this.#database.prepare(\"SELECT COUNT(*) AS n FROM traces\").get()?.n ??\n 0,\n );\n if (count > MAX_TRACES) {\n this.#database\n .prepare(\n \"DELETE FROM traces WHERE trace_id IN (SELECT trace_id FROM traces ORDER BY start_ms ASC LIMIT ?)\",\n )\n .run(count - MAX_TRACES);\n }\n } catch {\n // Pruning is housekeeping; try again next time.\n }\n }\n\n info(): HistoryInfo {\n this.flush();\n const row = this.#database\n .prepare(\"SELECT COUNT(*) AS n, MIN(start_ms) AS oldest FROM traces\")\n .get();\n return {\n days: this.days,\n count: Number(row?.n ?? 0),\n oldestMs: number(row?.oldest),\n };\n }\n\n /** Matching requests, without spans, and how many match in total. */\n traces(query: HistoryQuery): { total: number; traces: HistoryTrace[] } {\n this.flush();\n const { sql, params } = filterSql(query);\n const total = Number(\n this.#database\n .prepare(`SELECT COUNT(*) AS n FROM traces WHERE ${sql}`)\n .get(...params)?.n ?? 0,\n );\n const limit = Math.min(\n Math.max(query.limit ?? DEFAULT_LIMIT, 1),\n MAX_LIMIT,\n );\n const offset = Math.max(query.offset ?? 0, 0);\n const order =\n query.sort === \"slowest\"\n ? \"duration_ms DESC, start_ms DESC\"\n : \"start_ms DESC\";\n const rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${order} LIMIT ? OFFSET ?`,\n )\n .all(...params, limit, offset);\n return { total, traces: rows.map(toHistoryTrace) };\n }\n\n /** Counts for each filter over the range, ignoring that filter's own choice. */\n facets(query: HistoryQuery): HistoryFacets {\n this.flush();\n const count = (facet: Facet): FacetValue[] => {\n const { sql, params } = filterSql(query, facet);\n const column = FACET_COLUMNS[facet];\n return this.#database\n .prepare(\n `SELECT ${column} AS value, COUNT(*) AS n FROM traces\n WHERE ${sql} AND ${column} IS NOT NULL\n GROUP BY value ORDER BY n DESC, value ASC LIMIT ?`,\n )\n .all(...params, MAX_FACET_VALUES)\n .map((row) => ({ value: String(row.value), count: Number(row.n) }));\n };\n return {\n outcome: count(\"outcome\"),\n method: count(\"method\"),\n service: count(\"service\"),\n endpoint: count(\"endpoint\"),\n };\n }\n\n /** Matching requests per time bucket across the range, by outcome. */\n volume(query: HistoryQuery, buckets = VOLUME_BUCKETS): VolumeBucket[] {\n this.flush();\n const { sql, params } = filterSql(query);\n const bucketMs = Math.max(Math.ceil((query.to - query.from) / buckets), 1);\n const result: VolumeBucket[] = Array.from(\n { length: buckets },\n (_, index) => ({\n start: query.from + index * bucketMs,\n ok: 0,\n client: 0,\n server: 0,\n }),\n );\n const rows = this.#database\n .prepare(\n `SELECT CAST((start_ms - ?) / ? AS INTEGER) AS bucket, ${OUTCOME_CASE} AS outcome,\n COUNT(*) AS n\n FROM traces WHERE ${sql} GROUP BY bucket, outcome`,\n )\n .all(query.from, bucketMs, ...params);\n for (const row of rows) {\n const bucket =\n result[Math.min(Math.max(Number(row.bucket), 0), buckets - 1)];\n const outcome = String(row.outcome) as Outcome;\n if (bucket) bucket[outcome] += Number(row.n);\n }\n return result;\n }\n\n /** Every matching request, newest first, as CSV for a spreadsheet. */\n exportCsv(query: HistoryQuery): string {\n this.flush();\n const { sql, params } = filterSql(query);\n const order =\n query.sort === \"slowest\"\n ? \"duration_ms DESC, start_ms DESC\"\n : \"start_ms DESC\";\n const rows = this.#database\n .prepare(\n `SELECT ${LIST_COLUMNS}\n FROM traces WHERE ${sql} ORDER BY ${order} LIMIT ?`,\n )\n .all(...params, MAX_EXPORT_ROWS);\n return tracesToCsv(rows.map(toHistoryTrace));\n }\n\n /** One request with all its spans. */\n trace(traceId: string): TraceSummary | undefined {\n this.flush();\n const row = this.#database\n .prepare(`SELECT ${LIST_COLUMNS}, spans FROM traces WHERE trace_id = ?`)\n .get(traceId);\n if (!row) return undefined;\n const { endpoint: _endpoint, ...trace } = toHistoryTrace(row);\n return { ...trace, spans: JSON.parse(String(row.spans)) };\n }\n\n /** How many requests match, how many failed, and how long they took. */\n summary(query: HistoryQuery): HistorySummary {\n this.flush();\n const { sql, params } = filterSql(query);\n let total = 0;\n let clientErrors = 0;\n let serverErrors = 0;\n const counts = this.#database\n .prepare(\n `SELECT ${OUTCOME_CASE} AS outcome, COUNT(*) AS n\n FROM traces WHERE ${sql} GROUP BY outcome`,\n )\n .all(...params);\n for (const row of counts) {\n const n = Number(row.n);\n total += n;\n if (row.outcome === \"client\") clientErrors = n;\n if (row.outcome === \"server\") serverErrors = n;\n }\n const durations = this.#database\n .prepare(\n `SELECT duration_ms FROM traces\n WHERE ${sql} AND duration_ms IS NOT NULL ORDER BY duration_ms`,\n )\n .all(...params)\n .map((row) => Number(row.duration_ms));\n return {\n total,\n clientErrors,\n serverErrors,\n medianMs: percentile(durations, 0.5),\n p95Ms: percentile(durations, 0.95),\n };\n }\n\n /** Write what is queued and release the database. */\n close(): void {\n if (this.#closed) return;\n this.flush();\n this.#closed = true;\n clearInterval(this.#pruneTimer);\n try {\n this.#database.close();\n } catch {\n // Already closed.\n }\n }\n}\n\n/** Query-string values the dashboard sends, parsed defensively. */\nexport function parseHistoryQuery(\n params: URLSearchParams,\n now = Date.now(),\n): HistoryQuery {\n const integer = (name: string): number | undefined => {\n const raw = params.get(name);\n if (raw === null || raw.trim() === \"\") return undefined;\n const value = Number(raw);\n return Number.isFinite(value) ? value : undefined;\n };\n const all = (name: string): string[] | undefined => {\n const values = params.getAll(name).filter((value) => value !== \"\");\n return values.length > 0 ? values : undefined;\n };\n const to = integer(\"to\") ?? now;\n return {\n to,\n from: integer(\"from\") ?? to - 7 * DAY_MS,\n endpoints: all(\"endpoint\"),\n methods: all(\"method\"),\n services: all(\"service\"),\n outcomes: all(\"outcome\")?.filter((value): value is Outcome =>\n OUTCOMES.has(value),\n ),\n minMs: integer(\"minMs\"),\n query: params.get(\"q\") || undefined,\n sort: params.get(\"sort\") === \"slowest\" ? \"slowest\" : \"recent\",\n limit: integer(\"limit\"),\n offset: integer(\"offset\"),\n };\n}\n","/**\n * The page the dashboard serves at `/`. The React app and its styles load from\n * `/assets/`; the inline script applies the saved theme before first paint. The\n * import map lets the project's own docs components, bundled apart from the\n * dashboard, share its copy of React.\n */\nexport const DEV_DASHBOARD_SHELL = `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Brick dev</title>\n<link rel=\"icon\" href=\"data:,\">\n<script>\n(function () {\n try {\n var theme = localStorage.getItem(\"brick-dashboard-theme\");\n var dark = theme === \"dark\" || (theme !== \"light\" && window.matchMedia(\"(prefers-color-scheme: dark)\").matches);\n if (dark) document.documentElement.classList.add(\"dark\");\n } catch (error) {}\n})();\n</script>\n<link rel=\"stylesheet\" href=\"/assets/app.css\">\n<script type=\"importmap\">\n{\"imports\":{\"react\":\"/assets/react.js\",\"react/jsx-runtime\":\"/assets/react-jsx-runtime.js\",\"react/jsx-dev-runtime\":\"/assets/react-jsx-runtime.js\"}}\n</script>\n</head>\n<body>\n<div id=\"root\"></div>\n<script type=\"module\" src=\"/assets/app.js\"></script>\n</body>\n</html>\n`;\n","import { createHash, timingSafeEqual } from \"node:crypto\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { DashboardAuth } from \"@brickkit/core\";\n\n/** What to do with a request: let it through, or answer it with this. */\nexport type Access =\n | { allowed: true }\n | {\n allowed: false;\n status: number;\n headers: Record<string, string | string[]>;\n body: string | Uint8Array;\n };\n\n/** How long the app's `authorize` may take before the request is refused. */\nexport const AUTHORIZE_TIMEOUT_MS = 5000;\n\n/** Whether `host` can only be reached from the machine it runs on. */\nexport function isLoopbackHost(host: string): boolean {\n const name = host.toLowerCase();\n return (\n name === \"localhost\" ||\n name === \"::1\" ||\n name === \"[::1]\" ||\n /^127(\\.\\d{1,3}){3}$/.test(name)\n );\n}\n\nconst NOT_COPIED = new Set([\n \"set-cookie\",\n \"content-length\",\n \"content-encoding\",\n \"transfer-encoding\",\n \"connection\",\n \"keep-alive\",\n]);\n\nconst digest = (value: string) => createHash(\"sha256\").update(value).digest();\n\n/** Whether `candidate` is one of `tokens`, in the same time whichever it is. */\nfunction isToken(candidate: string | undefined, tokens: readonly string[]) {\n if (candidate === undefined) return false;\n const given = digest(candidate);\n let match = false;\n // Every token is compared, so the time does not say which one was close.\n for (const token of tokens)\n if (timingSafeEqual(given, digest(token))) match = true;\n return match;\n}\n\n/** The secret in an `Authorization` header: a Bearer token, or a Basic password. */\nfunction credential(request: IncomingMessage): string | undefined {\n const header = request.headers.authorization;\n if (!header) return undefined;\n const space = header.indexOf(\" \");\n if (space < 0) return undefined;\n const scheme = header.slice(0, space).toLowerCase();\n const value = header.slice(space + 1).trim();\n if (scheme === \"bearer\") return value;\n if (scheme === \"basic\") {\n const decoded = Buffer.from(value, \"base64\").toString(\"utf8\");\n const colon = decoded.indexOf(\":\");\n return colon < 0 ? undefined : decoded.slice(colon + 1);\n }\n return undefined;\n}\n\n/** The request as the app's `authorize` sees it: standard, with no body. */\nfunction webRequest(request: IncomingMessage): Request {\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (value === undefined) continue;\n try {\n headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n } catch {\n // A header the platform will not take cannot matter to a check.\n }\n }\n const forwarded = request.headers[\"x-forwarded-proto\"];\n const protocol =\n (Array.isArray(forwarded) ? forwarded[0] : forwarded)\n ?.split(\",\")[0]\n ?.trim() === \"https\"\n ? \"https\"\n : \"http\";\n const host = request.headers.host ?? \"localhost\";\n let url: string;\n try {\n url = new URL(request.url ?? \"/\", `${protocol}://${host}`).href;\n } catch {\n url = `${protocol}://localhost${request.url ?? \"/\"}`;\n }\n return new Request(url, { method: request.method ?? \"GET\", headers });\n}\n\nconst refusal = (\n status: number,\n body: string,\n headers: Record<string, string> = {},\n): Access => ({\n allowed: false,\n status,\n body,\n headers: { \"content-type\": \"text/plain; charset=utf-8\", ...headers },\n});\n\n/**\n * The check for the dashboard's requests. A request passes with a valid token,\n * or when the app's `authorize` returns `true`. Anything else is answered:\n * what `authorize` returned if it returned a `Response`, else 401 (with a\n * browser sign-in prompt when tokens are in use), and 503 when `authorize`\n * threw or ran out of time, since a check that cannot answer must not let\n * anyone in.\n */\nexport function createAccess(\n auth: DashboardAuth,\n onError: (error: unknown) => void = () => {},\n timeoutMs = AUTHORIZE_TIMEOUT_MS,\n): (request: IncomingMessage) => Promise<Access> {\n const tokens =\n auth.token === undefined\n ? []\n : typeof auth.token === \"string\"\n ? [auth.token]\n : [...auth.token];\n const prompt: Record<string, string> =\n tokens.length > 0\n ? { \"www-authenticate\": 'Basic realm=\"Brick dashboard\", charset=\"UTF-8\"' }\n : {};\n return async (request) => {\n if (tokens.length > 0 && isToken(credential(request), tokens))\n return { allowed: true };\n if (!auth.authorize) return refusal(401, \"Unauthorized\", prompt);\n\n let decision: boolean | Response;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n decision = await Promise.race([\n Promise.resolve(auth.authorize(webRequest(request))),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(\"dashboard authorize timed out\")),\n timeoutMs,\n );\n }),\n ]);\n } catch (error) {\n onError(error);\n return refusal(503, \"Sign-in is unavailable.\");\n } finally {\n clearTimeout(timer);\n }\n if (decision === true) return { allowed: true };\n if (decision instanceof Response) {\n const headers: Record<string, string | string[]> = {};\n decision.headers.forEach((value, name) => {\n // The body is sent as bytes with its own length; these describe the\n // connection or an encoding already undone.\n if (!NOT_COPIED.has(name)) headers[name] = value;\n });\n const cookies = decision.headers.getSetCookie();\n if (cookies.length > 0) headers[\"set-cookie\"] = cookies;\n return {\n allowed: false,\n status: decision.status,\n headers,\n body: new Uint8Array(await decision.arrayBuffer()),\n };\n }\n return refusal(401, \"Unauthorized\", prompt);\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport {\n createServer,\n type IncomingMessage,\n type ServerResponse,\n} from \"node:http\";\nimport { extname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { DevDocs } from \"./dev-docs\";\nimport { parseHistoryQuery, type DevHistory } from \"./dev-history\";\nimport type { TelemetryRecord } from \"./dev-telemetry\";\nimport type {\n DevTelemetryEvent,\n DevTelemetryStore,\n} from \"./dev-telemetry-store\";\nimport { DEV_DASHBOARD_SHELL } from \"./dev-dashboard-shell\";\nimport type { DashboardAuth } from \"@brickkit/core\";\nimport { createAccess, isLoopbackHost } from \"./dashboard-access\";\n\nexport const DEFAULT_DASHBOARD_PORT = 9400;\nconst KEEPALIVE_MS = 15_000;\nconst MAX_INGEST_BYTES = 5 * 1024 * 1024;\nconst MAX_PROXY_BYTES = 10 * 1024 * 1024;\n// Request headers that describe one hop or the dashboard's own page, and\n// response headers that fetch has already applied or that mean nothing here.\nconst NOT_FORWARDED = new Set([\n \"host\",\n \"connection\",\n \"keep-alive\",\n \"proxy-connection\",\n \"transfer-encoding\",\n \"te\",\n \"trailer\",\n \"upgrade\",\n \"content-length\",\n \"accept-encoding\",\n \"origin\",\n \"referer\",\n \"cookie\",\n]);\nconst NOT_RETURNED = new Set([\n \"connection\",\n \"keep-alive\",\n \"transfer-encoding\",\n \"content-length\",\n \"content-encoding\",\n \"set-cookie\",\n]);\n\n/**\n * What a production dashboard may show: the shell and its assets, the live\n * state and its event stream, and stored history. Nothing that changes the app\n * or reaches into it (restart, the API proxy, ingest) and nothing from the\n * project's source (documentation, OpenAPI documents).\n */\nconst isMonitoringRoute = (method: string | undefined, pathname: string) =>\n method === \"GET\" &&\n (pathname === \"/\" ||\n pathname.startsWith(\"/assets/\") ||\n pathname === \"/api/state\" ||\n pathname === \"/api/events\" ||\n pathname.startsWith(\"/api/history\"));\n\nconst PRODUCTION_HEADERS = {\n \"x-content-type-options\": \"nosniff\",\n \"x-frame-options\": \"DENY\",\n \"referrer-policy\": \"no-referrer\",\n \"cross-origin-opener-policy\": \"same-origin\",\n \"cross-origin-resource-policy\": \"same-origin\",\n // Requests and logs are private: nothing caches them on the way.\n \"cache-control\": \"no-store\",\n \"content-security-policy\":\n \"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'\",\n};\n\n/** How long `/_health` waits for the app before calling it down. */\nconst PROBE_TIMEOUT_MS = 3000;\n\nexport interface DevDashboardOptions {\n port: number;\n /**\n * The address to listen on; loopback by default. Any other address needs\n * `auth`, and the server refuses to start without it.\n */\n host?: string;\n /**\n * `\"production\"` is the read-only monitoring dashboard of `brick start`: it\n * serves only what `isMonitoringRoute` lists, with security headers, and\n * tells its page to hide the tabs that need a developer's machine.\n */\n mode?: \"dev\" | \"production\";\n /** Who may use the dashboard, checked before anything but `/_health`. */\n auth?: DashboardAuth;\n /** Whether the app answers; `/_health` reports it, for uptime monitors. */\n probe?: () => Promise<boolean>;\n store: DevTelemetryStore;\n /** Requests kept on disk; omit to serve live data only. The page hides its History view. */\n history?: DevHistory;\n /** The app's developer documentation, when it has any, as of this request. */\n docs?: () => DevDocs | undefined;\n /** Omit when the host cannot restart the application; the page hides its button. */\n restart?: () => void;\n}\n\nexport interface DevDashboard {\n readonly port: number;\n stop(): void;\n}\n\n/**\n * Serve the dashboard, on loopback unless told otherwise. On loopback requests\n * must name a local host (blocks DNS rebinding), and restart requires a header\n * that cross-origin pages cannot send without a preflight. Elsewhere `auth` is\n * required and decides who gets in. Uses node:http, so it runs under Bun and\n * under Node (Vite's dev server runs under Node).\n */\nexport function startDevDashboard(\n options: DevDashboardOptions,\n): Promise<DevDashboard> {\n const host = options.host ?? \"127.0.0.1\";\n const loopback = isLoopbackHost(host);\n const production = options.mode === \"production\";\n if (!loopback && !options.auth) {\n return Promise.reject(\n new Error(\n `Brick: the dashboard would listen on ${host}, where others can reach it, so it needs access control. Set dashboard.auth with a token or an authorize function.`,\n ),\n );\n }\n const access = options.auth\n ? createAccess(options.auth, (error) =>\n console.error(\"[Brick-TS] The dashboard sign-in check failed:\", error),\n )\n : undefined;\n let allowedHosts = new Set<string>();\n const server = createServer((request, response) => {\n respond(request, response).catch((error: unknown) => {\n console.error(\"[Brick-TS] The dashboard failed to answer:\", error);\n if (response.headersSent) response.end();\n else send(response, 500, \"Server error\");\n });\n });\n\n async function respond(\n request: IncomingMessage,\n response: ServerResponse,\n ): Promise<void> {\n if (production)\n for (const [name, value] of Object.entries(PRODUCTION_HEADERS))\n response.setHeader(name, value);\n if (loopback && !allowedHosts.has(request.headers.host ?? \"\")) {\n send(response, 403, \"Forbidden\");\n return;\n }\n const url = new URL(request.url ?? \"/\", \"http://127.0.0.1\");\n const { pathname } = url;\n // The one route open to everyone: uptime monitors cannot sign in.\n if (\n pathname === \"/_health\" &&\n (request.method === \"GET\" || request.method === \"HEAD\")\n ) {\n await health(response);\n return;\n }\n if (access) {\n const decision = await access(request);\n if (!decision.allowed) {\n send(response, decision.status, decision.body, decision.headers);\n return;\n }\n }\n if (production && !isMonitoringRoute(request.method, pathname)) {\n send(response, 404, \"Not found\");\n return;\n }\n handle(request, response, url);\n }\n\n /** 200 while the app answers its own health check, 503 when it does not. */\n async function health(response: ServerResponse): Promise<void> {\n const probe = options.probe;\n let up = true;\n if (probe) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n up = await Promise.race([\n probe().catch(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), PROBE_TIMEOUT_MS);\n }),\n ]);\n clearTimeout(timer);\n }\n send(\n response,\n up ? 200 : 503,\n JSON.stringify({\n status: up ? \"ok\" : \"degraded\",\n ...(probe ? { app: up ? \"up\" : \"down\" } : {}),\n }),\n { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" },\n );\n }\n\n function handle(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ): void {\n const { pathname } = url;\n if (request.method === \"GET\" && pathname === \"/\") {\n send(response, 200, DEV_DASHBOARD_SHELL, {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n return;\n }\n if (request.method === \"GET\" && pathname.startsWith(\"/assets/\")) {\n serveAsset(response, pathname.slice(\"/assets/\".length));\n return;\n }\n if (request.method === \"GET\" && pathname === \"/api/state\") {\n send(response, 200, JSON.stringify(snapshot()), {\n \"content-type\": \"application/json\",\n });\n return;\n }\n if (request.method === \"GET\" && pathname === \"/api/events\") {\n eventStream(request, response);\n return;\n }\n if (\n request.method === \"GET\" &&\n pathname.startsWith(\"/api/history\") &&\n options.history\n ) {\n history(options.history, pathname, url.searchParams, response);\n return;\n }\n if (request.method === \"GET\" && pathname.startsWith(\"/api/docs\")) {\n void docsRoute(response, pathname, url.searchParams);\n return;\n }\n if (request.method === \"GET\" && pathname === \"/api/openapi\") {\n send(response, 200, JSON.stringify(options.store.apiDocuments()), {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n });\n return;\n }\n if (pathname === \"/api/proxy\") {\n void proxy(request, response, url);\n return;\n }\n if (request.method === \"POST\" && pathname === \"/api/ingest\") {\n ingest(request, response);\n return;\n }\n if (\n request.method === \"POST\" &&\n pathname === \"/api/restart\" &&\n options.restart\n ) {\n if (request.headers[\"x-brick-dashboard\"] !== \"1\") {\n send(response, 403, \"Forbidden\");\n return;\n }\n options.restart();\n send(response, 202, \"\");\n return;\n }\n send(response, 404, \"Not found\");\n }\n\n function snapshot() {\n return {\n ...options.store.snapshot(),\n canRestart: Boolean(options.restart),\n historyDays: options.history?.days ?? 0,\n mode: production ? \"production\" : \"dev\",\n };\n }\n\n /**\n * Accept telemetry from an application process that cannot share memory with\n * the dashboard, such as a dev server worker: span batches, and a notice when\n * the app loads.\n */\n function ingest(request: IncomingMessage, response: ServerResponse) {\n if (request.headers[\"x-brick-dashboard\"] !== \"1\") {\n send(response, 403, \"Forbidden\");\n return;\n }\n let body = \"\";\n let rejected = false;\n request.setEncoding(\"utf8\");\n request.on(\"data\", (chunk: string) => {\n if (rejected) return;\n body += chunk;\n if (body.length > MAX_INGEST_BYTES) {\n rejected = true;\n send(response, 413, \"Payload too large\");\n request.destroy();\n }\n });\n request.on(\"end\", () => {\n if (rejected) return;\n try {\n const payload = JSON.parse(body) as {\n records?: TelemetryRecord[];\n worker?: string;\n };\n if (Array.isArray(payload.records)) {\n options.store.ingest(payload.records, options.store.latestGeneration);\n }\n if (typeof payload.worker === \"string\") {\n options.store.startGeneration(payload.worker);\n }\n send(response, 204, \"\");\n } catch {\n send(response, 400, \"Bad request\");\n }\n });\n }\n\n /** The Docs tab's data: tree, compiled pages, search, images, components. */\n async function docsRoute(\n response: ServerResponse,\n pathname: string,\n params: URLSearchParams,\n ): Promise<void> {\n const docs = options.docs?.();\n if (!docs) {\n send(response, 404, \"The app has no documentation.\");\n return;\n }\n const json = (body: unknown) =>\n send(response, 200, JSON.stringify(body), {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n });\n try {\n if (pathname === \"/api/docs\") return json(docs.info());\n if (pathname === \"/api/docs/search\")\n return json(await docs.search(params.get(\"q\") ?? \"\"));\n if (pathname === \"/api/docs/components.js\") {\n const code = await docs.components();\n if (code === undefined) return send(response, 404, \"No components.\");\n return send(response, 200, code, {\n \"content-type\": \"text/javascript; charset=utf-8\",\n \"cache-control\": \"no-store\",\n });\n }\n const pagePrefix = \"/api/docs/page\";\n if (pathname === pagePrefix || pathname.startsWith(`${pagePrefix}/`)) {\n const slugs = pathname\n .slice(pagePrefix.length)\n .split(\"/\")\n .filter(Boolean)\n .map(decodeURIComponent);\n const page = await docs.page(slugs);\n return page ? json(page) : send(response, 404, \"No such page.\");\n }\n const filePrefix = \"/api/docs/files/\";\n if (pathname.startsWith(filePrefix)) {\n const file = await docs.file(\n pathname\n .slice(filePrefix.length)\n .split(\"/\")\n .map(decodeURIComponent)\n .join(\"/\"),\n );\n if (!file) return send(response, 404, \"No such file.\");\n return send(response, 200, file.body, {\n \"content-type\": file.type,\n \"cache-control\": \"no-store\",\n // An image in a page; a document opened directly cannot run scripts.\n \"content-security-policy\": \"sandbox\",\n });\n }\n send(response, 404, \"Not found\");\n } catch (error) {\n send(\n response,\n error instanceof URIError ? 400 : 500,\n error instanceof Error ? error.message : String(error),\n );\n }\n }\n\n /**\n * Send a request on to the app for the APIs view, which cannot call the app\n * directly: it is another origin. Only the dashboard's own page may use this,\n * and only to reach the app being shown. The address to call is `?url=`; a\n * `?cookie=` is the cookie parameters the reader typed into Try it, and the\n * only cookie the app is sent (the dashboard's own are never forwarded).\n */\n async function proxy(\n request: IncomingMessage,\n response: ServerResponse,\n url: URL,\n ): Promise<void> {\n const site = request.headers[\"sec-fetch-site\"];\n const origin = request.headers.origin;\n if (\n (site !== undefined && site !== \"same-origin\") ||\n (origin !== undefined && origin !== `http://${request.headers.host}`)\n ) {\n send(response, 403, \"Forbidden\");\n return;\n }\n let target: URL | undefined;\n try {\n target = new URL(url.searchParams.get(\"url\") ?? \"\");\n } catch {\n // Not an address; refused below.\n }\n const appUrl = options.store.apiSnapshot()?.appUrl;\n if (!target || !appUrl || target.origin !== new URL(appUrl).origin) {\n send(\n response,\n 403,\n \"Only the app shown in the dashboard can be reached.\",\n );\n return;\n }\n const body = await readBytes(request, MAX_PROXY_BYTES);\n if (!body) {\n send(response, 413, \"Payload too large\");\n return;\n }\n const headers = new Headers();\n for (const [name, value] of Object.entries(request.headers)) {\n if (value === undefined || NOT_FORWARDED.has(name)) continue;\n if (name.startsWith(\"sec-\")) continue;\n headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n }\n const cookie = url.searchParams.get(\"cookie\");\n if (cookie) headers.set(\"cookie\", cookie);\n const bodyless = request.method === \"GET\" || request.method === \"HEAD\";\n try {\n const upstream = await fetch(target, {\n method: request.method,\n headers,\n body: bodyless ? undefined : (body as BodyInit),\n redirect: \"manual\",\n });\n const returned: Record<string, string> = {};\n upstream.headers.forEach((value, name) => {\n if (!NOT_RETURNED.has(name)) returned[name] = value;\n });\n send(\n response,\n upstream.status,\n new Uint8Array(await upstream.arrayBuffer()),\n returned,\n );\n } catch {\n send(response, 502, \"Could not reach the app.\");\n }\n }\n\n function eventStream(request: IncomingMessage, response: ServerResponse) {\n response.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n // So a proxy in front passes events on as they come.\n \"x-accel-buffering\": \"no\",\n });\n const write = (chunk: string) => {\n if (response.writableEnded || response.destroyed) return;\n response.write(chunk);\n };\n write(`event: snapshot\\ndata: ${JSON.stringify(snapshot())}\\n\\n`);\n const unsubscribe = options.store.subscribe((event: DevTelemetryEvent) =>\n write(`event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`),\n );\n const keepalive = setInterval(() => write(\": keepalive\\n\\n\"), KEEPALIVE_MS);\n request.on(\"close\", () => {\n clearInterval(keepalive);\n unsubscribe();\n });\n }\n\n return new Promise((resolve, reject) => {\n server.once(\"error\", (error) => {\n reject(\n new Error(\n production\n ? `Brick: dashboard port ${options.port} is unavailable. Set dashboard.port in brick() to another.`\n : `Brick: dashboard port ${options.port} is unavailable. Use --dashboard-port <number> or --no-dashboard.`,\n { cause: error },\n ),\n );\n });\n server.listen(options.port, host, () => {\n const address = server.address();\n const port =\n typeof address === \"object\" && address !== null\n ? address.port\n : options.port;\n allowedHosts = new Set([\n `127.0.0.1:${port}`,\n `localhost:${port}`,\n `[::1]:${port}`,\n ]);\n resolve({\n port,\n stop() {\n server.close();\n server.closeAllConnections();\n },\n });\n });\n });\n}\n\n/** The whole request body, or undefined when it is larger than `limit`. */\nfunction readBytes(\n request: IncomingMessage,\n limit: number,\n): Promise<Uint8Array | undefined> {\n return new Promise((resolve) => {\n const chunks: Buffer[] = [];\n let size = 0;\n request.on(\"data\", (chunk: Buffer) => {\n size += chunk.length;\n if (size > limit) {\n resolve(undefined);\n request.destroy();\n return;\n }\n chunks.push(chunk);\n });\n request.on(\"end\", () => resolve(new Uint8Array(Buffer.concat(chunks))));\n request.on(\"error\", () => resolve(undefined));\n });\n}\n\nfunction history(\n store: DevHistory,\n pathname: string,\n params: URLSearchParams,\n response: ServerResponse,\n): void {\n const json = (body: unknown) =>\n send(response, 200, JSON.stringify(body), {\n \"content-type\": \"application/json\",\n });\n try {\n if (pathname === \"/api/history\") return json(store.info());\n if (pathname === \"/api/history/summary\") {\n return json(store.summary(parseHistoryQuery(params)));\n }\n if (pathname === \"/api/history/traces\") {\n return json(store.traces(parseHistoryQuery(params)));\n }\n if (pathname === \"/api/history/facets\") {\n return json(store.facets(parseHistoryQuery(params)));\n }\n if (pathname === \"/api/history/volume\") {\n return json(store.volume(parseHistoryQuery(params)));\n }\n if (pathname === \"/api/history/export\") {\n return send(response, 200, store.exportCsv(parseHistoryQuery(params)), {\n \"content-type\": \"text/csv; charset=utf-8\",\n \"content-disposition\": 'attachment; filename=\"brick-requests.csv\"',\n \"cache-control\": \"no-store\",\n });\n }\n const prefix = \"/api/history/traces/\";\n if (pathname.startsWith(prefix)) {\n const trace = store.trace(\n decodeURIComponent(pathname.slice(prefix.length)),\n );\n if (trace) return json(trace);\n }\n send(response, 404, \"Not found\");\n } catch {\n send(response, 500, \"History query failed\");\n }\n}\n\nconst ASSET_TYPES: Record<string, string> = {\n \".js\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".woff2\": \"font/woff2\",\n};\n\n/** The built React app, next to `src/` in the repo and next to `dist/` when published. */\nfunction assetsDirectory(): string | undefined {\n for (const relative of [\"../dashboard-dist/\", \"../../dashboard-dist/\"]) {\n const directory = fileURLToPath(new URL(relative, import.meta.url));\n if (existsSync(join(directory, \"app.js\"))) return directory;\n }\n return undefined;\n}\n\nfunction serveAsset(response: ServerResponse, name: string): void {\n // Plain file names only: no separators, so a request cannot leave the folder.\n if (!/^[\\w.-]+$/.test(name) || name.startsWith(\".\")) {\n send(response, 404, \"Not found\");\n return;\n }\n const directory = assetsDirectory();\n if (!directory) {\n send(\n response,\n 503,\n \"Dashboard assets are missing. Build them with: bun run --filter @brickkit/cli build\",\n );\n return;\n }\n readFile(join(directory, name)).then(\n (body) =>\n send(response, 200, body, {\n \"content-type\":\n ASSET_TYPES[extname(name)] ?? \"application/octet-stream\",\n \"cache-control\": \"no-store\",\n }),\n () => send(response, 404, \"Not found\"),\n );\n}\n\nfunction send(\n response: ServerResponse,\n status: number,\n body: string | Uint8Array,\n headers: Record<string, string | string[]> = {\n \"content-type\": \"text/plain; charset=utf-8\",\n },\n): void {\n response.writeHead(status, headers);\n response.end(body);\n}\n","import { watch, type FSWatcher } from \"node:fs\";\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport {\n basename,\n dirname,\n extname,\n join,\n posix,\n relative,\n resolve,\n sep,\n} from \"node:path\";\nimport type { DocumentationOptions } from \"@brickkit/core\";\nimport type { DevTelemetryStore, DocsSnapshot } from \"./dev-telemetry-store\";\n\n/*\n * Developer documentation for the dashboard's Docs tab. The folder follows\n * Fumadocs' layout (frontmatter, meta.json, folder groups), and fumadocs-core\n * builds the page tree and search. MDX is compiled here and run in the browser\n * with the dashboard's components plus the project's own.\n *\n * fumadocs-core and @mdx-js/mdx are optional peers, loaded only when an app\n * sets `documentation`, so projects without docs do not install them.\n */\n\n/** One entry of the docs sidebar. */\nexport type DocsNode =\n | { type: \"page\"; name: string; url: string; description?: string }\n | {\n type: \"folder\";\n name: string;\n index?: { name: string; url: string };\n children: DocsNode[];\n defaultOpen?: boolean;\n }\n | { type: \"separator\"; name?: string };\n\nexport interface DocsTree {\n name: string;\n children: DocsNode[];\n}\n\nexport interface DocsHeading {\n title: string;\n url: string;\n depth: number;\n}\n\n/** A page ready to run in the browser. */\nexport interface DocsPage {\n title: string;\n description?: string;\n /** The file, relative to the docs folder. */\n path: string;\n slugs: string[];\n toc: DocsHeading[];\n /** MDX compiled to a function body; see `runMdx` in the dashboard. */\n code: string;\n /** Set instead of `code` when the page does not compile. */\n error?: string;\n}\n\nexport interface DocsSearchHit {\n id: string;\n type: \"page\" | \"heading\" | \"text\";\n content: string;\n /** Route within the docs, with a `#heading` when the hit is inside a page. */\n url: string;\n}\n\nexport interface DocsInfo {\n tree: DocsTree;\n /** Whether the project supplied components of its own. */\n components: boolean;\n revision: number;\n}\n\nexport type OpenedDocs =\n | { status: \"ready\"; docs: DevDocs }\n | { status: \"missing\"; packages: string[] }\n | { status: \"error\"; message: string };\n\nconst PACKAGES = [\"fumadocs-core\", \"@mdx-js/mdx\"] as const;\nconst PAGE_EXTENSIONS = new Set([\".md\", \".mdx\"]);\nconst IMAGE_TYPES: Record<string, string> = {\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n};\nconst REFRESH_DELAY_MS = 100;\n\ninterface Fumadocs {\n loader: typeof import(\"fumadocs-core/source\").loader;\n frontmatter: typeof import(\"fumadocs-core/content/md/frontmatter\").frontmatter;\n plugins: typeof import(\"fumadocs-core/mdx-plugins\");\n createSearchAPI: typeof import(\"fumadocs-core/search/server\").createSearchAPI;\n compile: typeof import(\"@mdx-js/mdx\").compile;\n}\n\nasync function loadFumadocs(): Promise<Fumadocs | string[]> {\n try {\n const [source, matter, plugins, search, mdx] = await Promise.all([\n import(\"fumadocs-core/source\"),\n import(\"fumadocs-core/content/md/frontmatter\"),\n import(\"fumadocs-core/mdx-plugins\"),\n import(\"fumadocs-core/search/server\"),\n import(\"@mdx-js/mdx\"),\n ]);\n return {\n loader: source.loader,\n frontmatter: matter.frontmatter,\n plugins,\n createSearchAPI: search.createSearchAPI,\n compile: mdx.compile,\n };\n } catch (error) {\n // Only a missing package is the project's to fix; anything else is a bug.\n if (\n (error as { code?: string }).code === \"ERR_MODULE_NOT_FOUND\" ||\n /Cannot find (module|package)/.test(String((error as Error)?.message))\n )\n return [...PACKAGES];\n throw error;\n }\n}\n\ninterface PageFile {\n /** Relative to the docs folder, with forward slashes. */\n path: string;\n absolute: string;\n title: string;\n description?: string;\n /** The file's text after the frontmatter. */\n content: string;\n data: Record<string, unknown>;\n}\n\ninterface MetaFile {\n path: string;\n data: Record<string, unknown>;\n}\n\nconst humanize = (name: string): string => {\n const spaced = name.replace(/[-_]+/g, \" \").trim();\n return spaced.charAt(0).toUpperCase() + spaced.slice(1);\n};\n\nconst H1 = /^#\\s+(.+?)\\s*#*\\s*$/;\n\n/**\n * The first `# Heading` outside code fences: its text, and the content without\n * it. The page shows its title above the content, so a heading that only\n * repeats the title would appear twice.\n */\nfunction firstHeading(\n content: string,\n): { text: string; rest: string; leading: boolean } | undefined {\n const lines = content.split(\"\\n\");\n let fenced = false;\n let seenText = false;\n for (const [index, line] of lines.entries()) {\n if (/^\\s*(```|~~~)/.test(line)) {\n fenced = !fenced;\n seenText = true;\n } else if (!fenced) {\n const match = H1.exec(line);\n if (match) {\n const rest = [...lines.slice(0, index), ...lines.slice(index + 1)];\n // Drop the blank line that followed it as well.\n if (rest[index]?.trim() === \"\") rest.splice(index, 1);\n return { text: match[1]!, rest: rest.join(\"\\n\"), leading: !seenText };\n }\n if (line.trim() !== \"\") seenText = true;\n }\n }\n return undefined;\n}\n\nasync function scan(\n root: string,\n fumadocs: Fumadocs,\n warn: (message: string) => void,\n): Promise<{ pages: PageFile[]; metas: MetaFile[] }> {\n const pages: PageFile[] = [];\n const metas: MetaFile[] = [];\n async function visit(directory: string): Promise<void> {\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n const absolute = join(directory, entry.name);\n const path = relative(root, absolute).split(sep).join(\"/\");\n if (entry.isDirectory()) {\n await visit(absolute);\n } else if (entry.name === \"meta.json\") {\n try {\n const data = JSON.parse(await readFile(absolute, \"utf8\"));\n if (data && typeof data === \"object\") metas.push({ path, data });\n } catch (error) {\n warn(`[Brick-TS] Skipping docs ${path}: ${errorMessage(error)}`);\n }\n } else if (PAGE_EXTENSIONS.has(extname(entry.name))) {\n const text = await readFile(absolute, \"utf8\");\n let data: Record<string, unknown> = {};\n let content = text;\n try {\n const parsed = fumadocs.frontmatter(text);\n data = parsed.data as Record<string, unknown>;\n content = parsed.content;\n } catch (error) {\n warn(\n `[Brick-TS] Ignoring the frontmatter of docs ${path}: ${errorMessage(error)}`,\n );\n }\n const name = basename(entry.name, extname(entry.name));\n const heading = firstHeading(content);\n const given =\n typeof data.title === \"string\" && data.title ? data.title : undefined;\n const title =\n given ??\n heading?.text ??\n humanize(name === \"index\" ? basename(dirname(path)) || \"Home\" : name);\n // A title taken from the heading, or a leading heading that repeats the\n // frontmatter title, is shown once, above the content.\n if (heading && (!given || (heading.leading && heading.text === given)))\n content = heading.rest;\n pages.push({\n path,\n absolute,\n title,\n description:\n typeof data.description === \"string\" ? data.description : undefined,\n content,\n data,\n });\n }\n }\n }\n await visit(root);\n return { pages, metas };\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype MdastNode = {\n type: string;\n url?: string;\n name?: string | null;\n attributes?: { type: string; name?: string; value?: unknown }[];\n children?: MdastNode[];\n};\n\nfunction walk(node: MdastNode, visit: (node: MdastNode) => void): void {\n visit(node);\n for (const child of node.children ?? []) walk(child, visit);\n}\n\n/** Ways a link inside a page can point at another page or a local image. */\nfunction resolveInside(from: string, href: string): string | undefined {\n if (/^[a-z][a-z\\d+.-]*:/i.test(href) || href.startsWith(\"#\"))\n return undefined;\n if (href.startsWith(\"/\")) return undefined;\n const [target] = href.split(/[?#]/);\n if (!target) return undefined;\n const resolved = posix.normalize(posix.join(posix.dirname(from), target));\n return resolved.startsWith(\"../\") ? undefined : resolved;\n}\n\n/**\n * The page tree and compiled pages of one docs folder. It watches the folder,\n * so edits show in the dashboard as they are saved.\n */\nexport class DevDocs {\n readonly #root: string;\n readonly #documentation: DocumentationOptions;\n /** Relative paths in `documentation` start here: the app entry's folder. */\n readonly #base: string;\n readonly #fumadocs: Fumadocs;\n readonly #warn: (message: string) => void;\n readonly #listeners = new Set<() => void>();\n readonly #watchers: FSWatcher[] = [];\n #loader: Source | undefined;\n #pages = new Map<string, PageFile>();\n #byPath = new Map<string, string>();\n #compiled = new Map<string, DocsPage>();\n #search:\n | Promise<{ search(query: string): Promise<DocsSearchHit[]> }>\n | undefined;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #refreshing: Promise<void> = Promise.resolve();\n #closed = false;\n #title = \"Docs\";\n revision = 0;\n\n constructor(\n base: string,\n documentation: DocumentationOptions,\n fumadocs: Fumadocs,\n warn: (message: string) => void,\n ) {\n this.#base = base;\n this.#documentation = documentation;\n this.#root = resolve(base, documentation.dir);\n this.#fumadocs = fumadocs;\n this.#warn = warn;\n }\n\n /** Read the folder again and tell listeners. */\n async refresh(): Promise<void> {\n // Refreshes run one at a time, so a slow scan cannot overwrite a newer one.\n this.#refreshing = this.#refreshing.then(() => this.#scan());\n await this.#refreshing;\n }\n\n async #scan(): Promise<void> {\n const { pages, metas } = await scan(this.#root, this.#fumadocs, this.#warn);\n if (this.#closed) return;\n const source = this.#fumadocs.loader({\n baseUrl: \"/\",\n source: {\n files: [\n ...pages.map((page) => ({\n type: \"page\" as const,\n path: page.path,\n data: {\n ...page.data,\n title: page.title,\n description: page.description,\n },\n })),\n ...metas.map((meta) => ({\n type: \"meta\" as const,\n path: meta.path,\n data: meta.data,\n })),\n ],\n },\n });\n this.#loader = source as unknown as Source;\n this.#pages = new Map();\n this.#byPath = new Map();\n for (const page of this.#loader.getPages()) {\n const slug = page.slugs.join(\"/\");\n const file = pages.find((candidate) => candidate.path === page.path);\n if (!file) continue;\n this.#pages.set(slug, file);\n this.#byPath.set(file.path, slug);\n }\n this.#compiled.clear();\n this.#search = undefined;\n const tree = this.#loader.getPageTree();\n this.#title = typeof tree.name === \"string\" ? tree.name : \"Docs\";\n this.revision++;\n for (const listener of this.#listeners) listener();\n }\n\n /** Start watching the folder, and the project's components module. */\n watch(): void {\n const changed = () => {\n clearTimeout(this.#timer);\n this.#timer = setTimeout(() => {\n void this.refresh().catch((error) =>\n this.#warn(`[Brick-TS] Docs: ${errorMessage(error)}`),\n );\n }, REFRESH_DELAY_MS);\n };\n const folders = [this.#root];\n if (this.#documentation.components)\n folders.push(dirname(this.#componentsPath()!));\n for (const [index, folder] of folders.entries()) {\n try {\n // Recursive for the docs; the components module's folder is the\n // project's own source, where only its direct files matter.\n this.#watchers.push(\n watch(folder, { recursive: index === 0 }, () => changed()),\n );\n } catch {\n try {\n this.#watchers.push(watch(folder, () => changed()));\n } catch {\n // A folder that cannot be watched still works; it just needs a reload.\n }\n }\n }\n }\n\n onChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n snapshot(): DocsSnapshot {\n return {\n revision: this.revision,\n status: \"ready\",\n title: this.#title,\n components: Boolean(this.#documentation.components),\n };\n }\n\n info(): DocsInfo {\n return {\n tree: simplify(this.#loader?.getPageTree()),\n components: Boolean(this.#documentation.components),\n revision: this.revision,\n };\n }\n\n /** Compile one page; undefined when there is no such page. */\n async page(slugs: string[]): Promise<DocsPage | undefined> {\n const key = slugs.join(\"/\");\n const file = this.#pages.get(key);\n if (!file) return undefined;\n const cached = this.#compiled.get(key);\n if (cached) return cached;\n const page = await this.#compile(file, slugs);\n // A refresh while compiling clears the cache; do not put stale output back.\n if (this.#pages.get(key) === file) this.#compiled.set(key, page);\n return page;\n }\n\n async #compile(file: PageFile, slugs: string[]): Promise<DocsPage> {\n const { plugins, compile } = this.#fumadocs;\n const base = {\n title: file.title,\n description: file.description,\n path: file.path,\n slugs,\n };\n try {\n const result = await compile(\n { path: file.absolute, value: file.content },\n {\n outputFormat: \"function-body\",\n development: false,\n remarkPlugins: [\n plugins.remarkGfm,\n plugins.remarkHeading,\n plugins.remarkCodeTab,\n plugins.remarkNpm,\n plugins.remarkAdmonition,\n () => (tree: MdastNode) => this.#rewriteLinks(tree, file.path),\n ],\n rehypePlugins: [plugins.rehypeCode],\n },\n );\n const toc = (result.data.toc ?? []) as {\n title: unknown;\n url: string;\n depth: number;\n }[];\n return {\n ...base,\n toc: toc.map((item) => ({\n title: plainText(item.title),\n url: item.url,\n depth: item.depth,\n })),\n code: String(result),\n };\n } catch (error) {\n return { ...base, toc: [], code: \"\", error: errorMessage(error) };\n }\n }\n\n /**\n * Links to other pages become dashboard routes, and local images are served\n * from the docs folder, so a folder reads the same here as on a docs site.\n * This covers markdown links and the `href` of components such as `<Card>`.\n */\n #rewriteLinks(tree: MdastNode, from: string): void {\n const file = (resolved: string) =>\n `/api/docs/files/${resolved.split(\"/\").map(encodeURIComponent).join(\"/\")}`;\n walk(tree, (node) => {\n if (node.type === \"link\" && node.url !== undefined) {\n node.url = this.#route(from, node.url) ?? node.url;\n } else if (node.type === \"image\" && node.url !== undefined) {\n const resolved = resolveInside(from, node.url);\n if (resolved !== undefined) node.url = file(resolved);\n } else if (\n node.type === \"mdxJsxFlowElement\" ||\n node.type === \"mdxJsxTextElement\"\n ) {\n for (const attribute of node.attributes ?? []) {\n if (attribute.type !== \"mdxJsxAttribute\") continue;\n if (typeof attribute.value !== \"string\") continue;\n if (attribute.name === \"href\")\n attribute.value =\n this.#route(from, attribute.value) ?? attribute.value;\n else if (attribute.name === \"src\" && node.name === \"img\") {\n const resolved = resolveInside(from, attribute.value);\n if (resolved !== undefined) attribute.value = file(resolved);\n }\n }\n }\n });\n }\n\n /**\n * The dashboard route for a link to a page of these docs, or undefined for\n * anything else (other sites, in-page anchors, files). A link to a page that\n * does not exist still becomes a route, so it says \"No such page\" here\n * instead of leaving the dashboard.\n */\n #route(from: string, href: string): string | undefined {\n const hashAt = href.indexOf(\"#\");\n const hash = hashAt >= 0 ? href.slice(hashAt) : \"\";\n const target =\n (hashAt >= 0 ? href.slice(0, hashAt) : href).split(\"?\")[0] ?? \"\";\n const route = (slug: string) => `#/docs${slug ? `/${slug}` : \"\"}${hash}`;\n if (/^[a-z][a-z\\d+.-]*:/i.test(href) || href.startsWith(\"#\") || !target)\n return undefined;\n if (target.startsWith(\"/\")) {\n // A docs site links by address (/guide/setup); so can these pages.\n const slug = target.replace(/^\\/+|\\/+$/g, \"\");\n return this.#pages.has(slug) ? route(slug) : undefined;\n }\n const resolved = resolveInside(from, target);\n if (resolved === undefined) return undefined;\n const known = this.#byPath.get(resolved);\n if (known !== undefined) return route(known);\n if (!PAGE_EXTENSIONS.has(extname(resolved))) return undefined;\n const guess = resolved\n .slice(0, -extname(resolved).length)\n .replace(/(^|\\/)index$/, \"\");\n return route(guess);\n }\n\n async search(query: string): Promise<DocsSearchHit[]> {\n if (!query.trim()) return [];\n this.#search ??= this.#buildSearch();\n return (await this.#search).search(query);\n }\n\n async #buildSearch() {\n const { plugins, createSearchAPI } = this.#fumadocs;\n const indexes = [...this.#pages.entries()].map(([slug, file]) => ({\n id: file.path,\n title: file.title,\n description: file.description,\n url: `/${slug}`,\n structuredData: plugins.structure(file.content),\n }));\n const api = createSearchAPI(\"advanced\", { indexes });\n return {\n async search(query: string) {\n return (await api.search(query)) as DocsSearchHit[];\n },\n };\n }\n\n /** A file from the docs folder that a page can show, such as an image. */\n async file(\n relativePath: string,\n ): Promise<{ body: Uint8Array; type: string } | undefined> {\n const type = IMAGE_TYPES[extname(relativePath).toLowerCase()];\n if (!type) return undefined;\n const absolute = resolve(this.#root, relativePath);\n // Stay inside the docs folder, whatever the path says.\n if (absolute !== this.#root && !absolute.startsWith(this.#root + sep))\n return undefined;\n try {\n if (!(await stat(absolute)).isFile()) return undefined;\n return { body: new Uint8Array(await readFile(absolute)), type };\n } catch {\n return undefined;\n }\n }\n\n #componentsPath(): string | undefined {\n const { components } = this.#documentation;\n return components ? resolve(this.#base, components) : undefined;\n }\n\n /** The project's components as one browser module; undefined when it has none. */\n async components(): Promise<string | undefined> {\n const entry = this.#componentsPath();\n return entry ? bundleComponents(entry) : undefined;\n }\n\n close(): void {\n this.#closed = true;\n clearTimeout(this.#timer);\n for (const watcher of this.#watchers) watcher.close();\n this.#watchers.length = 0;\n this.#listeners.clear();\n }\n}\n\n// What the dashboard supplies to the project's components itself, so there is\n// only one copy of React on the page. See the import map in the page shell.\nconst SHARED = [\"react\", \"react/jsx-runtime\", \"react/jsx-dev-runtime\"];\n\n/** Bundle a module of React components for the dashboard to import. */\nexport async function bundleComponents(entry: string): Promise<string> {\n if (typeof Bun !== \"undefined\") {\n const result = await Bun.build({\n entrypoints: [entry],\n target: \"browser\",\n format: \"esm\",\n external: SHARED,\n minify: false,\n });\n if (!result.success)\n throw new Error(result.logs.map((log) => log.message).join(\"\\n\"));\n return result.outputs[0]!.text();\n }\n // Under Node the dev server's own bundler does the work. The name is not\n // written as a literal so the CLI's Bun bundle, which never gets here,\n // stays free of a Vite import.\n const bundler = \"vite\";\n const { build } = (await import(bundler)) as typeof import(\"vite\");\n const output = await build({\n configFile: false,\n logLevel: \"silent\",\n root: dirname(entry),\n oxc: { jsx: { runtime: \"automatic\" } },\n esbuild: { jsx: \"automatic\" },\n define: { \"process.env.NODE_ENV\": '\"development\"' },\n build: {\n write: false,\n minify: false,\n lib: { entry, formats: [\"es\"], fileName: \"components\" },\n rollupOptions: { external: SHARED },\n },\n } as never);\n const bundles = Array.isArray(output) ? output : [output];\n for (const bundle of bundles) {\n const chunk = (\"output\" in bundle ? bundle.output : []).find(\n (item) => item.type === \"chunk\" && item.isEntry,\n );\n if (chunk && \"code\" in chunk) return chunk.code;\n }\n throw new Error(\"Brick: the docs components module produced no output.\");\n}\n\n/** Flatten what MDX gives for a heading to text. */\nfunction plainText(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.map(plainText).join(\"\");\n if (value && typeof value === \"object\") {\n const node = value as {\n props?: { children?: unknown };\n children?: unknown;\n value?: unknown;\n };\n if (typeof node.value === \"string\") return node.value;\n return plainText(node.props?.children ?? node.children);\n }\n return \"\";\n}\n\ninterface RawNode {\n type: string;\n name?: unknown;\n url?: string;\n description?: unknown;\n index?: RawNode;\n children?: RawNode[];\n defaultOpen?: boolean;\n}\ntype RawTree = { name?: unknown; children: RawNode[] };\n\n/** What this module uses of a fumadocs-core loader. */\ninterface Source {\n getPages(): { slugs: string[]; path: string }[];\n getPageTree(): RawTree;\n}\n\n/** The page tree as plain data for the dashboard; icons and links are left out. */\nfunction simplify(tree: RawTree | undefined): DocsTree {\n const text = (value: unknown): string =>\n typeof value === \"string\" ? value : plainText(value);\n const convert = (node: RawNode): DocsNode | undefined => {\n if (node.type === \"page\" && node.url !== undefined)\n return {\n type: \"page\",\n name: text(node.name),\n url: node.url,\n ...(typeof node.description === \"string\"\n ? { description: node.description }\n : {}),\n };\n if (node.type === \"separator\")\n return {\n type: \"separator\",\n ...(node.name ? { name: text(node.name) } : {}),\n };\n if (node.type === \"folder\")\n return {\n type: \"folder\",\n name: text(node.name),\n ...(node.index?.url !== undefined\n ? { index: { name: text(node.index.name), url: node.index.url } }\n : {}),\n children: (node.children ?? []).flatMap(\n (child) => convert(child) ?? [],\n ),\n ...(node.defaultOpen ? { defaultOpen: true } : {}),\n };\n return undefined;\n };\n return {\n name: text(tree?.name) || \"Docs\",\n children: (tree?.children ?? []).flatMap((child) => convert(child) ?? []),\n };\n}\n\n/** Open a docs folder; says what is missing when it cannot be shown. */\nexport async function openDocs(options: {\n /** Where relative paths in `documentation` start: the app entry's folder. */\n base: string;\n documentation: DocumentationOptions;\n warn: (message: string) => void;\n}): Promise<OpenedDocs> {\n const fumadocs = await loadFumadocs();\n if (Array.isArray(fumadocs)) return { status: \"missing\", packages: fumadocs };\n const docs = new DevDocs(\n options.base,\n options.documentation,\n fumadocs,\n options.warn,\n );\n try {\n await docs.refresh();\n } catch (error) {\n docs.close();\n const root = resolve(options.base, options.documentation.dir);\n return {\n status: \"error\",\n message:\n (error as { code?: string }).code === \"ENOENT\"\n ? `The docs folder ${root} does not exist.`\n : errorMessage(error),\n };\n }\n docs.watch();\n return { status: \"ready\", docs };\n}\n\n/**\n * The docs of whichever app is running: opened when the app says where they\n * are, replaced when that changes, and closed when it stops asking for them.\n */\nexport class DocsHost {\n readonly #store: DevTelemetryStore;\n readonly #warn: (message: string) => void;\n #docs: DevDocs | undefined;\n #stopListening: (() => void) | undefined;\n #key: string | undefined;\n #pending: Promise<void> = Promise.resolve();\n\n constructor(store: DevTelemetryStore, warn: (message: string) => void) {\n this.#store = store;\n this.#warn = warn;\n }\n\n get current(): DevDocs | undefined {\n return this.#docs;\n }\n\n /**\n * Follow the app's `documentation`. Relative paths in it start at `base`, the\n * folder of the app entry, as they read in the file that sets them.\n */\n configure(\n base: string,\n documentation: DocumentationOptions | undefined,\n ): Promise<void> {\n this.#pending = this.#pending.then(() =>\n this.#configure(base, documentation),\n );\n return this.#pending;\n }\n\n async #configure(\n base: string,\n documentation: DocumentationOptions | undefined,\n ): Promise<void> {\n const key = JSON.stringify([base, documentation ?? null]);\n if (key === this.#key) return;\n this.#key = key;\n this.#release();\n if (!documentation) {\n this.#store.setDocs(null);\n return;\n }\n const opened = await openDocs({\n base,\n documentation,\n warn: this.#warn,\n });\n if (opened.status !== \"ready\") {\n const message =\n opened.status === \"missing\"\n ? `The docs need ${opened.packages.join(\" and \")}. Install with: bun add -d ${opened.packages.join(\" \")}`\n : opened.message;\n this.#warn(`[Brick-TS] Docs are off. ${message}`);\n this.#store.setDocs({\n revision: 1,\n status: opened.status,\n title: \"Docs\",\n components: false,\n message,\n ...(opened.status === \"missing\" ? { packages: opened.packages } : {}),\n });\n return;\n }\n this.#docs = opened.docs;\n this.#stopListening = opened.docs.onChange(() =>\n this.#store.setDocs(opened.docs.snapshot()),\n );\n this.#store.setDocs(opened.docs.snapshot());\n }\n\n #release(): void {\n this.#stopListening?.();\n this.#stopListening = undefined;\n this.#docs?.close();\n this.#docs = undefined;\n }\n\n close(): void {\n this.#key = undefined;\n this.#release();\n }\n}\n","import type { Attributes } from \"@opentelemetry/api\";\nimport type { ApiDocument, ArchitectureSchema } from \"@brickkit/core\";\nimport type { DevHistory } from \"./dev-history\";\nimport type {\n SerializedError,\n SpanEndRecord,\n SpanEventRecord,\n SpanStartRecord,\n TelemetryRecord,\n WorkerErrorPhase,\n} from \"./dev-telemetry\";\n\nexport type SpanOutcome = \"running\" | \"ok\" | \"error\" | \"interrupted\";\n\nexport interface TraceSpan {\n spanId: string;\n parentSpanId?: string;\n name: string;\n startMs: number;\n endMs?: number;\n status: SpanOutcome;\n statusMessage?: string;\n attributes: Attributes;\n events: SpanEventRecord[];\n}\n\nexport interface TraceSummary {\n traceId: string;\n name: string;\n method?: string;\n route?: string;\n /** The request's actual path, which differs from a wildcard route template. */\n path?: string;\n httpStatus?: number;\n generation: number;\n startMs: number;\n endMs?: number;\n durationMs?: number;\n status: SpanOutcome;\n truncated: boolean;\n /** The service and action that handled the request, when it ran one. */\n service?: string;\n action?: string;\n /** Why it failed, when it did. */\n message?: string;\n spans: TraceSpan[];\n}\n\nexport interface FailureSummary {\n id: number;\n at: number;\n phase: \"request\" | WorkerErrorPhase;\n code: string;\n message: string;\n status?: number;\n stack?: string;\n traceId?: string;\n route?: string;\n service?: string;\n action?: string;\n generation: number;\n}\n\nexport type ReloadKind = \"started\" | \"restarting\" | \"exited\" | \"contract-ready\";\n\nexport interface ReloadSummary {\n id: number;\n at: number;\n kind: ReloadKind;\n generation: number;\n detail?: string;\n}\n\n/** Services, actions, and routes of the application as last started. */\nexport interface ArchitectureSnapshot {\n generation: number;\n schema: ArchitectureSchema;\n}\n\n/** The OpenAPI documents the app offers, for the dashboard's APIs view. */\nexport interface ApiSnapshot {\n /** Changes each time the documents are replaced, so views know to reload. */\n revision: number;\n /** Where the app listens; Try it in the APIs view sends requests here. */\n appUrl?: string;\n /** Names of the documents, in order. */\n titles: string[];\n}\n\n/** What the dashboard knows about the app's developer documentation. */\nexport interface DocsSnapshot {\n /** Changes whenever the pages change, so the Docs tab reloads. */\n revision: number;\n status: \"ready\" | \"missing\" | \"error\";\n title: string;\n /** Whether the project supplied components of its own. */\n components: boolean;\n /** Why the docs cannot be shown, when `status` is not ready. */\n message?: string;\n /** Packages to install, when `status` is \"missing\". */\n packages?: string[];\n}\n\nexport type DevTelemetryEvent =\n | { type: \"trace\"; trace: TraceSummary }\n | { type: \"failure\"; failure: FailureSummary }\n | { type: \"reload\"; reload: ReloadSummary }\n | { type: \"architecture\"; architecture: ArchitectureSnapshot }\n | { type: \"api\"; api: ApiSnapshot }\n | { type: \"docs\"; docs: DocsSnapshot | null };\n\nexport interface DevTelemetrySnapshot {\n traces: TraceSummary[];\n failures: FailureSummary[];\n reloads: ReloadSummary[];\n architecture: ArchitectureSnapshot | null;\n api: ApiSnapshot | null;\n /** Null when the app has no `documentation`. */\n docs: DocsSnapshot | null;\n}\n\nconst LIMITS = { traces: 200, spansPerTrace: 500, failures: 200, reloads: 100 };\n\nconst WORKER_FAILURE_CODES: Record<WorkerErrorPhase, string> = {\n startup: \"STARTUP_FAILED\",\n uncaught: \"UNCAUGHT_EXCEPTION\",\n \"unhandled-rejection\": \"UNHANDLED_REJECTION\",\n};\n\ninterface TraceEntry {\n traceId: string;\n generation: number;\n spans: Map<string, TraceSpan>;\n rootSpanId?: string;\n name: string;\n method?: string;\n route?: string;\n path?: string;\n httpStatus?: number;\n startMs: number;\n endMs?: number;\n status: SpanOutcome;\n failureRecorded: boolean;\n truncated: boolean;\n message?: string;\n}\n\n/**\n * Supervisor-side history of requests, failures, and reloads. It lives in the\n * parent process, so it survives application restarts.\n */\nexport class DevTelemetryStore {\n readonly #traces = new Map<string, TraceEntry>();\n readonly #failures: FailureSummary[] = [];\n readonly #reloads: ReloadSummary[] = [];\n readonly #listeners = new Set<(event: DevTelemetryEvent) => void>();\n readonly #history: DevHistory | undefined;\n #architecture: ArchitectureSnapshot | null = null;\n #api: ApiSnapshot | null = null;\n #docs: DocsSnapshot | null = null;\n #apiDocuments: ApiDocument[] = [];\n #sequence = 0;\n #generation = 0;\n\n /** Finished requests and failures are also kept in `history`, when given. */\n constructor(options: { history?: DevHistory } = {}) {\n this.#history = options.history;\n }\n\n /** Replace the architecture with the one from the latest successful start. */\n setArchitecture(schema: ArchitectureSchema, generation: number): void {\n this.#architecture = { generation, schema };\n this.#emit({ type: \"architecture\", architecture: this.#architecture });\n }\n\n ingest(records: TelemetryRecord[], generation: number): void {\n const touched = new Set<TraceEntry>();\n for (const record of records) {\n const timeMs = record.phase === \"start\" ? record.startMs : record.endMs;\n const entry = this.#entry(record.traceId, generation, timeMs);\n touched.add(entry);\n if (record.phase === \"start\") this.#start(entry, record);\n else this.#end(entry, record);\n }\n for (const entry of touched) {\n const trace = summarize(entry);\n this.#emit({ type: \"trace\", trace });\n // A request cut off by a restart is not a result worth keeping, and one\n // still running will be saved when it finishes.\n if (entry.status === \"ok\" || entry.status === \"error\") {\n this.#history?.saveTrace(trace);\n }\n }\n }\n\n recordWorkerError(\n phase: WorkerErrorPhase,\n error: SerializedError,\n generation: number,\n ): void {\n this.#pushFailure({\n phase,\n code: WORKER_FAILURE_CODES[phase],\n message: error.message,\n stack: error.stack,\n generation,\n });\n }\n\n recordReload(reload: Omit<ReloadSummary, \"id\" | \"at\">): void {\n const summary: ReloadSummary = {\n id: ++this.#sequence,\n at: Date.now(),\n ...reload,\n };\n this.#reloads.unshift(summary);\n if (this.#reloads.length > LIMITS.reloads) {\n this.#reloads.length = LIMITS.reloads;\n }\n this.#emit({ type: \"reload\", reload: summary });\n }\n\n /** Newest generation; spans reported without a process identity belong to it. */\n get latestGeneration(): number {\n return this.#generation;\n }\n\n /** Begin a generation when an application process loads, and record the reload. */\n startGeneration(detail: string): number {\n this.#generation += 1;\n this.recordReload({\n kind: \"started\",\n generation: this.#generation,\n detail,\n });\n return this.#generation;\n }\n\n /** Mark requests still running in a process that has exited as interrupted. */\n interruptGeneration(generation: number): void {\n const now = Date.now();\n for (const entry of this.#traces.values()) {\n if (entry.generation !== generation || entry.status !== \"running\")\n continue;\n entry.status = \"interrupted\";\n entry.endMs = now;\n for (const span of entry.spans.values()) {\n if (span.status !== \"running\") continue;\n span.status = \"interrupted\";\n span.endMs = now;\n }\n this.#emit({ type: \"trace\", trace: summarize(entry) });\n }\n }\n\n /** Replace the OpenAPI documents with the ones from the latest start. */\n setApiDocuments(documents: ApiDocument[], appUrl?: string): void {\n this.#apiDocuments = documents;\n this.#api = {\n revision: (this.#api?.revision ?? 0) + 1,\n ...(appUrl ? { appUrl } : {}),\n titles: documents.map((item) => item.title),\n };\n this.#emit({ type: \"api\", api: this.#api });\n }\n\n /** Set what the Docs tab shows; null when the app has no documentation. */\n setDocs(docs: DocsSnapshot | null): void {\n this.#docs = docs;\n this.#emit({ type: \"docs\", docs });\n }\n\n /** What the APIs view knows about the documents, without the documents. */\n apiSnapshot(): ApiSnapshot | null {\n return this.#api;\n }\n\n /** The documents themselves; the snapshot carries only their names. */\n apiDocuments(): ApiDocument[] {\n return this.#apiDocuments;\n }\n\n snapshot(): DevTelemetrySnapshot {\n return {\n traces: [...this.#traces.values()].reverse().map(summarize),\n failures: [...this.#failures],\n reloads: [...this.#reloads],\n architecture: this.#architecture,\n api: this.#api,\n docs: this.#docs,\n };\n }\n\n subscribe(listener: (event: DevTelemetryEvent) => void): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #entry(traceId: string, generation: number, timeMs: number): TraceEntry {\n let entry = this.#traces.get(traceId);\n if (!entry) {\n entry = {\n traceId,\n generation,\n spans: new Map(),\n name: \"\",\n startMs: timeMs,\n status: \"running\",\n failureRecorded: false,\n truncated: false,\n };\n this.#traces.set(traceId, entry);\n if (this.#traces.size > LIMITS.traces) {\n const oldest = this.#traces.keys().next().value;\n if (oldest !== undefined) this.#traces.delete(oldest);\n }\n }\n return entry;\n }\n\n #start(entry: TraceEntry, record: SpanStartRecord): void {\n entry.startMs = Math.min(entry.startMs, record.startMs);\n // The local root has no parent here: either none, or a remote caller's span\n // from an incoming traceparent. Children start after it in this process.\n const parentIsLocal =\n record.parentSpanId !== undefined && entry.spans.has(record.parentSpanId);\n if (!parentIsLocal && entry.rootSpanId === undefined) {\n entry.rootSpanId = record.spanId;\n entry.name = record.name;\n entry.method = stringAttribute(record.attributes, \"http.request.method\");\n entry.route = stringAttribute(record.attributes, \"http.route\");\n entry.path = stringAttribute(record.attributes, \"url.path\");\n }\n if (entry.spans.size >= LIMITS.spansPerTrace) {\n entry.truncated = true;\n return;\n }\n entry.spans.set(record.spanId, {\n spanId: record.spanId,\n parentSpanId: record.parentSpanId,\n name: record.name,\n startMs: record.startMs,\n status: \"running\",\n attributes: record.attributes,\n events: [],\n });\n }\n\n #end(entry: TraceEntry, record: SpanEndRecord): void {\n const existing = entry.spans.get(record.spanId);\n const span: TraceSpan = existing ?? {\n spanId: record.spanId,\n name: record.name,\n startMs: record.endMs,\n status: \"running\",\n attributes: {},\n events: [],\n };\n if (!existing) {\n if (entry.spans.size < LIMITS.spansPerTrace) {\n entry.spans.set(record.spanId, span);\n } else {\n entry.truncated = true;\n }\n }\n span.endMs = record.endMs;\n span.status = record.status === \"error\" ? \"error\" : \"ok\";\n span.statusMessage = record.statusMessage;\n span.attributes = { ...span.attributes, ...record.attributes };\n span.events = record.events;\n\n const code = stringAttribute(record.attributes, \"brick.error.code\");\n if (code !== undefined) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code,\n message:\n stringAttribute(exception, \"exception.message\") ??\n stringAttribute(record.attributes, \"brick.error.message\") ??\n code,\n status: numberAttribute(record.attributes, \"brick.error.status\"),\n stack: stringAttribute(exception, \"exception.stacktrace\"),\n traceId: entry.traceId,\n route: entry.route,\n service: stringAttribute(record.attributes, \"brick.service\"),\n action: stringAttribute(record.attributes, \"brick.action\"),\n generation: entry.generation,\n });\n entry.failureRecorded = true;\n }\n\n if (record.spanId !== entry.rootSpanId) return;\n entry.endMs = record.endMs;\n entry.httpStatus = numberAttribute(\n record.attributes,\n \"http.response.status_code\",\n );\n // Server faults make the trace an error. Client errors still show in the\n // Errors tab, so a raw route's 401 is visible without a coded failure.\n const status = entry.httpStatus ?? 0;\n const serverFault = status >= 500;\n const failed = record.status === \"error\" || serverFault;\n entry.status = failed ? \"error\" : \"ok\";\n if ((failed || status >= 400) && !entry.failureRecorded) {\n const exception = findException(record.events);\n this.#pushFailure({\n phase: \"request\",\n code: status >= 400 ? `HTTP_${status}` : \"UNHANDLED_ERROR\",\n message:\n stringAttribute(exception, \"exception.message\") ??\n record.statusMessage ??\n describeResponse(entry, status),\n status: entry.httpStatus,\n stack: stringAttribute(exception, \"exception.stacktrace\"),\n traceId: entry.traceId,\n route: entry.route,\n generation: entry.generation,\n });\n entry.failureRecorded = true;\n }\n }\n\n #pushFailure(failure: Omit<FailureSummary, \"id\" | \"at\">): void {\n const entry: FailureSummary = {\n id: ++this.#sequence,\n at: Date.now(),\n ...failure,\n };\n this.#failures.unshift(entry);\n if (this.#failures.length > LIMITS.failures) {\n this.#failures.length = LIMITS.failures;\n }\n // The request keeps the first reason it failed, to show beside it.\n const trace =\n failure.traceId === undefined\n ? undefined\n : this.#traces.get(failure.traceId);\n if (trace) trace.message ??= failure.message;\n this.#emit({ type: \"failure\", failure: entry });\n }\n\n #emit(event: DevTelemetryEvent): void {\n for (const listener of this.#listeners) {\n try {\n listener(event);\n } catch {\n this.#listeners.delete(listener);\n }\n }\n }\n}\n\nfunction summarize(entry: TraceEntry): TraceSummary {\n const spans = [...entry.spans.values()].sort((a, b) => a.startMs - b.startMs);\n const actionSpan = spans.find((span) => span.name.startsWith(\"action \"));\n return {\n traceId: entry.traceId,\n name: entry.name || spans[0]?.name || entry.traceId,\n method: entry.method,\n route: entry.route,\n path: entry.path,\n httpStatus: entry.httpStatus,\n generation: entry.generation,\n startMs: entry.startMs,\n endMs: entry.endMs,\n durationMs:\n entry.endMs === undefined ? undefined : entry.endMs - entry.startMs,\n status: entry.status,\n truncated: entry.truncated,\n service: stringAttribute(actionSpan?.attributes, \"brick.service\"),\n action: stringAttribute(actionSpan?.attributes, \"brick.action\"),\n message: entry.message,\n spans,\n };\n}\n\nfunction describeResponse(entry: TraceEntry, status: number): string {\n const target = entry.path ?? entry.route ?? entry.name;\n const request = entry.method ? `${entry.method} ${target}` : target;\n return status ? `${request} returned ${status}` : request;\n}\n\nfunction findException(events: SpanEventRecord[]): Attributes | undefined {\n return events.find((event) => event.name === \"exception\")?.attributes;\n}\n\nfunction stringAttribute(\n attributes: Attributes | undefined,\n key: string,\n): string | undefined {\n const value = attributes?.[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction numberAttribute(\n attributes: Attributes | undefined,\n key: string,\n): number | undefined {\n const value = attributes?.[key];\n return typeof value === \"number\" ? value : undefined;\n}\n"],"mappings":";;;;;;;AAKA,MAAM,cAAc;CAClB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,SAAS,QAAQ,OAA4C;CAC3D,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,MAAM,OAAO,OAAO,KAAK;CAEzB,MAAM,OAAO,eAAe,KAAK,IAAI,IAAI,IAAI,SAAS;CACtD,OAAO,WAAW,KAAK,IAAI,IAAI,IAAI,KAAK,QAAQ,MAAM,MAAI,EAAE,KAAK;AACnE;;AAGA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EACf;CACF;AACF;AAEA,SAAS,iBAAiB,OAAmB,QAAwB;CACnE,MAAM,SAAS,MAAM,QAAQ,MAAM,SAAS,MAAM;CAClD,MAAM,UAAU,MAAM,SAAS,GAAG,MAAM,OAAO,GAAG,WAAW;CAC7D,OAAO,SAAS,GAAG,QAAQ,YAAY,WAAW;AACpD;AAEA,SAAS,cAAc,QAAmD;CACxE,OAAO,OAAO,MAAM,UAAU,MAAM,SAAS,WAAW,CAAC,EAAE;AAC7D;AAEA,SAAS,gBACP,YACA,KACoB;CACpB,MAAM,QAAQ,aAAa;CAC3B,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;AAEA,SAAS,gBACP,YACA,KACoB;CACpB,MAAM,QAAQ,aAAa;CAC3B,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C"}
@@ -0,0 +1,199 @@
1
+ import { SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
2
+ import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
3
+ import { W3CTraceContextPropagator } from "@opentelemetry/core";
4
+ import { BasicTracerProvider } from "@opentelemetry/sdk-trace-base";
5
+ //#region src/dev-telemetry.ts
6
+ /** Read by @brickkit/core's logger; see `createLogger` there. */
7
+ const LOG_CAPTURE = Symbol.for("brickkit.logs.capture");
8
+ /** Core's function that records a line on the running span; see `recordActive` there. */
9
+ const LOG_RECORD = Symbol.for("brickkit.logs.record");
10
+ const CONSOLE_CAPTURED = Symbol.for("brickkit.console.captured");
11
+ const CONSOLE_LEVELS = {
12
+ log: "info",
13
+ info: "info",
14
+ warn: "warn",
15
+ error: "error",
16
+ debug: "debug"
17
+ };
18
+ const MAX_TEXT_LENGTH = 500;
19
+ const MAX_STACK_LENGTH = 4e3;
20
+ const FLUSH_DELAY_MS = 20;
21
+ const MAX_BATCH_SIZE = 200;
22
+ const SEND_TIMEOUT_MS = 1e3;
23
+ /**
24
+ * Register the tracer provider, context manager, and W3C trace context
25
+ * propagator. Span records are batched and passed to `onRecords`. Returns false
26
+ * when another tracer provider was already registered, in which case
27
+ * `onRecords` never runs.
28
+ */
29
+ function installTracing(onRecords) {
30
+ const batcher = new RecordBatcher(onRecords);
31
+ const registered = trace.setGlobalTracerProvider(new BasicTracerProvider({ spanProcessors: [new SupervisorSpanProcessor(batcher)] }));
32
+ context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());
33
+ propagation.setGlobalPropagator(new W3CTraceContextPropagator());
34
+ if (registered) {
35
+ globalThis[LOG_CAPTURE] = true;
36
+ captureConsole();
37
+ }
38
+ return registered;
39
+ }
40
+ /**
41
+ * Send `console.log`, `info`, `warn`, `error`, and `debug` to the dashboard
42
+ * while a traced request is running, as `ctx.logger` does, so code that logs
43
+ * with `console` needs no change. Lines logged outside a request print as
44
+ * usual. Only a dashboard turns this on, `brick dev`'s or the monitoring one
45
+ * of `brick start`: with neither, the console is left alone. Calling it again
46
+ * does nothing; the returned function puts the console back.
47
+ */
48
+ function captureConsole() {
49
+ const target = console;
50
+ const existing = target[CONSOLE_CAPTURED];
51
+ if (typeof existing === "function") return existing;
52
+ const globals = globalThis;
53
+ const originals = /* @__PURE__ */ new Map();
54
+ for (const [method, level] of Object.entries(CONSOLE_LEVELS)) {
55
+ const original = target[method];
56
+ originals.set(method, original);
57
+ target[method] = function(...args) {
58
+ const record = globals[LOG_RECORD];
59
+ if (globals[LOG_CAPTURE] === true && typeof record === "function" && record(level, args) === true) return;
60
+ original.apply(this, args);
61
+ };
62
+ }
63
+ const restore = () => {
64
+ for (const [method, original] of originals) target[method] = original;
65
+ delete target[CONSOLE_CAPTURED];
66
+ };
67
+ target[CONSOLE_CAPTURED] = restore;
68
+ return restore;
69
+ }
70
+ /**
71
+ * Install tracing in the dev worker, so spans from apps built with
72
+ * `brick({ telemetry: true })` reach the supervisor and join callers' traces.
73
+ * Call before the app entry is imported.
74
+ */
75
+ function installWorkerTelemetry() {
76
+ installTracing((records) => {
77
+ sendToSupervisor({
78
+ type: "brick:telemetry",
79
+ records
80
+ });
81
+ });
82
+ }
83
+ /** Resolves once the message is written, or after a short timeout if the channel is gone. */
84
+ function sendToSupervisor(message) {
85
+ if (!process.send) return Promise.resolve();
86
+ return new Promise((resolve) => {
87
+ const timer = setTimeout(resolve, SEND_TIMEOUT_MS);
88
+ try {
89
+ process.send(message, () => {
90
+ clearTimeout(timer);
91
+ resolve();
92
+ });
93
+ } catch {
94
+ clearTimeout(timer);
95
+ resolve();
96
+ }
97
+ });
98
+ }
99
+ function reportWorkerError(phase, error) {
100
+ return sendToSupervisor({
101
+ type: "brick:error",
102
+ phase,
103
+ error: serializeError(error)
104
+ });
105
+ }
106
+ function serializeError(error) {
107
+ if (error instanceof Error) return {
108
+ name: error.name,
109
+ message: truncate(error.message),
110
+ stack: error.stack === void 0 ? void 0 : truncate(error.stack, MAX_STACK_LENGTH)
111
+ };
112
+ return {
113
+ name: "Error",
114
+ message: truncate(String(error))
115
+ };
116
+ }
117
+ function truncate(text, limit = MAX_TEXT_LENGTH) {
118
+ return text.length > limit ? `${text.slice(0, limit)}…` : text;
119
+ }
120
+ function toMs(time) {
121
+ return time[0] * 1e3 + time[1] / 1e6;
122
+ }
123
+ function statusName(code) {
124
+ if (code === SpanStatusCode.ERROR) return "error";
125
+ if (code === SpanStatusCode.OK) return "ok";
126
+ return "unset";
127
+ }
128
+ function boundAttributes(attributes) {
129
+ const bounded = {};
130
+ for (const [key, value] of Object.entries(attributes ?? {})) bounded[key] = typeof value === "string" ? truncate(value, MAX_STACK_LENGTH) : value;
131
+ return bounded;
132
+ }
133
+ var RecordBatcher = class {
134
+ #records = [];
135
+ #timer;
136
+ #send;
137
+ constructor(send) {
138
+ this.#send = send;
139
+ }
140
+ push(record) {
141
+ this.#records.push(record);
142
+ if (this.#records.length >= MAX_BATCH_SIZE) this.flush();
143
+ else this.#timer ??= setTimeout(() => this.flush(), FLUSH_DELAY_MS);
144
+ }
145
+ flush() {
146
+ clearTimeout(this.#timer);
147
+ this.#timer = void 0;
148
+ if (this.#records.length === 0) return;
149
+ const records = this.#records;
150
+ this.#records = [];
151
+ this.#send(records);
152
+ }
153
+ };
154
+ var SupervisorSpanProcessor = class {
155
+ #batcher;
156
+ constructor(batcher) {
157
+ this.#batcher = batcher;
158
+ }
159
+ onStart(span) {
160
+ const { traceId, spanId } = span.spanContext();
161
+ this.#batcher.push({
162
+ phase: "start",
163
+ traceId,
164
+ spanId,
165
+ parentSpanId: span.parentSpanContext?.spanId,
166
+ name: span.name,
167
+ startMs: toMs(span.startTime),
168
+ attributes: boundAttributes(span.attributes)
169
+ });
170
+ }
171
+ onEnd(span) {
172
+ const { traceId, spanId } = span.spanContext();
173
+ this.#batcher.push({
174
+ phase: "end",
175
+ traceId,
176
+ spanId,
177
+ name: span.name,
178
+ endMs: toMs(span.endTime),
179
+ status: statusName(span.status.code),
180
+ statusMessage: span.status.message,
181
+ attributes: boundAttributes(span.attributes),
182
+ events: span.events.map((event) => ({
183
+ name: event.name,
184
+ timeMs: toMs(event.time),
185
+ attributes: boundAttributes(event.attributes)
186
+ }))
187
+ });
188
+ }
189
+ async forceFlush() {
190
+ this.#batcher.flush();
191
+ }
192
+ async shutdown() {
193
+ this.#batcher.flush();
194
+ }
195
+ };
196
+ //#endregion
197
+ export { sendToSupervisor as i, installWorkerTelemetry as n, reportWorkerError as r, installTracing as t };
198
+
199
+ //# sourceMappingURL=dev-telemetry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-telemetry.js","names":[],"sources":["../src/dev-telemetry.ts"],"sourcesContent":["import {\n context,\n propagation,\n SpanStatusCode,\n trace,\n type Attributes,\n type HrTime,\n} from \"@opentelemetry/api\";\nimport { AsyncLocalStorageContextManager } from \"@opentelemetry/context-async-hooks\";\nimport { W3CTraceContextPropagator } from \"@opentelemetry/core\";\nimport {\n BasicTracerProvider,\n type ReadableSpan,\n type Span,\n type SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport type {\n ApiDocument,\n ArchitectureSchema,\n DocumentationOptions,\n} from \"@brickkit/core\";\n\n/** Read by @brickkit/core's logger; see `createLogger` there. */\nconst LOG_CAPTURE = Symbol.for(\"brickkit.logs.capture\");\n/** Core's function that records a line on the running span; see `recordActive` there. */\nconst LOG_RECORD = Symbol.for(\"brickkit.logs.record\");\nconst CONSOLE_CAPTURED = Symbol.for(\"brickkit.console.captured\");\n\nconst CONSOLE_LEVELS = {\n log: \"info\",\n info: \"info\",\n warn: \"warn\",\n error: \"error\",\n debug: \"debug\",\n} as const;\n\nconst MAX_TEXT_LENGTH = 500;\nconst MAX_STACK_LENGTH = 4000;\nconst FLUSH_DELAY_MS = 20;\nconst MAX_BATCH_SIZE = 200;\nconst SEND_TIMEOUT_MS = 1000;\n\nexport interface SpanEventRecord {\n name: string;\n timeMs: number;\n attributes: Attributes;\n}\n\nexport interface SpanStartRecord {\n phase: \"start\";\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n name: string;\n startMs: number;\n attributes: Attributes;\n}\n\nexport interface SpanEndRecord {\n phase: \"end\";\n traceId: string;\n spanId: string;\n name: string;\n endMs: number;\n status: \"unset\" | \"ok\" | \"error\";\n statusMessage?: string;\n attributes: Attributes;\n events: SpanEventRecord[];\n}\n\nexport type TelemetryRecord = SpanStartRecord | SpanEndRecord;\n\nexport type WorkerErrorPhase = \"startup\" | \"uncaught\" | \"unhandled-rejection\";\n\nexport interface SerializedError {\n name: string;\n message: string;\n stack?: string;\n}\n\n/** Messages the dev worker sends to the supervisor over the IPC channel. */\nexport type WorkerMessage =\n | { type: \"brick:telemetry\"; records: TelemetryRecord[] }\n | { type: \"brick:error\"; phase: WorkerErrorPhase; error: SerializedError }\n | { type: \"brick:architecture\"; architecture: ArchitectureSchema }\n | { type: \"brick:api-documents\"; documents: ApiDocument[] }\n | {\n type: \"brick:documentation\";\n /** The app's `documentation` option; absent when it has none. */\n documentation?: DocumentationOptions;\n };\n\n/**\n * Register the tracer provider, context manager, and W3C trace context\n * propagator. Span records are batched and passed to `onRecords`. Returns false\n * when another tracer provider was already registered, in which case\n * `onRecords` never runs.\n */\nexport function installTracing(\n onRecords: (records: TelemetryRecord[]) => void,\n): boolean {\n const batcher = new RecordBatcher(onRecords);\n const registered = trace.setGlobalTracerProvider(\n new BasicTracerProvider({\n spanProcessors: [new SupervisorSpanProcessor(batcher)],\n }),\n );\n context.setGlobalContextManager(\n new AsyncLocalStorageContextManager().enable(),\n );\n propagation.setGlobalPropagator(new W3CTraceContextPropagator());\n // From here the dashboard shows what actions and tools log, as span events,\n // so @brickkit/core stops printing it. The key is shared by name because the\n // app and the dev server may each hold their own copy of core.\n if (registered) {\n (globalThis as Record<symbol, unknown>)[LOG_CAPTURE] = true;\n captureConsole();\n }\n return registered;\n}\n\ntype Restore = () => void;\n\n/**\n * Send `console.log`, `info`, `warn`, `error`, and `debug` to the dashboard\n * while a traced request is running, as `ctx.logger` does, so code that logs\n * with `console` needs no change. Lines logged outside a request print as\n * usual. Only a dashboard turns this on, `brick dev`'s or the monitoring one\n * of `brick start`: with neither, the console is left alone. Calling it again\n * does nothing; the returned function puts the console back.\n */\nexport function captureConsole(): Restore {\n const target = console as unknown as Record<string | symbol, unknown>;\n const existing = target[CONSOLE_CAPTURED];\n if (typeof existing === \"function\") return existing as Restore;\n\n const globals = globalThis as Record<symbol, unknown>;\n const originals = new Map<string, (...args: unknown[]) => void>();\n for (const [method, level] of Object.entries(CONSOLE_LEVELS)) {\n const original = target[method] as (...args: unknown[]) => void;\n originals.set(method, original);\n target[method] = function (this: unknown, ...args: unknown[]) {\n const record = globals[LOG_RECORD];\n if (\n globals[LOG_CAPTURE] === true &&\n typeof record === \"function\" &&\n record(level, args) === true\n )\n return;\n original.apply(this, args);\n };\n }\n const restore: Restore = () => {\n for (const [method, original] of originals) target[method] = original;\n delete target[CONSOLE_CAPTURED];\n };\n target[CONSOLE_CAPTURED] = restore;\n return restore;\n}\n\n/**\n * Install tracing in the dev worker, so spans from apps built with\n * `brick({ telemetry: true })` reach the supervisor and join callers' traces.\n * Call before the app entry is imported.\n */\nexport function installWorkerTelemetry(): void {\n installTracing((records) => {\n void sendToSupervisor({ type: \"brick:telemetry\", records });\n });\n}\n\n/** Resolves once the message is written, or after a short timeout if the channel is gone. */\nexport function sendToSupervisor(message: WorkerMessage): Promise<void> {\n if (!process.send) return Promise.resolve();\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, SEND_TIMEOUT_MS);\n try {\n process.send!(message, () => {\n clearTimeout(timer);\n resolve();\n });\n } catch {\n clearTimeout(timer);\n resolve();\n }\n });\n}\n\nexport function reportWorkerError(\n phase: WorkerErrorPhase,\n error: unknown,\n): Promise<void> {\n return sendToSupervisor({\n type: \"brick:error\",\n phase,\n error: serializeError(error),\n });\n}\n\nexport function serializeError(error: unknown): SerializedError {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: truncate(error.message),\n stack:\n error.stack === undefined\n ? undefined\n : truncate(error.stack, MAX_STACK_LENGTH),\n };\n }\n return { name: \"Error\", message: truncate(String(error)) };\n}\n\nfunction truncate(text: string, limit = MAX_TEXT_LENGTH): string {\n return text.length > limit ? `${text.slice(0, limit)}…` : text;\n}\n\nfunction toMs(time: HrTime): number {\n return time[0] * 1000 + time[1] / 1e6;\n}\n\nfunction statusName(code: SpanStatusCode): \"unset\" | \"ok\" | \"error\" {\n if (code === SpanStatusCode.ERROR) return \"error\";\n if (code === SpanStatusCode.OK) return \"ok\";\n return \"unset\";\n}\n\nfunction boundAttributes(attributes: Attributes | undefined): Attributes {\n const bounded: Attributes = {};\n for (const [key, value] of Object.entries(attributes ?? {})) {\n bounded[key] =\n typeof value === \"string\" ? truncate(value, MAX_STACK_LENGTH) : value;\n }\n return bounded;\n}\n\nclass RecordBatcher {\n #records: TelemetryRecord[] = [];\n #timer: ReturnType<typeof setTimeout> | undefined;\n readonly #send: (records: TelemetryRecord[]) => void;\n\n constructor(send: (records: TelemetryRecord[]) => void) {\n this.#send = send;\n }\n\n push(record: TelemetryRecord): void {\n this.#records.push(record);\n if (this.#records.length >= MAX_BATCH_SIZE) this.flush();\n else this.#timer ??= setTimeout(() => this.flush(), FLUSH_DELAY_MS);\n }\n\n flush(): void {\n clearTimeout(this.#timer);\n this.#timer = undefined;\n if (this.#records.length === 0) return;\n const records = this.#records;\n this.#records = [];\n this.#send(records);\n }\n}\n\nclass SupervisorSpanProcessor implements SpanProcessor {\n readonly #batcher: RecordBatcher;\n\n constructor(batcher: RecordBatcher) {\n this.#batcher = batcher;\n }\n\n onStart(span: Span): void {\n const { traceId, spanId } = span.spanContext();\n this.#batcher.push({\n phase: \"start\",\n traceId,\n spanId,\n parentSpanId: span.parentSpanContext?.spanId,\n name: span.name,\n startMs: toMs(span.startTime),\n attributes: boundAttributes(span.attributes),\n });\n }\n\n onEnd(span: ReadableSpan): void {\n const { traceId, spanId } = span.spanContext();\n this.#batcher.push({\n phase: \"end\",\n traceId,\n spanId,\n name: span.name,\n endMs: toMs(span.endTime),\n status: statusName(span.status.code),\n statusMessage: span.status.message,\n attributes: boundAttributes(span.attributes),\n events: span.events.map((event) => ({\n name: event.name,\n timeMs: toMs(event.time),\n attributes: boundAttributes(event.attributes),\n })),\n });\n }\n\n async forceFlush(): Promise<void> {\n this.#batcher.flush();\n }\n\n async shutdown(): Promise<void> {\n this.#batcher.flush();\n }\n}\n"],"mappings":";;;;;;AAuBA,MAAM,cAAc,OAAO,IAAI,uBAAuB;;AAEtD,MAAM,aAAa,OAAO,IAAI,sBAAsB;AACpD,MAAM,mBAAmB,OAAO,IAAI,2BAA2B;AAE/D,MAAM,iBAAiB;CACrB,KAAK;CACL,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;AACT;AAEA,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;;;;;;;AA0DxB,SAAgB,eACd,WACS;CACT,MAAM,UAAU,IAAI,cAAc,SAAS;CAC3C,MAAM,aAAa,MAAM,wBACvB,IAAI,oBAAoB,EACtB,gBAAg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